-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.go
478 lines (396 loc) · 11.1 KB
/
server.go
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
package nativedtls
/*
#cgo LDFLAGS: ${SRCDIR}/openssl/libssl.a ${SRCDIR}/openssl/libcrypto.a -ldl
#cgo CFLAGS: -g -Wno-deprecated -I${SRCDIR}/openssl/include
#include <stdlib.h>
#include <string.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/bio.h>
extern int go_session_bio_write(BIO* bio, char* buf, int num);
extern int go_session_bio_read(BIO* bio, char* buf, int num);
extern int go_session_bio_free(BIO* bio);
extern unsigned int go_server_psk_callback(SSL *ssl, char *identity, char *psk, unsigned int max_psk_len);
extern int generate_cookie_callback(SSL* ssl, unsigned char* cookie, unsigned int *cookie_len);
extern int verify_cookie_callback(SSL* ssl, unsigned char* cookie, unsigned int cookie_len);
extern int get_errno(void);
extern void set_errno(int e);
static long go_session_bio_ctrl(BIO *bp,int cmd,long larg,void *parg) {
//always return operation not supported
//http://www.openssl.org/docs/crypto/BIO_ctrl.html
//printf("go_bio_ctrl %d\n", cmd);
return 1;
}
static int write_wrapper(BIO* bio,const char* data, int n) {
return go_session_bio_write(bio,data,n);
}
static int go_session_bio_create( BIO *b ) {
BIO_set_init(b,1);
//BIO_set_num(b,-1);
//BIO_set_ptr(b,NULL);
BIO_set_flags(b, BIO_FLAGS_READ | BIO_FLAGS_WRITE);
printf("bio created\n");
return 1;
}
// a BIO for a client conencted to our server
static BIO_METHOD* go_session_bio_method;
static int init_session_bio_method() {
go_session_bio_method = BIO_meth_new(BIO_TYPE_SOURCE_SINK,"go session dtls");
BIO_meth_set_write(go_session_bio_method,write_wrapper);
BIO_meth_set_read(go_session_bio_method,go_session_bio_read);
BIO_meth_set_ctrl(go_session_bio_method,go_session_bio_ctrl);
BIO_meth_set_create(go_session_bio_method,go_session_bio_create);
BIO_meth_set_destroy(go_session_bio_method,go_session_bio_free);
}
//{
// BIO_TYPE_SOURCE_SINK,
// "go session dtls",
// (int (*)(BIO *, const char *, int))go_session_bio_write,
// go_session_bio_read,
// NULL,
// NULL,
// go_session_bio_ctrl, // ctrl
// go_session_bio_create, // new
// go_session_bio_free // delete
//};
static void init_server_ctx(SSL_CTX *ctx) {
SSL_CTX_set_min_proto_version(ctx, 0xFEFD); // 1.2
SSL_CTX_set_max_proto_version(ctx, 0xFEFD); // 1.2
SSL_CTX_set_read_ahead(ctx, 1);
SSL_CTX_set_cookie_generate_cb(ctx, &generate_cookie_callback);
SSL_CTX_set_cookie_verify_cb(ctx, &verify_cookie_callback);
}
static BIO_METHOD* BIO_go_session() {
return go_session_bio_method;
}
static void setGoSessionId(BIO* bio, unsigned int clientId) {
unsigned int * pId = malloc(sizeof(unsigned int));
*pId = clientId;
BIO_set_data(bio,pId);
}
static unsigned int server_psk_callback(SSL *ssl, const char *identity, unsigned char *psk, unsigned int max_psk_len) {
return go_server_psk_callback(ssl,identity,(char*)psk,max_psk_len);
}
static void set_psk_callback(SSL *ssl) {
SSL_set_psk_server_callback(ssl,&server_psk_callback);
}
static void set_cookie_option(SSL *ssl) {
SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);
}
*/
import "C"
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"errors"
"fmt"
"io"
"math/rand"
"net"
"sync/atomic"
"syscall"
"time"
"unsafe"
)
// init server BIO method
func server_bio_method_init() {
C.init_session_bio_method()
}
// Create a new DTLS context for servers.
// DTLSContext is were you configure chipersuite and secrets
func NewServerDTLSContext() *DTLSCtx {
ctx := C.SSL_CTX_new(C.DTLSv1_2_server_method())
if ctx == nil {
panic("error creating SSL context")
}
C.init_server_ctx(ctx)
self := DTLSCtx{ctx}
return &self
}
type DTLSServer struct {
started bool
ctx *C.SSL_CTX
sessions map[string]*session
conn net.PacketConn // socket for receiving/writting data
pskCallback func(pskId string) []byte
createdSession chan struct {
sess *session
err error
}
cookieSecret []byte // the secret used for cookie verification
}
// DTLS session between a client and the server
type session struct {
closed bool
addr net.Addr
ssl *C.SSL
bio *C.BIO
server *DTLSServer
rcvd chan []byte // where we push raw byte comming from the server socket
}
func NewDTLSServer(ctx *DTLSCtx, conn net.PacketConn) *DTLSServer {
secret := make([]byte, 32)
if n, err := rand.Read(secret); n != 32 || err != nil {
panic(err)
}
server := DTLSServer{false, ctx.ctx, make(map[string]*session), conn, nil, make(chan struct {
sess *session
err error
}), secret}
return &server
}
func (s *DTLSServer) SetPskCallback(callback func(string) []byte) {
s.pskCallback = callback
}
var sessions = make(map[int32]*session)
var nextSessionId int32 = 0
func (s *DTLSServer) newSession(addr net.Addr) *session {
ssl := C.SSL_new(s.ctx)
id := atomic.AddInt32(&nextSessionId, 1)
// add the PSK callback
if s.pskCallback != nil {
C.set_psk_callback(ssl)
}
// dump ciphers
//index := C.int(0)
// for {
// next := C.SSL_get_cipher_list(ssl, index)
// if next != nil {
// fmt.Println("chiper", index, C.GoString(next))
// index = index + 1
// } else {
// break
// }
// }
// create the BIO
bio := C.BIO_new(C.BIO_go_session())
if bio == nil {
return nil
}
C.SSL_set_bio(ssl, bio, bio)
sess := session{addr: addr, ssl: ssl, bio: bio, server: s, rcvd: make(chan []byte)}
sessions[id] = &sess
// the ID is used as link between the Go and C lang since sharing Go pointers is
// so the C is going to own the pointer to the id value
C.setGoSessionId(bio, C.uint(id))
// this session should start by doing a server handshake
C.set_cookie_option(ssl)
C.SSL_set_accept_state(ssl)
C.DTLSv1_listen
return &sess
}
// Wait for new DTLS connection and provide a unciphered net.Conn
// this method should be called in a loop, it will be in charge of reading the UDP server socket
// and feeding the different sesssions
func (s *DTLSServer) Accept() (net.Conn, error) {
if !s.started {
go s.loop()
}
// wait for sessions
res := <-s.createdSession
return res.sess, res.err
}
// server loop, read from socket and send event to the correspoing channels
func (s *DTLSServer) loop() {
buffer := make([]byte, 1500)
for {
n, addr, err := s.conn.ReadFrom(buffer)
if err != nil {
s.createdSession <- struct {
sess *session
err error
}{sess: nil, err: err}
}
tmpBuff := buffer[:n]
// do we have a session for this address?
sess := s.sessions[addr.String()]
if sess == nil {
// create a new session, start it feed it and return it
sess = s.newSession(addr)
s.sessions[addr.String()] = sess
s.createdSession <- struct {
sess *session
err error
}{sess: sess, err: nil}
}
// push the data to the session and wait for more data
sess.rcvd <- tmpBuff
}
}
func (s *session) Close() error {
if s.closed {
return nil
}
s.closed = true
defer func() {
C.SSL_free(s.ssl)
//TODO??C.SSL_free(s.bio)
}()
ret := C.SSL_shutdown(s.ssl)
if int(ret) == 0 {
ret = C.SSL_shutdown(s.ssl)
if int(ret) != 1 {
return s.getError(ret)
}
}
return nil
}
func (s *session) LocalAddr() net.Addr {
return nil
}
func (s *session) RemoteAddr() net.Addr {
return s.addr
}
func (s *session) Read(b []byte) (n int, err error) {
// TODO test if closed?
length := len(b)
ret := C.SSL_read(s.ssl, unsafe.Pointer(&b[0]), C.int(length))
fmt.Println("SSL READ done")
if err := s.getError(ret); err != nil {
return 0, err
}
// if there's no error, but a return value of 0
// let's say it's an EOF
if ret == 0 {
return 0, io.EOF
}
return int(ret), nil
}
func (s *session) Write(b []byte) (int, error) {
// TODO test is connected ?
length := len(b)
ret := C.SSL_write(s.ssl, unsafe.Pointer(&b[0]), C.int(length))
if err := s.getError(ret); err != nil {
return 0, err
}
return int(ret), nil
}
func (s *session) getError(ret C.int) error {
err := C.SSL_get_error(s.ssl, ret)
switch err {
case C.SSL_ERROR_NONE:
return nil
case C.SSL_ERROR_ZERO_RETURN:
return io.EOF
case C.SSL_ERROR_SYSCALL:
if int(C.ERR_peek_error()) != 0 {
return syscall.Errno(C.get_errno())
}
default:
msg := ""
for {
errCode := C.ERR_get_error()
if errCode == 0 {
break
}
msg += getErrorString(errCode)
}
C.ERR_clear_error()
return errors.New(msg)
}
return nil
}
func (s *session) SetDeadline(t time.Time) error {
return nil
}
func (s *session) SetReadDeadline(t time.Time) error {
return nil
}
func (s *session) SetWriteDeadline(t time.Time) error {
return nil
}
//export go_session_bio_read
func go_session_bio_read(bio *C.BIO, buf *C.char, num C.int) C.int {
sess := sessions[*(*int32)(C.BIO_get_data(bio))]
socketData := <-sess.rcvd
data := goSliceFromCString(buf, int(num))
if data == nil {
return 0
}
wrote := copy(data, socketData)
return C.int(wrote)
}
//export go_session_bio_write
func go_session_bio_write(bio *C.BIO, buf *C.char, num C.int) C.int {
session := sessions[*(*int32)(C.BIO_get_data(bio))]
data := goSliceFromCString(buf, int(num))
n, err := session.server.conn.WriteTo(data, session.addr)
if err != nil && err != io.EOF {
//We expect either a syscall error
//or a netOp error wrapping a syscall error
TESTERR:
switch err.(type) {
case syscall.Errno:
C.set_errno(C.int(err.(syscall.Errno)))
case *net.OpError:
err = err.(*net.OpError).Err
break TESTERR
}
return C.int(-1)
}
return C.int(n)
}
//export go_session_bio_free
func go_session_bio_free(bio *C.BIO) C.int {
sess := sessions[*(*int32)(C.BIO_get_data(bio))]
sess.Close()
// some flags magic
if C.int(C.BIO_get_shutdown(bio)) != 0 {
C.BIO_set_data(bio, nil)
C.BIO_set_flags(bio, 0)
C.BIO_set_init(bio, 0)
}
return C.int(1)
}
//export go_server_psk_callback
func go_server_psk_callback(ssl *C.SSL, identity *C.char, psk *C.char, max_psk_len C.uint) C.uint {
bio := C.SSL_get_rbio(ssl)
sess := sessions[*(*int32)(C.BIO_get_data(bio))]
if sess.server.pskCallback == nil {
return 0
}
// TODO test nil ?
goPskID := C.GoString(identity)
serverPsk := sess.server.pskCallback(goPskID)
if serverPsk == nil {
return 0
}
if len(serverPsk) >= int(max_psk_len) {
return 0
}
targetPsk := goSliceFromCString(psk, int(max_psk_len))
return C.uint(copy(targetPsk, serverPsk))
}
//export generate_cookie_callback
func generate_cookie_callback(ssl *C.SSL, cookie *C.uchar, cookie_len *C.uint) C.int {
bio := C.SSL_get_rbio(ssl)
sess := sessions[*(*int32)(C.BIO_get_data(bio))]
mac := hmac.New(sha256.New, sess.server.cookieSecret)
mac.Write([]byte(sess.RemoteAddr().String()))
cookieValue := mac.Sum(nil)
if len(cookieValue) >= int(*cookie_len) {
fmt.Println("no enough cookie space (should not happen..)")
return 0
}
data := goSliceFromUCString(cookie, int(*cookie_len))
*cookie_len = C.uint(copy(data, cookieValue))
return 1
}
//export verify_cookie_callback
func verify_cookie_callback(ssl *C.SSL, cookie *C.uchar, cookie_len C.uint) C.int {
bio := C.SSL_get_rbio(ssl)
sess := sessions[*(*int32)(C.BIO_get_data(bio))]
mac := hmac.New(sha256.New, sess.server.cookieSecret)
mac.Write([]byte(sess.RemoteAddr().String()))
cookieValue := mac.Sum(nil)
if len(cookieValue) != int(cookie_len) {
return 0
}
data := goSliceFromUCString(cookie, int(cookie_len))
if bytes.Equal(data, cookieValue) {
return 1
} else {
return 0
}
}