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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use crate::net::TcpStream;
pub use fluvio_async_tls::client::TlsStream as ClientTlsStream;
pub use fluvio_async_tls::server::TlsStream as ServerTlsStream;
pub use fluvio_async_tls::TlsAcceptor;
pub use fluvio_async_tls::TlsConnector;
pub type DefaultServerTlsStream = ServerTlsStream<TcpStream>;
pub type DefaultClientTlsStream = ClientTlsStream<TcpStream>;
use rustls::Certificate;
use rustls::ClientConfig;
use rustls::PrivateKey;
use rustls::RootCertStore;
use rustls::ServerConfig;
pub use builder::*;
pub use cert::*;
pub use connector::*;
mod split {
use futures_util::AsyncReadExt;
use super::*;
use crate::net::{BoxReadConnection, BoxWriteConnection, SplitConnection};
impl SplitConnection for DefaultClientTlsStream {
fn split_connection(self) -> (BoxWriteConnection, BoxReadConnection) {
let (read, write) = self.split();
(Box::new(write), Box::new(read))
}
}
impl SplitConnection for DefaultServerTlsStream {
fn split_connection(self) -> (BoxWriteConnection, BoxReadConnection) {
let (read, write) = self.split();
(Box::new(write), Box::new(read))
}
}
}
mod cert {
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::io::Error as IoError;
use std::io::ErrorKind;
use std::path::Path;
use rustls::internal::pemfile::certs;
use rustls::internal::pemfile::rsa_private_keys;
use super::Certificate;
use super::PrivateKey;
use super::RootCertStore;
pub fn load_certs<P: AsRef<Path>>(path: P) -> Result<Vec<Certificate>, IoError> {
load_certs_from_reader(&mut BufReader::new(File::open(path)?))
}
pub fn load_certs_from_reader(rd: &mut dyn BufRead) -> Result<Vec<Certificate>, IoError> {
certs(rd).map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid cert"))
}
pub fn load_keys<P: AsRef<Path>>(path: P) -> Result<Vec<PrivateKey>, IoError> {
load_keys_from_reader(&mut BufReader::new(File::open(path)?))
}
pub fn load_keys_from_reader(rd: &mut dyn BufRead) -> Result<Vec<PrivateKey>, IoError> {
rsa_private_keys(rd).map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid key"))
}
pub fn load_root_ca<P: AsRef<Path>>(path: P) -> Result<RootCertStore, IoError> {
let mut root_store = RootCertStore::empty();
root_store
.add_pem_file(&mut BufReader::new(File::open(path)?))
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid ca crt"))?;
Ok(root_store)
}
}
mod connector {
use std::io::Error as IoError;
use std::os::unix::io::AsRawFd;
use std::os::unix::io::RawFd;
use async_trait::async_trait;
use log::debug;
use crate::net::{
BoxReadConnection, BoxWriteConnection, DomainConnector, SplitConnection, TcpDomainConnector,
};
use super::TcpStream;
use super::TlsConnector;
pub type TlsError = IoError;
#[derive(Clone)]
pub struct TlsAnonymousConnector(TlsConnector);
impl From<TlsConnector> for TlsAnonymousConnector {
fn from(connector: TlsConnector) -> Self {
Self(connector)
}
}
#[async_trait]
impl TcpDomainConnector for TlsAnonymousConnector {
async fn connect(
&self,
domain: &str,
) -> Result<(BoxWriteConnection, BoxReadConnection, RawFd), IoError> {
let tcp_stream = TcpStream::connect(domain).await?;
let fd = tcp_stream.as_raw_fd();
let (write, read) = self.0.connect(domain, tcp_stream).await?.split_connection();
Ok((write, read, fd))
}
fn new_domain(&self, _domain: String) -> DomainConnector {
Box::new(self.clone())
}
fn domain(&self) -> &str {
"localhost"
}
}
#[derive(Clone)]
pub struct TlsDomainConnector {
domain: String,
connector: TlsConnector,
}
impl TlsDomainConnector {
pub fn new(connector: TlsConnector, domain: String) -> Self {
Self { domain, connector }
}
}
#[async_trait]
impl TcpDomainConnector for TlsDomainConnector {
async fn connect(
&self,
addr: &str,
) -> Result<(BoxWriteConnection, BoxReadConnection, RawFd), IoError> {
debug!("connect to tls addr: {}", addr);
let tcp_stream = TcpStream::connect(addr).await?;
let fd = tcp_stream.as_raw_fd();
debug!("connect to tls domain: {}", self.domain);
let (write, read) = self
.connector
.connect(&self.domain, tcp_stream)
.await?
.split_connection();
Ok((write, read, fd))
}
fn new_domain(&self, domain: String) -> DomainConnector {
let mut connector = self.clone();
connector.domain = domain;
Box::new(connector)
}
fn domain(&self) -> &str {
&self.domain
}
}
}
mod builder {
use std::fs::File;
use std::io::BufReader;
use std::io::Cursor;
use std::io::Error as IoError;
use std::io::ErrorKind;
use std::path::Path;
use std::sync::Arc;
use rustls::AllowAnyAuthenticatedClient;
use rustls::ServerCertVerified;
use rustls::ServerCertVerifier;
use rustls::TLSError;
use webpki::DNSNameRef;
use super::load_certs;
use super::load_certs_from_reader;
use super::load_keys;
use super::load_keys_from_reader;
use super::load_root_ca;
use super::Certificate;
use super::ClientConfig;
use super::RootCertStore;
use super::ServerConfig;
use super::TlsAcceptor;
use super::TlsConnector;
pub struct ConnectorBuilder(ClientConfig);
impl ConnectorBuilder {
pub fn new() -> Self {
Self(ClientConfig::new())
}
pub fn load_ca_cert<P: AsRef<Path>>(mut self, path: P) -> Result<Self, IoError> {
self.0
.root_store
.add_pem_file(&mut BufReader::new(File::open(path)?))
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid ca crt"))?;
Ok(self)
}
pub fn load_ca_cert_from_bytes(mut self, buffer: &[u8]) -> Result<Self, IoError> {
let mut bytes = Cursor::new(buffer);
self.0
.root_store
.add_pem_file(&mut bytes)
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid ca crt"))?;
Ok(self)
}
pub fn load_client_certs<P: AsRef<Path>>(
mut self,
cert_path: P,
key_path: P,
) -> Result<Self, IoError> {
let client_certs = load_certs(cert_path)?;
let mut client_keys = load_keys(key_path)?;
self.0
.set_single_client_cert(client_certs, client_keys.remove(0))
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid cert"))?;
Ok(self)
}
pub fn load_client_certs_from_bytes(
mut self,
cert_buf: &[u8],
key_buf: &[u8],
) -> Result<Self, IoError> {
let client_certs = load_certs_from_reader(&mut Cursor::new(cert_buf))?;
let mut client_keys = load_keys_from_reader(&mut Cursor::new(key_buf))?;
self.0
.set_single_client_cert(client_certs, client_keys.remove(0))
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid cert"))?;
Ok(self)
}
pub fn no_cert_verification(mut self) -> Self {
self.0
.dangerous()
.set_certificate_verifier(Arc::new(NoCertificateVerification {}));
self
}
pub fn build(self) -> TlsConnector {
self.0.into()
}
}
impl Default for ConnectorBuilder {
fn default() -> Self {
Self::new()
}
}
pub struct AcceptorBuilder(ServerConfig);
impl AcceptorBuilder {
pub fn new_no_client_authentication() -> Self {
use rustls::NoClientAuth;
Self(ServerConfig::new(NoClientAuth::new()))
}
pub fn new_client_authenticate<P: AsRef<Path>>(path: P) -> Result<Self, IoError> {
let root_store = load_root_ca(path)?;
Ok(Self(ServerConfig::new(AllowAnyAuthenticatedClient::new(
root_store,
))))
}
pub fn load_server_certs<P: AsRef<Path>>(
mut self,
cert_path: P,
key_path: P,
) -> Result<Self, IoError> {
let server_crt = load_certs(cert_path)?;
let mut server_keys = load_keys(key_path)?;
self.0
.set_single_cert(server_crt, server_keys.remove(0))
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid cert"))?;
Ok(self)
}
pub fn build(self) -> TlsAcceptor {
TlsAcceptor::from(Arc::new(self.0))
}
}
struct NoCertificateVerification {}
impl ServerCertVerifier for NoCertificateVerification {
fn verify_server_cert(
&self,
_roots: &RootCertStore,
_presented_certs: &[Certificate],
_dns_name: DNSNameRef<'_>,
_ocsp: &[u8],
) -> Result<ServerCertVerified, TLSError> {
log::debug!("ignoring server cert");
Ok(ServerCertVerified::assertion())
}
}
}
#[cfg(test)]
mod test {
use std::io::Error as IoError;
use std::net::SocketAddr;
use std::time;
use bytes::BufMut;
use bytes::Bytes;
use bytes::BytesMut;
use fluvio_async_tls::TlsAcceptor;
use fluvio_async_tls::TlsConnector;
use futures_lite::future::zip;
use futures_lite::stream::StreamExt;
use futures_util::sink::SinkExt;
use log::debug;
use tokio_util::codec::BytesCodec;
use tokio_util::codec::Framed;
use tokio_util::compat::FuturesAsyncReadCompatExt;
use fluvio_future::net::TcpListener;
use fluvio_future::net::TcpStream;
use fluvio_future::test_async;
use fluvio_future::timer::sleep;
use super::{AcceptorBuilder, ConnectorBuilder};
const CA_PATH: &str = "certs/test-certs/ca.crt";
const ITER: u16 = 10;
fn to_bytes(bytes: Vec<u8>) -> Bytes {
let mut buf = BytesMut::with_capacity(bytes.len());
buf.put_slice(&bytes);
buf.freeze()
}
#[test_async]
async fn test_async_tls() -> Result<(), IoError> {
test_tls(
AcceptorBuilder::new_no_client_authentication()
.load_server_certs("certs/test-certs/server.crt", "certs/test-certs/server.key")?
.build(),
ConnectorBuilder::new().no_cert_verification().build(),
)
.await
.expect("no client cert test failed");
test_tls(
AcceptorBuilder::new_client_authenticate(CA_PATH)?
.load_server_certs("certs/test-certs/server.crt", "certs/test-certs/server.key")?
.build(),
ConnectorBuilder::new()
.load_client_certs("certs/test-certs/client.crt", "certs/test-certs/client.key")?
.load_ca_cert(CA_PATH)?
.build(),
)
.await
.expect("client cert test fail");
Ok(())
}
async fn test_tls(acceptor: TlsAcceptor, connector: TlsConnector) -> Result<(), IoError> {
let addr = "127.0.0.1:19998".parse::<SocketAddr>().expect("parse");
let server_ft = async {
debug!("server: binding");
let listener = TcpListener::bind(&addr).await.expect("listener failed");
debug!("server: successfully binding. waiting for incoming");
let mut incoming = listener.incoming();
let stream = incoming.next().await.expect("stream");
let tcp_stream = stream.expect("no stream");
let acceptor = acceptor.clone();
debug!("server: got connection from client");
debug!("server: try to accept tls connection");
let handshake = acceptor.accept(tcp_stream);
debug!("server: handshaking");
let tls_stream = handshake.await.expect("hand shake failed");
let mut framed = Framed::new(tls_stream.compat(), BytesCodec::new());
for i in 0..ITER {
let receives_bytes = framed.next().await.expect("frame");
let bytes = receives_bytes.expect("invalid value");
debug!(
"server: loop {}, received from client: {} bytes",
i,
bytes.len()
);
let slice = bytes.as_ref();
let mut str_bytes = vec![];
for b in slice {
str_bytes.push(b.to_owned());
}
let message = String::from_utf8(str_bytes).expect("utf8");
assert_eq!(message, format!("message{}", i));
let resply = format!("{}reply", message);
let reply_bytes = resply.as_bytes();
debug!("sever: send back reply: {}", resply);
framed
.send(to_bytes(reply_bytes.to_vec()))
.await
.expect("send failed");
}
Ok(()) as Result<(), IoError>
};
let client_ft = async {
debug!("client: sleep to give server chance to come up");
sleep(time::Duration::from_millis(100)).await;
debug!("client: trying to connect");
let tcp_stream = TcpStream::connect(&addr).await.expect("connection fail");
let tls_stream = connector
.connect("localhost", tcp_stream)
.await
.expect("tls failed");
let all_stream = Box::new(tls_stream);
let mut framed = Framed::new(all_stream.compat(), BytesCodec::new());
debug!("client: got connection. waiting");
for i in 0..ITER {
let message = format!("message{}", i);
let bytes = message.as_bytes();
debug!("client: loop {} sending test message", i);
framed
.send(to_bytes(bytes.to_vec()))
.await
.expect("send failed");
let reply = framed.next().await.expect("messages").expect("frame");
debug!("client: loop {}, received reply back", i);
let slice = reply.as_ref();
let mut str_bytes = vec![];
for b in slice {
str_bytes.push(b.to_owned());
}
let message = String::from_utf8(str_bytes).expect("utf8");
assert_eq!(message, format!("message{}reply", i));
}
Ok(()) as Result<(), IoError>
};
let _ = zip(client_ft, server_ft).await;
Ok(())
}
}