tls_o.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728
  1. /* tls_o.c - Handle tls/ssl using OpenSSL */
  2. /* $OpenLDAP$ */
  3. /* This work is part of OpenLDAP Software <http://www.openldap.org/>.
  4. *
  5. * Copyright 2008-2022 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: Rewritten by Howard Chu
  17. */
  18. #include "portable.h"
  19. #ifdef HAVE_OPENSSL
  20. #include "ldap_config.h"
  21. #include <stdio.h>
  22. #include <ac/stdlib.h>
  23. #include <ac/errno.h>
  24. #include <ac/socket.h>
  25. #include <ac/string.h>
  26. #include <ac/ctype.h>
  27. #include <ac/time.h>
  28. #include <ac/unistd.h>
  29. #include <ac/param.h>
  30. #include <ac/dirent.h>
  31. #include "ldap-int.h"
  32. #include "ldap-tls.h"
  33. #ifdef HAVE_OPENSSL_SSL_H
  34. #include <openssl/ssl.h>
  35. #include <openssl/x509v3.h>
  36. #include <openssl/err.h>
  37. #include <openssl/rand.h>
  38. #include <openssl/safestack.h>
  39. #include <openssl/bn.h>
  40. #include <openssl/rsa.h>
  41. #include <openssl/dh.h>
  42. #endif
  43. #if OPENSSL_VERSION_NUMBER >= 0x10100000
  44. #define ASN1_STRING_data(x) ASN1_STRING_get0_data(x)
  45. #endif
  46. #if OPENSSL_VERSION_MAJOR >= 3
  47. #define ERR_get_error_line( a, b ) ERR_get_error_all( a, b, NULL, NULL, NULL )
  48. #define SSL_get_peer_certificate( s ) SSL_get1_peer_certificate( s )
  49. #endif
  50. typedef SSL_CTX tlso_ctx;
  51. typedef SSL tlso_session;
  52. static BIO_METHOD * tlso_bio_method = NULL;
  53. static BIO_METHOD * tlso_bio_setup( void );
  54. static int tlso_opt_trace = 1;
  55. static void tlso_report_error( char *errmsg );
  56. static void tlso_info_cb( const SSL *ssl, int where, int ret );
  57. static int tlso_verify_cb( int ok, X509_STORE_CTX *ctx );
  58. static int tlso_verify_ok( int ok, X509_STORE_CTX *ctx );
  59. static int tlso_seed_PRNG( const char *randfile );
  60. #if OPENSSL_VERSION_NUMBER < 0x10100000
  61. /*
  62. * OpenSSL 1.1 API and later has new locking code
  63. */
  64. static RSA * tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length );
  65. #ifdef LDAP_R_COMPILE
  66. /*
  67. * provide mutexes for the OpenSSL library.
  68. */
  69. static ldap_pvt_thread_mutex_t tlso_mutexes[CRYPTO_NUM_LOCKS];
  70. static void tlso_locking_cb( int mode, int type, const char *file, int line )
  71. {
  72. if ( mode & CRYPTO_LOCK ) {
  73. ldap_pvt_thread_mutex_lock( &tlso_mutexes[type] );
  74. } else {
  75. ldap_pvt_thread_mutex_unlock( &tlso_mutexes[type] );
  76. }
  77. }
  78. #if OPENSSL_VERSION_NUMBER >= 0x0909000
  79. static void tlso_thread_self( CRYPTO_THREADID *id )
  80. {
  81. CRYPTO_THREADID_set_pointer( id, (void *)ldap_pvt_thread_self() );
  82. }
  83. #define CRYPTO_set_id_callback(foo) CRYPTO_THREADID_set_callback(foo)
  84. #else
  85. static unsigned long tlso_thread_self( void )
  86. {
  87. /* FIXME: CRYPTO_set_id_callback only works when ldap_pvt_thread_t
  88. * is an integral type that fits in an unsigned long
  89. */
  90. /* force an error if the ldap_pvt_thread_t type is too large */
  91. enum { ok = sizeof( ldap_pvt_thread_t ) <= sizeof( unsigned long ) };
  92. typedef struct { int dummy: ok ? 1 : -1; } Check[ok ? 1 : -1];
  93. return (unsigned long) ldap_pvt_thread_self();
  94. }
  95. #endif
  96. static void tlso_thr_init( void )
  97. {
  98. int i;
  99. for( i=0; i< CRYPTO_NUM_LOCKS ; i++ ) {
  100. ldap_pvt_thread_mutex_init( &tlso_mutexes[i] );
  101. }
  102. CRYPTO_set_locking_callback( tlso_locking_cb );
  103. CRYPTO_set_id_callback( tlso_thread_self );
  104. }
  105. #endif /* LDAP_R_COMPILE */
  106. #else
  107. #ifdef LDAP_R_COMPILE
  108. static void tlso_thr_init( void ) {}
  109. #endif
  110. #endif /* OpenSSL 1.1 */
  111. #if OPENSSL_VERSION_NUMBER < 0x10100000
  112. /*
  113. * OpenSSL 1.1 API and later makes the BIO method concrete types internal.
  114. */
  115. static BIO_METHOD *
  116. BIO_meth_new( int type, const char *name )
  117. {
  118. BIO_METHOD *method = LDAP_MALLOC( sizeof(BIO_METHOD) );
  119. memset( method, 0, sizeof(BIO_METHOD) );
  120. method->type = type;
  121. method->name = name;
  122. return method;
  123. }
  124. static void
  125. BIO_meth_free( BIO_METHOD *meth )
  126. {
  127. if ( meth == NULL ) {
  128. return;
  129. }
  130. LDAP_FREE( meth );
  131. }
  132. #define BIO_meth_set_write(m, f) (m)->bwrite = (f)
  133. #define BIO_meth_set_read(m, f) (m)->bread = (f)
  134. #define BIO_meth_set_puts(m, f) (m)->bputs = (f)
  135. #define BIO_meth_set_gets(m, f) (m)->bgets = (f)
  136. #define BIO_meth_set_ctrl(m, f) (m)->ctrl = (f)
  137. #define BIO_meth_set_create(m, f) (m)->create = (f)
  138. #define BIO_meth_set_destroy(m, f) (m)->destroy = (f)
  139. #endif /* OpenSSL 1.1 */
  140. static STACK_OF(X509_NAME) *
  141. tlso_ca_list( char * bundle, char * dir, X509 *cert )
  142. {
  143. STACK_OF(X509_NAME) *ca_list = NULL;
  144. if ( bundle ) {
  145. ca_list = SSL_load_client_CA_file( bundle );
  146. }
  147. if ( dir ) {
  148. char **dirs = ldap_str2charray( dir, CERTPATHSEP );
  149. int freeit = 0, i, success = 0;
  150. if ( !ca_list ) {
  151. ca_list = sk_X509_NAME_new_null();
  152. freeit = 1;
  153. }
  154. for ( i=0; dirs[i]; i++ ) {
  155. success += SSL_add_dir_cert_subjects_to_stack( ca_list, dir );
  156. }
  157. if ( !success && freeit ) {
  158. sk_X509_NAME_free( ca_list );
  159. ca_list = NULL;
  160. }
  161. ldap_charray_free( dirs );
  162. }
  163. if ( cert ) {
  164. X509_NAME *xn = X509_get_subject_name( cert );
  165. xn = X509_NAME_dup( xn );
  166. if ( !ca_list )
  167. ca_list = sk_X509_NAME_new_null();
  168. if ( xn && ca_list )
  169. sk_X509_NAME_push( ca_list, xn );
  170. }
  171. return ca_list;
  172. }
  173. /*
  174. * Initialize TLS subsystem. Should be called only once.
  175. */
  176. static int
  177. tlso_init( void )
  178. {
  179. struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
  180. #ifdef HAVE_EBCDIC
  181. {
  182. char *file = LDAP_STRDUP( lo->ldo_tls_randfile );
  183. if ( file ) __atoe( file );
  184. (void) tlso_seed_PRNG( file );
  185. LDAP_FREE( file );
  186. }
  187. #else
  188. (void) tlso_seed_PRNG( lo->ldo_tls_randfile );
  189. #endif
  190. #if OPENSSL_VERSION_NUMBER < 0x10100000
  191. SSL_load_error_strings();
  192. SSL_library_init();
  193. OpenSSL_add_all_digests();
  194. #else
  195. OPENSSL_init_ssl(0, NULL);
  196. #endif
  197. /* FIXME: mod_ssl does this */
  198. X509V3_add_standard_extensions();
  199. tlso_bio_method = tlso_bio_setup();
  200. return 0;
  201. }
  202. /*
  203. * Tear down the TLS subsystem. Should only be called once.
  204. */
  205. static void
  206. tlso_destroy( void )
  207. {
  208. struct ldapoptions *lo = LDAP_INT_GLOBAL_OPT();
  209. BIO_meth_free( tlso_bio_method );
  210. #if OPENSSL_VERSION_NUMBER < 0x10100000
  211. EVP_cleanup();
  212. ERR_remove_thread_state(NULL);
  213. ERR_free_strings();
  214. #endif
  215. if ( lo->ldo_tls_randfile ) {
  216. LDAP_FREE( lo->ldo_tls_randfile );
  217. lo->ldo_tls_randfile = NULL;
  218. }
  219. }
  220. static tls_ctx *
  221. tlso_ctx_new( struct ldapoptions *lo )
  222. {
  223. return (tls_ctx *) SSL_CTX_new( SSLv23_method() );
  224. }
  225. static void
  226. tlso_ctx_ref( tls_ctx *ctx )
  227. {
  228. tlso_ctx *c = (tlso_ctx *)ctx;
  229. #if OPENSSL_VERSION_NUMBER < 0x10100000
  230. #define SSL_CTX_up_ref(ctx) CRYPTO_add( &(ctx->references), 1, CRYPTO_LOCK_SSL_CTX )
  231. #endif
  232. SSL_CTX_up_ref( c );
  233. }
  234. static void
  235. tlso_ctx_free ( tls_ctx *ctx )
  236. {
  237. tlso_ctx *c = (tlso_ctx *)ctx;
  238. SSL_CTX_free( c );
  239. }
  240. #if OPENSSL_VERSION_NUMBER >= 0x10101000
  241. static char *
  242. tlso_stecpy( char *dst, const char *src, const char *end )
  243. {
  244. while ( dst < end && *src )
  245. *dst++ = *src++;
  246. if ( dst < end )
  247. *dst = '\0';
  248. return dst;
  249. }
  250. /* OpenSSL 1.1.1 uses a separate API for TLS1.3 ciphersuites.
  251. * Try to find any TLS1.3 ciphers in the given list of suites.
  252. */
  253. static void
  254. tlso_ctx_cipher13( tlso_ctx *ctx, char *suites )
  255. {
  256. char tls13_suites[1024], *ts = tls13_suites, *te = tls13_suites + sizeof(tls13_suites);
  257. char *ptr, *colon, *nptr;
  258. char sname[128];
  259. STACK_OF(SSL_CIPHER) *cs;
  260. SSL *s = SSL_new( ctx );
  261. int ret;
  262. if ( !s )
  263. return;
  264. *ts = '\0';
  265. /* check individual suites in a separate SSL handle before
  266. * mucking with the provided ctx. Init it to a known
  267. * mostly-empty state.
  268. */
  269. SSL_set_ciphersuites( s, "" );
  270. SSL_set_cipher_list( s, SSL3_TXT_RSA_NULL_SHA );
  271. for ( ptr = suites;; ) {
  272. colon = strchr( ptr, ':' );
  273. if ( colon ) {
  274. int len = colon - ptr;
  275. if ( len > 63 ) len = 63;
  276. strncpy( sname, ptr, len );
  277. sname[len] = '\0';
  278. nptr = sname;
  279. } else {
  280. nptr = ptr;
  281. }
  282. if ( SSL_set_ciphersuites( s, nptr )) {
  283. cs = SSL_get_ciphers( s );
  284. if ( cs ) {
  285. const char *ver = SSL_CIPHER_get_version( sk_SSL_CIPHER_value( cs, 0 ));
  286. if ( !strncmp( ver, "TLSv", 4 ) && strncmp( ver+4, "1.3", 3 ) >= 0 ) {
  287. if ( tls13_suites[0] )
  288. ts = tlso_stecpy( ts, ":", te );
  289. ts = tlso_stecpy( ts, nptr, te );
  290. }
  291. }
  292. }
  293. if ( !colon || ts >= te )
  294. break;
  295. ptr = colon+1;
  296. }
  297. SSL_free( s );
  298. /* If no TLS1.3 ciphersuites were specified, leave current settings untouched. */
  299. if ( tls13_suites[0] )
  300. SSL_CTX_set_ciphersuites( ctx, tls13_suites );
  301. }
  302. #endif /* OpenSSL 1.1.1 */
  303. /*
  304. * initialize a new TLS context
  305. */
  306. static int
  307. tlso_ctx_init( struct ldapoptions *lo, struct ldaptls *lt, int is_server, char *errmsg )
  308. {
  309. tlso_ctx *ctx = (tlso_ctx *)lo->ldo_tls_ctx;
  310. int i;
  311. if ( is_server ) {
  312. SSL_CTX_set_session_id_context( ctx,
  313. (const unsigned char *) "OpenLDAP", sizeof("OpenLDAP")-1 );
  314. }
  315. if ( lo->ldo_tls_protocol_min ) {
  316. int opt = 0;
  317. if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL2 ) {
  318. opt |= SSL_OP_NO_SSLv2;
  319. SSL_CTX_clear_options( ctx, SSL_OP_NO_SSLv3 );
  320. }
  321. if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
  322. opt |= SSL_OP_NO_SSLv3;
  323. #ifdef SSL_OP_NO_TLSv1
  324. if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_0 )
  325. opt |= SSL_OP_NO_TLSv1;
  326. #endif
  327. #ifdef SSL_OP_NO_TLSv1_1
  328. if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_1 )
  329. opt |= SSL_OP_NO_TLSv1_1;
  330. #endif
  331. #ifdef SSL_OP_NO_TLSv1_2
  332. if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_2 )
  333. opt |= SSL_OP_NO_TLSv1_2;
  334. #endif
  335. #ifdef SSL_OP_NO_TLSv1_3
  336. if ( lo->ldo_tls_protocol_min > LDAP_OPT_X_TLS_PROTOCOL_TLS1_3 )
  337. opt |= SSL_OP_NO_TLSv1_3;
  338. #endif
  339. if ( opt )
  340. SSL_CTX_set_options( ctx, opt );
  341. }
  342. if ( lo->ldo_tls_protocol_max ) {
  343. int opt = 0;
  344. #ifdef SSL_OP_NO_TLSv1_3
  345. if ( lo->ldo_tls_protocol_max < LDAP_OPT_X_TLS_PROTOCOL_TLS1_3 )
  346. opt |= SSL_OP_NO_TLSv1_3;
  347. #endif
  348. #ifdef SSL_OP_NO_TLSv1_2
  349. if ( lo->ldo_tls_protocol_max < LDAP_OPT_X_TLS_PROTOCOL_TLS1_2 )
  350. opt |= SSL_OP_NO_TLSv1_2;
  351. #endif
  352. #ifdef SSL_OP_NO_TLSv1_1
  353. if ( lo->ldo_tls_protocol_max < LDAP_OPT_X_TLS_PROTOCOL_TLS1_1 )
  354. opt |= SSL_OP_NO_TLSv1_1;
  355. #endif
  356. #ifdef SSL_OP_NO_TLSv1
  357. if ( lo->ldo_tls_protocol_max < LDAP_OPT_X_TLS_PROTOCOL_TLS1_0 )
  358. opt |= SSL_OP_NO_TLSv1;
  359. #endif
  360. if ( lo->ldo_tls_protocol_max < LDAP_OPT_X_TLS_PROTOCOL_SSL3 )
  361. opt |= SSL_OP_NO_SSLv3;
  362. if ( opt )
  363. SSL_CTX_set_options( ctx, opt );
  364. }
  365. if ( lo->ldo_tls_ciphersuite ) {
  366. #if OPENSSL_VERSION_NUMBER >= 0x10101000
  367. tlso_ctx_cipher13( ctx, lt->lt_ciphersuite );
  368. #endif
  369. if ( !SSL_CTX_set_cipher_list( ctx, lt->lt_ciphersuite ) )
  370. {
  371. Debug1( LDAP_DEBUG_ANY,
  372. "TLS: could not set cipher list %s.\n",
  373. lo->ldo_tls_ciphersuite );
  374. tlso_report_error( errmsg );
  375. return -1;
  376. }
  377. }
  378. if ( lo->ldo_tls_cacertfile == NULL && lo->ldo_tls_cacertdir == NULL &&
  379. lo->ldo_tls_cacert.bv_val == NULL ) {
  380. if ( !SSL_CTX_set_default_verify_paths( ctx ) ) {
  381. Debug0( LDAP_DEBUG_ANY, "TLS: "
  382. "could not use default certificate paths" );
  383. tlso_report_error( errmsg );
  384. return -1;
  385. }
  386. } else {
  387. X509 *cert = NULL;
  388. if ( lo->ldo_tls_cacert.bv_val ) {
  389. const unsigned char *pp = (const unsigned char *) (lo->ldo_tls_cacert.bv_val);
  390. cert = d2i_X509( NULL, &pp, lo->ldo_tls_cacert.bv_len );
  391. X509_STORE *store = SSL_CTX_get_cert_store( ctx );
  392. if ( !X509_STORE_add_cert( store, cert )) {
  393. Debug0( LDAP_DEBUG_ANY, "TLS: "
  394. "could not use CA certificate" );
  395. tlso_report_error( errmsg );
  396. return -1;
  397. }
  398. }
  399. if ( lt->lt_cacertfile || lt->lt_cacertdir ) {
  400. char **dirs, *dummy = NULL;
  401. if ( lt->lt_cacertdir ) {
  402. dirs = ldap_str2charray( lt->lt_cacertdir, CERTPATHSEP );
  403. } else {
  404. dirs = &dummy;
  405. }
  406. /* Start with the first dir in path */
  407. if ( !SSL_CTX_load_verify_locations( ctx,
  408. lt->lt_cacertfile, dirs[0] ) )
  409. {
  410. Debug2( LDAP_DEBUG_ANY, "TLS: "
  411. "could not load verify locations (file:`%s',dir:`%s').\n",
  412. lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
  413. dirs[0] ? dirs[0] : "" );
  414. tlso_report_error( errmsg );
  415. if ( dirs != &dummy )
  416. ldap_charray_free( dirs );
  417. return -1;
  418. }
  419. /* Then additional dirs, if any */
  420. if ( dirs != &dummy ) {
  421. if ( dirs[1] ) {
  422. int i;
  423. X509_STORE *store = SSL_CTX_get_cert_store( ctx );
  424. X509_LOOKUP *lookup = X509_STORE_add_lookup( store, X509_LOOKUP_hash_dir() );
  425. for ( i=1; dirs[i]; i++ )
  426. X509_LOOKUP_add_dir( lookup, dirs[i], X509_FILETYPE_PEM );
  427. }
  428. ldap_charray_free( dirs );
  429. }
  430. }
  431. if ( is_server ) {
  432. STACK_OF(X509_NAME) *calist;
  433. /* List of CA names to send to a client */
  434. calist = tlso_ca_list( lt->lt_cacertfile, lt->lt_cacertdir, cert );
  435. if ( !calist ) {
  436. Debug2( LDAP_DEBUG_ANY, "TLS: "
  437. "could not load client CA list (file:`%s',dir:`%s').\n",
  438. lo->ldo_tls_cacertfile ? lo->ldo_tls_cacertfile : "",
  439. lo->ldo_tls_cacertdir ? lo->ldo_tls_cacertdir : "" );
  440. tlso_report_error( errmsg );
  441. return -1;
  442. }
  443. SSL_CTX_set_client_CA_list( ctx, calist );
  444. }
  445. if ( cert )
  446. X509_free( cert );
  447. }
  448. if ( lo->ldo_tls_cert.bv_val )
  449. {
  450. const unsigned char *pp = (const unsigned char *) (lo->ldo_tls_cert.bv_val);
  451. X509 *cert = d2i_X509( NULL, &pp, lo->ldo_tls_cert.bv_len );
  452. if ( !SSL_CTX_use_certificate( ctx, cert )) {
  453. Debug0( LDAP_DEBUG_ANY,
  454. "TLS: could not use certificate.\n" );
  455. tlso_report_error( errmsg );
  456. return -1;
  457. }
  458. X509_free( cert );
  459. } else
  460. if ( lo->ldo_tls_certfile &&
  461. !SSL_CTX_use_certificate_chain_file( ctx, lt->lt_certfile) )
  462. {
  463. Debug1( LDAP_DEBUG_ANY,
  464. "TLS: could not use certificate file `%s'.\n",
  465. lo->ldo_tls_certfile );
  466. tlso_report_error( errmsg );
  467. return -1;
  468. }
  469. /* Key validity is checked automatically if cert has already been set */
  470. if ( lo->ldo_tls_key.bv_val )
  471. {
  472. const unsigned char *pp = (const unsigned char *) (lo->ldo_tls_key.bv_val);
  473. EVP_PKEY *pkey = d2i_AutoPrivateKey( NULL, &pp, lo->ldo_tls_key.bv_len );
  474. if ( !SSL_CTX_use_PrivateKey( ctx, pkey ))
  475. {
  476. Debug0( LDAP_DEBUG_ANY,
  477. "TLS: could not use private key.\n" );
  478. tlso_report_error( errmsg );
  479. return -1;
  480. }
  481. EVP_PKEY_free( pkey );
  482. } else
  483. if ( lo->ldo_tls_keyfile &&
  484. !SSL_CTX_use_PrivateKey_file( ctx,
  485. lt->lt_keyfile, SSL_FILETYPE_PEM ) )
  486. {
  487. Debug1( LDAP_DEBUG_ANY,
  488. "TLS: could not use key file `%s'.\n",
  489. lo->ldo_tls_keyfile );
  490. tlso_report_error( errmsg );
  491. return -1;
  492. }
  493. if ( is_server && lo->ldo_tls_dhfile ) {
  494. #if OPENSSL_VERSION_MAJOR >= 3
  495. EVP_PKEY *dh;
  496. #define bio_params( bio, dh ) dh = PEM_read_bio_Parameters( bio, &dh )
  497. #else
  498. DH *dh;
  499. #define bio_params( bio, dh ) dh = PEM_read_bio_DHparams( bio, NULL, NULL, NULL )
  500. #endif
  501. BIO *bio;
  502. if (( bio=BIO_new_file( lt->lt_dhfile,"r" )) == NULL ) {
  503. Debug1( LDAP_DEBUG_ANY,
  504. "TLS: could not use DH parameters file `%s'.\n",
  505. lo->ldo_tls_dhfile );
  506. tlso_report_error( errmsg );
  507. return -1;
  508. }
  509. if (!( bio_params( bio, dh ))) {
  510. Debug1( LDAP_DEBUG_ANY,
  511. "TLS: could not read DH parameters file `%s'.\n",
  512. lo->ldo_tls_dhfile );
  513. tlso_report_error( errmsg );
  514. BIO_free( bio );
  515. return -1;
  516. }
  517. BIO_free( bio );
  518. #if OPENSSL_VERSION_MAJOR >= 3
  519. SSL_CTX_set0_tmp_dh_pkey( ctx, dh );
  520. #else
  521. SSL_CTX_set_tmp_dh( ctx, dh );
  522. SSL_CTX_set_options( ctx, SSL_OP_SINGLE_DH_USE );
  523. DH_free( dh );
  524. #endif
  525. }
  526. if ( lo->ldo_tls_ecname ) {
  527. #ifdef OPENSSL_NO_EC
  528. Debug0( LDAP_DEBUG_ANY,
  529. "TLS: Elliptic Curves not supported.\n" );
  530. return -1;
  531. #else
  532. if ( !SSL_CTX_set1_curves_list( ctx, lt->lt_ecname )) {
  533. Debug1( LDAP_DEBUG_ANY,
  534. "TLS: could not set EC name `%s'.\n",
  535. lo->ldo_tls_ecname );
  536. tlso_report_error( errmsg );
  537. return -1;
  538. }
  539. /*
  540. * This is a NOP in OpenSSL 1.1.0 and later, where curves are always
  541. * auto-negotiated.
  542. */
  543. #if OPENSSL_VERSION_NUMBER < 0x10100000UL
  544. if ( SSL_CTX_set_ecdh_auto( ctx, 1 ) <= 0 ) {
  545. Debug0( LDAP_DEBUG_ANY,
  546. "TLS: could not enable automatic EC negotiation.\n" );
  547. }
  548. #endif
  549. #endif /* OPENSSL_NO_EC */
  550. }
  551. if ( tlso_opt_trace ) {
  552. SSL_CTX_set_info_callback( ctx, tlso_info_cb );
  553. }
  554. i = SSL_VERIFY_NONE;
  555. if ( lo->ldo_tls_require_cert ) {
  556. i = SSL_VERIFY_PEER;
  557. if ( lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_DEMAND ||
  558. lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_HARD ) {
  559. i |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
  560. }
  561. }
  562. SSL_CTX_set_verify( ctx, i,
  563. lo->ldo_tls_require_cert == LDAP_OPT_X_TLS_ALLOW ?
  564. tlso_verify_ok : tlso_verify_cb );
  565. #if OPENSSL_VERSION_NUMBER < 0x10100000
  566. SSL_CTX_set_tmp_rsa_callback( ctx, tlso_tmp_rsa_cb );
  567. #endif
  568. if ( lo->ldo_tls_crlcheck ) {
  569. X509_STORE *x509_s = SSL_CTX_get_cert_store( ctx );
  570. if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_PEER ) {
  571. X509_STORE_set_flags( x509_s, X509_V_FLAG_CRL_CHECK );
  572. } else if ( lo->ldo_tls_crlcheck == LDAP_OPT_X_TLS_CRL_ALL ) {
  573. X509_STORE_set_flags( x509_s,
  574. X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL );
  575. }
  576. }
  577. /* Explicitly honor the server side cipher suite preference */
  578. SSL_CTX_set_options( ctx, SSL_OP_CIPHER_SERVER_PREFERENCE );
  579. return 0;
  580. }
  581. static tls_session *
  582. tlso_session_new( tls_ctx *ctx, int is_server )
  583. {
  584. tlso_ctx *c = (tlso_ctx *)ctx;
  585. return (tls_session *)SSL_new( c );
  586. }
  587. static int
  588. tlso_session_connect( LDAP *ld, tls_session *sess, const char *name_in )
  589. {
  590. tlso_session *s = (tlso_session *)sess;
  591. int rc;
  592. #ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
  593. if ( name_in ) {
  594. rc = SSL_set_tlsext_host_name( s, name_in );
  595. if ( !rc ) /* can fail to strdup the name */
  596. return -1;
  597. }
  598. #endif
  599. /* Caller expects 0 = success, OpenSSL returns 1 = success */
  600. rc = SSL_connect( s ) - 1;
  601. return rc;
  602. }
  603. static int
  604. tlso_session_accept( tls_session *sess )
  605. {
  606. tlso_session *s = (tlso_session *)sess;
  607. /* Caller expects 0 = success, OpenSSL returns 1 = success */
  608. return SSL_accept( s ) - 1;
  609. }
  610. static int
  611. tlso_session_upflags( Sockbuf *sb, tls_session *sess, int rc )
  612. {
  613. tlso_session *s = (tlso_session *)sess;
  614. /* 1 was subtracted above, offset it back now */
  615. rc = SSL_get_error(s, rc+1);
  616. if (rc == SSL_ERROR_WANT_READ) {
  617. sb->sb_trans_needs_read = 1;
  618. return 1;
  619. } else if (rc == SSL_ERROR_WANT_WRITE) {
  620. sb->sb_trans_needs_write = 1;
  621. return 1;
  622. } else if (rc == SSL_ERROR_WANT_CONNECT) {
  623. return 1;
  624. }
  625. return 0;
  626. }
  627. static char *
  628. tlso_session_errmsg( tls_session *sess, int rc, char *buf, size_t len )
  629. {
  630. char err[256] = "";
  631. const char *certerr=NULL;
  632. tlso_session *s = (tlso_session *)sess;
  633. rc = ERR_peek_error();
  634. if ( rc ) {
  635. ERR_error_string_n( rc, err, sizeof(err) );
  636. if ( ( ERR_GET_LIB(rc) == ERR_LIB_SSL ) &&
  637. ( ERR_GET_REASON(rc) == SSL_R_CERTIFICATE_VERIFY_FAILED ) ) {
  638. int certrc = SSL_get_verify_result(s);
  639. certerr = (char *)X509_verify_cert_error_string(certrc);
  640. }
  641. snprintf(buf, len, "%s%s%s%s", err, certerr ? " (" :"",
  642. certerr ? certerr : "", certerr ? ")" : "" );
  643. return buf;
  644. }
  645. return NULL;
  646. }
  647. static int
  648. tlso_session_my_dn( tls_session *sess, struct berval *der_dn )
  649. {
  650. tlso_session *s = (tlso_session *)sess;
  651. X509 *x;
  652. X509_NAME *xn;
  653. x = SSL_get_certificate( s );
  654. if (!x) return LDAP_INVALID_CREDENTIALS;
  655. xn = X509_get_subject_name(x);
  656. #if OPENSSL_VERSION_NUMBER < 0x10100000
  657. der_dn->bv_len = i2d_X509_NAME( xn, NULL );
  658. der_dn->bv_val = xn->bytes->data;
  659. #else
  660. {
  661. size_t len = 0;
  662. der_dn->bv_val = NULL;
  663. X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
  664. der_dn->bv_len = len;
  665. }
  666. #endif
  667. /* Don't X509_free, the session is still using it */
  668. return 0;
  669. }
  670. static X509 *
  671. tlso_get_cert( SSL *s )
  672. {
  673. /* If peer cert was bad, treat as if no cert was given */
  674. if (SSL_get_verify_result(s)) {
  675. return NULL;
  676. }
  677. return SSL_get_peer_certificate(s);
  678. }
  679. static int
  680. tlso_session_peer_dn( tls_session *sess, struct berval *der_dn )
  681. {
  682. tlso_session *s = (tlso_session *)sess;
  683. X509 *x = tlso_get_cert( s );
  684. X509_NAME *xn;
  685. if ( !x )
  686. return LDAP_INVALID_CREDENTIALS;
  687. xn = X509_get_subject_name(x);
  688. #if OPENSSL_VERSION_NUMBER < 0x10100000
  689. der_dn->bv_len = i2d_X509_NAME( xn, NULL );
  690. der_dn->bv_val = xn->bytes->data;
  691. #else
  692. {
  693. size_t len = 0;
  694. der_dn->bv_val = NULL;
  695. X509_NAME_get0_der( xn, (const unsigned char **)&der_dn->bv_val, &len );
  696. der_dn->bv_len = len;
  697. }
  698. #endif
  699. X509_free(x);
  700. return 0;
  701. }
  702. /* what kind of hostname were we given? */
  703. #define IS_DNS 0
  704. #define IS_IP4 1
  705. #define IS_IP6 2
  706. static int
  707. tlso_session_chkhost( LDAP *ld, tls_session *sess, const char *name_in )
  708. {
  709. tlso_session *s = (tlso_session *)sess;
  710. int i, ret = LDAP_LOCAL_ERROR;
  711. int chkSAN = ld->ld_options.ldo_tls_require_san, gotSAN = 0;
  712. X509 *x;
  713. const char *name;
  714. char *ptr;
  715. int ntype = IS_DNS, nlen;
  716. #ifdef LDAP_PF_INET6
  717. struct in6_addr addr;
  718. #else
  719. struct in_addr addr;
  720. #endif
  721. if( ldap_int_hostname &&
  722. ( !name_in || !strcasecmp( name_in, "localhost" ) ) )
  723. {
  724. name = ldap_int_hostname;
  725. } else {
  726. name = name_in;
  727. }
  728. nlen = strlen(name);
  729. x = tlso_get_cert(s);
  730. if (!x) {
  731. Debug0( LDAP_DEBUG_ANY,
  732. "TLS: unable to get peer certificate.\n" );
  733. /* If this was a fatal condition, things would have
  734. * aborted long before now.
  735. */
  736. return LDAP_SUCCESS;
  737. }
  738. #ifdef LDAP_PF_INET6
  739. if (inet_pton(AF_INET6, name, &addr)) {
  740. ntype = IS_IP6;
  741. } else
  742. #endif
  743. if ((ptr = strrchr(name, '.')) && isdigit((unsigned char)ptr[1])) {
  744. if (inet_aton(name, (struct in_addr *)&addr)) ntype = IS_IP4;
  745. }
  746. if (chkSAN) {
  747. i = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
  748. if (i >= 0) {
  749. X509_EXTENSION *ex;
  750. STACK_OF(GENERAL_NAME) *alt;
  751. ex = X509_get_ext(x, i);
  752. alt = X509V3_EXT_d2i(ex);
  753. if (alt) {
  754. int n, len2 = 0;
  755. char *domain = NULL;
  756. GENERAL_NAME *gn;
  757. gotSAN = 1;
  758. if (ntype == IS_DNS) {
  759. domain = strchr(name, '.');
  760. if (domain) {
  761. len2 = nlen - (domain-name);
  762. }
  763. }
  764. n = sk_GENERAL_NAME_num(alt);
  765. for (i=0; i<n; i++) {
  766. char *sn;
  767. int sl;
  768. gn = sk_GENERAL_NAME_value(alt, i);
  769. if (gn->type == GEN_DNS) {
  770. if (ntype != IS_DNS) continue;
  771. sn = (char *) ASN1_STRING_data(gn->d.ia5);
  772. sl = ASN1_STRING_length(gn->d.ia5);
  773. /* ignore empty */
  774. if (sl == 0) continue;
  775. /* Is this an exact match? */
  776. if ((nlen == sl) && !strncasecmp(name, sn, nlen)) {
  777. break;
  778. }
  779. /* Is this a wildcard match? */
  780. if (domain && (sn[0] == '*') && (sn[1] == '.') &&
  781. (len2 == sl-1) && !strncasecmp(domain, &sn[1], len2))
  782. {
  783. break;
  784. }
  785. } else if (gn->type == GEN_IPADD) {
  786. if (ntype == IS_DNS) continue;
  787. sn = (char *) ASN1_STRING_data(gn->d.ia5);
  788. sl = ASN1_STRING_length(gn->d.ia5);
  789. #ifdef LDAP_PF_INET6
  790. if (ntype == IS_IP6 && sl != sizeof(struct in6_addr)) {
  791. continue;
  792. } else
  793. #endif
  794. if (ntype == IS_IP4 && sl != sizeof(struct in_addr)) {
  795. continue;
  796. }
  797. if (!memcmp(sn, &addr, sl)) {
  798. break;
  799. }
  800. }
  801. }
  802. GENERAL_NAMES_free(alt);
  803. if (i < n) { /* Found a match */
  804. ret = LDAP_SUCCESS;
  805. }
  806. }
  807. }
  808. }
  809. if (ret != LDAP_SUCCESS && chkSAN) {
  810. switch(chkSAN) {
  811. case LDAP_OPT_X_TLS_DEMAND:
  812. case LDAP_OPT_X_TLS_HARD:
  813. if (!gotSAN) {
  814. Debug0( LDAP_DEBUG_ANY,
  815. "TLS: unable to get subjectAltName from peer certificate.\n" );
  816. ret = LDAP_CONNECT_ERROR;
  817. if ( ld->ld_error ) {
  818. LDAP_FREE( ld->ld_error );
  819. }
  820. ld->ld_error = LDAP_STRDUP(
  821. _("TLS: unable to get subjectAltName from peer certificate"));
  822. goto done;
  823. }
  824. /* FALLTHRU */
  825. case LDAP_OPT_X_TLS_TRY:
  826. if (gotSAN) {
  827. Debug1( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
  828. "subjectAltName in certificate.\n",
  829. name );
  830. ret = LDAP_CONNECT_ERROR;
  831. if ( ld->ld_error ) {
  832. LDAP_FREE( ld->ld_error );
  833. }
  834. ld->ld_error = LDAP_STRDUP(
  835. _("TLS: hostname does not match subjectAltName in peer certificate"));
  836. goto done;
  837. }
  838. break;
  839. case LDAP_OPT_X_TLS_ALLOW:
  840. break;
  841. }
  842. }
  843. if (ret != LDAP_SUCCESS) {
  844. X509_NAME *xn;
  845. X509_NAME_ENTRY *ne;
  846. ASN1_OBJECT *obj;
  847. ASN1_STRING *cn = NULL;
  848. int navas;
  849. /* find the last CN */
  850. obj = OBJ_nid2obj( NID_commonName );
  851. if ( !obj ) goto no_cn; /* should never happen */
  852. xn = X509_get_subject_name(x);
  853. navas = X509_NAME_entry_count( xn );
  854. for ( i=navas-1; i>=0; i-- ) {
  855. ne = X509_NAME_get_entry( xn, i );
  856. if ( !OBJ_cmp( X509_NAME_ENTRY_get_object(ne), obj )) {
  857. cn = X509_NAME_ENTRY_get_data( ne );
  858. break;
  859. }
  860. }
  861. if( !cn )
  862. {
  863. no_cn:
  864. Debug0( LDAP_DEBUG_ANY,
  865. "TLS: unable to get common name from peer certificate.\n" );
  866. ret = LDAP_CONNECT_ERROR;
  867. if ( ld->ld_error ) {
  868. LDAP_FREE( ld->ld_error );
  869. }
  870. ld->ld_error = LDAP_STRDUP(
  871. _("TLS: unable to get CN from peer certificate"));
  872. } else if ( cn->length == nlen &&
  873. strncasecmp( name, (char *) cn->data, nlen ) == 0 ) {
  874. ret = LDAP_SUCCESS;
  875. } else if (( cn->data[0] == '*' ) && ( cn->data[1] == '.' )) {
  876. char *domain = strchr(name, '.');
  877. if( domain ) {
  878. int dlen;
  879. dlen = nlen - (domain-name);
  880. /* Is this a wildcard match? */
  881. if ((dlen == cn->length-1) &&
  882. !strncasecmp(domain, (char *) &cn->data[1], dlen)) {
  883. ret = LDAP_SUCCESS;
  884. }
  885. }
  886. }
  887. if( ret == LDAP_LOCAL_ERROR ) {
  888. Debug3( LDAP_DEBUG_ANY, "TLS: hostname (%s) does not match "
  889. "common name in certificate (%.*s).\n",
  890. name, cn->length, cn->data );
  891. ret = LDAP_CONNECT_ERROR;
  892. if ( ld->ld_error ) {
  893. LDAP_FREE( ld->ld_error );
  894. }
  895. ld->ld_error = LDAP_STRDUP(
  896. _("TLS: hostname does not match name in peer certificate"));
  897. }
  898. }
  899. done:
  900. X509_free(x);
  901. return ret;
  902. }
  903. static int
  904. tlso_session_strength( tls_session *sess )
  905. {
  906. tlso_session *s = (tlso_session *)sess;
  907. return SSL_CIPHER_get_bits(SSL_get_current_cipher(s), NULL);
  908. }
  909. static int
  910. tlso_session_unique( tls_session *sess, struct berval *buf, int is_server)
  911. {
  912. tlso_session *s = (tlso_session *)sess;
  913. /* Usually the client sends the finished msg. But if the
  914. * session was resumed, the server sent the msg.
  915. */
  916. if (SSL_session_reused(s) ^ !is_server)
  917. buf->bv_len = SSL_get_finished(s, buf->bv_val, buf->bv_len);
  918. else
  919. buf->bv_len = SSL_get_peer_finished(s, buf->bv_val, buf->bv_len);
  920. return buf->bv_len;
  921. }
  922. static int
  923. tlso_session_endpoint( tls_session *sess, struct berval *buf, int is_server )
  924. {
  925. tlso_session *s = (tlso_session *)sess;
  926. const EVP_MD *md;
  927. unsigned int md_len;
  928. X509 *cert;
  929. if ( buf->bv_len < EVP_MAX_MD_SIZE )
  930. return 0;
  931. if ( is_server )
  932. cert = SSL_get_certificate( s );
  933. else
  934. cert = SSL_get_peer_certificate( s );
  935. if ( cert == NULL )
  936. return 0;
  937. #if OPENSSL_VERSION_NUMBER >= 0x10100000
  938. md = EVP_get_digestbynid( X509_get_signature_nid( cert ));
  939. #else
  940. md = EVP_get_digestbynid(OBJ_obj2nid( cert->sig_alg->algorithm ));
  941. #endif
  942. /* See RFC 5929 */
  943. if ( md == NULL ||
  944. md == EVP_md_null() ||
  945. #ifndef OPENSSL_NO_MD2
  946. md == EVP_md2() ||
  947. #endif
  948. #ifndef OPENSSL_NO_MD4
  949. md == EVP_md4() ||
  950. #endif
  951. #ifndef OPENSSL_NO_MD5
  952. md == EVP_md5() ||
  953. #endif
  954. md == EVP_sha1() )
  955. md = EVP_sha256();
  956. if ( !X509_digest( cert, md, (unsigned char *) (buf->bv_val), &md_len ))
  957. md_len = 0;
  958. buf->bv_len = md_len;
  959. if ( !is_server )
  960. X509_free( cert );
  961. return md_len;
  962. }
  963. static const char *
  964. tlso_session_version( tls_session *sess )
  965. {
  966. tlso_session *s = (tlso_session *)sess;
  967. return SSL_get_version(s);
  968. }
  969. static const char *
  970. tlso_session_cipher( tls_session *sess )
  971. {
  972. tlso_session *s = (tlso_session *)sess;
  973. return SSL_CIPHER_get_name(SSL_get_current_cipher(s));
  974. }
  975. static int
  976. tlso_session_peercert( tls_session *sess, struct berval *der )
  977. {
  978. tlso_session *s = (tlso_session *)sess;
  979. int ret = -1;
  980. X509 *x = SSL_get_peer_certificate(s);
  981. if ( x ) {
  982. der->bv_len = i2d_X509(x, NULL);
  983. der->bv_val = LDAP_MALLOC(der->bv_len);
  984. if ( der->bv_val ) {
  985. unsigned char *ptr = (unsigned char *) (der->bv_val);
  986. i2d_X509(x, &ptr);
  987. ret = 0;
  988. }
  989. X509_free( x );
  990. }
  991. return ret;
  992. }
  993. static int
  994. tlso_session_pinning( LDAP *ld, tls_session *sess, char *hashalg, struct berval *hash )
  995. {
  996. tlso_session *s = (tlso_session *)sess;
  997. unsigned char *tmp, digest[EVP_MAX_MD_SIZE];
  998. struct berval key,
  999. keyhash = { sizeof(digest), (char *) digest };
  1000. X509 *cert = SSL_get_peer_certificate(s);
  1001. int len, rc = LDAP_SUCCESS;
  1002. if ( !cert )
  1003. return -1;
  1004. len = i2d_X509_PUBKEY( X509_get_X509_PUBKEY(cert), NULL );
  1005. tmp = LDAP_MALLOC( len );
  1006. key.bv_val = (char *) tmp;
  1007. if ( !key.bv_val ) {
  1008. rc = -1;
  1009. goto done;
  1010. }
  1011. key.bv_len = i2d_X509_PUBKEY( X509_get_X509_PUBKEY(cert), &tmp );
  1012. if ( hashalg ) {
  1013. const EVP_MD *md;
  1014. EVP_MD_CTX *mdctx;
  1015. unsigned int len = keyhash.bv_len;
  1016. md = EVP_get_digestbyname( hashalg );
  1017. if ( !md ) {
  1018. Debug1( LDAP_DEBUG_TRACE, "tlso_session_pinning: "
  1019. "hash %s not recognised by OpenSSL\n", hashalg );
  1020. rc = -1;
  1021. goto done;
  1022. }
  1023. #if OPENSSL_VERSION_NUMBER >= 0x10100000
  1024. mdctx = EVP_MD_CTX_new();
  1025. #else
  1026. mdctx = EVP_MD_CTX_create();
  1027. #endif
  1028. if ( !mdctx ) {
  1029. rc = -1;
  1030. goto done;
  1031. }
  1032. EVP_DigestInit_ex( mdctx, md, NULL );
  1033. EVP_DigestUpdate( mdctx, key.bv_val, key.bv_len );
  1034. EVP_DigestFinal_ex( mdctx, (unsigned char *)keyhash.bv_val, &len );
  1035. keyhash.bv_len = len;
  1036. #if OPENSSL_VERSION_NUMBER >= 0x10100000
  1037. EVP_MD_CTX_free( mdctx );
  1038. #else
  1039. EVP_MD_CTX_destroy( mdctx );
  1040. #endif
  1041. } else {
  1042. keyhash = key;
  1043. }
  1044. if ( ber_bvcmp( hash, &keyhash ) ) {
  1045. rc = LDAP_CONNECT_ERROR;
  1046. Debug0( LDAP_DEBUG_ANY, "tlso_session_pinning: "
  1047. "public key hash does not match provided pin.\n" );
  1048. if ( ld->ld_error ) {
  1049. LDAP_FREE( ld->ld_error );
  1050. }
  1051. ld->ld_error = LDAP_STRDUP(
  1052. _("TLS: public key hash does not match provided pin"));
  1053. }
  1054. done:
  1055. LDAP_FREE( key.bv_val );
  1056. X509_free( cert );
  1057. return rc;
  1058. }
  1059. /*
  1060. * TLS support for LBER Sockbufs
  1061. */
  1062. struct tls_data {
  1063. tlso_session *session;
  1064. Sockbuf_IO_Desc *sbiod;
  1065. };
  1066. #if OPENSSL_VERSION_NUMBER < 0x10100000
  1067. #define BIO_set_init(b, x) b->init = x
  1068. #define BIO_set_data(b, x) b->ptr = x
  1069. #define BIO_clear_flags(b, x) b->flags &= ~(x)
  1070. #define BIO_get_data(b) b->ptr
  1071. #endif
  1072. static int
  1073. tlso_bio_create( BIO *b ) {
  1074. BIO_set_init( b, 1 );
  1075. BIO_set_data( b, NULL );
  1076. BIO_clear_flags( b, ~0 );
  1077. return 1;
  1078. }
  1079. static int
  1080. tlso_bio_destroy( BIO *b )
  1081. {
  1082. if ( b == NULL ) return 0;
  1083. BIO_set_data( b, NULL ); /* sb_tls_remove() will free it */
  1084. BIO_set_init( b, 0 );
  1085. BIO_clear_flags( b, ~0 );
  1086. return 1;
  1087. }
  1088. static int
  1089. tlso_bio_read( BIO *b, char *buf, int len )
  1090. {
  1091. struct tls_data *p;
  1092. int ret;
  1093. if ( buf == NULL || len <= 0 ) return 0;
  1094. p = (struct tls_data *)BIO_get_data(b);
  1095. if ( p == NULL || p->sbiod == NULL ) {
  1096. return 0;
  1097. }
  1098. ret = LBER_SBIOD_READ_NEXT( p->sbiod, buf, len );
  1099. BIO_clear_retry_flags( b );
  1100. if ( ret < 0 ) {
  1101. int err = sock_errno();
  1102. if ( err == EAGAIN || err == EWOULDBLOCK ) {
  1103. BIO_set_retry_read( b );
  1104. }
  1105. }
  1106. return ret;
  1107. }
  1108. static int
  1109. tlso_bio_write( BIO *b, const char *buf, int len )
  1110. {
  1111. struct tls_data *p;
  1112. int ret;
  1113. if ( buf == NULL || len <= 0 ) return 0;
  1114. p = (struct tls_data *)BIO_get_data(b);
  1115. if ( p == NULL || p->sbiod == NULL ) {
  1116. return 0;
  1117. }
  1118. ret = LBER_SBIOD_WRITE_NEXT( p->sbiod, (char *)buf, len );
  1119. BIO_clear_retry_flags( b );
  1120. if ( ret < 0 ) {
  1121. int err = sock_errno();
  1122. if ( err == EAGAIN || err == EWOULDBLOCK ) {
  1123. BIO_set_retry_write( b );
  1124. }
  1125. }
  1126. return ret;
  1127. }
  1128. static long
  1129. tlso_bio_ctrl( BIO *b, int cmd, long num, void *ptr )
  1130. {
  1131. if ( cmd == BIO_CTRL_FLUSH ) {
  1132. /* The OpenSSL library needs this */
  1133. return 1;
  1134. }
  1135. return 0;
  1136. }
  1137. static int
  1138. tlso_bio_gets( BIO *b, char *buf, int len )
  1139. {
  1140. return -1;
  1141. }
  1142. static int
  1143. tlso_bio_puts( BIO *b, const char *str )
  1144. {
  1145. return tlso_bio_write( b, str, strlen( str ) );
  1146. }
  1147. static BIO_METHOD *
  1148. tlso_bio_setup( void )
  1149. {
  1150. /* it's a source/sink BIO */
  1151. BIO_METHOD * method = BIO_meth_new( 100 | 0x400, "sockbuf glue" );
  1152. BIO_meth_set_write( method, tlso_bio_write );
  1153. BIO_meth_set_read( method, tlso_bio_read );
  1154. BIO_meth_set_puts( method, tlso_bio_puts );
  1155. BIO_meth_set_gets( method, tlso_bio_gets );
  1156. BIO_meth_set_ctrl( method, tlso_bio_ctrl );
  1157. BIO_meth_set_create( method, tlso_bio_create );
  1158. BIO_meth_set_destroy( method, tlso_bio_destroy );
  1159. return method;
  1160. }
  1161. static int
  1162. tlso_sb_setup( Sockbuf_IO_Desc *sbiod, void *arg )
  1163. {
  1164. struct tls_data *p;
  1165. BIO *bio;
  1166. assert( sbiod != NULL );
  1167. p = LBER_MALLOC( sizeof( *p ) );
  1168. if ( p == NULL ) {
  1169. return -1;
  1170. }
  1171. p->session = arg;
  1172. p->sbiod = sbiod;
  1173. bio = BIO_new( tlso_bio_method );
  1174. BIO_set_data( bio, p );
  1175. SSL_set_bio( p->session, bio, bio );
  1176. sbiod->sbiod_pvt = p;
  1177. return 0;
  1178. }
  1179. static int
  1180. tlso_sb_remove( Sockbuf_IO_Desc *sbiod )
  1181. {
  1182. struct tls_data *p;
  1183. assert( sbiod != NULL );
  1184. assert( sbiod->sbiod_pvt != NULL );
  1185. p = (struct tls_data *)sbiod->sbiod_pvt;
  1186. SSL_free( p->session );
  1187. LBER_FREE( sbiod->sbiod_pvt );
  1188. sbiod->sbiod_pvt = NULL;
  1189. return 0;
  1190. }
  1191. static int
  1192. tlso_sb_close( Sockbuf_IO_Desc *sbiod )
  1193. {
  1194. struct tls_data *p;
  1195. assert( sbiod != NULL );
  1196. assert( sbiod->sbiod_pvt != NULL );
  1197. p = (struct tls_data *)sbiod->sbiod_pvt;
  1198. SSL_shutdown( p->session );
  1199. return 0;
  1200. }
  1201. static int
  1202. tlso_sb_ctrl( Sockbuf_IO_Desc *sbiod, int opt, void *arg )
  1203. {
  1204. struct tls_data *p;
  1205. assert( sbiod != NULL );
  1206. assert( sbiod->sbiod_pvt != NULL );
  1207. p = (struct tls_data *)sbiod->sbiod_pvt;
  1208. if ( opt == LBER_SB_OPT_GET_SSL ) {
  1209. *((tlso_session **)arg) = p->session;
  1210. return 1;
  1211. } else if ( opt == LBER_SB_OPT_DATA_READY ) {
  1212. if( SSL_pending( p->session ) > 0 ) {
  1213. return 1;
  1214. }
  1215. }
  1216. return LBER_SBIOD_CTRL_NEXT( sbiod, opt, arg );
  1217. }
  1218. static ber_slen_t
  1219. tlso_sb_read( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
  1220. {
  1221. struct tls_data *p;
  1222. ber_slen_t ret;
  1223. int err;
  1224. assert( sbiod != NULL );
  1225. assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
  1226. p = (struct tls_data *)sbiod->sbiod_pvt;
  1227. ret = SSL_read( p->session, (char *)buf, len );
  1228. #ifdef HAVE_WINSOCK
  1229. errno = WSAGetLastError();
  1230. #endif
  1231. err = SSL_get_error( p->session, ret );
  1232. if (err == SSL_ERROR_WANT_READ ) {
  1233. sbiod->sbiod_sb->sb_trans_needs_read = 1;
  1234. sock_errset(EWOULDBLOCK);
  1235. }
  1236. else
  1237. sbiod->sbiod_sb->sb_trans_needs_read = 0;
  1238. return ret;
  1239. }
  1240. static ber_slen_t
  1241. tlso_sb_write( Sockbuf_IO_Desc *sbiod, void *buf, ber_len_t len)
  1242. {
  1243. struct tls_data *p;
  1244. ber_slen_t ret;
  1245. int err;
  1246. assert( sbiod != NULL );
  1247. assert( SOCKBUF_VALID( sbiod->sbiod_sb ) );
  1248. p = (struct tls_data *)sbiod->sbiod_pvt;
  1249. ret = SSL_write( p->session, (char *)buf, len );
  1250. #ifdef HAVE_WINSOCK
  1251. errno = WSAGetLastError();
  1252. #endif
  1253. err = SSL_get_error( p->session, ret );
  1254. if (err == SSL_ERROR_WANT_WRITE ) {
  1255. sbiod->sbiod_sb->sb_trans_needs_write = 1;
  1256. sock_errset(EWOULDBLOCK);
  1257. } else {
  1258. sbiod->sbiod_sb->sb_trans_needs_write = 0;
  1259. }
  1260. return ret;
  1261. }
  1262. static Sockbuf_IO tlso_sbio =
  1263. {
  1264. tlso_sb_setup, /* sbi_setup */
  1265. tlso_sb_remove, /* sbi_remove */
  1266. tlso_sb_ctrl, /* sbi_ctrl */
  1267. tlso_sb_read, /* sbi_read */
  1268. tlso_sb_write, /* sbi_write */
  1269. tlso_sb_close /* sbi_close */
  1270. };
  1271. /* Derived from openssl/apps/s_cb.c */
  1272. static void
  1273. tlso_info_cb( const SSL *ssl, int where, int ret )
  1274. {
  1275. int w;
  1276. char *op;
  1277. char *state = (char *) SSL_state_string_long( (SSL *)ssl );
  1278. w = where & ~SSL_ST_MASK;
  1279. if ( w & SSL_ST_CONNECT ) {
  1280. op = "SSL_connect";
  1281. } else if ( w & SSL_ST_ACCEPT ) {
  1282. op = "SSL_accept";
  1283. } else {
  1284. op = "undefined";
  1285. }
  1286. #ifdef HAVE_EBCDIC
  1287. if ( state ) {
  1288. state = LDAP_STRDUP( state );
  1289. __etoa( state );
  1290. }
  1291. #endif
  1292. if ( where & SSL_CB_LOOP ) {
  1293. Debug2( LDAP_DEBUG_TRACE,
  1294. "TLS trace: %s:%s\n",
  1295. op, state );
  1296. } else if ( where & SSL_CB_ALERT ) {
  1297. char *atype = (char *) SSL_alert_type_string_long( ret );
  1298. char *adesc = (char *) SSL_alert_desc_string_long( ret );
  1299. op = ( where & SSL_CB_READ ) ? "read" : "write";
  1300. #ifdef HAVE_EBCDIC
  1301. if ( atype ) {
  1302. atype = LDAP_STRDUP( atype );
  1303. __etoa( atype );
  1304. }
  1305. if ( adesc ) {
  1306. adesc = LDAP_STRDUP( adesc );
  1307. __etoa( adesc );
  1308. }
  1309. #endif
  1310. Debug3( LDAP_DEBUG_TRACE,
  1311. "TLS trace: SSL3 alert %s:%s:%s\n",
  1312. op, atype, adesc );
  1313. #ifdef HAVE_EBCDIC
  1314. if ( atype ) LDAP_FREE( atype );
  1315. if ( adesc ) LDAP_FREE( adesc );
  1316. #endif
  1317. } else if ( where & SSL_CB_EXIT ) {
  1318. if ( ret == 0 ) {
  1319. Debug2( LDAP_DEBUG_TRACE,
  1320. "TLS trace: %s:failed in %s\n",
  1321. op, state );
  1322. } else if ( ret < 0 ) {
  1323. Debug2( LDAP_DEBUG_TRACE,
  1324. "TLS trace: %s:error in %s\n",
  1325. op, state );
  1326. }
  1327. }
  1328. #ifdef HAVE_EBCDIC
  1329. if ( state ) LDAP_FREE( state );
  1330. #endif
  1331. }
  1332. static int
  1333. tlso_verify_cb( int ok, X509_STORE_CTX *ctx )
  1334. {
  1335. X509 *cert;
  1336. int errnum;
  1337. int errdepth;
  1338. X509_NAME *subject;
  1339. X509_NAME *issuer;
  1340. char *sname;
  1341. char *iname;
  1342. char *certerr = NULL;
  1343. cert = X509_STORE_CTX_get_current_cert( ctx );
  1344. errnum = X509_STORE_CTX_get_error( ctx );
  1345. errdepth = X509_STORE_CTX_get_error_depth( ctx );
  1346. /*
  1347. * X509_get_*_name return pointers to the internal copies of
  1348. * those things requested. So do not free them.
  1349. */
  1350. subject = X509_get_subject_name( cert );
  1351. issuer = X509_get_issuer_name( cert );
  1352. /* X509_NAME_oneline, if passed a NULL buf, allocate memory */
  1353. sname = X509_NAME_oneline( subject, NULL, 0 );
  1354. iname = X509_NAME_oneline( issuer, NULL, 0 );
  1355. if ( !ok ) certerr = (char *)X509_verify_cert_error_string( errnum );
  1356. #ifdef HAVE_EBCDIC
  1357. if ( sname ) __etoa( sname );
  1358. if ( iname ) __etoa( iname );
  1359. if ( certerr ) {
  1360. certerr = LDAP_STRDUP( certerr );
  1361. __etoa( certerr );
  1362. }
  1363. #endif
  1364. Debug3( LDAP_DEBUG_TRACE,
  1365. "TLS certificate verification: depth: %d, err: %d, subject: %s,",
  1366. errdepth, errnum,
  1367. sname ? sname : "-unknown-" );
  1368. Debug1( LDAP_DEBUG_TRACE, " issuer: %s\n", iname ? iname : "-unknown-" );
  1369. if ( !ok ) {
  1370. Debug1( LDAP_DEBUG_ANY,
  1371. "TLS certificate verification: Error, %s\n",
  1372. certerr );
  1373. }
  1374. if ( sname )
  1375. OPENSSL_free ( sname );
  1376. if ( iname )
  1377. OPENSSL_free ( iname );
  1378. #ifdef HAVE_EBCDIC
  1379. if ( certerr ) LDAP_FREE( certerr );
  1380. #endif
  1381. return ok;
  1382. }
  1383. static int
  1384. tlso_verify_ok( int ok, X509_STORE_CTX *ctx )
  1385. {
  1386. (void) tlso_verify_cb( ok, ctx );
  1387. return 1;
  1388. }
  1389. /* Inspired by ERR_print_errors in OpenSSL */
  1390. static void
  1391. tlso_report_error( char *errmsg )
  1392. {
  1393. unsigned long l;
  1394. char buf[ERRBUFSIZE];
  1395. const char *file;
  1396. int line;
  1397. while ( ( l = ERR_get_error_line( &file, &line ) ) != 0 ) {
  1398. ERR_error_string_n( l, buf, ERRBUFSIZE );
  1399. if ( !*errmsg )
  1400. strcpy(errmsg, buf );
  1401. #ifdef HAVE_EBCDIC
  1402. if ( file ) {
  1403. file = LDAP_STRDUP( file );
  1404. __etoa( (char *)file );
  1405. }
  1406. __etoa( buf );
  1407. #endif
  1408. Debug3( LDAP_DEBUG_ANY, "TLS: %s %s:%d\n",
  1409. buf, file, line );
  1410. #ifdef HAVE_EBCDIC
  1411. if ( file ) LDAP_FREE( (void *)file );
  1412. #endif
  1413. }
  1414. }
  1415. #if OPENSSL_VERSION_NUMBER < 0x10100000
  1416. static RSA *
  1417. tlso_tmp_rsa_cb( SSL *ssl, int is_export, int key_length )
  1418. {
  1419. RSA *tmp_rsa;
  1420. /* FIXME: Pregenerate the key on startup */
  1421. /* FIXME: Who frees the key? */
  1422. BIGNUM *bn = BN_new();
  1423. tmp_rsa = NULL;
  1424. if ( bn ) {
  1425. if ( BN_set_word( bn, RSA_F4 )) {
  1426. tmp_rsa = RSA_new();
  1427. if ( tmp_rsa && !RSA_generate_key_ex( tmp_rsa, key_length, bn, NULL )) {
  1428. RSA_free( tmp_rsa );
  1429. tmp_rsa = NULL;
  1430. }
  1431. }
  1432. BN_free( bn );
  1433. }
  1434. if ( !tmp_rsa ) {
  1435. Debug2( LDAP_DEBUG_ANY,
  1436. "TLS: Failed to generate temporary %d-bit %s RSA key\n",
  1437. key_length, is_export ? "export" : "domestic" );
  1438. }
  1439. return tmp_rsa;
  1440. }
  1441. #endif /* OPENSSL_VERSION_NUMBER < 1.1 */
  1442. static int
  1443. tlso_seed_PRNG( const char *randfile )
  1444. {
  1445. #ifndef URANDOM_DEVICE
  1446. /* no /dev/urandom (or equiv) */
  1447. long total=0;
  1448. char buffer[MAXPATHLEN];
  1449. if (randfile == NULL) {
  1450. /* The seed file is $RANDFILE if defined, otherwise $HOME/.rnd.
  1451. * If $HOME is not set or buffer too small to hold the pathname,
  1452. * an error occurs. - From RAND_file_name() man page.
  1453. * The fact is that when $HOME is NULL, .rnd is used.
  1454. */
  1455. randfile = RAND_file_name( buffer, sizeof( buffer ) );
  1456. }
  1457. #ifndef OPENSSL_NO_EGD
  1458. else if (RAND_egd(randfile) > 0) {
  1459. /* EGD socket */
  1460. return 0;
  1461. }
  1462. #endif
  1463. if (randfile == NULL) {
  1464. Debug0( LDAP_DEBUG_ANY,
  1465. "TLS: Use configuration file or $RANDFILE to define seed PRNG\n" );
  1466. return -1;
  1467. }
  1468. total = RAND_load_file(randfile, -1);
  1469. if (RAND_status() == 0) {
  1470. Debug0( LDAP_DEBUG_ANY,
  1471. "TLS: PRNG not been seeded with enough data\n" );
  1472. return -1;
  1473. }
  1474. /* assume if there was enough bits to seed that it's okay
  1475. * to write derived bits to the file
  1476. */
  1477. RAND_write_file(randfile);
  1478. #endif
  1479. return 0;
  1480. }
  1481. tls_impl ldap_int_tls_impl = {
  1482. "OpenSSL",
  1483. tlso_init,
  1484. tlso_destroy,
  1485. tlso_ctx_new,
  1486. tlso_ctx_ref,
  1487. tlso_ctx_free,
  1488. tlso_ctx_init,
  1489. tlso_session_new,
  1490. tlso_session_connect,
  1491. tlso_session_accept,
  1492. tlso_session_upflags,
  1493. tlso_session_errmsg,
  1494. tlso_session_my_dn,
  1495. tlso_session_peer_dn,
  1496. tlso_session_chkhost,
  1497. tlso_session_strength,
  1498. tlso_session_unique,
  1499. tlso_session_endpoint,
  1500. tlso_session_version,
  1501. tlso_session_cipher,
  1502. tlso_session_peercert,
  1503. tlso_session_pinning,
  1504. &tlso_sbio,
  1505. #ifdef LDAP_R_COMPILE
  1506. tlso_thr_init,
  1507. #else
  1508. NULL,
  1509. #endif
  1510. 0
  1511. };
  1512. #endif /* HAVE_OPENSSL */