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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
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_pemfile::certs;
use rustls_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(|v| v.into_iter().map(Certificate).collect())
.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(|v| v.into_iter().map(PrivateKey).collect())
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid key"))
}
pub(crate) fn load_first_key<P: AsRef<Path>>(path: P) -> Result<PrivateKey, IoError> {
load_first_key_from_reader(&mut BufReader::new(File::open(path)?))
}
pub(crate) fn load_first_key_from_reader(rd: &mut dyn BufRead) -> Result<PrivateKey, IoError> {
let mut keys = load_keys_from_reader(rd)?;
if keys.is_empty() {
Err(IoError::new(ErrorKind::InvalidInput, "no keys found"))
} else {
Ok(keys.remove(0))
}
}
pub fn load_root_ca<P: AsRef<Path>>(path: P) -> Result<RootCertStore, IoError> {
let certs = load_certs(path)
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid ca crt"))?;
let mut root_store = RootCertStore::empty();
for cert in &certs {
root_store
.add(cert)
.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::io::Cursor;
use std::io::Error as IoError;
use std::io::ErrorKind;
use std::path::Path;
use std::sync::Arc;
use std::time::SystemTime;
use rustls::{
client::ServerCertVerified, server::WantsServerCert, PrivateKey, RootCertStore, ServerName,
};
use rustls::{client::ServerCertVerifier, ConfigBuilder};
use rustls::{client::WantsTransparencyPolicyOrClientCert, Error as TlsError};
use rustls::{server::AllowAnyAuthenticatedClient, WantsVerifier};
use super::load_root_ca;
use super::Certificate;
use super::ClientConfig;
use super::ServerConfig;
use super::TlsAcceptor;
use super::TlsConnector;
use super::{load_certs, load_first_key_from_reader};
use super::{load_certs_from_reader, load_first_key};
pub type ClientConfigBuilder<Stage> = ConfigBuilder<ClientConfig, Stage>;
pub struct ConnectorBuilder;
impl ConnectorBuilder {
pub fn with_safe_defaults() -> ConnectorBuilderStage<WantsVerifier> {
ConnectorBuilderStage(ClientConfig::builder().with_safe_defaults())
}
}
pub struct ConnectorBuilderStage<S>(ConfigBuilder<ClientConfig, S>);
impl ConnectorBuilderStage<WantsVerifier> {
pub fn load_ca_cert<P: AsRef<Path>>(
self,
path: P,
) -> Result<ConnectorBuilderStage<WantsTransparencyPolicyOrClientCert>, IoError> {
let certs = load_certs(path)?;
self.with_root_certificates(&certs)
}
pub fn load_ca_cert_from_bytes(
self,
buffer: &[u8],
) -> Result<ConnectorBuilderStage<WantsTransparencyPolicyOrClientCert>, IoError> {
let certs = load_certs_from_reader(&mut Cursor::new(buffer))?;
self.with_root_certificates(&certs)
}
pub fn no_cert_verification(self) -> ConnectorBuilderWithConfig {
let config = self
.0
.with_custom_certificate_verifier(Arc::new(NoCertificateVerification))
.with_no_client_auth();
ConnectorBuilderWithConfig(config)
}
fn with_root_certificates(
self,
certs: &[Certificate],
) -> Result<ConnectorBuilderStage<WantsTransparencyPolicyOrClientCert>, IoError> {
let mut root_store = RootCertStore::empty();
for cert in certs {
root_store
.add(cert)
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid ca crt"))?;
}
Ok(ConnectorBuilderStage(
self.0.with_root_certificates(root_store),
))
}
}
impl ConnectorBuilderStage<WantsTransparencyPolicyOrClientCert> {
pub fn load_client_certs<P: AsRef<Path>>(
self,
cert_path: P,
key_path: P,
) -> Result<ConnectorBuilderWithConfig, IoError> {
let certs = load_certs(cert_path)?;
let key = load_first_key(key_path)?;
self.with_single_cert(certs, key)
}
pub fn load_client_certs_from_bytes(
self,
cert_buf: &[u8],
key_buf: &[u8],
) -> Result<ConnectorBuilderWithConfig, IoError> {
let certs = load_certs_from_reader(&mut Cursor::new(cert_buf))?;
let key = load_first_key_from_reader(&mut Cursor::new(key_buf))?;
self.with_single_cert(certs, key)
}
pub fn no_client_auth(self) -> ConnectorBuilderWithConfig {
ConnectorBuilderWithConfig(self.0.with_no_client_auth())
}
fn with_single_cert(
self,
certs: Vec<Certificate>,
key: PrivateKey,
) -> Result<ConnectorBuilderWithConfig, IoError> {
let config = self
.0
.with_single_cert(certs, key)
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid cert"))?;
Ok(ConnectorBuilderWithConfig(config))
}
}
pub struct ConnectorBuilderWithConfig(ClientConfig);
impl ConnectorBuilderWithConfig {
pub fn build(self) -> TlsConnector {
self.0.into()
}
}
pub struct AcceptorBuilder;
impl AcceptorBuilder {
pub fn with_safe_defaults() -> AcceptorBuilderStage<WantsVerifier> {
AcceptorBuilderStage(ServerConfig::builder().with_safe_defaults())
}
}
pub struct AcceptorBuilderStage<S>(ConfigBuilder<ServerConfig, S>);
impl AcceptorBuilderStage<WantsVerifier> {
pub fn no_client_authentication(self) -> AcceptorBuilderStage<WantsServerCert> {
AcceptorBuilderStage(self.0.with_no_client_auth())
}
pub fn client_authenticate<P: AsRef<Path>>(
self,
path: P,
) -> Result<AcceptorBuilderStage<WantsServerCert>, IoError> {
let root_store = load_root_ca(path)?;
Ok(AcceptorBuilderStage(self.0.with_client_cert_verifier(
AllowAnyAuthenticatedClient::new(root_store),
)))
}
}
impl AcceptorBuilderStage<WantsServerCert> {
pub fn load_server_certs(
self,
cert_path: impl AsRef<Path>,
key_path: impl AsRef<Path>,
) -> Result<AcceptorBuilderWithConfig, IoError> {
let certs = load_certs(cert_path)?;
let key = load_first_key(key_path)?;
let config = self
.0
.with_single_cert(certs, key)
.map_err(|_| IoError::new(ErrorKind::InvalidInput, "invalid cert"))?;
Ok(AcceptorBuilderWithConfig(config))
}
}
pub struct AcceptorBuilderWithConfig(ServerConfig);
impl AcceptorBuilderWithConfig {
pub fn build(self) -> TlsAcceptor {
TlsAcceptor::from(Arc::new(self.0))
}
}
struct NoCertificateVerification;
impl ServerCertVerifier for NoCertificateVerification {
fn verify_server_cert(
&self,
_end_entity: &Certificate,
_intermediates: &[Certificate],
_server_name: &ServerName,
_scts: &mut dyn Iterator<Item = &[u8]>,
_ocsp_response: &[u8],
_now: SystemTime,
) -> 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::with_safe_defaults()
.no_client_authentication()
.load_server_certs("certs/test-certs/server.crt", "certs/test-certs/server.key")?
.build(),
ConnectorBuilder::with_safe_defaults()
.no_cert_verification()
.build(),
)
.await
.expect("no client cert test failed");
test_tls(
AcceptorBuilder::with_safe_defaults()
.client_authenticate(CA_PATH)?
.load_server_certs("certs/test-certs/server.crt", "certs/test-certs/server.key")?
.build(),
ConnectorBuilder::with_safe_defaults()
.load_ca_cert(CA_PATH)?
.load_client_certs("certs/test-certs/client.crt", "certs/test-certs/client.key")?
.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).expect("accept failed");
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(())
}
}