-
Notifications
You must be signed in to change notification settings - Fork 259
/
lib.rs
473 lines (406 loc) · 13.6 KB
/
lib.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
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License..
#![crate_name = "server"]
#![crate_type = "staticlib"]
#![allow(dead_code)]
#![cfg_attr(not(target_env = "sgx"), no_std)]
#![cfg_attr(target_env = "sgx", feature(rustc_private))]
#[cfg(not(target_env = "sgx"))]
#[macro_use]
extern crate sgx_tstd as std;
#[macro_use]
extern crate log;
use std::untrusted::fs;
use std::vec::Vec;
use std::io::{self, Write, Read, BufReader};
use std::sync::Arc;
use std::collections::HashMap;
use std::net;
use std::net::Shutdown;
extern crate webpki;
extern crate rustls;
extern crate mio;
extern crate sgx_types;
use rustls::{Session, NoClientAuth};
use mio::net::{TcpListener, TcpStream};
use sgx_types::uint8_t;
// Token for our listening socket.
const LISTENER: mio::Token = mio::Token(0);
// Which mode the server operates in.
#[derive(Clone)]
enum ServerMode {
/// Write back received bytes
Echo,
/// Do one read, then write a bodged HTTP response and
/// cleanly close the connection.
Http,
/// Forward traffic to/from given port on localhost.
Forward(u16),
}
/// This binds together a TCP listening socket, some outstanding
/// connections, and a TLS server configuration.
struct TlsServer {
server: TcpListener,
connections: HashMap<mio::Token, Connection>,
next_id: usize,
tls_config: Arc<rustls::ServerConfig>,
mode: ServerMode,
}
impl TlsServer {
fn new(server: TcpListener, mode: ServerMode, cfg: Arc<rustls::ServerConfig>) -> TlsServer {
TlsServer {
server,
connections: HashMap::new(),
next_id: 2,
tls_config: cfg,
mode,
}
}
fn accept(&mut self, poll: &mut mio::Poll) -> bool {
match self.server.accept() {
Ok((socket, addr)) => {
debug!("Accepting new connection from {:?}", addr);
let tls_session = rustls::ServerSession::new(&self.tls_config);
let mode = self.mode.clone();
let token = mio::Token(self.next_id);
self.next_id += 1;
self.connections.insert(token, Connection::new(socket, token, mode, tls_session));
self.connections[&token].register(poll);
true
}
Err(e) => {
println!("encountered error while accepting connection; err={:?}", e);
false
}
}
}
fn conn_event(&mut self, poll: &mut mio::Poll, event: &mio::event::Event) {
let token = event.token();
if self.connections.contains_key(&token) {
self.connections
.get_mut(&token)
.unwrap()
.ready(poll, event);
if self.connections[&token].is_closed() {
self.connections.remove(&token);
}
}
}
}
/// This is a connection which has been accepted by the server,
/// and is currently being served.
///
/// It has a TCP-level stream, a TLS-level session, and some
/// other state/metadata.
struct Connection {
socket: TcpStream,
token: mio::Token,
closing: bool,
closed: bool,
mode: ServerMode,
tls_session: rustls::ServerSession,
back: Option<TcpStream>,
sent_http_response: bool,
}
/// Open a plaintext TCP-level connection for forwarded connections.
fn open_back(mode: &ServerMode) -> Option<TcpStream> {
match *mode {
ServerMode::Forward(ref port) => {
let addr = net::SocketAddrV4::new(net::Ipv4Addr::new(127, 0, 0, 1), *port);
let conn = TcpStream::connect(&net::SocketAddr::V4(addr)).unwrap();
Some(conn)
}
_ => None,
}
}
/// This used to be conveniently exposed by mio: map EWOULDBLOCK
/// errors to something less-errory.
fn try_read(r: io::Result<usize>) -> io::Result<Option<usize>> {
match r {
Ok(len) => Ok(Some(len)),
Err(e) => {
if e.kind() == io::ErrorKind::WouldBlock {
Ok(None)
} else {
Err(e)
}
}
}
}
impl Connection {
fn new(socket: TcpStream,
token: mio::Token,
mode: ServerMode,
tls_session: rustls::ServerSession)
-> Connection {
let back = open_back(&mode);
Connection {
socket,
token,
closing: false,
closed: false,
mode,
tls_session,
back,
sent_http_response: false,
}
}
/// We're a connection, and we have something to do.
fn ready(&mut self, poll: &mut mio::Poll, ev: &mio::event::Event) {
// If we're readable: read some TLS. Then
// see if that yielded new plaintext. Then
// see if the backend is readable too.
if ev.readiness().is_readable() {
self.do_tls_read();
self.try_plain_read();
self.try_back_read();
}
if ev.readiness().is_writable() {
self.do_tls_write();
}
if self.closing {
let _ = self.socket.shutdown(Shutdown::Both);
self.close_back();
self.closed = true;
} else {
self.reregister(poll);
}
}
/// Close the backend connection for forwarded sessions.
fn close_back(&mut self) {
if self.back.is_some() {
let back = self.back.as_mut().unwrap();
back.shutdown(Shutdown::Both).unwrap();
}
self.back = None;
}
fn do_tls_read(&mut self) {
// Read some TLS data.
let rc = self.tls_session.read_tls(&mut self.socket);
if rc.is_err() {
let err = rc.unwrap_err();
if let io::ErrorKind::WouldBlock = err.kind() {
return;
}
error!("read error {:?}", err);
self.closing = true;
return;
}
if rc.unwrap() == 0 {
debug!("eof");
self.closing = true;
return;
}
// Process newly-received TLS messages.
let processed = self.tls_session.process_new_packets();
if processed.is_err() {
error!("cannot process packet: {:?}", processed);
self.closing = true;
return;
}
}
fn try_plain_read(&mut self) {
// Read and process all available plaintext.
let mut buf = Vec::new();
let rc = self.tls_session.read_to_end(&mut buf);
if rc.is_err() {
error!("plaintext read failed: {:?}", rc);
self.closing = true;
return;
}
if !buf.is_empty() {
debug!("plaintext read {:?}", buf.len());
self.incoming_plaintext(&buf);
}
}
fn try_back_read(&mut self) {
if self.back.is_none() {
return;
}
// Try a non-blocking read.
let mut buf = [0u8; 1024];
let back = self.back.as_mut().unwrap();
let rc = try_read(back.read(&mut buf));
if rc.is_err() {
error!("backend read failed: {:?}", rc);
self.closing = true;
return;
}
let maybe_len = rc.unwrap();
// If we have a successful but empty read, that's an EOF.
// Otherwise, we shove the data into the TLS session.
match maybe_len {
Some(len) if len == 0 => {
debug!("back eof");
self.closing = true;
}
Some(len) => {
self.tls_session.write_all(&buf[..len]).unwrap();
}
None => {}
};
}
/// Process some amount of received plaintext.
fn incoming_plaintext(&mut self, buf: &[u8]) {
match self.mode {
ServerMode::Echo => {
self.tls_session.write_all(buf).unwrap();
}
ServerMode::Http => {
self.send_http_response_once();
}
ServerMode::Forward(_) => {
self.back.as_mut().unwrap().write_all(buf).unwrap();
}
}
}
fn send_http_response_once(&mut self) {
let response = b"HTTP/1.0 200 OK\r\nConnection: close\r\n\r\nHello world from server\r\n";
if !self.sent_http_response {
self.tls_session
.write_all(response)
.unwrap();
self.sent_http_response = true;
self.tls_session.send_close_notify();
println!("Returned to client successfully!");
}
}
fn do_tls_write(&mut self) {
let rc = self.tls_session.write_tls(&mut self.socket);
if rc.is_err() {
error!("write failed {:?}", rc);
self.closing = true;
return;
}
}
fn register(&self, poll: &mut mio::Poll) {
poll.register(&self.socket,
self.token,
self.event_set(),
mio::PollOpt::level() | mio::PollOpt::oneshot())
.unwrap();
if self.back.is_some() {
poll.register(self.back.as_ref().unwrap(),
self.token,
mio::Ready::readable(),
mio::PollOpt::level() | mio::PollOpt::oneshot())
.unwrap();
}
}
fn reregister(&self, poll: &mut mio::Poll) {
poll.reregister(&self.socket,
self.token,
self.event_set(),
mio::PollOpt::level() | mio::PollOpt::oneshot())
.unwrap();
if self.back.is_some() {
poll.reregister(self.back.as_ref().unwrap(),
self.token,
mio::Ready::readable(),
mio::PollOpt::level() | mio::PollOpt::oneshot())
.unwrap();
}
}
/// What IO events we're currently waiting for,
/// based on wants_read/wants_write.
fn event_set(&self) -> mio::Ready {
let rd = self.tls_session.wants_read();
let wr = self.tls_session.wants_write();
if rd && wr {
mio::Ready::readable() | mio::Ready::writable()
} else if wr {
mio::Ready::writable()
} else {
mio::Ready::readable()
}
}
fn is_closed(&self) -> bool {
self.closed
}
}
fn load_certs(filename: &str) -> Vec<rustls::Certificate> {
let certfile = fs::File::open(filename).expect("cannot open certificate file");
let mut reader = BufReader::new(certfile);
rustls::internal::pemfile::certs(&mut reader).unwrap()
}
fn load_private_key(filename: &str) -> rustls::PrivateKey {
let rsa_keys = {
let keyfile = fs::File::open(filename)
.expect("cannot open private key file");
let mut reader = BufReader::new(keyfile);
rustls::internal::pemfile::rsa_private_keys(&mut reader)
.expect("file contains invalid rsa private key")
};
let pkcs8_keys = {
let keyfile = fs::File::open(filename)
.expect("cannot open private key file");
let mut reader = BufReader::new(keyfile);
rustls::internal::pemfile::pkcs8_private_keys(&mut reader)
.expect("file contains invalid pkcs8 private key (encrypted keys not supported)")
};
// prefer to load pkcs8 keys
if !pkcs8_keys.is_empty() {
pkcs8_keys[0].clone()
} else {
assert!(!rsa_keys.is_empty());
rsa_keys[0].clone()
}
}
fn make_config(cert: &str, key: &str) -> Arc<rustls::ServerConfig> {
let mut config = rustls::ServerConfig::new(NoClientAuth::new());
let certs = load_certs(cert);
let privkey = load_private_key(key);
config.set_single_cert_with_ocsp_and_sct(certs, privkey, vec![], vec![]).unwrap();
Arc::new(config)
}
#[no_mangle]
pub extern "C" fn run_server(max_conn: uint8_t) {
let addr: net::SocketAddr = "0.0.0.0:8443".parse().unwrap();
let cert = "end.fullchain";
let key = "end.rsa";
//let mode = ServerMode::Echo;
let mode = ServerMode::Http;
let config = make_config(cert, key);
let listener = net::TcpListener::bind(&addr).expect("cannot listen on port");
let listener = TcpListener::from_std(listener).unwrap();
let mut poll = mio::Poll::new()
.unwrap();
poll.register(&listener,
LISTENER,
mio::Ready::readable(),
mio::PollOpt::level())
.unwrap();
let mut tlsserv = TlsServer::new(listener, mode, config);
let mut events = mio::Events::with_capacity(256);
'outer: loop {
poll.poll(&mut events, None)
.unwrap();
for event in events.iter() {
match event.token() {
LISTENER => {
if tlsserv.connections.len() as u8 == max_conn {
continue;
}
if !tlsserv.accept(&mut poll) {
break 'outer;
}
}
_ => tlsserv.conn_event(&mut poll, &event)
}
}
}
}