]> git.sur5r.net Git - openldap/blob - libraries/libldap/tls_g.c
ITS#8753 Public key pinning support in libldap
[openldap] / libraries / libldap / tls_g.c
1 /* tls_g.c - Handle tls/ssl using GNUTLS. */
2 /* $OpenLDAP$ */
3 /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
4  *
5  * Copyright 2008-2017 The OpenLDAP Foundation.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted only as authorized by the OpenLDAP
10  * Public License.
11  *
12  * A copy of this license is available in the file LICENSE in the
13  * top-level directory of the distribution or, alternatively, at
14  * <http://www.OpenLDAP.org/license.html>.
15  */
16 /* ACKNOWLEDGEMENTS: GNUTLS support written by Howard Chu and
17  * Emily Backes; sponsored by The Written Word (thewrittenword.com)
18  * and Stanford University (stanford.edu).
19  */
20
21 #include "portable.h"
22
23 #ifdef HAVE_GNUTLS
24
25 #include "ldap_config.h"
26
27 #include <stdio.h>
28
29 #include <ac/stdlib.h>
30 #include <ac/errno.h>
31 #include <ac/socket.h>
32 #include <ac/string.h>
33 #include <ac/ctype.h>
34 #include <ac/time.h>
35 #include <ac/unistd.h>
36 #include <ac/param.h>
37 #include <ac/dirent.h>
38 #include <sys/stat.h>
39 #include <fcntl.h>
40
41 #include "ldap-int.h"
42 #include "ldap-tls.h"
43
44 #include <gnutls/gnutls.h>
45 #include <gnutls/x509.h>
46 #include <gnutls/abstract.h>
47 #include <gnutls/crypto.h>
48
49 typedef struct tlsg_ctx {
50         gnutls_certificate_credentials_t cred;
51         gnutls_dh_params_t dh_params;
52         unsigned long verify_depth;
53         int refcount;
54         int reqcert;
55         gnutls_priority_t prios;
56 #ifdef LDAP_R_COMPILE
57         ldap_pvt_thread_mutex_t ref_mutex;
58 #endif
59 } tlsg_ctx;
60
61 typedef struct tlsg_session {
62         gnutls_session_t session;
63         tlsg_ctx *ctx;
64         struct berval peer_der_dn;
65 } tlsg_session;
66
67 static int tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites );
68 static int tlsg_cert_verify( tlsg_session *s );
69
70 #ifdef LDAP_R_COMPILE
71
72 static int
73 tlsg_mutex_init( void **priv )
74 {
75         int err = 0;
76         ldap_pvt_thread_mutex_t *lock = LDAP_MALLOC( sizeof( ldap_pvt_thread_mutex_t ));
77
78         if ( !lock )
79                 err = ENOMEM;
80         if ( !err ) {
81                 err = ldap_pvt_thread_mutex_init( lock );
82                 if ( err )
83                         LDAP_FREE( lock );
84                 else
85                         *priv = lock;
86         }
87         return err;
88 }
89
90 static int
91 tlsg_mutex_destroy( void **lock )
92 {
93         int err = ldap_pvt_thread_mutex_destroy( *lock );
94         LDAP_FREE( *lock );
95         return err;
96 }
97
98 static int
99 tlsg_mutex_lock( void **lock )
100 {
101         return ldap_pvt_thread_mutex_lock( *lock );
102 }
103
104 static int
105 tlsg_mutex_unlock( void **lock )
106 {
107         return ldap_pvt_thread_mutex_unlock( *lock );
108 }
109
110 static void
111 tlsg_thr_init( void )
112 {
113         gnutls_global_set_mutex (tlsg_mutex_init,
114                 tlsg_mutex_destroy,
115                 tlsg_mutex_lock,
116                 tlsg_mutex_unlock);
117 }
118 #endif /* LDAP_R_COMPILE */
119
120 /*
121  * Initialize TLS subsystem. Should be called only once.
122  */
123 static int
124 tlsg_init( void )
125 {
126         gnutls_global_init();
127         return 0;
128 }
129
130 /*
131  * Tear down the TLS subsystem. Should only be called once.
132  */
133 static void
134 tlsg_destroy( void )
135 {
136         gnutls_global_deinit();
137 }
138
139 static tls_ctx *
140 tlsg_ctx_new ( struct ldapoptions *lo )
141 {
142         tlsg_ctx *ctx;
143
144         ctx = ber_memcalloc ( 1, sizeof (*ctx) );
145         if ( ctx ) {
146                 if ( gnutls_certificate_allocate_credentials( &ctx->cred )) {
147                         ber_memfree( ctx );
148                         return NULL;
149                 }
150                 ctx->refcount = 1;
151                 gnutls_priority_init( &ctx->prios, "NORMAL", NULL );
152 #ifdef LDAP_R_COMPILE
153                 ldap_pvt_thread_mutex_init( &ctx->ref_mutex );
154 #endif
155         }
156         return (tls_ctx *)ctx;
157 }
158
159 static void
160 tlsg_ctx_ref( tls_ctx *ctx )
161 {
162         tlsg_ctx *c = (tlsg_ctx *)ctx;
163         LDAP_MUTEX_LOCK( &c->ref_mutex );
164         c->refcount++;
165         LDAP_MUTEX_UNLOCK( &c->ref_mutex );
166 }
167
168 static void
169 tlsg_ctx_free ( tls_ctx *ctx )
170 {
171         tlsg_ctx *c = (tlsg_ctx *)ctx;
172         int refcount;
173
174         if ( !c ) return;
175
176         LDAP_MUTEX_LOCK( &c->ref_mutex );
177         refcount = --c->refcount;
178         LDAP_MUTEX_UNLOCK( &c->ref_mutex );
179         if ( refcount )
180                 return;
181         gnutls_priority_deinit( c->prios );
182         gnutls_certificate_free_credentials( c->cred );
183         if ( c->dh_params )
184                 gnutls_dh_params_deinit( c->dh_params );
185         ber_memfree ( c );
186 }
187
188 static int
189 tlsg_getfile( const char *path, gnutls_datum_t *buf )
190 {
191         int rc = -1, fd;
192         struct stat st;
193
194         fd = open( path, O_RDONLY );
195         if ( fd >= 0 && fstat( fd, &st ) == 0 ) {
196                 buf->size = st.st_size;
197                 buf->data = LDAP_MALLOC( st.st_size + 1 );
198                 if ( buf->data ) {
199                         rc = read( fd, buf->data, st.st_size );
200                         close( fd );
201                         if ( rc < st.st_size )
202                                 rc = -1;
203                         else
204                                 rc = 0;
205                 }
206         }
207         return rc;
208 }
209
210 /* This is the GnuTLS default */
211 #define VERIFY_DEPTH    6
212
213 /*
214  * initialize a new TLS context
215  */
216 static int
217 tlsg_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server )
218 {
219         tlsg_ctx *ctx = lo->ldo_tls_ctx;
220         int rc;
221
222         if ( lo->ldo_tls_ciphersuite &&
223                 tlsg_parse_ciphers( ctx, lt->lt_ciphersuite )) {
224                 Debug( LDAP_DEBUG_ANY,
225                            "TLS: could not set cipher list %s.\n",
226                            lo->ldo_tls_ciphersuite, 0, 0 );
227                 return -1;
228         }
229
230         if (lo->ldo_tls_cacertdir != NULL) {
231                 Debug( LDAP_DEBUG_ANY, 
232                        "TLS: warning: cacertdir not implemented for gnutls\n",
233                        NULL, NULL, NULL );
234         }
235
236         if (lo->ldo_tls_cacertfile != NULL) {
237                 rc = gnutls_certificate_set_x509_trust_file( 
238                         ctx->cred,
239                         lt->lt_cacertfile,
240                         GNUTLS_X509_FMT_PEM );
241                 if ( rc < 0 ) return -1;
242         }
243         if (lo->ldo_tls_cacert.bv_val != NULL ) {
244                 gnutls_datum_t buf;
245                 buf.data = (unsigned char *)lo->ldo_tls_cacert.bv_val;
246                 buf.size = lo->ldo_tls_cacert.bv_len;
247                 rc = gnutls_certificate_set_x509_trust_mem(
248                         ctx->cred,
249                         &buf,
250                         GNUTLS_X509_FMT_DER );
251                 if ( rc < 0 ) return -1;
252         }
253
254         if (( lo->ldo_tls_certfile && lo->ldo_tls_keyfile ) ||
255                 ( lo->ldo_tls_cert.bv_val && lo->ldo_tls_key.bv_val )) {
256                 gnutls_x509_privkey_t key;
257                 gnutls_datum_t buf;
258                 gnutls_x509_crt_t certs[VERIFY_DEPTH];
259                 unsigned int max = VERIFY_DEPTH;
260
261                 rc = gnutls_x509_privkey_init( &key );
262                 if ( rc ) return -1;
263
264                 /* OpenSSL builds the cert chain for us, but GnuTLS
265                  * expects it to be present in the certfile. If it's
266                  * not, we have to build it ourselves. So we have to
267                  * do some special checks here...
268                  */
269                 if ( lo->ldo_tls_key.bv_val ) {
270                         buf.data = (unsigned char *)lo->ldo_tls_key.bv_val;
271                         buf.size = lo->ldo_tls_key.bv_len;
272                         rc = gnutls_x509_privkey_import( key, &buf,
273                                 GNUTLS_X509_FMT_DER );
274                 } else {
275                         rc = tlsg_getfile( lt->lt_keyfile, &buf );
276                         if ( rc ) return -1;
277                         rc = gnutls_x509_privkey_import( key, &buf,
278                                 GNUTLS_X509_FMT_PEM );
279                         LDAP_FREE( buf.data );
280                 }
281                 if ( rc < 0 ) return rc;
282
283                 if ( lo->ldo_tls_cert.bv_val ) {
284                         buf.data = (unsigned char *)lo->ldo_tls_cert.bv_val;
285                         buf.size = lo->ldo_tls_cert.bv_len;
286                         rc = gnutls_x509_crt_list_import( certs, &max, &buf,
287                                 GNUTLS_X509_FMT_DER, 0 );
288                 } else {
289                         rc = tlsg_getfile( lt->lt_certfile, &buf );
290                         if ( rc ) return -1;
291                         rc = gnutls_x509_crt_list_import( certs, &max, &buf,
292                                 GNUTLS_X509_FMT_PEM, 0 );
293                         LDAP_FREE( buf.data );
294                 }
295                 if ( rc < 0 ) return rc;
296
297                 /* If there's only one cert and it's not self-signed,
298                  * then we have to build the cert chain.
299                  */
300                 if ( max == 1 && !gnutls_x509_crt_check_issuer( certs[0], certs[0] )) {
301                         unsigned int i;
302                         for ( i = 1; i<VERIFY_DEPTH; i++ ) {
303                                 if ( gnutls_certificate_get_issuer( ctx->cred, certs[i-1], &certs[i], 0 ))
304                                         break;
305                                 max++;
306                                 /* If this CA is self-signed, we're done */
307                                 if ( gnutls_x509_crt_check_issuer( certs[i], certs[i] ))
308                                         break;
309                         }
310                 }
311                 rc = gnutls_certificate_set_x509_key( ctx->cred, certs, max, key );
312                 if ( rc ) return -1;
313         } else if (( lo->ldo_tls_certfile || lo->ldo_tls_keyfile )) {
314                 Debug( LDAP_DEBUG_ANY,
315                        "TLS: only one of certfile and keyfile specified\n",
316                        NULL, NULL, NULL );
317                 return -1;
318         } else if (( lo->ldo_tls_cert.bv_val || lo->ldo_tls_key.bv_val )) {
319                 Debug( LDAP_DEBUG_ANY,
320                        "TLS: only one of cert and key specified\n",
321                        NULL, NULL, NULL );
322                 return -1;
323         }
324
325         if ( lo->ldo_tls_crlfile ) {
326                 rc = gnutls_certificate_set_x509_crl_file( 
327                         ctx->cred,
328                         lt->lt_crlfile,
329                         GNUTLS_X509_FMT_PEM );
330                 if ( rc < 0 ) return -1;
331                 rc = 0;
332         }
333
334         /* FIXME: ITS#5992 - this should be configurable,
335          * and V1 CA certs should be phased out ASAP.
336          */
337         gnutls_certificate_set_verify_flags( ctx->cred,
338                 GNUTLS_VERIFY_ALLOW_X509_V1_CA_CRT );
339
340         if ( is_server && lo->ldo_tls_dhfile ) {
341                 gnutls_datum_t buf;
342                 rc = tlsg_getfile( lo->ldo_tls_dhfile, &buf );
343                 if ( rc ) return -1;
344                 rc = gnutls_dh_params_init( &ctx->dh_params );
345                 if ( rc == 0 )
346                         rc = gnutls_dh_params_import_pkcs3( ctx->dh_params, &buf,
347                                 GNUTLS_X509_FMT_PEM );
348                 LDAP_FREE( buf.data );
349                 if ( rc ) return -1;
350                 gnutls_certificate_set_dh_params( ctx->cred, ctx->dh_params );
351         }
352
353         ctx->reqcert = lo->ldo_tls_require_cert;
354
355         return 0;
356 }
357
358 static tls_session *
359 tlsg_session_new ( tls_ctx * ctx, int is_server )
360 {
361         tlsg_ctx *c = (tlsg_ctx *)ctx;
362         tlsg_session *session;
363
364         session = ber_memcalloc ( 1, sizeof (*session) );
365         if ( !session )
366                 return NULL;
367
368         session->ctx = c;
369         gnutls_init( &session->session, is_server ? GNUTLS_SERVER : GNUTLS_CLIENT );
370         gnutls_priority_set( session->session, c->prios );
371         if ( c->cred )
372                 gnutls_credentials_set( session->session, GNUTLS_CRD_CERTIFICATE, c->cred );
373         
374         if ( is_server ) {
375                 int flag = 0;
376                 if ( c->reqcert ) {
377                         flag = GNUTLS_CERT_REQUEST;
378                         if ( c->reqcert == LDAP_OPT_X_TLS_DEMAND ||
379                                 c->reqcert == LDAP_OPT_X_TLS_HARD )
380                                 flag = GNUTLS_CERT_REQUIRE;
381                         gnutls_certificate_server_set_request( session->session, flag );
382                 }
383         }
384         return (tls_session *)session;
385
386
387 static int
388 tlsg_session_accept( tls_session *session )
389 {
390         tlsg_session *s = (tlsg_session *)session;
391         int rc;
392
393         for ( rc = gnutls_handshake ( s->session );
394               rc == GNUTLS_E_INTERRUPTED || rc == GNUTLS_E_AGAIN;
395               rc = gnutls_handshake ( s->session ) );
396         if ( rc == 0 && s->ctx->reqcert != LDAP_OPT_X_TLS_NEVER ) {
397                 const gnutls_datum_t *peer_cert_list;
398                 unsigned int list_size;
399
400                 peer_cert_list = gnutls_certificate_get_peers( s->session, 
401                                                 &list_size );
402                 if ( !peer_cert_list && s->ctx->reqcert == LDAP_OPT_X_TLS_TRY )
403                         rc = 0;
404                 else {
405                         rc = tlsg_cert_verify( s );
406                         if ( rc && s->ctx->reqcert == LDAP_OPT_X_TLS_ALLOW )
407                                 rc = 0;
408                 }
409         }
410         return rc;
411 }
412
413 static int
414 tlsg_session_connect( LDAP *ld, tls_session *session )
415 {
416         return tlsg_session_accept( session);
417 }
418
419 static int
420 tlsg_session_upflags( Sockbuf *sb, tls_session *session, int rc )
421 {
422         tlsg_session *s = (tlsg_session *)session;
423
424         if ( rc != GNUTLS_E_INTERRUPTED && rc != GNUTLS_E_AGAIN )
425                 return 0;
426
427         switch (gnutls_record_get_direction (s->session)) {
428         case 0: 
429                 sb->sb_trans_needs_read = 1;
430                 return 1;
431         case 1:
432                 sb->sb_trans_needs_write = 1;
433                 return 1;
434         }
435         return 0;
436 }
437
438 static char *
439 tlsg_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
440 {
441         return (char *)gnutls_strerror( rc );
442 }
443
444 static void
445 tlsg_x509_cert_dn( struct berval *cert, struct berval *dn, int get_subject )
446 {
447         BerElementBuffer berbuf;
448         BerElement *ber = (BerElement *)&berbuf;
449         ber_tag_t tag;
450         ber_len_t len;
451         ber_int_t i;
452
453         ber_init2( ber, cert, LBER_USE_DER );
454         tag = ber_skip_tag( ber, &len );        /* Sequence */
455         tag = ber_skip_tag( ber, &len );        /* Sequence */
456         tag = ber_peek_tag( ber, &len );        /* Context + Constructed (version) */
457         if ( tag == 0xa0 ) {    /* Version is optional */
458                 tag = ber_skip_tag( ber, &len );
459                 tag = ber_get_int( ber, &i );   /* Int: Version */
460         }
461         tag = ber_skip_tag( ber, &len );        /* Int: Serial (can be longer than ber_int_t) */
462         ber_skip_data( ber, len );
463         tag = ber_skip_tag( ber, &len );        /* Sequence: Signature */
464         ber_skip_data( ber, len );
465         if ( !get_subject ) {
466                 tag = ber_peek_tag( ber, &len );        /* Sequence: Issuer DN */
467         } else {
468                 tag = ber_skip_tag( ber, &len );
469                 ber_skip_data( ber, len );
470                 tag = ber_skip_tag( ber, &len );        /* Sequence: Validity */
471                 ber_skip_data( ber, len );
472                 tag = ber_peek_tag( ber, &len );        /* Sequence: Subject DN */
473         }
474         len = ber_ptrlen( ber );
475         dn->bv_val = cert->bv_val + len;
476         dn->bv_len = cert->bv_len - len;
477 }
478
479 static int
480 tlsg_session_my_dn( tls_session *session, struct berval *der_dn )
481 {
482         tlsg_session *s = (tlsg_session *)session;
483         const gnutls_datum_t *x;
484         struct berval bv;
485
486         x = gnutls_certificate_get_ours( s->session );
487
488         if (!x) return LDAP_INVALID_CREDENTIALS;
489         
490         bv.bv_val = (char *) x->data;
491         bv.bv_len = x->size;
492
493         tlsg_x509_cert_dn( &bv, der_dn, 1 );
494         return 0;
495 }
496
497 static int
498 tlsg_session_peer_dn( tls_session *session, struct berval *der_dn )
499 {
500         tlsg_session *s = (tlsg_session *)session;
501         if ( !s->peer_der_dn.bv_val ) {
502                 const gnutls_datum_t *peer_cert_list;
503                 unsigned int list_size;
504                 struct berval bv;
505
506                 peer_cert_list = gnutls_certificate_get_peers( s->session, 
507                                                         &list_size );
508                 if ( !peer_cert_list ) return LDAP_INVALID_CREDENTIALS;
509
510                 bv.bv_len = peer_cert_list->size;
511                 bv.bv_val = (char *) peer_cert_list->data;
512
513                 tlsg_x509_cert_dn( &bv, &s->peer_der_dn, 1 );
514         }
515         *der_dn = s->peer_der_dn;
516         return 0;
517 }
518
519 /* what kind of hostname were we given? */
520 #define IS_DNS  0
521 #define IS_IP4  1
522 #define IS_IP6  2
523
524 #define CN_OID  "2.5.4.3"
525
526 static int
527 tlsg_session_chkhost( LDAP *ld, tls_session *session, const char *name_in )
528 {
529         tlsg_session *s = (tlsg_session *)session;
530         int i, ret;
531         const gnutls_datum_t *peer_cert_list;
532         unsigned int list_size;
533         char altname[NI_MAXHOST];
534         size_t altnamesize;
535
536         gnutls_x509_crt_t cert;
537         const char *name;
538         char *ptr;
539         char *domain = NULL;
540 #ifdef LDAP_PF_INET6
541         struct in6_addr addr;
542 #else
543         struct in_addr addr;
544 #endif
545         int len1 = 0, len2 = 0;
546         int ntype = IS_DNS;
547
548         if( ldap_int_hostname &&
549                 ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
550         {
551                 name = ldap_int_hostname;
552         } else {
553                 name = name_in;
554         }
555
556         peer_cert_list = gnutls_certificate_get_peers( s->session, 
557                                                 &list_size );
558         if ( !peer_cert_list ) {
559                 Debug( LDAP_DEBUG_ANY,
560                         "TLS: unable to get peer certificate.\n",
561                         0, 0, 0 );
562                 /* If this was a fatal condition, things would have
563                  * aborted long before now.
564                  */
565                 return LDAP_SUCCESS;
566         }
567         ret = gnutls_x509_crt_init( &cert );
568         if ( ret < 0 )
569                 return LDAP_LOCAL_ERROR;
570         ret = gnutls_x509_crt_import( cert, peer_cert_list, GNUTLS_X509_FMT_DER );
571         if ( ret ) {
572                 gnutls_x509_crt_deinit( cert );
573                 return LDAP_LOCAL_ERROR;
574         }
575
576 #ifdef LDAP_PF_INET6
577         if (inet_pton(AF_INET6, name, &addr)) {
578                 ntype = IS_IP6;
579         } else 
580 #endif
581         if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
582                 if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
583         }
584         
585         if (ntype == IS_DNS) {
586                 len1 = strlen(name);
587                 domain = strchr(name, '.');
588                 if (domain) {
589                         len2 = len1 - (domain-name);
590                 }
591         }
592
593         for ( i=0, ret=0; ret >= 0; i++ ) {
594                 altnamesize = sizeof(altname);
595                 ret = gnutls_x509_crt_get_subject_alt_name( cert, i, 
596                         altname, &altnamesize, NULL );
597                 if ( ret < 0 ) break;
598
599                 /* ignore empty */
600                 if ( altnamesize == 0 ) continue;
601
602                 if ( ret == GNUTLS_SAN_DNSNAME ) {
603                         if (ntype != IS_DNS) continue;
604         
605                         /* Is this an exact match? */
606                         if ((len1 == altnamesize) && !strncasecmp(name, altname, len1)) {
607                                 break;
608                         }
609
610                         /* Is this a wildcard match? */
611                         if (domain && (altname[0] == '*') && (altname[1] == '.') &&
612                                 (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2))
613                         {
614                                 break;
615                         }
616                 } else if ( ret == GNUTLS_SAN_IPADDRESS ) {
617                         if (ntype == IS_DNS) continue;
618
619 #ifdef LDAP_PF_INET6
620                         if (ntype == IS_IP6 && altnamesize != sizeof(struct in6_addr)) {
621                                 continue;
622                         } else
623 #endif
624                         if (ntype == IS_IP4 && altnamesize != sizeof(struct in_addr)) {
625                                 continue;
626                         }
627                         if (!memcmp(altname, &addr, altnamesize)) {
628                                 break;
629                         }
630                 }
631         }
632         if ( ret >= 0 ) {
633                 ret = LDAP_SUCCESS;
634         } else {
635                 /* find the last CN */
636                 i=0;
637                 do {
638                         altnamesize = 0;
639                         ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
640                                 i, 1, altname, &altnamesize );
641                         if ( ret == GNUTLS_E_SHORT_MEMORY_BUFFER )
642                                 i++;
643                         else
644                                 break;
645                 } while ( 1 );
646
647                 if ( i ) {
648                         altnamesize = sizeof(altname);
649                         ret = gnutls_x509_crt_get_dn_by_oid( cert, CN_OID,
650                                 i-1, 0, altname, &altnamesize );
651                 }
652
653                 if ( ret < 0 ) {
654                         Debug( LDAP_DEBUG_ANY,
655                                 "TLS: unable to get common name from peer certificate.\n",
656                                 0, 0, 0 );
657                         ret = LDAP_CONNECT_ERROR;
658                         if ( ld->ld_error ) {
659                                 LDAP_FREE( ld->ld_error );
660                         }
661                         ld->ld_error = LDAP_STRDUP(
662                                 _("TLS: unable to get CN from peer certificate"));
663
664                 } else {
665                         ret = LDAP_LOCAL_ERROR;
666                         if ( !len1 ) len1 = strlen( name );
667                         if ( len1 == altnamesize && strncasecmp(name, altname, altnamesize) == 0 ) {
668                                 ret = LDAP_SUCCESS;
669
670                         } else if (( altname[0] == '*' ) && ( altname[1] == '.' )) {
671                                         /* Is this a wildcard match? */
672                                 if( domain &&
673                                         (len2 == altnamesize-1) && !strncasecmp(domain, &altname[1], len2)) {
674                                         ret = LDAP_SUCCESS;
675                                 }
676                         }
677                 }
678
679                 if( ret == LDAP_LOCAL_ERROR ) {
680                         altname[altnamesize] = '\0';
681                         Debug( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
682                                 "common name in certificate (%s).\n", 
683                                 name, altname, 0 );
684                         ret = LDAP_CONNECT_ERROR;
685                         if ( ld->ld_error ) {
686                                 LDAP_FREE( ld->ld_error );
687                         }
688                         ld->ld_error = LDAP_STRDUP(
689                                 _("TLS: hostname does not match CN in peer certificate"));
690                 }
691         }
692         gnutls_x509_crt_deinit( cert );
693         return ret;
694 }
695
696 static int
697 tlsg_session_strength( tls_session *session )
698 {
699         tlsg_session *s = (tlsg_session *)session;
700         gnutls_cipher_algorithm_t c;
701
702         c = gnutls_cipher_get( s->session );
703         return gnutls_cipher_get_key_size( c ) * 8;
704 }
705
706 static int
707 tlsg_session_unique( tls_session *sess, struct berval *buf, int is_server)
708 {
709         tlsg_session *s = (tlsg_session *)sess;
710         gnutls_datum_t cb;
711         int rc;
712
713         rc = gnutls_session_channel_binding( s->session, GNUTLS_CB_TLS_UNIQUE, &cb );
714         if ( rc == 0 ) {
715                 int len = cb.size;
716                 if ( len > buf->bv_len )
717                         len = buf->bv_len;
718                 buf->bv_len = len;
719                 memcpy( buf->bv_val, cb.data, len );
720                 return len;
721         }
722         return 0;
723 }
724
725 static const char *
726 tlsg_session_version( tls_session *sess )
727 {
728         tlsg_session *s = (tlsg_session *)sess;
729         return gnutls_protocol_get_name(gnutls_protocol_get_version( s->session ));
730 }
731
732 static const char *
733 tlsg_session_cipher( tls_session *sess )
734 {
735         tlsg_session *s = (tlsg_session *)sess;
736         return gnutls_cipher_get_name(gnutls_cipher_get( s->session ));
737 }
738
739 static int
740 tlsg_session_peercert( tls_session *sess, struct berval *der )
741 {
742         tlsg_session *s = (tlsg_session *)sess;
743         const gnutls_datum_t *peer_cert_list;
744         unsigned int list_size;
745
746         peer_cert_list = gnutls_certificate_get_peers( s->session, &list_size );
747         if (!peer_cert_list)
748                 return -1;
749         der->bv_len = peer_cert_list[0].size;
750         der->bv_val = LDAP_MALLOC( der->bv_len );
751         if (!der->bv_val)
752                 return -1;
753         memcpy(der->bv_val, peer_cert_list[0].data, der->bv_len);
754         return 0;
755 }
756
757 static int
758 tlsg_session_pinning( LDAP *ld, tls_session *sess, char *hashalg, struct berval *hash )
759 {
760         tlsg_session *s = (tlsg_session *)sess;
761         const gnutls_datum_t *cert_list;
762         unsigned int cert_list_size = 0;
763         gnutls_x509_crt_t crt;
764         gnutls_pubkey_t pubkey;
765         gnutls_datum_t key = {};
766         gnutls_digest_algorithm_t alg;
767         struct berval keyhash;
768         size_t len;
769         int rc = -1;
770
771         if ( hashalg ) {
772                 alg = gnutls_digest_get_id( hashalg );
773                 if ( alg == GNUTLS_DIG_UNKNOWN ) {
774                         Debug( LDAP_DEBUG_ANY, "tlsg_session_pinning: "
775                                         "unknown hashing algorithm for GnuTLS: '%s'\n",
776                                         hashalg, 0, 0 );
777                         return rc;
778                 }
779         }
780
781         cert_list = gnutls_certificate_get_peers( s->session, &cert_list_size );
782         if ( cert_list_size == 0 ) {
783                 return rc;
784         }
785
786         if ( gnutls_x509_crt_init( &crt ) < 0 ) {
787                 return rc;
788         }
789
790         if ( gnutls_x509_crt_import( crt, &cert_list[0], GNUTLS_X509_FMT_DER ) ) {
791                 goto done;
792         }
793
794         if ( gnutls_pubkey_init( &pubkey ) ) {
795                 goto done;
796         }
797
798         if ( gnutls_pubkey_import_x509( pubkey, crt, 0 ) < 0 ) {
799                 goto done;
800         }
801
802         gnutls_pubkey_export( pubkey, GNUTLS_X509_FMT_DER, key.data, &len );
803         if ( len <= 0 ) {
804                 goto done;
805         }
806
807         key.data = LDAP_MALLOC( len );
808         if ( !key.data ) {
809                 goto done;
810         }
811
812         key.size = len;
813
814         if ( gnutls_pubkey_export( pubkey, GNUTLS_X509_FMT_DER,
815                                 key.data, &len ) < 0 ) {
816                 goto done;
817         }
818
819         if ( hashalg ) {
820                 keyhash.bv_len = gnutls_hash_get_len( alg );
821                 keyhash.bv_val = LDAP_MALLOC( keyhash.bv_len );
822                 if ( !keyhash.bv_val || gnutls_fingerprint( alg, &key,
823                                         keyhash.bv_val, &keyhash.bv_len ) < 0 ) {
824                         goto done;
825                 }
826         } else {
827                 keyhash.bv_val = (char *)key.data;
828                 keyhash.bv_len = key.size;
829         }
830
831         if ( ber_bvcmp( hash, &keyhash ) ) {
832                 rc = LDAP_CONNECT_ERROR;
833                 Debug( LDAP_DEBUG_ANY, "tlsg_session_pinning: "
834                                 "public key hash does not match provided pin.\n", 0, 0, 0 );
835                 if ( ld->ld_error ) {
836                         LDAP_FREE( ld->ld_error );
837                 }
838                 ld->ld_error = LDAP_STRDUP(
839                         _("TLS: public key hash does not match provided pin"));
840         } else {
841                 rc = LDAP_SUCCESS;
842         }
843
844 done:
845         if ( pubkey ) {
846                 gnutls_pubkey_deinit( pubkey );
847         }
848         if ( crt ) {
849                 gnutls_x509_crt_deinit( crt );
850         }
851         if ( keyhash.bv_val != (char *)key.data ) {
852                 LDAP_FREE( keyhash.bv_val );
853         }
854         if ( key.data ) {
855                 LDAP_FREE( key.data );
856         }
857         return rc;
858 }
859
860 /* suites is a string of colon-separated cipher suite names. */
861 static int
862 tlsg_parse_ciphers( tlsg_ctx *ctx, char *suites )
863 {
864         const char *err;
865         int rc = gnutls_priority_init( &ctx->prios, suites, &err );
866         if ( rc )
867                 ctx->prios = NULL;
868         return rc;
869 }
870
871 /*
872  * TLS support for LBER Sockbufs
873  */
874
875 struct tls_data {
876         tlsg_session            *session;
877         Sockbuf_IO_Desc         *sbiod;
878 };
879
880 static ssize_t
881 tlsg_recv( gnutls_transport_ptr_t ptr, void *buf, size_t len )
882 {
883         struct tls_data         *p;
884
885         if ( buf == NULL || len <= 0 ) return 0;
886
887         p = (struct tls_data *)ptr;
888
889         if ( p == NULL || p->sbiod == NULL ) {
890                 return 0;
891         }
892
893         return LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
894 }
895
896 static ssize_t
897 tlsg_send( gnutls_transport_ptr_t ptr, const void *buf, size_t len )
898 {
899         struct tls_data         *p;
900         
901         if ( buf == NULL || len <= 0 ) return 0;
902         
903         p = (struct tls_data *)ptr;
904
905         if ( p == NULL || p->sbiod == NULL ) {
906                 return 0;
907         }
908
909         return LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
910 }
911
912 static int
913 tlsg_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
914 {
915         struct tls_data         *p;
916         tlsg_session    *session = arg;
917
918         assert( sbiod != NULL );
919
920         p = LBER_MALLOC( sizeof( *p ) );
921         if ( p == NULL ) {
922                 return -1;
923         }
924         
925         gnutls_transport_set_ptr( session->session, (gnutls_transport_ptr_t)p );
926         gnutls_transport_set_pull_function( session->session, tlsg_recv );
927         gnutls_transport_set_push_function( session->session, tlsg_send );
928         p->session = session;
929         p->sbiod = sbiod;
930         sbiod->sbiod_pvt = p;
931         return 0;
932 }
933
934 static int
935 tlsg_sb_remove( Sockbuf_IO_Desc *sbiod )
936 {
937         struct tls_data         *p;
938         
939         assert( sbiod != NULL );
940         assert( sbiod->sbiod_pvt != NULL );
941
942         p = (struct tls_data *)sbiod->sbiod_pvt;
943         gnutls_deinit ( p->session->session );
944         LBER_FREE( p->session );
945         LBER_FREE( sbiod->sbiod_pvt );
946         sbiod->sbiod_pvt = NULL;
947         return 0;
948 }
949
950 static int
951 tlsg_sb_close( Sockbuf_IO_Desc *sbiod )
952 {
953         struct tls_data         *p;
954         
955         assert( sbiod != NULL );
956         assert( sbiod->sbiod_pvt != NULL );
957
958         p = (struct tls_data *)sbiod->sbiod_pvt;
959         gnutls_bye ( p->session->session, GNUTLS_SHUT_WR );
960         return 0;
961 }
962
963 static int
964 tlsg_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
965 {
966         struct tls_data         *p;
967         
968         assert( sbiod != NULL );
969         assert( sbiod->sbiod_pvt != NULL );
970
971         p = (struct tls_data *)sbiod->sbiod_pvt;
972         
973         if ( opt == LBER_SB_OPT_GET_SSL ) {
974                 *((tlsg_session **)arg) = p->session;
975                 return 1;
976                 
977         } else if ( opt == LBER_SB_OPT_DATA_READY ) {
978                 if( gnutls_record_check_pending( p->session->session ) > 0 ) {
979                         return 1;
980                 }
981         }
982         
983         return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
984 }
985
986 static ber_slen_t
987 tlsg_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
988 {
989         struct tls_data         *p;
990         ber_slen_t              ret;
991
992         assert( sbiod != NULL );
993         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
994
995         p = (struct tls_data *)sbiod->sbiod_pvt;
996
997         ret = gnutls_record_recv ( p->session->session, buf, len );
998         switch (ret) {
999         case GNUTLS_E_INTERRUPTED:
1000         case GNUTLS_E_AGAIN:
1001                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1002                 sock_errset(EWOULDBLOCK);
1003                 ret = 0;
1004                 break;
1005         case GNUTLS_E_REHANDSHAKE:
1006                 for ( ret = gnutls_handshake ( p->session->session );
1007                       ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN;
1008                       ret = gnutls_handshake ( p->session->session ) );
1009                 sbiod->sbiod_sb->sb_trans_needs_read = 1;
1010                 ret = 0;
1011                 break;
1012         default:
1013                 sbiod->sbiod_sb->sb_trans_needs_read = 0;
1014         }
1015         return ret;
1016 }
1017
1018 static ber_slen_t
1019 tlsg_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
1020 {
1021         struct tls_data         *p;
1022         ber_slen_t              ret;
1023
1024         assert( sbiod != NULL );
1025         assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
1026
1027         p = (struct tls_data *)sbiod->sbiod_pvt;
1028
1029         ret = gnutls_record_send ( p->session->session, (char *)buf, len );
1030
1031         if ( ret == GNUTLS_E_INTERRUPTED || ret == GNUTLS_E_AGAIN ) {
1032                 sbiod->sbiod_sb->sb_trans_needs_write = 1;
1033                 sock_errset(EWOULDBLOCK);
1034                 ret = 0;
1035         } else {
1036                 sbiod->sbiod_sb->sb_trans_needs_write = 0;
1037         }
1038         return ret;
1039 }
1040
1041 static Sockbuf_IO tlsg_sbio =
1042 {
1043         tlsg_sb_setup,          /* sbi_setup */
1044         tlsg_sb_remove,         /* sbi_remove */
1045         tlsg_sb_ctrl,           /* sbi_ctrl */
1046         tlsg_sb_read,           /* sbi_read */
1047         tlsg_sb_write,          /* sbi_write */
1048         tlsg_sb_close           /* sbi_close */
1049 };
1050
1051 /* Certs are not automatically varified during the handshake */
1052 static int
1053 tlsg_cert_verify( tlsg_session *ssl )
1054 {
1055         unsigned int status = 0;
1056         int err;
1057         time_t now = time(0);
1058         time_t peertime;
1059
1060         err = gnutls_certificate_verify_peers2( ssl->session, &status );
1061         if ( err < 0 ) {
1062                 Debug( LDAP_DEBUG_ANY,"TLS: gnutls_certificate_verify_peers2 failed %d\n",
1063                         err,0,0 );
1064                 return -1;
1065         }
1066         if ( status ) {
1067                 Debug( LDAP_DEBUG_TRACE,"TLS: peer cert untrusted or revoked (0x%x)\n",
1068                         status, 0,0 );
1069                 return -1;
1070         }
1071         peertime = gnutls_certificate_expiration_time_peers( ssl->session );
1072         if ( peertime == (time_t) -1 ) {
1073                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_expiration_time_peers failed\n",
1074                         0, 0, 0 );
1075                 return -1;
1076         }
1077         if ( peertime < now ) {
1078                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate is expired\n",
1079                         0, 0, 0 );
1080                 return -1;
1081         }
1082         peertime = gnutls_certificate_activation_time_peers( ssl->session );
1083         if ( peertime == (time_t) -1 ) {
1084                 Debug( LDAP_DEBUG_ANY, "TLS: gnutls_certificate_activation_time_peers failed\n",
1085                         0, 0, 0 );
1086                 return -1;
1087         }
1088         if ( peertime > now ) {
1089                 Debug( LDAP_DEBUG_ANY, "TLS: peer certificate not yet active\n",
1090                         0, 0, 0 );
1091                 return -1;
1092         }
1093         return 0;
1094 }
1095
1096 tls_impl ldap_int_tls_impl = {
1097         "GnuTLS",
1098
1099         tlsg_init,
1100         tlsg_destroy,
1101
1102         tlsg_ctx_new,
1103         tlsg_ctx_ref,
1104         tlsg_ctx_free,
1105         tlsg_ctx_init,
1106
1107         tlsg_session_new,
1108         tlsg_session_connect,
1109         tlsg_session_accept,
1110         tlsg_session_upflags,
1111         tlsg_session_errmsg,
1112         tlsg_session_my_dn,
1113         tlsg_session_peer_dn,
1114         tlsg_session_chkhost,
1115         tlsg_session_strength,
1116         tlsg_session_unique,
1117         tlsg_session_version,
1118         tlsg_session_cipher,
1119         tlsg_session_peercert,
1120         tlsg_session_pinning,
1121
1122         &tlsg_sbio,
1123
1124 #ifdef LDAP_R_COMPILE
1125         tlsg_thr_init,
1126 #else
1127         NULL,
1128 #endif
1129
1130         0
1131 };
1132
1133 #endif /* HAVE_GNUTLS */