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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
use libc::{c_int, c_void, c_long};
use std::ffi::{CStr, CString};
use std::fmt;
use std::io;
use std::io::prelude::*;
use std::ffi::AsOsStr;
use std::mem;
use std::net;
use std::num::FromPrimitive;
use std::num::Int;
use std::path::Path;
use std::ptr;
use std::sync::{Once, ONCE_INIT, Arc};
use std::ops::{Deref, DerefMut};
use std::cmp;
use bio::{MemBio};
use ffi;
use ssl::error::{SslError, SslSessionClosed, StreamError, OpenSslErrors};
use x509::{X509StoreContext, X509FileType, X509};
pub mod error;
#[cfg(test)]
mod tests;
static mut VERIFY_IDX: c_int = -1;
fn init() {
static mut INIT: Once = ONCE_INIT;
unsafe {
INIT.call_once(|| {
ffi::init();
let verify_idx = ffi::SSL_CTX_get_ex_new_index(0, ptr::null(), None,
None, None);
assert!(verify_idx >= 0);
VERIFY_IDX = verify_idx;
});
}
}
#[allow(non_camel_case_types)]
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum SslMethod {
#[cfg(feature = "sslv2")]
Sslv2,
Sslv23,
Sslv3,
Tlsv1,
#[cfg(feature = "tlsv1_1")]
Tlsv1_1,
#[cfg(feature = "tlsv1_2")]
Tlsv1_2,
}
impl SslMethod {
unsafe fn to_raw(&self) -> *const ffi::SSL_METHOD {
match *self {
#[cfg(feature = "sslv2")]
SslMethod::Sslv2 => ffi::SSLv2_method(),
SslMethod::Sslv3 => ffi::SSLv3_method(),
SslMethod::Tlsv1 => ffi::TLSv1_method(),
SslMethod::Sslv23 => ffi::SSLv23_method(),
#[cfg(feature = "tlsv1_1")]
SslMethod::Tlsv1_1 => ffi::TLSv1_1_method(),
#[cfg(feature = "tlsv1_2")]
SslMethod::Tlsv1_2 => ffi::TLSv1_2_method()
}
}
}
#[derive(Copy, Clone, Debug)]
#[repr(i32)]
pub enum SslVerifyMode {
SslVerifyPeer = ffi::SSL_VERIFY_PEER,
SslVerifyNone = ffi::SSL_VERIFY_NONE
}
fn get_verify_data_idx<T>() -> c_int {
static mut VERIFY_DATA_IDX: c_int = -1;
static mut INIT: Once = ONCE_INIT;
extern fn free_data_box<T>(_parent: *mut c_void, ptr: *mut c_void,
_ad: *mut ffi::CRYPTO_EX_DATA, _idx: c_int,
_argl: c_long, _argp: *mut c_void) {
let _: Box<T> = unsafe { mem::transmute(ptr) };
}
unsafe {
INIT.call_once(|| {
let f: ffi::CRYPTO_EX_free = free_data_box::<T>;
let idx = ffi::SSL_CTX_get_ex_new_index(0, ptr::null(), None,
None, Some(f));
assert!(idx >= 0);
VERIFY_DATA_IDX = idx;
});
VERIFY_DATA_IDX
}
}
extern fn raw_verify(preverify_ok: c_int, x509_ctx: *mut ffi::X509_STORE_CTX)
-> c_int {
unsafe {
let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx();
let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx);
let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl);
let verify = ffi::SSL_CTX_get_ex_data(ssl_ctx, VERIFY_IDX);
let verify: Option<VerifyCallback> = mem::transmute(verify);
let ctx = X509StoreContext::new(x509_ctx);
match verify {
None => preverify_ok,
Some(verify) => verify(preverify_ok != 0, &ctx) as c_int
}
}
}
extern fn raw_verify_with_data<T>(preverify_ok: c_int,
x509_ctx: *mut ffi::X509_STORE_CTX) -> c_int {
unsafe {
let idx = ffi::SSL_get_ex_data_X509_STORE_CTX_idx();
let ssl = ffi::X509_STORE_CTX_get_ex_data(x509_ctx, idx);
let ssl_ctx = ffi::SSL_get_SSL_CTX(ssl);
let verify = ffi::SSL_CTX_get_ex_data(ssl_ctx, VERIFY_IDX);
let verify: Option<VerifyCallbackData<T>> = mem::transmute(verify);
let data = ffi::SSL_CTX_get_ex_data(ssl_ctx, get_verify_data_idx::<T>());
let data: Box<T> = mem::transmute(data);
let ctx = X509StoreContext::new(x509_ctx);
let res = match verify {
None => preverify_ok,
Some(verify) => verify(preverify_ok != 0, &ctx, &*data) as c_int
};
mem::forget(data);
res
}
}
pub type VerifyCallback = fn(preverify_ok: bool,
x509_ctx: &X509StoreContext) -> bool;
pub type VerifyCallbackData<T> = fn(preverify_ok: bool,
x509_ctx: &X509StoreContext,
data: &T) -> bool;
#[inline]
fn wrap_ssl_result(res: c_int) -> Option<SslError> {
if res == 0 {
Some(SslError::get())
} else {
None
}
}
pub struct SslContext {
ctx: ptr::Unique<ffi::SSL_CTX>
}
impl fmt::Debug for SslContext {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "SslContext")
}
}
impl Drop for SslContext {
fn drop(&mut self) {
unsafe { ffi::SSL_CTX_free(*self.ctx) }
}
}
impl SslContext {
pub fn new(method: SslMethod) -> Result<SslContext, SslError> {
init();
let ctx = unsafe { ffi::SSL_CTX_new(method.to_raw()) };
if ctx == ptr::null_mut() {
return Err(SslError::get());
}
let ctx = unsafe { SslContext { ctx: ptr::Unique::new(ctx) } };
Ok(ctx)
}
pub fn set_verify(&mut self, mode: SslVerifyMode,
verify: Option<VerifyCallback>) {
unsafe {
ffi::SSL_CTX_set_ex_data(*self.ctx, VERIFY_IDX,
mem::transmute(verify));
let f: extern fn(c_int, *mut ffi::X509_STORE_CTX) -> c_int =
raw_verify;
ffi::SSL_CTX_set_verify(*self.ctx, mode as c_int, Some(f));
}
}
pub fn set_verify_with_data<T>(&mut self, mode: SslVerifyMode,
verify: VerifyCallbackData<T>,
data: T) {
let data = Box::new(data);
unsafe {
ffi::SSL_CTX_set_ex_data(*self.ctx, VERIFY_IDX,
mem::transmute(Some(verify)));
ffi::SSL_CTX_set_ex_data(*self.ctx, get_verify_data_idx::<T>(),
mem::transmute(data));
let f: extern fn(c_int, *mut ffi::X509_STORE_CTX) -> c_int =
raw_verify_with_data::<T>;
ffi::SSL_CTX_set_verify(*self.ctx, mode as c_int, Some(f));
}
}
pub fn set_verify_depth(&mut self, depth: u32) {
unsafe {
ffi::SSL_CTX_set_verify_depth(*self.ctx, depth as c_int);
}
}
#[allow(non_snake_case)]
pub fn set_CA_file(&mut self, file: &Path) -> Option<SslError> {
let file = CString::new(file.as_os_str().to_str().expect("invalid utf8")).unwrap();
wrap_ssl_result(
unsafe {
ffi::SSL_CTX_load_verify_locations(*self.ctx, file.as_ptr(), ptr::null())
})
}
pub fn set_certificate_file(&mut self, file: &Path,
file_type: X509FileType) -> Option<SslError> {
let file = CString::new(file.as_os_str().to_str().expect("invalid utf8")).unwrap();
wrap_ssl_result(
unsafe {
ffi::SSL_CTX_use_certificate_file(*self.ctx, file.as_ptr(), file_type as c_int)
})
}
pub fn set_private_key_file(&mut self, file: &Path,
file_type: X509FileType) -> Option<SslError> {
let file = CString::new(file.as_os_str().to_str().expect("invalid utf8")).unwrap();
wrap_ssl_result(
unsafe {
ffi::SSL_CTX_use_PrivateKey_file(*self.ctx, file.as_ptr(), file_type as c_int)
})
}
pub fn set_cipher_list(&mut self, cipher_list: &str) -> Option<SslError> {
wrap_ssl_result(
unsafe {
let cipher_list = CString::new(cipher_list.as_bytes()).unwrap();
ffi::SSL_CTX_set_cipher_list(*self.ctx, cipher_list.as_ptr())
})
}
}
#[allow(dead_code)]
struct MemBioRef<'ssl> {
ssl: &'ssl Ssl,
bio: MemBio,
}
impl<'ssl> Deref for MemBioRef<'ssl> {
type Target = MemBio;
fn deref(&self) -> &MemBio {
&self.bio
}
}
impl<'ssl> DerefMut for MemBioRef<'ssl> {
fn deref_mut(&mut self) -> &mut MemBio {
&mut self.bio
}
}
pub struct Ssl {
ssl: ptr::Unique<ffi::SSL>
}
impl fmt::Debug for Ssl {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "Ssl")
}
}
impl Drop for Ssl {
fn drop(&mut self) {
unsafe { ffi::SSL_free(*self.ssl) }
}
}
impl Ssl {
pub fn new(ctx: &SslContext) -> Result<Ssl, SslError> {
let ssl = unsafe { ffi::SSL_new(*ctx.ctx) };
if ssl == ptr::null_mut() {
return Err(SslError::get());
}
let ssl = unsafe { Ssl { ssl: ptr::Unique::new(ssl) } };
let rbio = try!(MemBio::new());
let wbio = try!(MemBio::new());
unsafe { ffi::SSL_set_bio(*ssl.ssl, rbio.unwrap(), wbio.unwrap()) }
Ok(ssl)
}
fn get_rbio<'a>(&'a self) -> MemBioRef<'a> {
unsafe { self.wrap_bio(ffi::SSL_get_rbio(*self.ssl)) }
}
fn get_wbio<'a>(&'a self) -> MemBioRef<'a> {
unsafe { self.wrap_bio(ffi::SSL_get_wbio(*self.ssl)) }
}
fn wrap_bio<'a>(&'a self, bio: *mut ffi::BIO) -> MemBioRef<'a> {
assert!(bio != ptr::null_mut());
MemBioRef {
ssl: self,
bio: MemBio::borrowed(bio)
}
}
fn connect(&self) -> c_int {
unsafe { ffi::SSL_connect(*self.ssl) }
}
fn accept(&self) -> c_int {
unsafe { ffi::SSL_accept(*self.ssl) }
}
fn read(&self, buf: &mut [u8]) -> c_int {
let len = cmp::min(<c_int as Int>::max_value() as usize, buf.len()) as c_int;
unsafe { ffi::SSL_read(*self.ssl, buf.as_ptr() as *mut c_void, len) }
}
fn write(&self, buf: &[u8]) -> c_int {
let len = cmp::min(<c_int as Int>::max_value() as usize, buf.len()) as c_int;
unsafe { ffi::SSL_write(*self.ssl, buf.as_ptr() as *const c_void, len) }
}
fn get_error(&self, ret: c_int) -> LibSslError {
let err = unsafe { ffi::SSL_get_error(*self.ssl, ret) };
match FromPrimitive::from_int(err as isize) {
Some(err) => err,
None => unreachable!()
}
}
pub fn set_hostname(&self, hostname: &str) -> Result<(), SslError> {
let ret = unsafe {
let hostname = CString::new(hostname.as_bytes()).unwrap();
ffi::SSL_ctrl(*self.ssl, ffi::SSL_CTRL_SET_TLSEXT_HOSTNAME,
ffi::TLSEXT_NAMETYPE_host_name,
hostname.as_ptr() as *mut c_void)
};
if ret == 0 {
Err(SslError::get())
} else {
Ok(())
}
}
pub fn get_peer_certificate(&self) -> Option<X509> {
unsafe {
let ptr = ffi::SSL_get_peer_certificate(*self.ssl);
if ptr.is_null() {
None
} else {
Some(X509::new(ptr, true))
}
}
}
}
#[derive(FromPrimitive, Debug)]
#[repr(i32)]
enum LibSslError {
ErrorNone = ffi::SSL_ERROR_NONE,
ErrorSsl = ffi::SSL_ERROR_SSL,
ErrorWantRead = ffi::SSL_ERROR_WANT_READ,
ErrorWantWrite = ffi::SSL_ERROR_WANT_WRITE,
ErrorWantX509Lookup = ffi::SSL_ERROR_WANT_X509_LOOKUP,
ErrorSyscall = ffi::SSL_ERROR_SYSCALL,
ErrorZeroReturn = ffi::SSL_ERROR_ZERO_RETURN,
ErrorWantConnect = ffi::SSL_ERROR_WANT_CONNECT,
ErrorWantAccept = ffi::SSL_ERROR_WANT_ACCEPT,
}
#[derive(Clone)]
pub struct SslStream<S> {
stream: S,
ssl: Arc<Ssl>,
buf: Vec<u8>
}
impl SslStream<net::TcpStream> {
pub fn try_clone(&self) -> io::Result<SslStream<net::TcpStream>> {
Ok(SslStream {
stream: try!(self.stream.try_clone()),
ssl: self.ssl.clone(),
buf: self.buf.clone(),
})
}
}
impl<S> fmt::Debug for SslStream<S> where S: fmt::Debug {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "SslStream {{ stream: {:?}, ssl: {:?} }}", self.stream, self.ssl)
}
}
impl<S: Read+Write> SslStream<S> {
fn new_base(ssl:Ssl, stream: S) -> SslStream<S> {
SslStream {
stream: stream,
ssl: Arc::new(ssl),
buf: {
const CAP: usize = 16 * 1024;
let mut v = Vec::with_capacity(CAP);
unsafe { v.set_len(CAP); }
v
}
}
}
pub fn new_server_from(ssl: Ssl, stream: S) -> Result<SslStream<S>, SslError> {
let mut ssl = SslStream::new_base(ssl, stream);
ssl.in_retry_wrapper(|ssl| { ssl.accept() }).and(Ok(ssl))
}
pub fn new_from(ssl: Ssl, stream: S) -> Result<SslStream<S>, SslError> {
let mut ssl = SslStream::new_base(ssl, stream);
ssl.in_retry_wrapper(|ssl| { ssl.connect() }).and(Ok(ssl))
}
pub fn new(ctx: &SslContext, stream: S) -> Result<SslStream<S>, SslError> {
let ssl = try!(Ssl::new(ctx));
SslStream::new_from(ssl, stream)
}
pub fn new_server(ctx: &SslContext, stream: S) -> Result<SslStream<S>, SslError> {
let ssl = try!(Ssl::new(ctx));
SslStream::new_server_from(ssl, stream)
}
#[deprecated="use get_mut instead"]
pub fn get_inner(&mut self) -> &mut S {
self.get_mut()
}
pub fn get_ref(&self) -> &S {
&self.stream
}
pub fn get_mut(&mut self) -> &mut S {
&mut self.stream
}
fn in_retry_wrapper<F>(&mut self, mut blk: F)
-> Result<c_int, SslError> where F: FnMut(&Ssl) -> c_int {
loop {
let ret = blk(&*self.ssl);
if ret > 0 {
return Ok(ret);
}
let e = self.ssl.get_error(ret);
match e {
LibSslError::ErrorWantRead => {
try_ssl_stream!(self.flush());
let len = try_ssl_stream!(self.stream.read(self.buf.as_mut_slice()));
if len == 0 {
return Ok(0);
}
try_ssl_stream!(self.ssl.get_rbio().write_all(&self.buf[..len]));
}
LibSslError::ErrorWantWrite => { try_ssl_stream!(self.flush()) }
LibSslError::ErrorZeroReturn => return Err(SslSessionClosed),
LibSslError::ErrorSsl => return Err(SslError::get()),
err => panic!("unexpected error {:?}", err),
}
}
}
fn write_through(&mut self) -> io::Result<()> {
io::copy(&mut *self.ssl.get_wbio(), &mut self.stream).map(|_| ())
}
pub fn get_compression(&self) -> Option<String> {
let ptr = unsafe { ffi::SSL_get_current_compression(*self.ssl.ssl) };
if ptr == ptr::null() {
return None;
}
let meth = unsafe { ffi::SSL_COMP_get_name(ptr) };
let s = unsafe {
String::from_utf8(CStr::from_ptr(meth).to_bytes().to_vec()).unwrap()
};
Some(s)
}
}
impl<S: Read+Write> Read for SslStream<S> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match self.in_retry_wrapper(|ssl| { ssl.read(buf) }) {
Ok(len) => Ok(len as usize),
Err(SslSessionClosed) => Ok(0),
Err(StreamError(e)) => Err(e),
Err(e @ OpenSslErrors(_)) => {
Err(io::Error::new(io::ErrorKind::Other, "OpenSSL error", Some(format!("{}", e))))
}
}
}
}
impl<S: Read+Write> Write for SslStream<S> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match self.in_retry_wrapper(|ssl| ssl.write(buf)) {
Ok(len) => Ok(len as usize),
Err(SslSessionClosed) => Ok(0),
Err(StreamError(e)) => return Err(e),
Err(e @ OpenSslErrors(_)) => {
Err(io::Error::new(io::ErrorKind::Other, "OpenSSL error", Some(format!("{}", e))))
}
}
}
fn flush(&mut self) -> io::Result<()> {
try!(self.write_through());
self.stream.flush()
}
}
#[derive(Debug)]
pub enum MaybeSslStream<S> where S: Read+Write {
Ssl(SslStream<S>),
Normal(S),
}
impl<S> Read for MaybeSslStream<S> where S: Read+Write {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
MaybeSslStream::Ssl(ref mut s) => s.read(buf),
MaybeSslStream::Normal(ref mut s) => s.read(buf),
}
}
}
impl<S> Write for MaybeSslStream<S> where S: Read+Write {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
match *self {
MaybeSslStream::Ssl(ref mut s) => s.write(buf),
MaybeSslStream::Normal(ref mut s) => s.write(buf),
}
}
fn flush(&mut self) -> io::Result<()> {
match *self {
MaybeSslStream::Ssl(ref mut s) => s.flush(),
MaybeSslStream::Normal(ref mut s) => s.flush(),
}
}
}
impl<S> MaybeSslStream<S> where S: Read+Write {
pub fn get_ref(&self) -> &S {
match *self {
MaybeSslStream::Ssl(ref s) => s.get_ref(),
MaybeSslStream::Normal(ref s) => s,
}
}
pub fn get_mut(&mut self) -> &mut S {
match *self {
MaybeSslStream::Ssl(ref mut s) => s.get_mut(),
MaybeSslStream::Normal(ref mut s) => s,
}
}
}