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
use libc::{c_int, c_void, c_long};
use std::ffi::{CString, c_str_to_bytes};
use std::io::{IoResult, IoError, EndOfFile, Stream, Reader, Writer};
use std::mem;
use std::num::FromPrimitive;
use std::ptr;
use std::sync::{Once, ONCE_INIT, Arc};
use bio::{MemBio};
use ffi;
use ssl::error::{SslError, SslSessionClosed, StreamError};
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;
});
}
}
#[derive(Show, Hash, PartialEq, Eq)]
#[allow(non_camel_case_types)]
#[derive(Copy)]
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)]
#[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 Drop for SslContext {
fn drop(&mut self) {
unsafe { ffi::SSL_CTX_free(self.ctx.0) }
}
}
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());
}
Ok(SslContext { ctx: ptr::Unique(ctx) })
}
pub fn set_verify(&mut self, mode: SslVerifyMode,
verify: Option<VerifyCallback>) {
unsafe {
ffi::SSL_CTX_set_ex_data(self.ctx.0, 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.0, 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.0, VERIFY_IDX,
mem::transmute(Some(verify)));
ffi::SSL_CTX_set_ex_data(self.ctx.0, 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.0, mode as c_int, Some(f));
}
}
pub fn set_verify_depth(&mut self, depth: u32) {
unsafe {
ffi::SSL_CTX_set_verify_depth(self.ctx.0, depth as c_int);
}
}
#[allow(non_snake_case)]
pub fn set_CA_file(&mut self, file: &Path) -> Option<SslError> {
wrap_ssl_result(
unsafe {
let file = CString::from_slice(file.as_vec());
ffi::SSL_CTX_load_verify_locations(self.ctx.0, file.as_ptr(), ptr::null())
})
}
pub fn set_certificate_file(&mut self, file: &Path,
file_type: X509FileType) -> Option<SslError> {
wrap_ssl_result(
unsafe {
let file = CString::from_slice(file.as_vec());
ffi::SSL_CTX_use_certificate_file(self.ctx.0, file.as_ptr(), file_type as c_int)
})
}
pub fn set_private_key_file(&mut self, file: &Path,
file_type: X509FileType) -> Option<SslError> {
wrap_ssl_result(
unsafe {
let file = CString::from_slice(file.as_vec());
ffi::SSL_CTX_use_PrivateKey_file(self.ctx.0, 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::from_slice(cipher_list.as_bytes());
ffi::SSL_CTX_set_cipher_list(self.ctx.0, cipher_list.as_ptr())
})
}
}
#[allow(dead_code)]
struct MemBioRef<'ssl> {
ssl: &'ssl Ssl,
bio: MemBio,
}
impl<'ssl> MemBioRef<'ssl> {
fn read(&mut self, buf: &mut [u8]) -> Option<usize> {
(&mut self.bio as &mut Reader).read(buf).ok()
}
fn write(&mut self, buf: &[u8]) {
let _ = (&mut self.bio as &mut Writer).write(buf);
}
}
pub struct Ssl {
ssl: ptr::Unique<ffi::SSL>
}
impl Drop for Ssl {
fn drop(&mut self) {
unsafe { ffi::SSL_free(self.ssl.0) }
}
}
impl Ssl {
pub fn new(ctx: &SslContext) -> Result<Ssl, SslError> {
let ssl = unsafe { ffi::SSL_new(ctx.ctx.0) };
if ssl == ptr::null_mut() {
return Err(SslError::get());
}
let ssl = Ssl { ssl: ptr::Unique(ssl) };
let rbio = try!(MemBio::new());
let wbio = try!(MemBio::new());
unsafe { ffi::SSL_set_bio(ssl.ssl.0, rbio.unwrap(), wbio.unwrap()) }
Ok(ssl)
}
fn get_rbio<'a>(&'a self) -> MemBioRef<'a> {
unsafe { self.wrap_bio(ffi::SSL_get_rbio(self.ssl.0)) }
}
fn get_wbio<'a>(&'a self) -> MemBioRef<'a> {
unsafe { self.wrap_bio(ffi::SSL_get_wbio(self.ssl.0)) }
}
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.0) }
}
fn accept(&self) -> c_int {
unsafe { ffi::SSL_accept(self.ssl.0) }
}
fn read(&self, buf: &mut [u8]) -> c_int {
unsafe { ffi::SSL_read(self.ssl.0, buf.as_ptr() as *mut c_void,
buf.len() as c_int) }
}
fn write(&self, buf: &[u8]) -> c_int {
unsafe { ffi::SSL_write(self.ssl.0, buf.as_ptr() as *const c_void,
buf.len() as c_int) }
}
fn get_error(&self, ret: c_int) -> LibSslError {
let err = unsafe { ffi::SSL_get_error(self.ssl.0, 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::from_slice(hostname.as_bytes());
ffi::SSL_ctrl(self.ssl.0, 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.0);
if ptr.is_null() {
None
} else {
Some(X509::new(ptr, true))
}
}
}
}
#[derive(FromPrimitive, Show)]
#[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<S: Stream> 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);
}
match self.ssl.get_error(ret) {
LibSslError::ErrorWantRead => {
try_ssl_stream!(self.flush());
let len = try_ssl_stream!(self.stream.read(self.buf.as_mut_slice()));
self.ssl.get_rbio().write(self.buf.slice_to(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) -> IoResult<()> {
loop {
match self.ssl.get_wbio().read(self.buf.as_mut_slice()) {
Some(len) => try!(self.stream.write(self.buf.slice_to(len))),
None => break
};
}
Ok(())
}
pub fn get_compression(&self) -> Option<String> {
let ptr = unsafe { ffi::SSL_get_current_compression(self.ssl.ssl.0) };
if ptr == ptr::null() {
return None;
}
let meth = unsafe { ffi::SSL_COMP_get_name(ptr) };
let s = unsafe {
String::from_utf8(c_str_to_bytes(&meth).to_vec()).unwrap()
};
Some(s)
}
}
impl<S: Stream> Reader for SslStream<S> {
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
match self.in_retry_wrapper(|ssl| { ssl.read(buf) }) {
Ok(len) => Ok(len as usize),
Err(SslSessionClosed) =>
Err(IoError {
kind: EndOfFile,
desc: "SSL session closed",
detail: None
}),
Err(StreamError(e)) => Err(e),
_ => unreachable!()
}
}
}
impl<S: Stream> Writer for SslStream<S> {
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
let mut start = 0;
while start < buf.len() {
let ret = self.in_retry_wrapper(|ssl| {
ssl.write(buf.split_at(start).1)
});
match ret {
Ok(len) => start += len as usize,
_ => unreachable!()
}
try!(self.write_through());
}
Ok(())
}
fn flush(&mut self) -> IoResult<()> {
try!(self.write_through());
self.stream.flush()
}
}
pub enum MaybeSslStream<S> where S: Stream {
Ssl(SslStream<S>),
Normal(S),
}
impl<S> Reader for MaybeSslStream<S> where S: Stream {
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
match *self {
MaybeSslStream::Ssl(ref mut s) => s.read(buf),
MaybeSslStream::Normal(ref mut s) => s.read(buf),
}
}
}
impl<S> Writer for MaybeSslStream<S> where S: Stream{
fn write(&mut self, buf: &[u8]) -> IoResult<()> {
match *self {
MaybeSslStream::Ssl(ref mut s) => s.write(buf),
MaybeSslStream::Normal(ref mut s) => s.write(buf),
}
}
fn flush(&mut self) -> IoResult<()> {
match *self {
MaybeSslStream::Ssl(ref mut s) => s.flush(),
MaybeSslStream::Normal(ref mut s) => s.flush(),
}
}
}
impl<S> MaybeSslStream<S> where S: Stream {
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,
}
}
}