tls_o.c 40 KB

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