r15854: more talloc_set_destructor() typesafe fixes
[bbaumbach/samba-autobuild/.git] / source4 / lib / tls / tls.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    transport layer security handling code
5
6    Copyright (C) Andrew Tridgell 2004-2005
7    Copyright (C) Stefan Metzmacher 2004
8    Copyright (C) Andrew Bartlett 2006
9  
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #include "includes.h"
26 #include "lib/events/events.h"
27 #include "lib/socket/socket.h"
28
29 #if HAVE_LIBGNUTLS
30 #include "gnutls/gnutls.h"
31
32 #define DH_BITS 1024
33
34 /* hold persistent tls data */
35 struct tls_params {
36         gnutls_certificate_credentials x509_cred;
37         gnutls_dh_params dh_params;
38         BOOL tls_enabled;
39 };
40 #endif
41
42 /* hold per connection tls data */
43 struct tls_context {
44         struct socket_context *socket;
45         struct fd_event *fde;
46         BOOL tls_enabled;
47 #if HAVE_LIBGNUTLS
48         gnutls_session session;
49         BOOL done_handshake;
50         BOOL have_first_byte;
51         uint8_t first_byte;
52         BOOL tls_detect;
53         const char *plain_chars;
54         BOOL output_pending;
55         gnutls_certificate_credentials xcred;
56         BOOL interrupted;
57 #endif
58 };
59
60 BOOL tls_enabled(struct socket_context *sock)
61 {
62         struct tls_context *tls;
63         if (!sock) {
64                 return False;
65         }
66         if (strcmp(sock->backend_name, "tls") != 0) {
67                 return False;
68         }
69         tls = talloc_get_type(sock->private_data, struct tls_context);
70         if (!tls) {
71                 return False;
72         }
73         return tls->tls_enabled;
74 }
75
76
77 #if HAVE_LIBGNUTLS
78
79 static const struct socket_ops tls_socket_ops;
80
81 static NTSTATUS tls_socket_init(struct socket_context *sock)
82 {
83         switch (sock->type) {
84         case SOCKET_TYPE_STREAM:
85                 break;
86         default:
87                 return NT_STATUS_INVALID_PARAMETER;
88         }
89
90         sock->backend_name = "tls";
91
92         return NT_STATUS_OK;
93 }
94
95 #define TLSCHECK(call) do { \
96         ret = call; \
97         if (ret < 0) { \
98                 DEBUG(0,("TLS %s - %s\n", #call, gnutls_strerror(ret))); \
99                 goto failed; \
100         } \
101 } while (0)
102
103
104 /*
105   callback for reading from a socket
106 */
107 static ssize_t tls_pull(gnutls_transport_ptr ptr, void *buf, size_t size)
108 {
109         struct tls_context *tls = talloc_get_type(ptr, struct tls_context);
110         NTSTATUS status;
111         size_t nread;
112         
113         if (tls->have_first_byte) {
114                 *(uint8_t *)buf = tls->first_byte;
115                 tls->have_first_byte = False;
116                 return 1;
117         }
118
119         status = socket_recv(tls->socket, buf, size, &nread);
120         if (NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)) {
121                 return 0;
122         }
123         if (NT_STATUS_IS_ERR(status)) {
124                 EVENT_FD_NOT_READABLE(tls->fde);
125                 EVENT_FD_NOT_WRITEABLE(tls->fde);
126                 errno = EBADF;
127                 return -1;
128         }
129         if (!NT_STATUS_IS_OK(status)) {
130                 EVENT_FD_READABLE(tls->fde);
131                 errno = EAGAIN;
132                 return -1;
133         }
134         if (tls->output_pending) {
135                 EVENT_FD_WRITEABLE(tls->fde);
136         }
137         if (size != nread) {
138                 EVENT_FD_READABLE(tls->fde);
139         }
140         return nread;
141 }
142
143 /*
144   callback for writing to a socket
145 */
146 static ssize_t tls_push(gnutls_transport_ptr ptr, const void *buf, size_t size)
147 {
148         struct tls_context *tls = talloc_get_type(ptr, struct tls_context);
149         NTSTATUS status;
150         size_t nwritten;
151         DATA_BLOB b;
152
153         if (!tls->tls_enabled) {
154                 return size;
155         }
156
157         b.data = discard_const(buf);
158         b.length = size;
159
160         status = socket_send(tls->socket, &b, &nwritten);
161         if (NT_STATUS_EQUAL(status, STATUS_MORE_ENTRIES)) {
162                 errno = EAGAIN;
163                 return -1;
164         }
165         if (!NT_STATUS_IS_OK(status)) {
166                 EVENT_FD_WRITEABLE(tls->fde);
167                 return -1;
168         }
169         if (size != nwritten) {
170                 EVENT_FD_WRITEABLE(tls->fde);
171         }
172         return nwritten;
173 }
174
175 /*
176   destroy a tls session
177  */
178 static int tls_destructor(struct tls_context *tls)
179 {
180         int ret;
181         ret = gnutls_bye(tls->session, GNUTLS_SHUT_WR);
182         if (ret < 0) {
183                 DEBUG(0,("TLS gnutls_bye failed - %s\n", gnutls_strerror(ret)));
184         }
185         return 0;
186 }
187
188
189 /*
190   possibly continue the handshake process
191 */
192 static NTSTATUS tls_handshake(struct tls_context *tls)
193 {
194         int ret;
195
196         if (tls->done_handshake) {
197                 return NT_STATUS_OK;
198         }
199         
200         ret = gnutls_handshake(tls->session);
201         if (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN) {
202                 if (gnutls_record_get_direction(tls->session) == 1) {
203                         EVENT_FD_WRITEABLE(tls->fde);
204                 }
205                 return STATUS_MORE_ENTRIES;
206         }
207         if (ret < 0) {
208                 DEBUG(0,("TLS gnutls_handshake failed - %s\n", gnutls_strerror(ret)));
209                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
210         }
211         tls->done_handshake = True;
212         return NT_STATUS_OK;
213 }
214
215 /*
216   possibly continue an interrupted operation
217 */
218 static NTSTATUS tls_interrupted(struct tls_context *tls)
219 {
220         int ret;
221
222         if (!tls->interrupted) {
223                 return NT_STATUS_OK;
224         }
225         if (gnutls_record_get_direction(tls->session) == 1) {
226                 ret = gnutls_record_send(tls->session, NULL, 0);
227         } else {
228                 ret = gnutls_record_recv(tls->session, NULL, 0);
229         }
230         if (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN) {
231                 return STATUS_MORE_ENTRIES;
232         }
233         tls->interrupted = False;
234         return NT_STATUS_OK;
235 }
236
237 /*
238   see how many bytes are pending on the connection
239 */
240 static NTSTATUS tls_socket_pending(struct socket_context *sock, size_t *npending)
241 {
242         struct tls_context *tls = talloc_get_type(sock->private_data, struct tls_context);
243         if (!tls->tls_enabled || tls->tls_detect) {
244                 return socket_pending(tls->socket, npending);
245         }
246         *npending = gnutls_record_check_pending(tls->session);
247         if (*npending == 0) {
248                 NTSTATUS status = socket_pending(tls->socket, npending);
249                 if (*npending == 0) {
250                         /* seems to be a gnutls bug */
251                         (*npending) = 100;
252                 }
253                 return status;
254         }
255         return NT_STATUS_OK;
256 }
257
258 /*
259   receive data either by tls or normal socket_recv
260 */
261 static NTSTATUS tls_socket_recv(struct socket_context *sock, void *buf, 
262                                 size_t wantlen, size_t *nread)
263 {
264         int ret;
265         NTSTATUS status;
266         struct tls_context *tls = talloc_get_type(sock->private_data, struct tls_context);
267
268         if (tls->tls_enabled && tls->tls_detect) {
269                 status = socket_recv(tls->socket, &tls->first_byte, 1, nread);
270                 NT_STATUS_NOT_OK_RETURN(status);
271                 if (*nread == 0) return NT_STATUS_OK;
272                 tls->tls_detect = False;
273                 /* look for the first byte of a valid HTTP operation */
274                 if (strchr(tls->plain_chars, tls->first_byte)) {
275                         /* not a tls link */
276                         tls->tls_enabled = False;
277                         *(uint8_t *)buf = tls->first_byte;
278                         return NT_STATUS_OK;
279                 }
280                 tls->have_first_byte = True;
281         }
282
283         if (!tls->tls_enabled) {
284                 return socket_recv(tls->socket, buf, wantlen, nread);
285         }
286
287         status = tls_handshake(tls);
288         NT_STATUS_NOT_OK_RETURN(status);
289
290         status = tls_interrupted(tls);
291         NT_STATUS_NOT_OK_RETURN(status);
292
293         ret = gnutls_record_recv(tls->session, buf, wantlen);
294         if (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN) {
295                 if (gnutls_record_get_direction(tls->session) == 1) {
296                         EVENT_FD_WRITEABLE(tls->fde);
297                 }
298                 tls->interrupted = True;
299                 return STATUS_MORE_ENTRIES;
300         }
301         if (ret < 0) {
302                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
303         }
304         *nread = ret;
305         return NT_STATUS_OK;
306 }
307
308
309 /*
310   send data either by tls or normal socket_recv
311 */
312 static NTSTATUS tls_socket_send(struct socket_context *sock, 
313                                 const DATA_BLOB *blob, size_t *sendlen)
314 {
315         NTSTATUS status;
316         int ret;
317         struct tls_context *tls = talloc_get_type(sock->private_data, struct tls_context);
318
319         if (!tls->tls_enabled) {
320                 return socket_send(tls->socket, blob, sendlen);
321         }
322
323         status = tls_handshake(tls);
324         NT_STATUS_NOT_OK_RETURN(status);
325
326         status = tls_interrupted(tls);
327         NT_STATUS_NOT_OK_RETURN(status);
328
329         ret = gnutls_record_send(tls->session, blob->data, blob->length);
330         if (ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN) {
331                 if (gnutls_record_get_direction(tls->session) == 1) {
332                         EVENT_FD_WRITEABLE(tls->fde);
333                 }
334                 tls->interrupted = True;
335                 return STATUS_MORE_ENTRIES;
336         }
337         if (ret < 0) {
338                 DEBUG(0,("gnutls_record_send of %d failed - %s\n", blob->length, gnutls_strerror(ret)));
339                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
340         }
341         *sendlen = ret;
342         tls->output_pending = (ret < blob->length);
343         return NT_STATUS_OK;
344 }
345
346
347 /*
348   initialise global tls state
349 */
350 struct tls_params *tls_initialise(TALLOC_CTX *mem_ctx)
351 {
352         struct tls_params *params;
353         int ret;
354         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
355         const char *keyfile = private_path(tmp_ctx, lp_tls_keyfile());
356         const char *certfile = private_path(tmp_ctx, lp_tls_certfile());
357         const char *cafile = private_path(tmp_ctx, lp_tls_cafile());
358         const char *crlfile = private_path(tmp_ctx, lp_tls_crlfile());
359         void tls_cert_generate(TALLOC_CTX *, const char *, const char *, const char *);
360
361         params = talloc(mem_ctx, struct tls_params);
362         if (params == NULL) {
363                 talloc_free(tmp_ctx);
364                 return NULL;
365         }
366
367         if (!lp_tls_enabled() || keyfile == NULL || *keyfile == 0) {
368                 params->tls_enabled = False;
369                 talloc_free(tmp_ctx);
370                 return params;
371         }
372
373         if (!file_exist(cafile)) {
374                 tls_cert_generate(params, keyfile, certfile, cafile);
375         }
376
377         ret = gnutls_global_init();
378         if (ret < 0) goto init_failed;
379
380         gnutls_certificate_allocate_credentials(&params->x509_cred);
381         if (ret < 0) goto init_failed;
382
383         if (cafile && *cafile) {
384                 ret = gnutls_certificate_set_x509_trust_file(params->x509_cred, cafile, 
385                                                              GNUTLS_X509_FMT_PEM);      
386                 if (ret < 0) {
387                         DEBUG(0,("TLS failed to initialise cafile %s\n", cafile));
388                         goto init_failed;
389                 }
390         }
391
392         if (crlfile && *crlfile) {
393                 ret = gnutls_certificate_set_x509_crl_file(params->x509_cred, 
394                                                            crlfile, 
395                                                            GNUTLS_X509_FMT_PEM);
396                 if (ret < 0) {
397                         DEBUG(0,("TLS failed to initialise crlfile %s\n", crlfile));
398                         goto init_failed;
399                 }
400         }
401         
402         ret = gnutls_certificate_set_x509_key_file(params->x509_cred, 
403                                                    certfile, keyfile,
404                                                    GNUTLS_X509_FMT_PEM);
405         if (ret < 0) {
406                 DEBUG(0,("TLS failed to initialise certfile %s and keyfile %s\n", 
407                          certfile, keyfile));
408                 goto init_failed;
409         }
410         
411         ret = gnutls_dh_params_init(&params->dh_params);
412         if (ret < 0) goto init_failed;
413
414         ret = gnutls_dh_params_generate2(params->dh_params, DH_BITS);
415         if (ret < 0) goto init_failed;
416
417         gnutls_certificate_set_dh_params(params->x509_cred, params->dh_params);
418
419         params->tls_enabled = True;
420
421         talloc_free(tmp_ctx);
422         return params;
423
424 init_failed:
425         DEBUG(0,("GNUTLS failed to initialise - %s\n", gnutls_strerror(ret)));
426         params->tls_enabled = False;
427         talloc_free(tmp_ctx);
428         return params;
429 }
430
431
432 /*
433   setup for a new connection
434 */
435 struct socket_context *tls_init_server(struct tls_params *params, 
436                                     struct socket_context *socket,
437                                     struct fd_event *fde, 
438                                     const char *plain_chars)
439 {
440         struct tls_context *tls;
441         int ret;
442         struct socket_context *new_sock;
443         NTSTATUS nt_status;
444         
445         nt_status = socket_create_with_ops(socket, &tls_socket_ops, &new_sock, 
446                                            SOCKET_TYPE_STREAM, 0);
447         if (!NT_STATUS_IS_OK(nt_status)) {
448                 return NULL;
449         }
450
451         tls = talloc(new_sock, struct tls_context);
452         if (tls == NULL) {
453                 return NULL;
454         }
455
456         tls->socket          = socket;
457         tls->fde             = fde;
458         if (talloc_reference(tls, fde) == NULL) {
459                 return NULL;
460         }
461         if (talloc_reference(tls, socket) == NULL) {
462                 return NULL;
463         }
464
465         new_sock->private_data    = tls;
466
467         if (!params->tls_enabled) {
468                 tls->tls_enabled = False;
469                 return new_sock;
470         }
471
472         TLSCHECK(gnutls_init(&tls->session, GNUTLS_SERVER));
473
474         talloc_set_destructor(tls, tls_destructor);
475
476         TLSCHECK(gnutls_set_default_priority(tls->session));
477         TLSCHECK(gnutls_credentials_set(tls->session, GNUTLS_CRD_CERTIFICATE, 
478                                         params->x509_cred));
479         gnutls_certificate_server_set_request(tls->session, GNUTLS_CERT_REQUEST);
480         gnutls_dh_set_prime_bits(tls->session, DH_BITS);
481         gnutls_transport_set_ptr(tls->session, (gnutls_transport_ptr)tls);
482         gnutls_transport_set_pull_function(tls->session, (gnutls_pull_func)tls_pull);
483         gnutls_transport_set_push_function(tls->session, (gnutls_push_func)tls_push);
484         gnutls_transport_set_lowat(tls->session, 0);
485
486         tls->plain_chars = plain_chars;
487         if (plain_chars) {
488                 tls->tls_detect = True;
489         } else {
490                 tls->tls_detect = False;
491         }
492
493         tls->output_pending  = False;
494         tls->done_handshake  = False;
495         tls->have_first_byte = False;
496         tls->tls_enabled     = True;
497         tls->interrupted     = False;
498         
499         new_sock->state = SOCKET_STATE_SERVER_CONNECTED;
500
501         return new_sock;
502
503 failed:
504         DEBUG(0,("TLS init connection failed - %s\n", gnutls_strerror(ret)));
505         tls->tls_enabled = False;
506         params->tls_enabled = False;
507         return new_sock;
508 }
509
510
511 /*
512   setup for a new client connection
513 */
514 struct socket_context *tls_init_client(struct socket_context *socket,
515                                        struct fd_event *fde)
516 {
517         struct tls_context *tls;
518         int ret = 0;
519         const int cert_type_priority[] = { GNUTLS_CRT_X509, GNUTLS_CRT_OPENPGP, 0 };
520         char *cafile;
521         struct socket_context *new_sock;
522         NTSTATUS nt_status;
523         
524         nt_status = socket_create_with_ops(socket, &tls_socket_ops, &new_sock, 
525                                            SOCKET_TYPE_STREAM, 0);
526         if (!NT_STATUS_IS_OK(nt_status)) {
527                 return NULL;
528         }
529
530         tls = talloc(new_sock, struct tls_context);
531         if (tls == NULL) return NULL;
532
533         tls->socket          = socket;
534         tls->fde             = fde;
535         if (talloc_reference(tls, fde) == NULL) {
536                 return NULL;
537         }
538         if (talloc_reference(tls, socket) == NULL) {
539                 return NULL;
540         }
541         new_sock->private_data    = tls;
542
543         cafile = private_path(tls, lp_tls_cafile());
544         if (!cafile || !*cafile) {
545                 goto failed;
546         }
547
548         gnutls_global_init();
549
550         gnutls_certificate_allocate_credentials(&tls->xcred);
551         gnutls_certificate_set_x509_trust_file(tls->xcred, cafile, GNUTLS_X509_FMT_PEM);
552         talloc_free(cafile);
553         TLSCHECK(gnutls_init(&tls->session, GNUTLS_CLIENT));
554         TLSCHECK(gnutls_set_default_priority(tls->session));
555         gnutls_certificate_type_set_priority(tls->session, cert_type_priority);
556         TLSCHECK(gnutls_credentials_set(tls->session, GNUTLS_CRD_CERTIFICATE, tls->xcred));
557
558         talloc_set_destructor(tls, tls_destructor);
559
560         gnutls_transport_set_ptr(tls->session, (gnutls_transport_ptr)tls);
561         gnutls_transport_set_pull_function(tls->session, (gnutls_pull_func)tls_pull);
562         gnutls_transport_set_push_function(tls->session, (gnutls_push_func)tls_push);
563         gnutls_transport_set_lowat(tls->session, 0);
564         tls->tls_detect = False;
565
566         tls->output_pending  = False;
567         tls->done_handshake  = False;
568         tls->have_first_byte = False;
569         tls->tls_enabled     = True;
570         tls->interrupted     = False;
571         
572         new_sock->state = SOCKET_STATE_CLIENT_CONNECTED;
573
574         return new_sock;
575
576 failed:
577         DEBUG(0,("TLS init connection failed - %s\n", gnutls_strerror(ret)));
578         tls->tls_enabled = False;
579         return new_sock;
580 }
581
582 static NTSTATUS tls_socket_set_option(struct socket_context *sock, const char *option, const char *val)
583 {
584         set_socket_options(socket_get_fd(sock), option);
585         return NT_STATUS_OK;
586 }
587
588 static char *tls_socket_get_peer_name(struct socket_context *sock, TALLOC_CTX *mem_ctx)
589 {
590         struct tls_context *tls = talloc_get_type(sock->private_data, struct tls_context);
591         return socket_get_peer_name(tls->socket, mem_ctx);
592 }
593
594 static struct socket_address *tls_socket_get_peer_addr(struct socket_context *sock, TALLOC_CTX *mem_ctx)
595 {
596         struct tls_context *tls = talloc_get_type(sock->private_data, struct tls_context);
597         return socket_get_peer_addr(tls->socket, mem_ctx);
598 }
599
600 static struct socket_address *tls_socket_get_my_addr(struct socket_context *sock, TALLOC_CTX *mem_ctx)
601 {
602         struct tls_context *tls = talloc_get_type(sock->private_data, struct tls_context);
603         return socket_get_my_addr(tls->socket, mem_ctx);
604 }
605
606 static int tls_socket_get_fd(struct socket_context *sock)
607 {
608         struct tls_context *tls = talloc_get_type(sock->private_data, struct tls_context);
609         return socket_get_fd(tls->socket);
610 }
611
612 static const struct socket_ops tls_socket_ops = {
613         .name                   = "tls",
614         .fn_init                = tls_socket_init,
615         .fn_recv                = tls_socket_recv,
616         .fn_send                = tls_socket_send,
617         .fn_pending             = tls_socket_pending,
618
619         .fn_set_option          = tls_socket_set_option,
620
621         .fn_get_peer_name       = tls_socket_get_peer_name,
622         .fn_get_peer_addr       = tls_socket_get_peer_addr,
623         .fn_get_my_addr         = tls_socket_get_my_addr,
624         .fn_get_fd              = tls_socket_get_fd
625 };
626
627 BOOL tls_support(struct tls_params *params)
628 {
629         return params->tls_enabled;
630 }
631
632 #else
633
634 /* for systems without tls we just map the tls socket calls to the
635    normal socket calls */
636
637 struct tls_params *tls_initialise(TALLOC_CTX *mem_ctx)
638 {
639         return talloc_new(mem_ctx);
640 }
641
642 /*
643   setup for a new connection
644 */
645 struct socket_context *tls_init_server(struct tls_params *params, 
646                                     struct socket_context *socket,
647                                     struct fd_event *fde, 
648                                     const char *plain_chars)
649 {
650         return socket;
651 }
652
653
654 /*
655   setup for a new client connection
656 */
657 struct socket_context *tls_init_client(struct socket_context *socket,
658                                        struct fd_event *fde)
659 {
660         return socket;
661 }
662
663 BOOL tls_support(struct tls_params *params)
664 {
665         return False;
666 }
667
668 #endif
669