-
-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathclient.rs
172 lines (155 loc) · 6.02 KB
/
client.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
use std::sync::Arc;
use bytes::BytesMut;
use tokio::net::TcpStream;
use tracing::*;
use warpgate_common::{configure_tls_connector, TargetMySqlOptions, TlsMode};
use warpgate_database_protocols::io::Decode;
use warpgate_database_protocols::mysql::protocol::auth::AuthPlugin;
use warpgate_database_protocols::mysql::protocol::connect::{
Handshake, HandshakeResponse, SslRequest,
};
use warpgate_database_protocols::mysql::protocol::response::ErrPacket;
use warpgate_database_protocols::mysql::protocol::Capabilities;
use crate::common::compute_auth_challenge_response;
use crate::error::MySqlError;
use crate::stream::MySqlStream;
pub struct MySqlClient {
pub stream: MySqlStream<tokio_rustls::client::TlsStream<TcpStream>>,
pub _capabilities: Capabilities,
}
pub struct ConnectionOptions {
pub collation: u8,
pub database: Option<String>,
pub max_packet_size: u32,
pub capabilities: Capabilities,
}
impl Default for ConnectionOptions {
fn default() -> Self {
ConnectionOptions {
collation: 33,
database: None,
max_packet_size: 0xffff_ffff,
capabilities: Capabilities::PROTOCOL_41
| Capabilities::PLUGIN_AUTH
| Capabilities::FOUND_ROWS
| Capabilities::LONG_FLAG
| Capabilities::NO_SCHEMA
| Capabilities::PLUGIN_AUTH_LENENC_DATA
| Capabilities::CONNECT_WITH_DB
| Capabilities::SESSION_TRACK
| Capabilities::IGNORE_SPACE
| Capabilities::INTERACTIVE
| Capabilities::TRANSACTIONS
| Capabilities::DEPRECATE_EOF
| Capabilities::SECURE_CONNECTION
| Capabilities::SSL,
}
}
}
impl MySqlClient {
pub async fn connect(
target: &TargetMySqlOptions,
mut options: ConnectionOptions,
) -> Result<Self, MySqlError> {
let mut stream =
MySqlStream::new(TcpStream::connect((target.host.clone(), target.port)).await?);
options.capabilities.remove(Capabilities::SSL);
if target.tls.mode != TlsMode::Disabled {
options.capabilities |= Capabilities::SSL;
}
let Some(payload) = stream.recv().await? else {
return Err(MySqlError::Eof);
};
let handshake = Handshake::decode(payload)?;
options.capabilities &= handshake.server_capabilities;
if target.tls.mode == TlsMode::Required && !options.capabilities.contains(Capabilities::SSL)
{
return Err(MySqlError::TlsNotSupported);
}
info!(capabilities=?options.capabilities, "Target handshake");
if options.capabilities.contains(Capabilities::SSL) && target.tls.mode != TlsMode::Disabled
{
let accept_invalid_certs = !target.tls.verify;
let accept_invalid_hostname = false; // ca + hostname verification
let client_config = Arc::new(
configure_tls_connector(accept_invalid_certs, accept_invalid_hostname, None)
.await?,
);
let req = SslRequest {
collation: options.collation,
max_packet_size: options.max_packet_size,
};
stream.push(&req, options.capabilities)?;
stream.flush().await?;
stream = stream
.upgrade((
target
.host
.clone()
.try_into()
.map_err(|_| MySqlError::InvalidDomainName)?,
client_config,
))
.await?;
info!("Target connection upgraded to TLS");
}
let mut response = HandshakeResponse {
auth_plugin: None,
auth_response: None,
collation: options.collation,
database: options.database,
max_packet_size: options.max_packet_size,
username: target.username.clone(),
};
if handshake.auth_plugin == Some(AuthPlugin::MySqlNativePassword) {
let scramble_bytes = [
&handshake.auth_plugin_data.first_ref()[..],
&handshake.auth_plugin_data.last_ref()[..],
]
.concat();
match scramble_bytes.try_into() as Result<[u8; 20], Vec<u8>> {
Err(scramble_bytes) => {
warn!("Invalid scramble length ({})", scramble_bytes.len());
}
Ok(scramble) => {
response.auth_plugin = Some(AuthPlugin::MySqlNativePassword);
response.auth_response = Some(
BytesMut::from(
compute_auth_challenge_response(
scramble,
target.password.as_deref().unwrap_or(""),
)
.map_err(MySqlError::other)?
.as_bytes(),
)
.freeze(),
);
trace!(response=?response.auth_response, ?scramble, "auth");
}
}
}
stream.push(&response, options.capabilities)?;
stream.flush().await?;
let Some(response) = stream.recv().await? else {
return Err(MySqlError::Eof);
};
if response.first() == Some(&0) || response.first() == Some(&0xfe) {
debug!("Authorized");
} else if response.first() == Some(&0xff) {
let error = ErrPacket::decode_with(response, options.capabilities)?;
return Err(MySqlError::ProtocolError(format!(
"handshake failed: {error:?}"
)));
} else {
return Err(MySqlError::ProtocolError(format!(
"unknown response type {:?}",
response.first()
)));
}
stream.reset_sequence_id();
Ok(Self {
stream,
_capabilities: options.capabilities,
})
}
}