tls_o.c 40 KB

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