ssl.c 117 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170
  1. /** BEGIN COPYRIGHT BLOCK
  2. * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission.
  3. * Copyright (C) 2005 Red Hat, Inc.
  4. * All rights reserved.
  5. *
  6. * License: GPL (version 3 or any later version).
  7. * See LICENSE for details.
  8. * END COPYRIGHT BLOCK **/
  9. #ifdef HAVE_CONFIG_H
  10. # include <config.h>
  11. #endif
  12. /* SSL-related stuff for slapd */
  13. #include <stdio.h>
  14. #include <sys/param.h>
  15. #include <ssl.h>
  16. #include <nss.h>
  17. #include <key.h>
  18. #include <sslproto.h>
  19. #include "secmod.h"
  20. #include <string.h>
  21. #include <errno.h>
  22. #define NEED_TOK_PBE /* defines tokPBE and ptokPBE - see slap.h */
  23. #include "slap.h"
  24. #include "svrcore.h"
  25. #include "fe.h"
  26. #include "certdb.h"
  27. #if !defined(USE_OPENLDAP)
  28. #include "ldap_ssl.h"
  29. #endif
  30. /* For IRIX... */
  31. #ifndef MAXPATHLEN
  32. #define MAXPATHLEN 1024
  33. #endif
  34. #if NSS_VMAJOR * 100 + NSS_VMINOR >= 315
  35. /* TLS1.2 is defined in RFC5246. */
  36. #define NSS_TLS12 1
  37. #elif NSS_VMAJOR * 100 + NSS_VMINOR >= 314
  38. /* TLS1.1 is defined in RFC4346. */
  39. #define NSS_TLS11 1
  40. #else
  41. #define NSS_TLS10 1
  42. #endif
  43. #if NSS_VMAJOR * 100 + NSS_VMINOR >= 320
  44. #define HAVE_NSS_DHE 1
  45. #endif
  46. /******************************************************************************
  47. * Default SSL Version Rule
  48. * Old SSL version attributes:
  49. * nsSSL3: off -- nsSSL3 == SSL_LIBRARY_VERSION_3_0
  50. * nsTLS1: on -- nsTLS1 == SSL_LIBRARY_VERSION_TLS_1_0 and greater
  51. * Note: TLS1.0 is defined in RFC2246, which is close to SSL 3.0.
  52. * New SSL version attributes:
  53. * sslVersionMin: TLS1.0
  54. * sslVersionMax: max ssl version supported by NSS
  55. ******************************************************************************/
  56. #define DEFVERSION "TLS1.0"
  57. #define CURRENT_DEFAULT_SSL_VERSION SSL_LIBRARY_VERSION_TLS_1_0
  58. extern char* slapd_SSL3ciphers;
  59. extern symbol_t supported_ciphers[];
  60. #if !defined(NSS_TLS10) /* NSS_TLS11 or newer */
  61. static SSLVersionRange enabledNSSVersions;
  62. static SSLVersionRange slapdNSSVersions;
  63. #endif
  64. /* dongle_file_name is set in slapd_nss_init when we set the path for the
  65. key, cert, and secmod files - the dongle file must be in the same directory
  66. and use the same naming scheme
  67. */
  68. static char* dongle_file_name = NULL;
  69. static int _security_library_initialized = 0;
  70. static int _ssl_listener_initialized = 0;
  71. static int _nss_initialized = 0;
  72. /* Our name for the internal token, must match PKCS-11 config data below */
  73. static char *internalTokenName = "Internal (Software) Token";
  74. static int stimeout;
  75. static char *ciphers = NULL;
  76. static char * configDN = "cn=encryption,cn=config";
  77. /* Copied from libadmin/libadmin.h public/nsapi.h */
  78. #define SERVER_KEY_NAME "Server-Key"
  79. #define MAGNUS_ERROR_LEN 1024
  80. #define LOG_WARN 0
  81. #define LOG_FAILURE 3
  82. #define FILE_PATHSEP '/'
  83. /* ----------------------- Multiple cipher support ------------------------ */
  84. /* cipher set flags */
  85. #define CIPHER_SET_NONE 0x0
  86. #define CIPHER_SET_ALL 0x1
  87. #define CIPHER_SET_DEFAULT 0x2
  88. #define CIPHER_SET_DEFAULTWEAKCIPHER 0x10 /* allowWeakCipher is not set in cn=encryption */
  89. #define CIPHER_SET_ALLOWWEAKCIPHER 0x20 /* allowWeakCipher is on */
  90. #define CIPHER_SET_DISALLOWWEAKCIPHER 0x40 /* allowWeakCipher is off */
  91. #ifdef HAVE_NSS_DHE
  92. #define CIPHER_SET_DEFAULTWEAKDHPARAM 0x100 /* allowWeakDhParam is not set in cn=encryption */
  93. #define CIPHER_SET_ALLOWWEAKDHPARAM 0x200 /* allowWeakDhParam is on */
  94. #define CIPHER_SET_DISALLOWWEAKDHPARAM 0x400 /* allowWeakDhParam is off */
  95. #endif
  96. #define CIPHER_SET_ISDEFAULT(flag) \
  97. (((flag)&CIPHER_SET_DEFAULT) ? PR_TRUE : PR_FALSE)
  98. #define CIPHER_SET_ISALL(flag) \
  99. (((flag)&CIPHER_SET_ALL) ? PR_TRUE : PR_FALSE)
  100. #define ALLOWWEAK_ISDEFAULT(flag) \
  101. (((flag)&CIPHER_SET_DEFAULTWEAKCIPHER) ? PR_TRUE : PR_FALSE)
  102. #define ALLOWWEAK_ISON(flag) \
  103. (((flag)&CIPHER_SET_ALLOWWEAKCIPHER) ? PR_TRUE : PR_FALSE)
  104. #define ALLOWWEAK_ISOFF(flag) \
  105. (((flag)&CIPHER_SET_DISALLOWWEAKCIPHER) ? PR_TRUE : PR_FALSE)
  106. /*
  107. * If ISALL or ISDEFAULT, allowWeakCipher is true only if CIPHER_SET_ALLOWWEAKCIPHER.
  108. * Otherwise (user specified cipher list), allowWeakCipher is true
  109. * if CIPHER_SET_ALLOWWEAKCIPHER or CIPHER_SET_DEFAULTWEAKCIPHER.
  110. */
  111. #define CIPHER_SET_ALLOWSWEAKCIPHER(flag) \
  112. ((CIPHER_SET_ISDEFAULT(flag)|CIPHER_SET_ISALL(flag)) ? \
  113. (ALLOWWEAK_ISON(flag) ? PR_TRUE : PR_FALSE) : \
  114. (!ALLOWWEAK_ISOFF(flag) ? PR_TRUE : PR_FALSE))
  115. #define CIPHER_SET_DISABLE_ALLOWSWEAKCIPHER(flag) \
  116. ((flag)&~CIPHER_SET_ALLOWWEAKCIPHER)
  117. /* flags */
  118. #define CIPHER_IS_DEFAULT 0x1
  119. #define CIPHER_MUST_BE_DISABLED 0x2
  120. #define CIPHER_IS_WEAK 0x4
  121. #define CIPHER_IS_DEPRECATED 0x8
  122. #ifdef HAVE_NSS_DHE
  123. static int allowweakdhparam = CIPHER_SET_DEFAULTWEAKDHPARAM;
  124. #endif
  125. static char **cipher_names = NULL;
  126. static char **enabled_cipher_names = NULL;
  127. typedef struct {
  128. char *name;
  129. int num;
  130. int flags;
  131. } cipherstruct;
  132. static cipherstruct *_conf_ciphers = NULL;
  133. static void _conf_init_ciphers();
  134. /*
  135. * This lookup table is for supporting the old cipher name.
  136. * Once swtiching to the NSS cipherSuiteName is done,
  137. * this lookup_cipher table can be removed.
  138. */
  139. typedef struct {
  140. char *alias;
  141. char *name;
  142. } lookup_cipher;
  143. static lookup_cipher _lookup_cipher[] = {
  144. {"rc4", "SSL_CK_RC4_128_WITH_MD5"},
  145. {"rc4export", "SSL_CK_RC4_128_EXPORT40_WITH_MD5"},
  146. {"rc2", "SSL_CK_RC2_128_CBC_WITH_MD5"},
  147. {"rc2export", "SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5"},
  148. /*{"idea", "SSL_EN_IDEA_128_CBC_WITH_MD5"}, */
  149. {"des", "SSL_CK_DES_64_CBC_WITH_MD5"},
  150. {"desede3", "SSL_CK_DES_192_EDE3_CBC_WITH_MD5"},
  151. {"rsa_rc4_128_md5", "TLS_RSA_WITH_RC4_128_MD5"},
  152. {"rsa_rc4_128_sha", "TLS_RSA_WITH_RC4_128_SHA"},
  153. {"rsa_3des_sha", "TLS_RSA_WITH_3DES_EDE_CBC_SHA"},
  154. {"tls_rsa_3des_sha", "TLS_RSA_WITH_3DES_EDE_CBC_SHA"},
  155. {"rsa_fips_3des_sha", "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA"},
  156. {"fips_3des_sha", "SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA"},
  157. {"rsa_des_sha", "TLS_RSA_WITH_DES_CBC_SHA"},
  158. {"rsa_fips_des_sha", "SSL_RSA_FIPS_WITH_DES_CBC_SHA"},
  159. {"fips_des_sha", "SSL_RSA_FIPS_WITH_DES_CBC_SHA"}, /* ditto */
  160. {"rsa_rc4_40_md5", "TLS_RSA_EXPORT_WITH_RC4_40_MD5"},
  161. {"tls_rsa_rc4_40_md5", "TLS_RSA_EXPORT_WITH_RC4_40_MD5"},
  162. {"rsa_rc2_40_md5", "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5"},
  163. {"tls_rsa_rc2_40_md5", "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5"},
  164. {"rsa_null_md5", "TLS_RSA_WITH_NULL_MD5"}, /* disabled by default */
  165. {"rsa_null_sha", "TLS_RSA_WITH_NULL_SHA"}, /* disabled by default */
  166. {"tls_rsa_export1024_with_rc4_56_sha", "TLS_RSA_EXPORT1024_WITH_RC4_56_SHA"},
  167. {"rsa_rc4_56_sha", "TLS_RSA_EXPORT1024_WITH_RC4_56_SHA"}, /* ditto */
  168. {"tls_rsa_export1024_with_des_cbc_sha", "TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA"},
  169. {"rsa_des_56_sha", "TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA"}, /* ditto */
  170. {"fortezza", ""}, /* deprecated */
  171. {"fortezza_rc4_128_sha", ""}, /* deprecated */
  172. {"fortezza_null", ""}, /* deprecated */
  173. /*{"dhe_dss_40_sha", SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, 0}, */
  174. {"dhe_dss_des_sha", "TLS_DHE_DSS_WITH_DES_CBC_SHA"},
  175. {"dhe_dss_3des_sha", "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"},
  176. {"dhe_rsa_40_sha", "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"},
  177. {"dhe_rsa_des_sha", "TLS_DHE_RSA_WITH_DES_CBC_SHA"},
  178. {"dhe_rsa_3des_sha", "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA"},
  179. {"tls_rsa_aes_128_sha", "TLS_RSA_WITH_AES_128_CBC_SHA"},
  180. {"rsa_aes_128_sha", "TLS_RSA_WITH_AES_128_CBC_SHA"}, /* ditto */
  181. {"tls_dh_dss_aes_128_sha", ""}, /* deprecated */
  182. {"tls_dh_rsa_aes_128_sha", ""}, /* deprecated */
  183. {"tls_dhe_dss_aes_128_sha", "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"},
  184. {"tls_dhe_rsa_aes_128_sha", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"},
  185. {"tls_rsa_aes_256_sha", "TLS_RSA_WITH_AES_256_CBC_SHA"},
  186. {"rsa_aes_256_sha", "TLS_RSA_WITH_AES_256_CBC_SHA"}, /* ditto */
  187. {"tls_dss_aes_256_sha", ""}, /* deprecated */
  188. {"tls_rsa_aes_256_sha", ""}, /* deprecated */
  189. {"tls_dhe_dss_aes_256_sha", "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"},
  190. {"tls_dhe_rsa_aes_256_sha", "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"},
  191. /*{"tls_dhe_dss_1024_des_sha", ""}, */
  192. {"tls_dhe_dss_1024_rc4_sha", "TLS_RSA_EXPORT1024_WITH_RC4_56_SHA"},
  193. {"tls_dhe_dss_rc4_128_sha", "TLS_DHE_DSS_WITH_RC4_128_SHA"},
  194. #if defined(NSS_TLS12)
  195. /* New in NSS 3.15 */
  196. {"tls_rsa_aes_128_gcm_sha", "TLS_RSA_WITH_AES_128_GCM_SHA256"},
  197. {"tls_dhe_rsa_aes_128_gcm_sha", "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"},
  198. {"tls_dhe_dss_aes_128_gcm_sha", NULL}, /* not available */
  199. #endif
  200. {NULL, NULL}
  201. };
  202. /* E.g., "SSL3", "TLS1.2", "Unknown SSL version: 0x0" */
  203. #define VERSION_STR_LENGTH 64
  204. /* Supported SSL versions */
  205. /* nsSSL2: on -- we don't allow this any more. */
  206. PRBool enableSSL2 = PR_FALSE;
  207. /*
  208. * nsSSL3: on -- disable SSLv3 by default.
  209. * Corresonding to SSL_LIBRARY_VERSION_3_0
  210. */
  211. PRBool enableSSL3 = PR_FALSE;
  212. /*
  213. * nsTLS1: on -- enable TLS1 by default.
  214. * Corresonding to SSL_LIBRARY_VERSION_TLS_1_0 and greater.
  215. */
  216. PRBool enableTLS1 = PR_TRUE;
  217. /*
  218. * OpenLDAP client library with OpenSSL (ticket 47536)
  219. */
  220. #define PEMEXT ".pem"
  221. /* CA cert pem file */
  222. static char *CACertPemFile = NULL;
  223. /* helper functions for openldap update. */
  224. static int slapd_extract_cert(Slapi_Entry *entry, int isCA);
  225. static int slapd_extract_key(Slapi_Entry *entry, char *token, PK11SlotInfo *slot);
  226. static void entrySetValue(Slapi_DN *sdn, char *type, char *value);
  227. static char *gen_pem_path(char *filename);
  228. static void
  229. slapd_SSL_report(int degree, char *fmt, va_list args)
  230. {
  231. char buf[2048];
  232. PR_vsnprintf( buf, sizeof(buf), fmt, args );
  233. LDAPDebug( LDAP_DEBUG_ANY, "SSL %s: %s\n",
  234. (degree == LOG_FAILURE) ? "failure" : "alert",
  235. buf, 0 );
  236. }
  237. void
  238. slapd_SSL_error(char *fmt, ...)
  239. {
  240. va_list args;
  241. va_start(args, fmt);
  242. slapd_SSL_report(LOG_FAILURE, fmt, args);
  243. va_end(args);
  244. }
  245. void
  246. slapd_SSL_warn(char *fmt, ...)
  247. {
  248. va_list args;
  249. va_start(args, fmt);
  250. slapd_SSL_report(LOG_WARN, fmt, args);
  251. va_end(args);
  252. }
  253. char **
  254. getSupportedCiphers()
  255. {
  256. SSLCipherSuiteInfo info;
  257. char *sep = "::";
  258. int number_of_ciphers = SSL_NumImplementedCiphers;
  259. int i;
  260. int idx = 0;
  261. PRBool isFIPS = slapd_pk11_isFIPS();
  262. _conf_init_ciphers();
  263. if ((cipher_names == NULL) && (_conf_ciphers)) {
  264. cipher_names = (char **)slapi_ch_calloc((number_of_ciphers + 1), sizeof(char *));
  265. for (i = 0 ; _conf_ciphers[i].name != NULL; i++ ) {
  266. SSL_GetCipherSuiteInfo((PRUint16)_conf_ciphers[i].num,&info,sizeof(info));
  267. /* only support FIPS approved ciphers in FIPS mode */
  268. if (!isFIPS || info.isFIPS) {
  269. cipher_names[idx++] = slapi_ch_smprintf("%s%s%s%s%s%s%d",
  270. _conf_ciphers[i].name,sep,
  271. info.symCipherName,sep,
  272. info.macAlgorithmName,sep,
  273. info.symKeyBits);
  274. }
  275. }
  276. cipher_names[idx] = NULL;
  277. }
  278. return cipher_names;
  279. }
  280. #ifdef HAVE_NSS_DHE
  281. int
  282. get_allow_weak_dh_param(Slapi_Entry *e)
  283. {
  284. /* Check if the user wants weak params */
  285. int allow = CIPHER_SET_DEFAULTWEAKDHPARAM;
  286. char *val;
  287. val = slapi_entry_attr_get_charptr(e, "allowWeakDHParam");
  288. if (val) {
  289. if (!PL_strcasecmp(val, "off") || !PL_strcasecmp(val, "false") ||
  290. !PL_strcmp(val, "0") || !PL_strcasecmp(val, "no")) {
  291. allow = CIPHER_SET_DISALLOWWEAKDHPARAM;
  292. } else if (!PL_strcasecmp(val, "on") || !PL_strcasecmp(val, "true") ||
  293. !PL_strcmp(val, "1") || !PL_strcasecmp(val, "yes")) {
  294. allow = CIPHER_SET_ALLOWWEAKDHPARAM;
  295. slapd_SSL_warn("The value of allowWeakDHParam is set to %s. THIS EXPOSES YOU TO CVE-2015-4000.", val);
  296. } else {
  297. slapd_SSL_warn("The value of allowWeakDHParam \"%s\" is invalid.",
  298. "Ignoring it and set it to default.", val);
  299. }
  300. }
  301. slapi_ch_free((void **) &val);
  302. return allow;
  303. }
  304. #endif
  305. char **
  306. getEnabledCiphers()
  307. {
  308. SSLCipherSuiteInfo info;
  309. char *sep = "::";
  310. int number_of_ciphers = 0;
  311. int x;
  312. int idx = 0;
  313. PRBool enabled;
  314. /* We have to wait until the SSL initialization is done. */
  315. if (!slapd_ssl_listener_is_initialized()) {
  316. return NULL;
  317. }
  318. if ((enabled_cipher_names == NULL) && _conf_ciphers) {
  319. for (x = 0; _conf_ciphers[x].name; x++) {
  320. SSL_CipherPrefGetDefault(_conf_ciphers[x].num, &enabled);
  321. if (enabled) {
  322. number_of_ciphers++;
  323. }
  324. }
  325. enabled_cipher_names = (char **)slapi_ch_calloc((number_of_ciphers + 1), sizeof(char *));
  326. for (x = 0; _conf_ciphers[x].name; x++) {
  327. SSL_CipherPrefGetDefault(_conf_ciphers[x].num, &enabled);
  328. if (enabled) {
  329. SSL_GetCipherSuiteInfo((PRUint16)_conf_ciphers[x].num,&info,sizeof(info));
  330. enabled_cipher_names[idx++] = slapi_ch_smprintf("%s%s%s%s%s%s%d",
  331. _conf_ciphers[x].name,sep,
  332. info.symCipherName,sep,
  333. info.macAlgorithmName,sep,
  334. info.symKeyBits);
  335. }
  336. }
  337. }
  338. return enabled_cipher_names;
  339. }
  340. static PRBool
  341. cipher_check_fips(int idx, char ***suplist, char ***unsuplist)
  342. {
  343. PRBool rc = PR_TRUE;
  344. if (_conf_ciphers && slapd_pk11_isFIPS()) {
  345. SSLCipherSuiteInfo info;
  346. if (SECFailure == SSL_GetCipherSuiteInfo((PRUint16)_conf_ciphers[idx].num,
  347. &info, sizeof info)) {
  348. PRErrorCode errorCode = PR_GetError();
  349. if (slapi_is_loglevel_set(SLAPI_LOG_CONFIG)) {
  350. slapd_SSL_warn("Security Initialization: no information for cipher suite [%s] "
  351. "error %d - %s", _conf_ciphers[idx].name,
  352. errorCode, slapd_pr_strerror(errorCode));
  353. }
  354. rc = PR_FALSE;
  355. }
  356. if (rc && !info.isFIPS) {
  357. if (slapi_is_loglevel_set(SLAPI_LOG_CONFIG)) {
  358. slapd_SSL_warn("Security Initialization: FIPS mode is enabled but "
  359. "cipher suite [%s] is not approved for FIPS - "
  360. "the cipher suite will be disabled - if "
  361. "you want to use this cipher suite, you must use modutil to "
  362. "disable FIPS in the internal token.",
  363. _conf_ciphers[idx].name);
  364. }
  365. rc = PR_FALSE;
  366. }
  367. if (!rc && unsuplist && !charray_inlist(*unsuplist, _conf_ciphers[idx].name)) {
  368. charray_add(unsuplist, _conf_ciphers[idx].name);
  369. }
  370. if (rc && suplist && !charray_inlist(*suplist, _conf_ciphers[idx].name)) {
  371. charray_add(suplist, _conf_ciphers[idx].name);
  372. }
  373. }
  374. return rc;
  375. }
  376. int
  377. getSSLVersionInfo(int *ssl2, int *ssl3, int *tls1)
  378. {
  379. if (!slapd_ssl_listener_is_initialized()) {
  380. return -1;
  381. }
  382. *ssl2 = enableSSL2;
  383. *ssl3 = enableSSL3;
  384. *tls1 = enableTLS1;
  385. return 0;
  386. }
  387. int
  388. getSSLVersionRange(char **min, char **max)
  389. {
  390. if (!min && !max) {
  391. return -1;
  392. }
  393. if (!slapd_ssl_listener_is_initialized()) {
  394. if (min) {
  395. *min = slapi_getSSLVersion_str(LDAP_OPT_X_TLS_PROTOCOL_TLS1_0, NULL, 0);
  396. }
  397. if (max) {
  398. *max = slapi_getSSLVersion_str(LDAP_OPT_X_TLS_PROTOCOL_TLS1_2, NULL, 0);
  399. }
  400. return -1;
  401. }
  402. #if defined(NSS_TLS10)
  403. return -1; /* not supported */
  404. #else /* NSS_TLS11 or newer */
  405. if (min) {
  406. *min = slapi_getSSLVersion_str(slapdNSSVersions.min, NULL, 0);
  407. }
  408. if (max) {
  409. *max = slapi_getSSLVersion_str(slapdNSSVersions.max, NULL, 0);
  410. }
  411. return 0;
  412. #endif
  413. }
  414. #if defined(USE_OPENLDAP)
  415. void
  416. getSSLVersionRangeOL(int *min, int *max)
  417. {
  418. /* default range values */
  419. if (min) {
  420. *min = LDAP_OPT_X_TLS_PROTOCOL_TLS1_0;
  421. }
  422. if (max) {
  423. *max = LDAP_OPT_X_TLS_PROTOCOL_TLS1_2;
  424. }
  425. if (!slapd_ssl_listener_is_initialized()) {
  426. return;
  427. }
  428. #if defined(NSS_TLS10)
  429. *max = LDAP_OPT_X_TLS_PROTOCOL_TLS1_0;
  430. return;
  431. #else /* NSS_TLS11 or newer */
  432. if (min) {
  433. switch (slapdNSSVersions.min) {
  434. case SSL_LIBRARY_VERSION_3_0:
  435. *min = LDAP_OPT_X_TLS_PROTOCOL_SSL3;
  436. break;
  437. case SSL_LIBRARY_VERSION_TLS_1_0:
  438. *min = LDAP_OPT_X_TLS_PROTOCOL_TLS1_0;
  439. break;
  440. case SSL_LIBRARY_VERSION_TLS_1_1:
  441. *min = LDAP_OPT_X_TLS_PROTOCOL_TLS1_1;
  442. break;
  443. case SSL_LIBRARY_VERSION_TLS_1_2:
  444. *min = LDAP_OPT_X_TLS_PROTOCOL_TLS1_2;
  445. break;
  446. default:
  447. if (slapdNSSVersions.min > SSL_LIBRARY_VERSION_TLS_1_2) {
  448. *min = LDAP_OPT_X_TLS_PROTOCOL_TLS1_2 + 1;
  449. } else {
  450. *min = LDAP_OPT_X_TLS_PROTOCOL_SSL3;
  451. }
  452. break;
  453. }
  454. }
  455. if (max) {
  456. switch (slapdNSSVersions.max) {
  457. case SSL_LIBRARY_VERSION_3_0:
  458. *max = LDAP_OPT_X_TLS_PROTOCOL_SSL3;
  459. break;
  460. case SSL_LIBRARY_VERSION_TLS_1_0:
  461. *max = LDAP_OPT_X_TLS_PROTOCOL_TLS1_0;
  462. break;
  463. case SSL_LIBRARY_VERSION_TLS_1_1:
  464. *max = LDAP_OPT_X_TLS_PROTOCOL_TLS1_1;
  465. break;
  466. case SSL_LIBRARY_VERSION_TLS_1_2:
  467. *max = LDAP_OPT_X_TLS_PROTOCOL_TLS1_2;
  468. break;
  469. default:
  470. if (slapdNSSVersions.max > SSL_LIBRARY_VERSION_TLS_1_2) {
  471. *max = LDAP_OPT_X_TLS_PROTOCOL_TLS1_2 + 1;
  472. } else {
  473. *max = LDAP_OPT_X_TLS_PROTOCOL_SSL3;
  474. }
  475. break;
  476. }
  477. }
  478. return;
  479. #endif
  480. }
  481. #endif /* USE_OPENLDAP */
  482. static void
  483. _conf_init_ciphers()
  484. {
  485. int x;
  486. SECStatus rc;
  487. SSLCipherSuiteInfo info;
  488. const PRUint16 *implementedCiphers = SSL_GetImplementedCiphers();
  489. /* Initialize _conf_ciphers */
  490. if (_conf_ciphers) {
  491. return;
  492. }
  493. _conf_ciphers = (cipherstruct *)slapi_ch_calloc(SSL_NumImplementedCiphers + 1, sizeof(cipherstruct));
  494. for (x = 0; implementedCiphers && (x < SSL_NumImplementedCiphers); x++) {
  495. rc = SSL_GetCipherSuiteInfo(implementedCiphers[x], &info, sizeof info);
  496. if (SECFailure == rc) {
  497. slapi_log_error(SLAPI_LOG_FATAL, "SSL Initialization",
  498. "Warning: failed to get the cipher suite info of cipher ID %d\n",
  499. implementedCiphers[x]);
  500. continue;
  501. }
  502. if (!_conf_ciphers[x].num) { /* initialize each cipher */
  503. _conf_ciphers[x].name = slapi_ch_strdup(info.cipherSuiteName);
  504. _conf_ciphers[x].num = implementedCiphers[x];
  505. if (info.symCipher == ssl_calg_null) {
  506. _conf_ciphers[x].flags |= CIPHER_MUST_BE_DISABLED;
  507. } else {
  508. _conf_ciphers[x].flags |= info.isExportable?CIPHER_IS_WEAK:
  509. (info.symCipher < ssl_calg_3des)?CIPHER_IS_WEAK:
  510. (info.effectiveKeyBits < 128)?CIPHER_IS_WEAK:0;
  511. }
  512. }
  513. }
  514. return;
  515. }
  516. /*
  517. * flag: CIPHER_SET_ALL -- enable all
  518. * CIPHER_SET_NONE -- disable all
  519. * CIPHER_SET_DEFAULT -- set default ciphers
  520. * CIPHER_SET_ALLOW_WEAKCIPHER -- allow weak ciphers (can be or'ed with the ather CIPHER_SET flags)
  521. */
  522. static void
  523. _conf_setallciphers(int flag, char ***suplist, char ***unsuplist)
  524. {
  525. int x;
  526. SECStatus rc;
  527. PRBool setdefault = CIPHER_SET_ISDEFAULT(flag);
  528. PRBool enabled = CIPHER_SET_ISALL(flag);
  529. PRBool allowweakcipher = CIPHER_SET_ALLOWSWEAKCIPHER(flag);
  530. PRBool setme = PR_FALSE;
  531. const PRUint16 *implementedCiphers = SSL_GetImplementedCiphers();
  532. _conf_init_ciphers();
  533. for (x = 0; implementedCiphers && (x < SSL_NumImplementedCiphers); x++) {
  534. if (_conf_ciphers[x].flags & CIPHER_IS_DEFAULT) {
  535. /* certainly, not the first time. */
  536. setme = PR_TRUE;
  537. } else if (setdefault) {
  538. /*
  539. * SSL_CipherPrefGetDefault
  540. * If the application has not previously set the default preference,
  541. * SSL_CipherPrefGetDefault returns the factory setting.
  542. */
  543. rc = SSL_CipherPrefGetDefault(_conf_ciphers[x].num, &setme);
  544. if (SECFailure == rc) {
  545. slapi_log_error(SLAPI_LOG_FATAL, "SSL Initialization",
  546. "Warning: failed to get the default state of cipher %s\n",
  547. _conf_ciphers[x].name);
  548. continue;
  549. }
  550. if (!allowweakcipher && (_conf_ciphers[x].flags & CIPHER_IS_WEAK)) {
  551. setme = PR_FALSE;
  552. }
  553. _conf_ciphers[x].flags |= setme?CIPHER_IS_DEFAULT:0;
  554. } else if (enabled && !(_conf_ciphers[x].flags & CIPHER_MUST_BE_DISABLED)) {
  555. if (!allowweakcipher && (_conf_ciphers[x].flags & CIPHER_IS_WEAK)) {
  556. setme = PR_FALSE;
  557. } else {
  558. setme = PR_TRUE;
  559. }
  560. } else {
  561. setme = PR_FALSE;
  562. }
  563. if (setme) {
  564. setme = cipher_check_fips(x, suplist, unsuplist);
  565. }
  566. SSL_CipherPrefSetDefault(_conf_ciphers[x].num, setme);
  567. }
  568. }
  569. static char *
  570. charray2str(char **ary, const char *delim)
  571. {
  572. char *str = NULL;
  573. while (ary && *ary) {
  574. if (str) {
  575. str = PR_sprintf_append(str, "%s%s", delim, *ary++);
  576. } else {
  577. str = slapi_ch_smprintf("%s", *ary++);
  578. }
  579. }
  580. return str;
  581. }
  582. void
  583. _conf_dumpciphers()
  584. {
  585. int x;
  586. PRBool enabled;
  587. /* {"SSL3","rc4", SSL_EN_RC4_128_WITH_MD5}, */
  588. slapd_SSL_warn("Configured NSS Ciphers");
  589. for (x = 0; _conf_ciphers[x].name; x++) {
  590. SSL_CipherPrefGetDefault(_conf_ciphers[x].num, &enabled);
  591. if (enabled) {
  592. slapd_SSL_warn("\t%s: enabled%s%s%s", _conf_ciphers[x].name,
  593. (_conf_ciphers[x].flags&CIPHER_IS_WEAK)?", (WEAK CIPHER)":"",
  594. (_conf_ciphers[x].flags&CIPHER_IS_DEPRECATED)?", (DEPRECATED)":"",
  595. (_conf_ciphers[x].flags&CIPHER_MUST_BE_DISABLED)?", (MUST BE DISABLED)":"");
  596. } else if (slapi_is_loglevel_set(SLAPI_LOG_CONFIG)) {
  597. slapd_SSL_warn("\t%s: disabled%s%s%s", _conf_ciphers[x].name,
  598. (_conf_ciphers[x].flags&CIPHER_IS_WEAK)?", (WEAK CIPHER)":"",
  599. (_conf_ciphers[x].flags&CIPHER_IS_DEPRECATED)?", (DEPRECATED)":"",
  600. (_conf_ciphers[x].flags&CIPHER_MUST_BE_DISABLED)?", (MUST BE DISABLED)":"");
  601. }
  602. }
  603. }
  604. char *
  605. _conf_setciphers(char *ciphers, int flags)
  606. {
  607. char *t, err[MAGNUS_ERROR_LEN];
  608. int x, i, active;
  609. char *raw = ciphers;
  610. char **suplist = NULL;
  611. char **unsuplist = NULL;
  612. PRBool enabledOne = PR_FALSE;
  613. /* #47838: harden the list of ciphers available by default */
  614. /* Default is to activate all of them ==> none of them*/
  615. if (!ciphers || (ciphers[0] == '\0') || !PL_strcasecmp(ciphers, "default")) {
  616. _conf_setallciphers((CIPHER_SET_DEFAULT|flags), NULL, NULL);
  617. slapd_SSL_warn("Security Initialization: Enabling default cipher set.");
  618. _conf_dumpciphers();
  619. return NULL;
  620. }
  621. if (PL_strcasestr(ciphers, "+all")) {
  622. /*
  623. * Enable all the ciphers if "+all" and the following while loop would
  624. * disable the user disabled ones. This is needed because we added a new
  625. * set of ciphers in the table. Right now there is no support for this
  626. * from the console
  627. */
  628. _conf_setallciphers((CIPHER_SET_ALL|flags), &suplist, NULL);
  629. enabledOne = PR_TRUE;
  630. } else {
  631. /* If "+all" is not in nsSSL3Ciphers value, disable all first,
  632. * then enable specified ciphers. */
  633. _conf_setallciphers(CIPHER_SET_NONE /* disabled */, NULL, NULL);
  634. }
  635. t = ciphers;
  636. while(t) {
  637. while((*ciphers) && (isspace(*ciphers))) ++ciphers;
  638. switch(*ciphers++) {
  639. case '+':
  640. active = 1; break;
  641. case '-':
  642. active = 0; break;
  643. default:
  644. PR_snprintf(err, sizeof(err), "invalid ciphers <%s>: format is "
  645. "+cipher1,-cipher2...", raw);
  646. return slapi_ch_strdup(err);
  647. }
  648. if( (t = strchr(ciphers, ',')) )
  649. *t++ = '\0';
  650. if (strcasecmp(ciphers, "all")) { /* if not all */
  651. PRBool enabled = active ? PR_TRUE : PR_FALSE;
  652. int lookup = 1;
  653. for (x = 0; _conf_ciphers[x].name; x++) {
  654. if (!PL_strcasecmp(ciphers, _conf_ciphers[x].name)) {
  655. if (_conf_ciphers[x].flags & CIPHER_IS_WEAK) {
  656. if (active && CIPHER_SET_ALLOWSWEAKCIPHER(flags)) {
  657. slapd_SSL_warn("Cipher %s is weak. It is enabled since allowWeakCipher is \"on\" "
  658. "(default setting for the backward compatibility). "
  659. "We strongly recommend to set it to \"off\". "
  660. "Please replace the value of allowWeakCipher with \"off\" in "
  661. "the encryption config entry cn=encryption,cn=config and "
  662. "restart the server.", ciphers);
  663. } else {
  664. /* if the cipher is weak and we don't allow weak cipher,
  665. disable it. */
  666. enabled = PR_FALSE;
  667. }
  668. }
  669. if (enabled) {
  670. /* if the cipher is not weak or we allow weak cipher,
  671. check fips. */
  672. enabled = cipher_check_fips(x, NULL, &unsuplist);
  673. }
  674. if (enabled) {
  675. enabledOne = PR_TRUE; /* At least one active cipher is set. */
  676. }
  677. SSL_CipherPrefSetDefault(_conf_ciphers[x].num, enabled);
  678. lookup = 0;
  679. break;
  680. }
  681. }
  682. if (lookup) { /* lookup with old cipher name and get NSS cipherSuiteName */
  683. for (i = 0; _lookup_cipher[i].alias; i++) {
  684. if (!PL_strcasecmp(ciphers, _lookup_cipher[i].alias)) {
  685. if (!_lookup_cipher[i].name[0]) {
  686. slapd_SSL_warn("Cipher suite %s is not available in NSS %d.%d. Ignoring %s",
  687. ciphers, NSS_VMAJOR, NSS_VMINOR, ciphers);
  688. continue;
  689. }
  690. for (x = 0; _conf_ciphers[x].name; x++) {
  691. if (!PL_strcasecmp(_lookup_cipher[i].name, _conf_ciphers[x].name)) {
  692. if (enabled) {
  693. if (_conf_ciphers[x].flags & CIPHER_IS_WEAK) {
  694. if (active && CIPHER_SET_ALLOWSWEAKCIPHER(flags)) {
  695. slapd_SSL_warn("Cipher %s is weak. "
  696. "It is enabled since allowWeakCipher is \"on\" "
  697. "(default setting for the backward compatibility). "
  698. "We strongly recommend to set it to \"off\". "
  699. "Please replace the value of allowWeakCipher with \"off\" in "
  700. "the encryption config entry cn=encryption,cn=config and "
  701. "restart the server.", ciphers);
  702. } else {
  703. /* if the cipher is weak and we don't allow weak cipher,
  704. disable it. */
  705. enabled = PR_FALSE;
  706. }
  707. }
  708. if (enabled) {
  709. /* if the cipher is not weak or we allow weak cipher,
  710. check fips. */
  711. enabled = cipher_check_fips(x, NULL, &unsuplist);
  712. }
  713. }
  714. if (enabled) {
  715. enabledOne = PR_TRUE; /* At least one active cipher is set. */
  716. }
  717. SSL_CipherPrefSetDefault(_conf_ciphers[x].num, enabled);
  718. break;
  719. }
  720. }
  721. break;
  722. }
  723. }
  724. }
  725. if (!lookup && !_conf_ciphers[x].name) { /* If lookup, it's already reported. */
  726. slapd_SSL_warn("Cipher suite %s is not available in NSS %d.%d. Ignoring %s",
  727. ciphers, NSS_VMAJOR, NSS_VMINOR, ciphers);
  728. }
  729. }
  730. if(t) {
  731. ciphers = t;
  732. }
  733. }
  734. if (unsuplist && *unsuplist) {
  735. char *strsup = charray2str(suplist, ",");
  736. char *strunsup = charray2str(unsuplist, ",");
  737. slapd_SSL_warn("Security Initialization: FIPS mode is enabled - only the following "
  738. "cipher suites are approved for FIPS: [%s] - "
  739. "the specified cipher suites [%s] are disabled - if "
  740. "you want to use these unsupported cipher suites, you must use modutil to "
  741. "disable FIPS in the internal token.",
  742. strsup ? strsup : "(none)", strunsup ? strunsup : "(none)");
  743. slapi_ch_free_string(&strsup);
  744. slapi_ch_free_string(&strunsup);
  745. }
  746. slapi_ch_free((void **)&suplist); /* strings inside are static */
  747. slapi_ch_free((void **)&unsuplist); /* strings inside are static */
  748. if (!enabledOne) {
  749. char *nocipher = slapi_ch_smprintf("No active cipher suite is available.");
  750. return nocipher;
  751. }
  752. _conf_dumpciphers();
  753. return NULL;
  754. }
  755. /* SSL Policy stuff */
  756. /*
  757. * SSLPLCY_Install
  758. *
  759. * Call the SSL_CipherPolicySet function for each ciphersuite.
  760. */
  761. PRStatus
  762. SSLPLCY_Install(void)
  763. {
  764. SECStatus s = 0;
  765. s = NSS_SetDomesticPolicy();
  766. return s?PR_FAILURE:PR_SUCCESS;
  767. }
  768. /**
  769. * Get a particular entry
  770. */
  771. static Slapi_Entry *
  772. getConfigEntry( const char *dn, Slapi_Entry **e2 ) {
  773. Slapi_DN sdn;
  774. slapi_sdn_init_dn_byref( &sdn, dn );
  775. slapi_search_internal_get_entry( &sdn, NULL, e2,
  776. plugin_get_default_component_id());
  777. slapi_sdn_done( &sdn );
  778. return *e2;
  779. }
  780. /**
  781. * Free an entry
  782. */
  783. static void
  784. freeConfigEntry( Slapi_Entry ** e ) {
  785. if ( (e != NULL) && (*e != NULL) ) {
  786. slapi_entry_free( *e );
  787. *e = NULL;
  788. }
  789. }
  790. /**
  791. * Get a list of child DNs
  792. */
  793. static char **
  794. getChildren( char *dn ) {
  795. Slapi_PBlock *new_pb = NULL;
  796. Slapi_Entry **e;
  797. int search_result = 1;
  798. int nEntries = 0;
  799. char **list = NULL;
  800. new_pb = slapi_search_internal ( dn, LDAP_SCOPE_ONELEVEL,
  801. "(objectclass=nsEncryptionModule)",
  802. NULL, NULL, 0);
  803. slapi_pblock_get( new_pb, SLAPI_NENTRIES, &nEntries);
  804. if ( nEntries > 0 ) {
  805. slapi_pblock_get( new_pb, SLAPI_PLUGIN_INTOP_RESULT, &search_result);
  806. slapi_pblock_get( new_pb, SLAPI_PLUGIN_INTOP_SEARCH_ENTRIES, &e);
  807. if ( e != NULL ) {
  808. int i;
  809. list = (char **)slapi_ch_malloc( sizeof(*list) * (nEntries + 1));
  810. for ( i = 0; e[i] != NULL; i++ ) {
  811. list[i] = slapi_ch_strdup(slapi_entry_get_dn(e[i]));
  812. }
  813. list[nEntries] = NULL;
  814. }
  815. }
  816. slapi_free_search_results_internal(new_pb);
  817. slapi_pblock_destroy(new_pb );
  818. return list;
  819. }
  820. /**
  821. * Free a list of child DNs
  822. */
  823. static void
  824. freeChildren( char **list ) {
  825. if ( list != NULL ) {
  826. int i;
  827. for ( i = 0; list[i] != NULL; i++ ) {
  828. slapi_ch_free( (void **)(&list[i]) );
  829. }
  830. slapi_ch_free( (void **)(&list) );
  831. }
  832. }
  833. static void
  834. entrySetValue(Slapi_DN *sdn, char *type, char *value)
  835. {
  836. Slapi_PBlock mypb;
  837. LDAPMod attr;
  838. LDAPMod *mods[2];
  839. char *values[2];
  840. values[0] = value;
  841. values[1] = NULL;
  842. /* modify the attribute */
  843. attr.mod_type = type;
  844. attr.mod_op = LDAP_MOD_REPLACE;
  845. attr.mod_values = values;
  846. mods[0] = &attr;
  847. mods[1] = NULL;
  848. pblock_init(&mypb);
  849. slapi_modify_internal_set_pb_ext(&mypb, sdn, mods, NULL, NULL, (void *)plugin_get_default_component_id(), 0);
  850. slapi_modify_internal_pb(&mypb);
  851. pblock_done(&mypb);
  852. }
  853. /* Logs a warning and returns 1 if cert file doesn't exist. You
  854. * can skip the warning log message by setting no_log to 1.*/
  855. static int
  856. warn_if_no_cert_file(const char *dir, int no_log)
  857. {
  858. int ret = 0;
  859. char *filename = slapi_ch_smprintf("%s/cert8.db", dir);
  860. PRStatus status = PR_Access(filename, PR_ACCESS_READ_OK);
  861. if (PR_SUCCESS != status) {
  862. slapi_ch_free_string(&filename);
  863. filename = slapi_ch_smprintf("%s/cert7.db", dir);
  864. status = PR_Access(filename, PR_ACCESS_READ_OK);
  865. if (PR_SUCCESS != status) {
  866. ret = 1;
  867. if (!no_log) {
  868. slapi_log_error(SLAPI_LOG_FATAL, "SSL Initialization",
  869. "Warning: certificate DB file cert8.db nor cert7.db exists in [%s] - "
  870. "SSL initialization will likely fail\n", dir);
  871. }
  872. }
  873. }
  874. slapi_ch_free_string(&filename);
  875. return ret;
  876. }
  877. /* Logs a warning and returns 1 if key file doesn't exist. You
  878. * can skip the warning log message by setting no_log to 1.*/
  879. static int
  880. warn_if_no_key_file(const char *dir, int no_log)
  881. {
  882. int ret = 0;
  883. char *filename = slapi_ch_smprintf("%s/key3.db", dir);
  884. PRStatus status = PR_Access(filename, PR_ACCESS_READ_OK);
  885. if (PR_SUCCESS != status) {
  886. ret = 1;
  887. if (!no_log) {
  888. slapi_log_error(SLAPI_LOG_FATAL, "SSL Initialization",
  889. "Warning: key DB file %s does not exist - SSL initialization will "
  890. "likely fail\n", filename);
  891. }
  892. }
  893. slapi_ch_free_string(&filename);
  894. return ret;
  895. }
  896. #if !defined(NSS_TLS10) /* NSS_TLS11 or newer */
  897. /*
  898. * If non NULL buf and positive bufsize is given,
  899. * the memory is used to store the version string.
  900. * Otherwise, the memory for the string is allocated.
  901. * The latter case, caller is responsible to free it.
  902. */
  903. char *
  904. slapi_getSSLVersion_str(PRUint16 vnum, char *buf, size_t bufsize)
  905. {
  906. char *vstr = buf;
  907. if (vnum >= SSL_LIBRARY_VERSION_3_0) {
  908. if (vnum == SSL_LIBRARY_VERSION_3_0) { /* SSL3 */
  909. if (buf && bufsize) {
  910. PR_snprintf(buf, bufsize, "SSL3");
  911. } else {
  912. vstr = slapi_ch_smprintf("SSL3");
  913. }
  914. } else { /* TLS v X.Y */
  915. const char *TLSFMT = "TLS%d.%d";
  916. int minor_offset = 0; /* e.g. 0x0401 -> TLS v 2.1, not 2.0 */
  917. if ((vnum & SSL_LIBRARY_VERSION_3_0) == SSL_LIBRARY_VERSION_3_0) {
  918. minor_offset = 1; /* e.g. 0x0301 -> TLS v 1.0, not 1.1 */
  919. }
  920. if (buf && bufsize) {
  921. PR_snprintf(buf, bufsize, TLSFMT, (vnum >> 8) - 2, (vnum & 0xff) - minor_offset);
  922. } else {
  923. vstr = slapi_ch_smprintf(TLSFMT, (vnum >> 8) - 2, (vnum & 0xff) - minor_offset);
  924. }
  925. }
  926. } else if (vnum == SSL_LIBRARY_VERSION_2) { /* SSL2 */
  927. if (buf && bufsize) {
  928. PR_snprintf(buf, bufsize, "SSL2");
  929. } else {
  930. vstr = slapi_ch_smprintf("SSL2");
  931. }
  932. } else {
  933. if (buf && bufsize) {
  934. PR_snprintf(buf, bufsize, "Unknown SSL version: 0x%x", vnum);
  935. } else {
  936. vstr = slapi_ch_smprintf("Unknown SSL version: 0x%x", vnum);
  937. }
  938. }
  939. return vstr;
  940. }
  941. #define SSLVGreater(x, y) (((x) > (y)) ? (x) : (y))
  942. /*
  943. * Check the SSLVersionRange and the old style config params (nsSSL3, nsTLS1) .
  944. * If there are conflicts, choose the secure setting.
  945. */
  946. static void
  947. restrict_SSLVersionRange(void)
  948. {
  949. char mymin[VERSION_STR_LENGTH], mymax[VERSION_STR_LENGTH];
  950. char emin[VERSION_STR_LENGTH], emax[VERSION_STR_LENGTH];
  951. (void) slapi_getSSLVersion_str(slapdNSSVersions.min, mymin, sizeof(mymin));
  952. (void) slapi_getSSLVersion_str(slapdNSSVersions.max, mymax, sizeof(mymax));
  953. (void) slapi_getSSLVersion_str(enabledNSSVersions.max, emax, sizeof(emax));
  954. (void) slapi_getSSLVersion_str(enabledNSSVersions.min, emin, sizeof(emin));
  955. if (slapdNSSVersions.min > slapdNSSVersions.max) {
  956. slapd_SSL_warn("Invalid configured SSL range: min: %s, max: %s; "
  957. "Resetting the max to the supported max SSL version: %s.",
  958. mymin, mymax, emax);
  959. slapdNSSVersions.max = enabledNSSVersions.max;
  960. }
  961. if (enableSSL3) {
  962. if (enableTLS1) {
  963. if (slapdNSSVersions.min >= CURRENT_DEFAULT_SSL_VERSION) {
  964. slapd_SSL_warn("Configured range: min: %s, max: %s; "
  965. "but both nsSSL3 and nsTLS1 are on. "
  966. "Respect the supported range.",
  967. mymin, mymax);
  968. enableSSL3 = PR_FALSE;
  969. } else {
  970. slapd_SSL_warn("Min value is too low in range: min: %s, max: %s; "
  971. "We strongly recommend to set sslVersionMin higher than %s.",
  972. mymin, mymax, DEFVERSION);
  973. }
  974. if (slapdNSSVersions.max < CURRENT_DEFAULT_SSL_VERSION) {
  975. slapd_SSL_warn("Configured range: min: %s, max: %s; "
  976. "but both nsSSL3 and nsTLS1 are on. "
  977. "Resetting the max to the supported max SSL version: %s.",
  978. mymin, mymax, emax);
  979. slapdNSSVersions.max = enabledNSSVersions.max;
  980. }
  981. } else {
  982. /* nsTLS1 is explicitly set to off. */
  983. if (enabledNSSVersions.min >= CURRENT_DEFAULT_SSL_VERSION) {
  984. slapd_SSL_warn("Supported range: min: %s, max: %s; "
  985. "but nsSSL3 is on and nsTLS1 is off. "
  986. "Respect the supported range.",
  987. emin, emax);
  988. slapdNSSVersions.min = SSLVGreater(slapdNSSVersions.min, enabledNSSVersions.min);
  989. enableSSL3 = PR_FALSE;
  990. enableTLS1 = PR_TRUE;
  991. } else if (slapdNSSVersions.min >= CURRENT_DEFAULT_SSL_VERSION) {
  992. slapd_SSL_warn("Configured range: min: %s, max: %s; "
  993. "but nsSSL3 is on and nsTLS1 is off. "
  994. "Respect the configured range.",
  995. mymin, mymax);
  996. enableSSL3 = PR_FALSE;
  997. enableTLS1 = PR_TRUE;
  998. } else if (slapdNSSVersions.min < CURRENT_DEFAULT_SSL_VERSION) {
  999. slapd_SSL_warn("Min value is too low in range: min: %s, max: %s; "
  1000. "We strongly recommend to set sslVersionMin higher than %s.",
  1001. mymin, mymax, DEFVERSION);
  1002. } else {
  1003. /*
  1004. * slapdNSSVersions.min < SSL_LIBRARY_VERSION_TLS_1_0 &&
  1005. * slapdNSSVersions.max >= SSL_LIBRARY_VERSION_TLS_1_1
  1006. */
  1007. slapd_SSL_warn("Configured range: min: %s, max: %s; "
  1008. "but nsSSL3 is on and nsTLS1 is off. "
  1009. "Respect the configured range.",
  1010. mymin, mymax);
  1011. enableTLS1 = PR_TRUE;
  1012. }
  1013. }
  1014. } else {
  1015. if (enableTLS1) {
  1016. if (enabledNSSVersions.max < CURRENT_DEFAULT_SSL_VERSION) {
  1017. /* TLS1 is on, but TLS1 is not supported by NSS. */
  1018. slapd_SSL_warn("Supported range: min: %s, max: %s; "
  1019. "Setting the version range based upon the supported range.",
  1020. emin, emax);
  1021. slapdNSSVersions.max = enabledNSSVersions.max;
  1022. slapdNSSVersions.min = enabledNSSVersions.min;
  1023. enableSSL3 = PR_TRUE;
  1024. enableTLS1 = PR_FALSE;
  1025. } else if ((slapdNSSVersions.max < CURRENT_DEFAULT_SSL_VERSION) ||
  1026. (slapdNSSVersions.min < CURRENT_DEFAULT_SSL_VERSION)) {
  1027. slapdNSSVersions.max = enabledNSSVersions.max;
  1028. slapdNSSVersions.min = SSLVGreater(CURRENT_DEFAULT_SSL_VERSION, enabledNSSVersions.min);
  1029. slapd_SSL_warn("nsTLS1 is on, but the version range is lower than \"%s\"; "
  1030. "Configuring the version range as default min: %s, max: %s.",
  1031. DEFVERSION, DEFVERSION, emax);
  1032. } else {
  1033. /*
  1034. * slapdNSSVersions.min >= SSL_LIBRARY_VERSION_TLS_1_0 &&
  1035. * slapdNSSVersions.max >= SSL_LIBRARY_VERSION_TLS_1_0
  1036. */
  1037. ;
  1038. }
  1039. } else {
  1040. slapd_SSL_warn("Supported range: min: %s, max: %s; "
  1041. "Respect the configured range.",
  1042. emin, emax);
  1043. /* nsTLS1 is explicitly set to off. */
  1044. if (slapdNSSVersions.min >= CURRENT_DEFAULT_SSL_VERSION) {
  1045. enableTLS1 = PR_TRUE;
  1046. } else if (slapdNSSVersions.max < CURRENT_DEFAULT_SSL_VERSION) {
  1047. enableSSL3 = PR_TRUE;
  1048. } else {
  1049. /*
  1050. * slapdNSSVersions.min < SSL_LIBRARY_VERSION_TLS_1_0 &&
  1051. * slapdNSSVersions.max >= SSL_LIBRARY_VERSION_TLS_1_0
  1052. */
  1053. enableSSL3 = PR_TRUE;
  1054. enableTLS1 = PR_TRUE;
  1055. }
  1056. }
  1057. }
  1058. }
  1059. #endif
  1060. /*
  1061. * slapd_nss_init() is always called from main(), even if we do not
  1062. * plan to listen on a secure port. If config_available is 0, the
  1063. * config. entries from dse.ldif are NOT available (used only when
  1064. * running in referral mode).
  1065. * As of DS6.1, the init_ssl flag passed is ignored.
  1066. *
  1067. * richm 20070126 - By default now we put the key/cert db files
  1068. * in an instance specific directory (the certdir directory) so
  1069. * we do not need a prefix any more.
  1070. */
  1071. int
  1072. slapd_nss_init(int init_ssl, int config_available)
  1073. {
  1074. SECStatus secStatus;
  1075. PRErrorCode errorCode;
  1076. int rv = 0;
  1077. int len = 0;
  1078. int create_certdb = 0;
  1079. PRUint32 nssFlags = 0;
  1080. char *certdir;
  1081. char *certdb_file_name = NULL;
  1082. char *keydb_file_name = NULL;
  1083. char *secmoddb_file_name = NULL;
  1084. #if !defined(NSS_TLS10) /* NSS_TLS11 or newer */
  1085. char emin[VERSION_STR_LENGTH], emax[VERSION_STR_LENGTH];
  1086. /* Get the range of the supported SSL version */
  1087. SSL_VersionRangeGetSupported(ssl_variant_stream, &enabledNSSVersions);
  1088. (void) slapi_getSSLVersion_str(enabledNSSVersions.min, emin, sizeof(emin));
  1089. (void) slapi_getSSLVersion_str(enabledNSSVersions.max, emax, sizeof(emax));
  1090. slapi_log_error(SLAPI_LOG_CONFIG, "SSL Initialization",
  1091. "supported range by NSS: min: %s, max: %s\n",
  1092. emin, emax);
  1093. #endif
  1094. /* set in slapd_bootstrap_config,
  1095. thus certdir is available even if config_available is false */
  1096. certdir = config_get_certdir();
  1097. /* make sure path does not end in the path separator character */
  1098. len = strlen(certdir);
  1099. if (certdir[len-1] == '/' || certdir[len-1] == '\\') {
  1100. certdir[len-1] = '\0';
  1101. }
  1102. /* If the server is configured to use SSL, we must have a key and cert db */
  1103. if (config_get_security()) {
  1104. warn_if_no_cert_file(certdir, 0);
  1105. warn_if_no_key_file(certdir, 0);
  1106. } else { /* otherwise, NSS will create empty databases */
  1107. /* we open the key/cert db in rw mode, so make sure the directory
  1108. is writable */
  1109. if (PR_SUCCESS != PR_Access(certdir, PR_ACCESS_WRITE_OK)) {
  1110. char *serveruser = "unknown";
  1111. serveruser = config_get_localuser();
  1112. slapi_log_error(SLAPI_LOG_FATAL, "SSL Initialization",
  1113. "Warning: The key/cert database directory [%s] is not writable by "
  1114. "the server uid [%s]: initialization likely to fail.\n",
  1115. certdir, serveruser);
  1116. slapi_ch_free_string(&serveruser);
  1117. }
  1118. }
  1119. /* Check if we have a certdb already. If not, set a flag that we are
  1120. * going to create one so we can set the appropriate permissions on it. */
  1121. if (warn_if_no_cert_file(certdir, 1) || warn_if_no_key_file(certdir, 1)) {
  1122. create_certdb = 1;
  1123. }
  1124. /******** Initialise NSS *********/
  1125. nssFlags &= (~NSS_INIT_READONLY);
  1126. slapd_pk11_configurePKCS11(NULL, NULL, tokPBE, ptokPBE, NULL, NULL, NULL, NULL, 0, 0 );
  1127. secStatus = NSS_Initialize(certdir, NULL, NULL, "secmod.db", nssFlags);
  1128. dongle_file_name = slapi_ch_smprintf("%s/pin.txt", certdir);
  1129. if (secStatus != SECSuccess) {
  1130. errorCode = PR_GetError();
  1131. slapd_SSL_warn("Security Initialization: NSS initialization failed ("
  1132. SLAPI_COMPONENT_NAME_NSPR " error %d - %s): "
  1133. "certdir: %s",
  1134. errorCode, slapd_pr_strerror(errorCode), certdir);
  1135. rv = -1;
  1136. }
  1137. if(SSLPLCY_Install() != PR_SUCCESS) {
  1138. errorCode = PR_GetError();
  1139. slapd_SSL_warn("Security Initialization: Unable to set SSL export policy ("
  1140. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1141. errorCode, slapd_pr_strerror(errorCode));
  1142. return -1;
  1143. }
  1144. /* NSS creates the certificate db files with a mode of 600. There
  1145. * is no way to pass in a mode to use for creation to NSS, so we
  1146. * need to modify it after creation. We need to allow read and
  1147. * write permission to the group so the certs can be managed via
  1148. * the console/adminserver. */
  1149. if (create_certdb) {
  1150. certdb_file_name = slapi_ch_smprintf("%s/cert8.db", certdir);
  1151. keydb_file_name = slapi_ch_smprintf("%s/key3.db", certdir);
  1152. secmoddb_file_name = slapi_ch_smprintf("%s/secmod.db", certdir);
  1153. if(chmod(certdb_file_name, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP )){
  1154. LDAPDebug(LDAP_DEBUG_ANY, "slapd_nss_init: chmod failed for file %s error (%d) %s.\n",
  1155. certdb_file_name, errno, slapd_system_strerror(errno));
  1156. }
  1157. if(chmod(keydb_file_name, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP )){
  1158. LDAPDebug(LDAP_DEBUG_ANY, "slapd_nss_init: chmod failed for file %s error (%d) %s.\n",
  1159. keydb_file_name, errno, slapd_system_strerror(errno));
  1160. }
  1161. if(chmod(secmoddb_file_name, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP )){
  1162. LDAPDebug(LDAP_DEBUG_ANY, "slapd_nss_init: chmod failed for file %s error (%d) %s.\n",
  1163. secmoddb_file_name, errno, slapd_system_strerror(errno));
  1164. }
  1165. }
  1166. /****** end of NSS Initialization ******/
  1167. _nss_initialized = 1;
  1168. slapi_ch_free_string(&certdb_file_name);
  1169. slapi_ch_free_string(&keydb_file_name);
  1170. slapi_ch_free_string(&secmoddb_file_name);
  1171. slapi_ch_free_string(&certdir);
  1172. return rv;
  1173. }
  1174. static int
  1175. svrcore_setup()
  1176. {
  1177. PRErrorCode errorCode;
  1178. int rv = 0;
  1179. #ifdef WITH_SYSTEMD
  1180. SVRCOREStdSystemdPinObj *StdPinObj;
  1181. StdPinObj = (SVRCOREStdSystemdPinObj *)SVRCORE_GetRegisteredPinObj();
  1182. #else
  1183. SVRCOREStdPinObj *StdPinObj;
  1184. StdPinObj = (SVRCOREStdPinObj *)SVRCORE_GetRegisteredPinObj();
  1185. #endif
  1186. if (StdPinObj) {
  1187. return 0; /* already registered */
  1188. }
  1189. #ifdef WITH_SYSTEMD
  1190. if ( SVRCORE_CreateStdSystemdPinObj(&StdPinObj, dongle_file_name, PR_TRUE, PR_TRUE, 90) != SVRCORE_Success) {
  1191. #else
  1192. if ( SVRCORE_CreateStdPinObj(&StdPinObj, dongle_file_name, PR_TRUE) != SVRCORE_Success) {
  1193. #endif
  1194. errorCode = PR_GetError();
  1195. slapd_SSL_warn("Security Initialization: Unable to create PinObj ("
  1196. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1197. errorCode, slapd_pr_strerror(errorCode));
  1198. return -1;
  1199. }
  1200. SVRCORE_RegisterPinObj((SVRCOREPinObj *)StdPinObj);
  1201. return rv;
  1202. }
  1203. /*
  1204. * slapd_ssl_init() is called from main() if we plan to listen
  1205. * on a secure port.
  1206. */
  1207. int
  1208. slapd_ssl_init()
  1209. {
  1210. PRErrorCode errorCode;
  1211. char ** family_list;
  1212. char *val = NULL;
  1213. PK11SlotInfo *slot;
  1214. Slapi_Entry *entry = NULL;
  1215. #ifdef HAVE_NSS_DHE
  1216. SECStatus rv = SECFailure;
  1217. #endif
  1218. /* Get general information */
  1219. getConfigEntry( configDN, &entry );
  1220. val = slapi_entry_attr_get_charptr( entry, "nssslSessionTimeout" );
  1221. ciphers = slapi_entry_attr_get_charptr( entry, "nsssl3ciphers" );
  1222. #ifdef HAVE_NSS_DHE
  1223. allowweakdhparam = get_allow_weak_dh_param(entry);
  1224. if (allowweakdhparam & CIPHER_SET_ALLOWWEAKDHPARAM) {
  1225. slapd_SSL_warn("notice, generating new WEAK DH param");
  1226. rv = SSL_EnableWeakDHEPrimeGroup(NULL, PR_TRUE);
  1227. if (rv != SECSuccess) {
  1228. slapd_SSL_warn("Warning, unable to generate weak dh parameters");
  1229. }
  1230. }
  1231. #endif
  1232. /* We are currently using the value of sslSessionTimeout
  1233. for ssl3SessionTimeout, see SSL_ConfigServerSessionIDCache() */
  1234. /* Note from Tom Weinstein on the meaning of the timeout:
  1235. Timeouts are in seconds. '0' means use the default, which is
  1236. 24hrs for SSL3 and 100 seconds for SSL2.
  1237. */
  1238. if(!val) {
  1239. errorCode = PR_GetError();
  1240. slapd_SSL_warn("Security Initialization: Failed to retrieve SSL "
  1241. "configuration information ("
  1242. SLAPI_COMPONENT_NAME_NSPR " error %d - %s): "
  1243. "nssslSessionTimeout: %s ",
  1244. errorCode, slapd_pr_strerror(errorCode),
  1245. (val ? "found" : "not found"));
  1246. slapi_ch_free((void **) &val);
  1247. slapi_ch_free((void **) &ciphers);
  1248. freeConfigEntry( &entry );
  1249. return -1;
  1250. }
  1251. stimeout = atoi(val);
  1252. slapi_ch_free((void **) &val);
  1253. if (svrcore_setup()) {
  1254. freeConfigEntry( &entry );
  1255. return -1;
  1256. }
  1257. if (config_get_extract_pem()) {
  1258. /* extract cert file and convert it to a pem file. */
  1259. slapd_extract_cert(entry, PR_TRUE);
  1260. }
  1261. if ((family_list = getChildren(configDN))) {
  1262. char **family;
  1263. char *token;
  1264. char *activation;
  1265. int isinternal = 0;
  1266. for (family = family_list; *family; family++) {
  1267. token = NULL;
  1268. activation = NULL;
  1269. freeConfigEntry( &entry );
  1270. getConfigEntry( *family, &entry );
  1271. if ( entry == NULL ) {
  1272. continue;
  1273. }
  1274. activation = slapi_entry_attr_get_charptr( entry, "nssslactivation" );
  1275. if((!activation) || (!PL_strcasecmp(activation, "off"))) {
  1276. /* this family was turned off, goto next */
  1277. slapi_ch_free((void **) &activation);
  1278. continue;
  1279. }
  1280. slapi_ch_free((void **) &activation);
  1281. token = slapi_entry_attr_get_charptr( entry, "nsssltoken" );
  1282. if ( token ) {
  1283. if (!PL_strcasecmp(token, "internal") ||
  1284. !PL_strcasecmp(token, "internal (software)")) {
  1285. slot = slapd_pk11_getInternalKeySlot();
  1286. isinternal = 1;
  1287. } else {
  1288. slot = slapd_pk11_findSlotByName(token);
  1289. }
  1290. } else {
  1291. errorCode = PR_GetError();
  1292. slapd_SSL_warn("Security Initialization: Unable to get token ("
  1293. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1294. errorCode, slapd_pr_strerror(errorCode));
  1295. freeChildren(family_list);
  1296. freeConfigEntry( &entry );
  1297. return -1;
  1298. }
  1299. if (!slot) {
  1300. errorCode = PR_GetError();
  1301. slapd_SSL_warn("Security Initialization: Unable to find slot ("
  1302. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1303. errorCode, slapd_pr_strerror(errorCode));
  1304. freeChildren(family_list);
  1305. freeConfigEntry( &entry );
  1306. slapi_ch_free((void **) &token);
  1307. return -1;
  1308. }
  1309. /* authenticate */
  1310. #ifdef WITH_SYSTEMD
  1311. slapd_SSL_warn("Sending pin request to SVRCore. You may need to run"
  1312. " systemd-tty-ask-password-agent to provide the password.");
  1313. #endif
  1314. if (slapd_pk11_authenticate(slot, PR_TRUE, NULL) != SECSuccess) {
  1315. errorCode = PR_GetError();
  1316. slapi_log_error(SLAPI_LOG_FATAL, "slapd_ssl_init",
  1317. "Unable to authenticate (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1318. errorCode, slapd_pr_strerror(errorCode));
  1319. freeChildren(family_list);
  1320. freeConfigEntry( &entry );
  1321. slapi_ch_free((void **) &token);
  1322. return -1;
  1323. }
  1324. if (config_get_extract_pem()) {
  1325. /* Get Server{Key,Cert}ExtractFile from cn=Cipher,cn=encryption entry if any. */
  1326. slapd_extract_cert(entry, PR_FALSE);
  1327. slapd_extract_key(entry, isinternal?internalTokenName:token, slot);
  1328. }
  1329. slapi_ch_free((void **) &token);
  1330. }
  1331. freeChildren( family_list );
  1332. freeConfigEntry( &entry );
  1333. }
  1334. freeConfigEntry( &entry );
  1335. /* Introduce a way of knowing whether slapd_ssl_init has
  1336. * already been executed. */
  1337. _security_library_initialized = 1;
  1338. return 0;
  1339. }
  1340. #if !defined(NSS_TLS10) /* NSS_TLS11 or newer */
  1341. /*
  1342. * val: sslVersionMin/Max value set in cn=encription,cn=config (INPUT)
  1343. * rval: Corresponding value to set SSLVersionRange (OUTPUT)
  1344. * ismin: True if val is sslVersionMin value
  1345. */
  1346. #define SSLSTR "ssl"
  1347. #define SSLLEN (sizeof(SSLSTR) - 1)
  1348. #define TLSSTR "tls"
  1349. #define TLSLEN (sizeof(TLSSTR) - 1)
  1350. static int
  1351. set_NSS_version(char *val, PRUint16 *rval, int ismin)
  1352. {
  1353. char *vp, *endp;
  1354. int vnum;
  1355. char emin[VERSION_STR_LENGTH], emax[VERSION_STR_LENGTH];
  1356. if (NULL == rval) {
  1357. return 1;
  1358. }
  1359. (void) slapi_getSSLVersion_str(enabledNSSVersions.min, emin, sizeof(emin));
  1360. (void) slapi_getSSLVersion_str(enabledNSSVersions.max, emax, sizeof(emax));
  1361. if (!strncasecmp(val, SSLSTR, SSLLEN)) { /* ssl# */
  1362. vp = val + SSLLEN;
  1363. vnum = strtol(vp, &endp, 10);
  1364. if (2 == vnum) {
  1365. if (ismin) {
  1366. if (enabledNSSVersions.min > SSL_LIBRARY_VERSION_2) {
  1367. slapd_SSL_warn("Security Initialization: The value of sslVersionMin "
  1368. "\"%s\" is lower than the supported version; "
  1369. "the default value \"%s\" is used.",
  1370. val, emin);
  1371. (*rval) = enabledNSSVersions.min;
  1372. } else {
  1373. (*rval) = SSL_LIBRARY_VERSION_2;
  1374. }
  1375. } else {
  1376. if (enabledNSSVersions.max < SSL_LIBRARY_VERSION_2) {
  1377. /* never happens */
  1378. slapd_SSL_warn("Security Initialization: The value of sslVersionMax "
  1379. "\"%s\" is higher than the supported version; "
  1380. "the default value \"%s\" is used.",
  1381. val, emax);
  1382. (*rval) = enabledNSSVersions.max;
  1383. } else {
  1384. (*rval) = SSL_LIBRARY_VERSION_2;
  1385. }
  1386. }
  1387. } else if (3 == vnum) {
  1388. if (ismin) {
  1389. if (enabledNSSVersions.min > SSL_LIBRARY_VERSION_3_0) {
  1390. slapd_SSL_warn("Security Initialization: The value of sslVersionMin "
  1391. "\"%s\" is lower than the supported version; "
  1392. "the default value \"%s\" is used.",
  1393. val, emin);
  1394. (*rval) = enabledNSSVersions.min;
  1395. } else {
  1396. (*rval) = SSL_LIBRARY_VERSION_3_0;
  1397. }
  1398. } else {
  1399. if (enabledNSSVersions.max < SSL_LIBRARY_VERSION_3_0) {
  1400. /* never happens */
  1401. slapd_SSL_warn("Security Initialization: The value of sslVersionMax "
  1402. "\"%s\" is higher than the supported version; "
  1403. "the default value \"%s\" is used.",
  1404. val, emax);
  1405. (*rval) = enabledNSSVersions.max;
  1406. } else {
  1407. (*rval) = SSL_LIBRARY_VERSION_3_0;
  1408. }
  1409. }
  1410. } else {
  1411. if (ismin) {
  1412. slapd_SSL_warn("Security Initialization: The value of sslVersionMin "
  1413. "\"%s\" is invalid; the default value \"%s\" is used.",
  1414. val, emin);
  1415. (*rval) = enabledNSSVersions.min;
  1416. } else {
  1417. slapd_SSL_warn("Security Initialization: The value of sslVersionMax "
  1418. "\"%s\" is invalid; the default value \"%s\" is used.",
  1419. val, emax);
  1420. (*rval) = enabledNSSVersions.max;
  1421. }
  1422. }
  1423. } else if (!strncasecmp(val, TLSSTR, TLSLEN)) { /* tls# */
  1424. float tlsv;
  1425. vp = val + TLSLEN;
  1426. sscanf(vp, "%4f", &tlsv);
  1427. if (tlsv < 1.1) { /* TLS1.0 */
  1428. if (ismin) {
  1429. if (enabledNSSVersions.min > CURRENT_DEFAULT_SSL_VERSION) {
  1430. slapd_SSL_warn("Security Initialization: The value of sslVersionMin "
  1431. "\"%s\" is lower than the supported version; "
  1432. "the default value \"%s\" is used.",
  1433. val, emin);
  1434. (*rval) = enabledNSSVersions.min;
  1435. } else {
  1436. (*rval) = CURRENT_DEFAULT_SSL_VERSION;
  1437. }
  1438. } else {
  1439. if (enabledNSSVersions.max < CURRENT_DEFAULT_SSL_VERSION) {
  1440. /* never happens */
  1441. slapd_SSL_warn("Security Initialization: The value of sslVersionMax "
  1442. "\"%s\" is higher than the supported version; "
  1443. "the default value \"%s\" is used.",
  1444. val, emax);
  1445. (*rval) = enabledNSSVersions.max;
  1446. } else {
  1447. (*rval) = CURRENT_DEFAULT_SSL_VERSION;
  1448. }
  1449. }
  1450. } else if (tlsv < 1.2) { /* TLS1.1 */
  1451. if (ismin) {
  1452. if (enabledNSSVersions.min > SSL_LIBRARY_VERSION_TLS_1_1) {
  1453. slapd_SSL_warn("Security Initialization: The value of sslVersionMin "
  1454. "\"%s\" is lower than the supported version; "
  1455. "the default value \"%s\" is used.",
  1456. val, emin);
  1457. (*rval) = enabledNSSVersions.min;
  1458. } else {
  1459. (*rval) = SSL_LIBRARY_VERSION_TLS_1_1;
  1460. }
  1461. } else {
  1462. if (enabledNSSVersions.max < SSL_LIBRARY_VERSION_TLS_1_1) {
  1463. /* never happens */
  1464. slapd_SSL_warn("Security Initialization: The value of sslVersionMax "
  1465. "\"%s\" is higher than the supported version; "
  1466. "the default value \"%s\" is used.",
  1467. val, emax);
  1468. (*rval) = enabledNSSVersions.max;
  1469. } else {
  1470. (*rval) = SSL_LIBRARY_VERSION_TLS_1_1;
  1471. }
  1472. }
  1473. } else if (tlsv < 1.3) { /* TLS1.2 */
  1474. #if defined(NSS_TLS12)
  1475. if (ismin) {
  1476. if (enabledNSSVersions.min > SSL_LIBRARY_VERSION_TLS_1_2) {
  1477. slapd_SSL_warn("Security Initialization: The value of sslVersionMin "
  1478. "\"%s\" is lower than the supported version; "
  1479. "the default value \"%s\" is used.",
  1480. val, emin);
  1481. (*rval) = enabledNSSVersions.min;
  1482. } else {
  1483. (*rval) = SSL_LIBRARY_VERSION_TLS_1_2;
  1484. }
  1485. } else {
  1486. if (enabledNSSVersions.max < SSL_LIBRARY_VERSION_TLS_1_2) {
  1487. /* never happens */
  1488. slapd_SSL_warn("Security Initialization: The value of sslVersionMax "
  1489. "\"%s\" is higher than the supported version; "
  1490. "the default value \"%s\" is used.",
  1491. val, emax);
  1492. (*rval) = enabledNSSVersions.max;
  1493. } else {
  1494. (*rval) = SSL_LIBRARY_VERSION_TLS_1_2;
  1495. }
  1496. }
  1497. #endif
  1498. } else { /* Specified TLS is newer than supported */
  1499. if (ismin) {
  1500. slapd_SSL_warn("Security Initialization: The value of sslVersionMin "
  1501. "\"%s\" is out of the range of the supported version; "
  1502. "the default value \"%s\" is used.",
  1503. val, emin);
  1504. (*rval) = enabledNSSVersions.min;
  1505. } else {
  1506. slapd_SSL_warn("Security Initialization: The value of sslVersionMax "
  1507. "\"%s\" is out of the range of the supported version; "
  1508. "the default value \"%s\" is used.",
  1509. val, emax);
  1510. (*rval) = enabledNSSVersions.max;
  1511. }
  1512. }
  1513. } else {
  1514. if (ismin) {
  1515. slapd_SSL_warn("Security Initialization: The value of sslVersionMin "
  1516. "\"%s\" is invalid; the default value \"%s\" is used.",
  1517. val, emin);
  1518. (*rval) = enabledNSSVersions.min;
  1519. } else {
  1520. slapd_SSL_warn("Security Initialization: The value of sslVersionMax "
  1521. "\"%s\" is invalid; the default value \"%s\" is used.",
  1522. val, emax);
  1523. (*rval) = enabledNSSVersions.max;
  1524. }
  1525. }
  1526. return 0;
  1527. }
  1528. #undef SSLSTR
  1529. #undef SSLLEN
  1530. #undef TLSSTR
  1531. #undef TLSLEN
  1532. #endif
  1533. int
  1534. slapd_ssl_init2(PRFileDesc **fd, int startTLS)
  1535. {
  1536. PRFileDesc *pr_sock, *sock = (*fd);
  1537. PRErrorCode errorCode;
  1538. SECStatus rv = SECFailure;
  1539. char ** family_list;
  1540. CERTCertificate *cert = NULL;
  1541. SECKEYPrivateKey *key = NULL;
  1542. char errorbuf[SLAPI_DSE_RETURNTEXT_SIZE] = {0};
  1543. char *val = NULL;
  1544. char *default_val = NULL;
  1545. int nFamilies = 0;
  1546. SECStatus sslStatus;
  1547. int slapd_SSLclientAuth;
  1548. char* tmpDir;
  1549. Slapi_Entry *e = NULL;
  1550. PRBool fipsMode = PR_FALSE;
  1551. #if !defined(NSS_TLS10) /* NSS_TLS11 or newer */
  1552. PRUint16 NSSVersionMin = enabledNSSVersions.min;
  1553. PRUint16 NSSVersionMax = enabledNSSVersions.max;
  1554. char mymin[VERSION_STR_LENGTH], mymax[VERSION_STR_LENGTH];
  1555. char newmax[VERSION_STR_LENGTH];
  1556. #endif
  1557. char cipher_string[1024];
  1558. int allowweakcipher = CIPHER_SET_DEFAULTWEAKCIPHER;
  1559. /* turn off the PKCS11 pin interactive mode */
  1560. /* wibrown 2016 */
  1561. /* We don't need to do the detection for the StdSystemPin, it does it */
  1562. /* automatically for us. */
  1563. #ifndef WITH_SYSTEMD
  1564. SVRCOREStdPinObj *StdPinObj;
  1565. if (svrcore_setup()) {
  1566. return 1;
  1567. }
  1568. StdPinObj = (SVRCOREStdPinObj *)SVRCORE_GetRegisteredPinObj();
  1569. SVRCORE_SetStdPinInteractive(StdPinObj, PR_FALSE);
  1570. #endif
  1571. /*
  1572. * Cipher preferences must be set before any sslSocket is created
  1573. * for such sockets to take preferences into account.
  1574. */
  1575. getConfigEntry(configDN, &e);
  1576. if (e == NULL) {
  1577. slapd_SSL_warn("Security Initialization: Failed get config entry %s", configDN);
  1578. return 1;
  1579. }
  1580. val = slapi_entry_attr_get_charptr(e, "allowWeakCipher");
  1581. if (val) {
  1582. if (!PL_strcasecmp(val, "off") || !PL_strcasecmp(val, "false") ||
  1583. !PL_strcmp(val, "0") || !PL_strcasecmp(val, "no")) {
  1584. allowweakcipher = CIPHER_SET_DISALLOWWEAKCIPHER;
  1585. } else if (!PL_strcasecmp(val, "on") || !PL_strcasecmp(val, "true") ||
  1586. !PL_strcmp(val, "1") || !PL_strcasecmp(val, "yes")) {
  1587. allowweakcipher = CIPHER_SET_ALLOWWEAKCIPHER;
  1588. } else {
  1589. slapd_SSL_warn("The value of allowWeakCipher \"%s\" in %s is invalid.",
  1590. "Ignoring it and set it to default.", val, configDN);
  1591. }
  1592. }
  1593. slapi_ch_free((void **) &val);
  1594. /* Set SSL cipher preferences */
  1595. *cipher_string = 0;
  1596. if(ciphers && (*ciphers) && PL_strcmp(ciphers, "blank"))
  1597. PL_strncpyz(cipher_string, ciphers, sizeof(cipher_string));
  1598. slapi_ch_free((void **) &ciphers);
  1599. if ( NULL != (val = _conf_setciphers(cipher_string, allowweakcipher)) ) {
  1600. errorCode = PR_GetError();
  1601. slapd_SSL_warn("Security Initialization: Failed to set SSL cipher "
  1602. "preference information: %s (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1603. val, errorCode, slapd_pr_strerror(errorCode));
  1604. slapi_ch_free((void **) &val);
  1605. }
  1606. freeConfigEntry(&e);
  1607. /* Import pr fd into SSL */
  1608. pr_sock = SSL_ImportFD( NULL, sock );
  1609. if( pr_sock == (PRFileDesc *)NULL ) {
  1610. errorCode = PR_GetError();
  1611. slapd_SSL_warn("Security Initialization: Failed to import NSPR "
  1612. "fd into SSL (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1613. errorCode, slapd_pr_strerror(errorCode));
  1614. return 1;
  1615. }
  1616. (*fd) = pr_sock;
  1617. /* Step / Three.6 /
  1618. * - If in FIPS mode, authenticate to the token before
  1619. * doing anything else
  1620. */
  1621. {
  1622. PK11SlotInfo *slot = slapd_pk11_getInternalSlot();
  1623. if (!slot) {
  1624. errorCode = PR_GetError();
  1625. slapd_SSL_warn("Security Initialization: Unable to get internal slot ("
  1626. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1627. errorCode, slapd_pr_strerror(errorCode));
  1628. return -1;
  1629. }
  1630. if(slapd_pk11_isFIPS()) {
  1631. if(slapd_pk11_authenticate(slot, PR_TRUE, NULL) != SECSuccess) {
  1632. errorCode = PR_GetError();
  1633. slapi_log_error(SLAPI_LOG_FATAL, "slapd_ssl_init2",
  1634. "Unable to authenticate (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)\n",
  1635. errorCode, slapd_pr_strerror(errorCode));
  1636. return -1;
  1637. }
  1638. fipsMode = PR_TRUE;
  1639. /* FIPS does not like to use SSLv3 */
  1640. enableSSL3 = PR_FALSE;
  1641. }
  1642. slapd_pk11_setSlotPWValues(slot, 0, 0);
  1643. }
  1644. /*
  1645. * Now, get the complete list of cipher families. Each family
  1646. * has a token name and personality name which we'll use to find
  1647. * appropriate keys and certs, and call SSL_ConfigSecureServer
  1648. * with.
  1649. */
  1650. if((family_list = getChildren(configDN))) {
  1651. char **family;
  1652. char cert_name[1024];
  1653. char *token;
  1654. char *personality;
  1655. char *activation;
  1656. for (family = family_list; *family; family++) {
  1657. token = NULL;
  1658. personality = NULL;
  1659. activation = NULL;
  1660. getConfigEntry( *family, &e );
  1661. if ( e == NULL ) {
  1662. continue;
  1663. }
  1664. activation = slapi_entry_attr_get_charptr( e, "nssslactivation" );
  1665. if((!activation) || (!PL_strcasecmp(activation, "off"))) {
  1666. /* this family was turned off, goto next */
  1667. slapi_ch_free((void **) &activation);
  1668. freeConfigEntry( &e );
  1669. continue;
  1670. }
  1671. slapi_ch_free((void **) &activation);
  1672. token = slapi_entry_attr_get_charptr( e, "nsssltoken" );
  1673. personality = slapi_entry_attr_get_charptr( e, "nssslpersonalityssl" );
  1674. if( token && personality ) {
  1675. if( !PL_strcasecmp(token, "internal") ||
  1676. !PL_strcasecmp(token, "internal (software)") )
  1677. PL_strncpyz(cert_name, personality, sizeof(cert_name));
  1678. else
  1679. /* external PKCS #11 token - attach token name */
  1680. PR_snprintf(cert_name, sizeof(cert_name), "%s:%s", token, personality);
  1681. }
  1682. else {
  1683. errorCode = PR_GetError();
  1684. slapd_SSL_warn("Security Initialization: Failed to get cipher "
  1685. "family information. Missing nsssltoken or"
  1686. "nssslpersonalityssl in %s ("
  1687. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1688. *family, errorCode, slapd_pr_strerror(errorCode));
  1689. slapi_ch_free((void **) &token);
  1690. slapi_ch_free((void **) &personality);
  1691. freeConfigEntry( &e );
  1692. continue;
  1693. }
  1694. slapi_ch_free((void **) &token);
  1695. /* Step Four -- Locate the server certificate */
  1696. cert = slapd_pk11_findCertFromNickname(cert_name, NULL);
  1697. if (cert == NULL) {
  1698. errorCode = PR_GetError();
  1699. slapd_SSL_warn("Security Initialization: Can't find "
  1700. "certificate (%s) for family %s ("
  1701. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1702. cert_name, *family,
  1703. errorCode, slapd_pr_strerror(errorCode));
  1704. }
  1705. /* Step Five -- Get the private key from cert */
  1706. if( cert != NULL )
  1707. key = slapd_pk11_findKeyByAnyCert(cert, NULL);
  1708. if (key == NULL) {
  1709. errorCode = PR_GetError();
  1710. slapd_SSL_warn("Security Initialization: Unable to retrieve "
  1711. "private key for cert %s of family %s ("
  1712. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1713. cert_name, *family,
  1714. errorCode, slapd_pr_strerror(errorCode));
  1715. slapi_ch_free((void **) &personality);
  1716. CERT_DestroyCertificate(cert);
  1717. cert = NULL;
  1718. freeConfigEntry( &e );
  1719. continue;
  1720. }
  1721. /* Step Six -- Configure Secure Server Mode */
  1722. if(pr_sock) {
  1723. SECCertificateUsage returnedUsages;
  1724. if (config_get_validate_cert_switch() == SLAPD_VALIDATE_CERT_OFF) {
  1725. /* If we're set to ignore certificate verification issues,
  1726. * just skip performing verification. */
  1727. rv = SECSuccess;
  1728. } else {
  1729. /* Check if the certificate is valid. */
  1730. rv = CERT_VerifyCertificateNow(
  1731. CERT_GetDefaultCertDB(), cert, PR_TRUE,
  1732. certificateUsageSSLServer,
  1733. SSL_RevealPinArg(pr_sock),
  1734. &returnedUsages);
  1735. if (rv != SECSuccess) {
  1736. /* Log warning */
  1737. errorCode = PR_GetError();
  1738. slapd_SSL_warn("CERT_VerifyCertificateNow: "
  1739. "verify certificate failed "
  1740. "for cert %s of family %s ("
  1741. SLAPI_COMPONENT_NAME_NSPR
  1742. " error %d - %s)",
  1743. cert_name, *family, errorCode,
  1744. slapd_pr_strerror(errorCode));
  1745. /* If we're set to only warn, go ahead and
  1746. * override rv to allow us to start up. */
  1747. if (config_get_validate_cert_switch() == SLAPD_VALIDATE_CERT_WARN) {
  1748. rv = SECSuccess;
  1749. }
  1750. }
  1751. }
  1752. if (SECSuccess == rv) {
  1753. #ifdef HAVE_NSS_DHE
  1754. /* Step If we want weak dh params, flag it on the socket now! */
  1755. rv = SSL_OptionSet(*fd, SSL_ENABLE_SERVER_DHE, PR_TRUE);
  1756. if (rv != SECSuccess) {
  1757. slapd_SSL_warn("Warning, unable to start DHE");
  1758. }
  1759. if (allowweakdhparam & CIPHER_SET_ALLOWWEAKDHPARAM) {
  1760. slapd_SSL_warn("notice, allowing weak parameters on socket.");
  1761. rv = SSL_EnableWeakDHEPrimeGroup(*fd, PR_TRUE);
  1762. if (rv != SECSuccess) {
  1763. slapd_SSL_warn("Warning, unable to allow weak DH params on socket.");
  1764. }
  1765. }
  1766. #endif
  1767. if( slapd_pk11_fortezzaHasKEA(cert) == PR_TRUE ) {
  1768. rv = SSL_ConfigSecureServer(*fd, cert, key, kt_fortezza);
  1769. }
  1770. else {
  1771. rv = SSL_ConfigSecureServer(*fd, cert, key, kt_rsa);
  1772. }
  1773. if (SECSuccess != rv) {
  1774. errorCode = PR_GetError();
  1775. slapd_SSL_warn("ConfigSecureServer: "
  1776. "Server key/certificate is "
  1777. "bad for cert %s of family %s ("
  1778. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1779. cert_name, *family, errorCode,
  1780. slapd_pr_strerror(errorCode));
  1781. }
  1782. }
  1783. }
  1784. if (cert) {
  1785. CERT_DestroyCertificate(cert);
  1786. cert = NULL;
  1787. }
  1788. if (key) {
  1789. slapd_pk11_DestroyPrivateKey(key);
  1790. key = NULL;
  1791. }
  1792. slapi_ch_free((void **) &personality);
  1793. if (SECSuccess != rv) {
  1794. freeConfigEntry( &e );
  1795. continue;
  1796. }
  1797. nFamilies++;
  1798. freeConfigEntry( &e );
  1799. }
  1800. freeChildren( family_list );
  1801. }
  1802. if ( !nFamilies ) {
  1803. slapd_SSL_error("None of the cipher are valid");
  1804. return -1;
  1805. }
  1806. /* Step Seven -- Configure Server Session ID Cache */
  1807. tmpDir = slapd_get_tmp_dir();
  1808. slapi_log_error(SLAPI_LOG_TRACE,
  1809. "slapd_ssl_init2", "tmp dir = %s\n", tmpDir);
  1810. rv = SSL_ConfigServerSessionIDCache(0, stimeout, stimeout, tmpDir);
  1811. slapi_ch_free_string(&tmpDir);
  1812. if (rv) {
  1813. errorCode = PR_GetError();
  1814. if (errorCode == ENOSPC) {
  1815. slapd_SSL_error("Config of server nonce cache failed, "
  1816. "out of disk space! Make more room in /tmp "
  1817. "and try again. (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1818. errorCode, slapd_pr_strerror(errorCode));
  1819. } else {
  1820. slapd_SSL_error("Config of server nonce cache failed (error %d - %s)",
  1821. errorCode, slapd_pr_strerror(errorCode));
  1822. }
  1823. return rv;
  1824. }
  1825. sslStatus = SSL_OptionSet(pr_sock, SSL_SECURITY, PR_TRUE);
  1826. if (sslStatus != SECSuccess) {
  1827. errorCode = PR_GetError();
  1828. slapd_SSL_warn("Security Initialization: Failed to enable security "
  1829. "on the imported socket (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1830. errorCode, slapd_pr_strerror(errorCode));
  1831. return -1;
  1832. }
  1833. /* Explicitly disabling SSL2 - NGK */
  1834. sslStatus = SSL_OptionSet(pr_sock, SSL_ENABLE_SSL2, enableSSL2);
  1835. if (sslStatus != SECSuccess) {
  1836. errorCode = PR_GetError();
  1837. slapd_SSL_warn("Security Initialization: Failed to %s SSLv2 "
  1838. "on the imported socket (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1839. enableSSL2 ? "enable" : "disable",
  1840. errorCode, slapd_pr_strerror(errorCode));
  1841. return -1;
  1842. }
  1843. /* Retrieve the SSL Client Authentication status from cn=config */
  1844. /* Set a default value if no value found */
  1845. getConfigEntry( configDN, &e );
  1846. val = NULL;
  1847. if ( e != NULL ) {
  1848. val = slapi_entry_attr_get_charptr( e, "nssslclientauth" );
  1849. }
  1850. if( !val ) {
  1851. errorCode = PR_GetError();
  1852. slapd_SSL_warn("Security Initialization: Cannot get SSL Client "
  1853. "Authentication status. No nsslclientauth in %s ("
  1854. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1855. configDN, errorCode, slapd_pr_strerror(errorCode));
  1856. switch( SLAPD_SSLCLIENTAUTH_DEFAULT ) {
  1857. case SLAPD_SSLCLIENTAUTH_OFF:
  1858. default_val = "off";
  1859. break;
  1860. case SLAPD_SSLCLIENTAUTH_ALLOWED:
  1861. default_val = "allowed";
  1862. break;
  1863. case SLAPD_SSLCLIENTAUTH_REQUIRED:
  1864. default_val = "required";
  1865. break;
  1866. default:
  1867. default_val = "allowed";
  1868. break;
  1869. }
  1870. val = default_val;
  1871. }
  1872. if( config_set_SSLclientAuth( "nssslclientauth", val, errorbuf,
  1873. CONFIG_APPLY ) != LDAP_SUCCESS ) {
  1874. errorCode = PR_GetError();
  1875. slapd_SSL_warn("Security Initialization: Cannot set SSL Client "
  1876. "Authentication status to \"%s\", error (%s). "
  1877. "Supported values are \"off\", \"allowed\" "
  1878. "and \"required\". (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1879. val, errorbuf, errorCode, slapd_pr_strerror(errorCode));
  1880. }
  1881. if (val != default_val) {
  1882. slapi_ch_free_string(&val);
  1883. }
  1884. if ( e != NULL ) {
  1885. val = slapi_entry_attr_get_charptr( e, "nsSSL3" );
  1886. if ( val ) {
  1887. if ( !PL_strcasecmp( val, "off" ) ) {
  1888. enableSSL3 = PR_FALSE;
  1889. } else if ( !PL_strcasecmp( val, "on" ) ) {
  1890. enableSSL3 = PR_TRUE;
  1891. } else {
  1892. enableSSL3 = slapi_entry_attr_get_bool( e, "nsSSL3" );
  1893. }
  1894. if ( fipsMode && enableSSL3 ) {
  1895. slapd_SSL_warn("Security Initialization: FIPS mode is enabled and "
  1896. "nsSSL3 explicitly set to on - SSLv3 is not approved "
  1897. "for use in FIPS mode - SSLv3 will be disabled - if "
  1898. "you want to use SSLv3, you must use modutil to "
  1899. "disable FIPS in the internal token.");
  1900. enableSSL3 = PR_FALSE;
  1901. }
  1902. }
  1903. slapi_ch_free_string( &val );
  1904. val = slapi_entry_attr_get_charptr( e, "nsTLS1" );
  1905. if ( val ) {
  1906. if ( !PL_strcasecmp( val, "off" ) ) {
  1907. enableTLS1 = PR_FALSE;
  1908. } else if ( !PL_strcasecmp( val, "on" ) ) {
  1909. enableTLS1 = PR_TRUE;
  1910. } else {
  1911. enableTLS1 = slapi_entry_attr_get_bool( e, "nsTLS1" );
  1912. }
  1913. } else if (enabledNSSVersions.max >= CURRENT_DEFAULT_SSL_VERSION) {
  1914. enableTLS1 = PR_TRUE; /* If available, enable TLS1 */
  1915. }
  1916. slapi_ch_free_string( &val );
  1917. #if !defined(NSS_TLS10) /* NSS_TLS11 or newer */
  1918. val = slapi_entry_attr_get_charptr( e, "sslVersionMin" );
  1919. if ( val ) {
  1920. (void)set_NSS_version(val, &NSSVersionMin, 1);
  1921. }
  1922. slapi_ch_free_string( &val );
  1923. val = slapi_entry_attr_get_charptr( e, "sslVersionMax" );
  1924. if ( val ) {
  1925. (void)set_NSS_version(val, &NSSVersionMax, 0);
  1926. }
  1927. slapi_ch_free_string( &val );
  1928. if (NSSVersionMin > NSSVersionMax) {
  1929. (void) slapi_getSSLVersion_str(NSSVersionMin, mymin, sizeof(mymin));
  1930. (void) slapi_getSSLVersion_str(NSSVersionMax, mymax, sizeof(mymax));
  1931. slapd_SSL_warn("The min value of NSS version range \"%s\" is greater than the max value \"%s\".",
  1932. mymin, mymax);
  1933. (void) slapi_getSSLVersion_str(enabledNSSVersions.max, newmax, sizeof(newmax));
  1934. slapd_SSL_warn("Reset the max \"%s\" to supported max \"%s\".",
  1935. mymax, newmax);
  1936. NSSVersionMax = enabledNSSVersions.max;
  1937. }
  1938. #endif
  1939. }
  1940. #if !defined(NSS_TLS10) /* NSS_TLS11 or newer */
  1941. if (NSSVersionMin > 0) {
  1942. /* Use new NSS API SSL_VersionRangeSet (NSS3.14 or newer) */
  1943. slapdNSSVersions.min = NSSVersionMin;
  1944. slapdNSSVersions.max = NSSVersionMax;
  1945. restrict_SSLVersionRange();
  1946. (void) slapi_getSSLVersion_str(slapdNSSVersions.min, mymin, sizeof(mymin));
  1947. (void) slapi_getSSLVersion_str(slapdNSSVersions.max, mymax, sizeof(mymax));
  1948. slapi_log_error(SLAPI_LOG_FATAL, "SSL Initialization",
  1949. "Configured SSL version range: min: %s, max: %s\n",
  1950. mymin, mymax);
  1951. sslStatus = SSL_VersionRangeSet(pr_sock, &slapdNSSVersions);
  1952. if (sslStatus == SECSuccess) {
  1953. /* Set the restricted value to the cn=encryption entry */
  1954. } else {
  1955. slapd_SSL_error("SSL Initialization 2: "
  1956. "Failed to set SSL range: min: %s, max: %s\n",
  1957. mymin, mymax);
  1958. }
  1959. } else {
  1960. #endif
  1961. /* deprecated code */
  1962. sslStatus = SSL_OptionSet(pr_sock, SSL_ENABLE_SSL3, enableSSL3);
  1963. if (sslStatus != SECSuccess) {
  1964. errorCode = PR_GetError();
  1965. slapd_SSL_warn("Security Initialization: Failed to %s SSLv3 "
  1966. "on the imported socket (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1967. enableSSL3 ? "enable" : "disable",
  1968. errorCode, slapd_pr_strerror(errorCode));
  1969. }
  1970. sslStatus = SSL_OptionSet(pr_sock, SSL_ENABLE_TLS, enableTLS1);
  1971. if (sslStatus != SECSuccess) {
  1972. errorCode = PR_GetError();
  1973. slapd_SSL_warn("Security Initialization: Failed to %s TLSv1 "
  1974. "on the imported socket (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  1975. enableTLS1 ? "enable" : "disable",
  1976. errorCode, slapd_pr_strerror(errorCode));
  1977. }
  1978. #if !defined(NSS_TLS10) /* NSS_TLS11 or newer */
  1979. }
  1980. #endif
  1981. freeConfigEntry( &e );
  1982. if(( slapd_SSLclientAuth = config_get_SSLclientAuth()) != SLAPD_SSLCLIENTAUTH_OFF ) {
  1983. int err;
  1984. switch (slapd_SSLclientAuth) {
  1985. case SLAPD_SSLCLIENTAUTH_ALLOWED:
  1986. #ifdef SSL_REQUIRE_CERTIFICATE /* new feature */
  1987. if ((err = SSL_OptionSet (pr_sock, SSL_REQUIRE_CERTIFICATE, PR_FALSE)) < 0) {
  1988. PRErrorCode prerr = PR_GetError();
  1989. LDAPDebug (LDAP_DEBUG_ANY,
  1990. "SSL_OptionSet(SSL_REQUIRE_CERTIFICATE,PR_FALSE) %d "
  1991. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  1992. err, prerr, slapd_pr_strerror(prerr));
  1993. }
  1994. #endif
  1995. /* Give the client a clear opportunity to send her certificate: */
  1996. case SLAPD_SSLCLIENTAUTH_REQUIRED:
  1997. if ((err = SSL_OptionSet (pr_sock, SSL_REQUEST_CERTIFICATE, PR_TRUE)) < 0) {
  1998. PRErrorCode prerr = PR_GetError();
  1999. LDAPDebug (LDAP_DEBUG_ANY,
  2000. "SSL_OptionSet(SSL_REQUEST_CERTIFICATE,PR_TRUE) %d "
  2001. SLAPI_COMPONENT_NAME_NSPR " error %d (%s)\n",
  2002. err, prerr, slapd_pr_strerror(prerr));
  2003. }
  2004. default: break;
  2005. }
  2006. }
  2007. /* Introduce a way of knowing whether slapd_ssl_init2 has
  2008. * already been executed.
  2009. * The cases in which slapd_ssl_init2 is executed during an
  2010. * Start TLS operation are not taken into account, for it is
  2011. * the fact of being executed by the server's SSL listener socket
  2012. * that matters. */
  2013. if (!startTLS)
  2014. _ssl_listener_initialized = 1; /* --ugaston */
  2015. return 0;
  2016. }
  2017. /* richm 20020227
  2018. To do LDAP client SSL init, we need to do
  2019. static void
  2020. ldapssl_basic_init( void )
  2021. {
  2022. PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
  2023. PR_SetConcurrency( 4 );
  2024. }
  2025. NSS_Init(certdbpath);
  2026. SSL_OptionSetDefault(SSL_ENABLE_SSL2, PR_FALSE);
  2027. SSL_OptionSetDefault(SSL_ENABLE_SSL3, PR_TRUE);
  2028. s = NSS_SetDomesticPolicy();
  2029. We already do pr_init, we don't need pr_setconcurrency, we already do nss_init and the rest
  2030. */
  2031. int
  2032. slapd_SSL_client_auth (LDAP* ld)
  2033. {
  2034. int rc = 0;
  2035. PRErrorCode errorCode;
  2036. char* pw = NULL;
  2037. char ** family_list;
  2038. Slapi_Entry *entry = NULL;
  2039. char cert_name[1024];
  2040. char *token = NULL;
  2041. SVRCOREStdPinObj *StdPinObj;
  2042. SVRCOREError err = SVRCORE_Success;
  2043. char *finalpersonality = NULL;
  2044. char *CertExtractFile = NULL;
  2045. char *KeyExtractFile = NULL;
  2046. if ((family_list = getChildren(configDN))) {
  2047. char **family;
  2048. char *activation = NULL;
  2049. char *cipher = NULL;
  2050. char *personality = NULL;
  2051. for (family = family_list; *family; family++) {
  2052. getConfigEntry( *family, &entry );
  2053. if ( entry == NULL ) {
  2054. continue;
  2055. }
  2056. activation = slapi_entry_attr_get_charptr( entry, "nssslactivation" );
  2057. if ((!activation) || (!PL_strcasecmp(activation, "off"))) {
  2058. /* this family was turned off, goto next */
  2059. slapi_ch_free((void **) &activation);
  2060. freeConfigEntry( &entry );
  2061. continue;
  2062. }
  2063. slapi_ch_free((void **) &activation);
  2064. personality = slapi_entry_attr_get_charptr( entry, "nssslpersonalityssl" );
  2065. cipher = slapi_entry_attr_get_charptr( entry, "cn" );
  2066. if ( cipher && !PL_strcasecmp(cipher, "RSA" )) {
  2067. char *ssltoken;
  2068. /* If there already is a token name, use it */
  2069. if (token) {
  2070. slapi_ch_free_string(&personality);
  2071. slapi_ch_free_string(&cipher);
  2072. freeConfigEntry( &entry );
  2073. continue;
  2074. }
  2075. ssltoken = slapi_entry_attr_get_charptr( entry, "nsssltoken" );
  2076. if( ssltoken && personality ) {
  2077. if (!PL_strcasecmp(ssltoken, "internal") ||
  2078. !PL_strcasecmp(ssltoken, "internal (software)")) {
  2079. /* Translate config internal name to more
  2080. * readable form. Certificate name is just
  2081. * the personality for internal tokens.
  2082. */
  2083. token = slapi_ch_strdup(internalTokenName);
  2084. #if defined(USE_OPENLDAP)
  2085. /* openldap needs tokenname:certnick */
  2086. PR_snprintf(cert_name, sizeof(cert_name), "%s:%s", token, personality);
  2087. #else
  2088. PL_strncpyz(cert_name, personality, sizeof(cert_name));
  2089. #endif
  2090. slapi_ch_free_string(&ssltoken);
  2091. } else {
  2092. /* external PKCS #11 token - attach token name */
  2093. token = ssltoken; /*ssltoken was already dupped */
  2094. PR_snprintf(cert_name, sizeof(cert_name), "%s:%s", token, personality);
  2095. }
  2096. } else {
  2097. errorCode = PR_GetError();
  2098. slapd_SSL_warn("Security Initialization: Failed to get cipher "
  2099. "family information. Missing nsssltoken or"
  2100. "nssslpersonalityssl in %s ("
  2101. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  2102. *family, errorCode, slapd_pr_strerror(errorCode));
  2103. slapi_ch_free_string(&ssltoken);
  2104. slapi_ch_free_string(&personality);
  2105. slapi_ch_free_string(&cipher);
  2106. freeConfigEntry( &entry );
  2107. continue;
  2108. }
  2109. } else { /* external PKCS #11 cipher */
  2110. char *ssltoken;
  2111. ssltoken = slapi_entry_attr_get_charptr( entry, "nsssltoken" );
  2112. if( ssltoken && personality ) {
  2113. /* free the old token and remember the new one */
  2114. if (token) slapi_ch_free_string(&token);
  2115. token = ssltoken; /*ssltoken was already dupped */
  2116. /* external PKCS #11 token - attach token name */
  2117. PR_snprintf(cert_name, sizeof(cert_name), "%s:%s", token, personality);
  2118. } else {
  2119. errorCode = PR_GetError();
  2120. slapd_SSL_warn("Security Initialization: Failed to get cipher "
  2121. "family information. Missing nsssltoken or"
  2122. "nssslpersonalityssl in %s ("
  2123. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  2124. * family, errorCode, slapd_pr_strerror(errorCode));
  2125. slapi_ch_free_string(&ssltoken);
  2126. slapi_ch_free_string(&personality);
  2127. slapi_ch_free_string(&cipher);
  2128. freeConfigEntry( &entry );
  2129. continue;
  2130. }
  2131. }
  2132. slapi_ch_free_string(&finalpersonality);
  2133. finalpersonality = personality;
  2134. slapi_ch_free_string(&cipher);
  2135. /* Get ServerCert/KeyExtractFile from given entry if any. */
  2136. slapi_ch_free_string(&CertExtractFile);
  2137. CertExtractFile = slapi_entry_attr_get_charptr(entry, "ServerCertExtractFile");
  2138. slapi_ch_free_string(&KeyExtractFile);
  2139. KeyExtractFile = slapi_entry_attr_get_charptr(entry, "ServerKeyExtractFile");
  2140. freeConfigEntry( &entry );
  2141. } /* end of for */
  2142. freeChildren( family_list );
  2143. }
  2144. /* Free config data */
  2145. if (!svrcore_setup()) {
  2146. #ifdef WITH_SYSTEMD
  2147. slapd_SSL_warn("Sending pin request to SVRCore. You may need to run "
  2148. "systemd-tty-ask-password-agent to provide the password.");
  2149. #endif
  2150. StdPinObj = (SVRCOREStdPinObj *)SVRCORE_GetRegisteredPinObj();
  2151. err = SVRCORE_StdPinGetPin( &pw, StdPinObj, token );
  2152. if ( err != SVRCORE_Success || pw == NULL) {
  2153. errorCode = PR_GetError();
  2154. slapd_SSL_warn("SSL client authentication cannot be used "
  2155. "(no password). (" SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  2156. errorCode, slapd_pr_strerror(errorCode));
  2157. } else {
  2158. #if defined(USE_OPENLDAP)
  2159. if (slapi_client_uses_non_nss(ld)) {
  2160. char *certdir = config_get_certdir();
  2161. char *keyfile = NULL;
  2162. char *certfile = NULL;
  2163. if (KeyExtractFile) {
  2164. if ('/' == *KeyExtractFile) {
  2165. keyfile = KeyExtractFile;
  2166. } else {
  2167. keyfile = slapi_ch_smprintf("%s/%s", certdir, KeyExtractFile);
  2168. slapi_ch_free_string(&KeyExtractFile);
  2169. }
  2170. } else {
  2171. keyfile = slapi_ch_smprintf("%s/%s-Key%s", certdir, finalpersonality, PEMEXT);
  2172. }
  2173. if (CertExtractFile) {
  2174. if ('/' == *CertExtractFile) {
  2175. certfile = CertExtractFile;
  2176. } else {
  2177. certfile = slapi_ch_smprintf("%s/%s", certdir, CertExtractFile);
  2178. slapi_ch_free_string(&CertExtractFile);
  2179. }
  2180. } else {
  2181. certfile = slapi_ch_smprintf("%s/%s%s", certdir, finalpersonality, PEMEXT);
  2182. }
  2183. slapi_ch_free_string(&certdir);
  2184. if (PR_SUCCESS != PR_Access(keyfile, PR_ACCESS_EXISTS)) {
  2185. slapi_ch_free_string(&keyfile);
  2186. slapd_SSL_warn("SSL key file (%s) for client authentication does not exist. "
  2187. "Using %s", keyfile, SERVER_KEY_NAME);
  2188. keyfile = slapi_ch_strdup(SERVER_KEY_NAME);
  2189. }
  2190. rc = ldap_set_option(ld, LDAP_OPT_X_TLS_KEYFILE, keyfile);
  2191. if (rc) {
  2192. slapd_SSL_warn("SSL client authentication cannot be used "
  2193. "unable to set the key to use to %s", keyfile);
  2194. }
  2195. slapi_ch_free_string(&keyfile);
  2196. rc = PR_Access(certfile, PR_ACCESS_EXISTS);
  2197. if (rc) {
  2198. slapi_ch_free_string(&certfile);
  2199. slapd_SSL_warn("SSL cert file (%s) for client authentication does not exist. "
  2200. "Using %s", certfile, cert_name);
  2201. certfile = cert_name;
  2202. }
  2203. rc = ldap_set_option(ld, LDAP_OPT_X_TLS_CERTFILE, certfile);
  2204. if (rc) {
  2205. slapd_SSL_warn("SSL client authentication cannot be used "
  2206. "unable to set the cert to use to %s", certfile);
  2207. }
  2208. if (certfile != cert_name) {
  2209. slapi_ch_free_string(&certfile);
  2210. }
  2211. } else {
  2212. rc = ldap_set_option(ld, LDAP_OPT_X_TLS_KEYFILE, SERVER_KEY_NAME);
  2213. if (rc) {
  2214. slapd_SSL_warn("SSL client authentication cannot be used "
  2215. "unable to set the key to use to %s", SERVER_KEY_NAME);
  2216. }
  2217. rc = ldap_set_option(ld, LDAP_OPT_X_TLS_CERTFILE, cert_name);
  2218. if (rc) {
  2219. slapd_SSL_warn("SSL client authentication cannot be used "
  2220. "unable to set the cert to use to %s", cert_name);
  2221. }
  2222. }
  2223. /*
  2224. * not sure what else needs to be done for client auth - don't
  2225. * currently have a way to pass in the password to use to unlock
  2226. * the keydb - nor a way to disable caching
  2227. */
  2228. #else /* !USE_OPENLDAP */
  2229. rc = ldapssl_enable_clientauth (ld, SERVER_KEY_NAME, pw, cert_name);
  2230. if (rc != 0) {
  2231. errorCode = PR_GetError();
  2232. slapd_SSL_warn("ldapssl_enable_clientauth(%s, %s) %i ("
  2233. SLAPI_COMPONENT_NAME_NSPR " error %d - %s)",
  2234. SERVER_KEY_NAME, cert_name, rc,
  2235. errorCode, slapd_pr_strerror(errorCode));
  2236. } else {
  2237. /*
  2238. * We cannot allow NSS to cache outgoing client auth connections -
  2239. * each client auth connection must have it's own non-shared SSL
  2240. * connection to the peer so that it will go through the
  2241. * entire handshake protocol every time including the use of its
  2242. * own unique client cert - see bug 605457
  2243. */
  2244. ldapssl_set_option(ld, SSL_NO_CACHE, PR_TRUE);
  2245. }
  2246. #endif
  2247. }
  2248. }
  2249. slapi_ch_free_string(&token);
  2250. slapi_ch_free_string(&pw);
  2251. slapi_ch_free_string(&finalpersonality);
  2252. LDAPDebug (LDAP_DEBUG_TRACE, "slapd_SSL_client_auth() %i\n", rc, 0, 0);
  2253. return rc;
  2254. }
  2255. /* Function for keeping track of the SSL initialization status:
  2256. * - returns 1: when slapd_ssl_init has been executed
  2257. */
  2258. int
  2259. slapd_security_library_is_initialized()
  2260. {
  2261. return _security_library_initialized;
  2262. }
  2263. /* Function for keeping track of the SSL listener socket initialization status:
  2264. * - returns 1: when slapd_ssl_init2 has been executed
  2265. */
  2266. int
  2267. slapd_ssl_listener_is_initialized()
  2268. {
  2269. return _ssl_listener_initialized;
  2270. }
  2271. int
  2272. slapd_nss_is_initialized()
  2273. {
  2274. return _nss_initialized;
  2275. }
  2276. /* memory to store tmpdir is allocated and returned; caller should free it. */
  2277. char* slapd_get_tmp_dir()
  2278. {
  2279. static char tmp[MAXPATHLEN];
  2280. char* tmpdir = NULL;;
  2281. tmp[0] = '\0';
  2282. if((tmpdir = config_get_tmpdir()) == NULL)
  2283. {
  2284. slapi_log_error(
  2285. SLAPI_LOG_FATAL,
  2286. "slapd_get_tmp_dir",
  2287. "config_get_tmpdir returns NULL Setting tmp dir to default\n");
  2288. strcpy(tmp, "/tmp");
  2289. return slapi_ch_strdup(tmp);
  2290. }
  2291. if(mkdir(tmpdir, 00770) == -1)
  2292. {
  2293. if (errno == EEXIST) {
  2294. slapi_log_error(
  2295. SLAPI_LOG_TRACE,
  2296. "slapd_get_tmp_dir",
  2297. "mkdir(%s, 00770) - already exists\n",
  2298. tmpdir);
  2299. } else {
  2300. slapi_log_error(
  2301. SLAPI_LOG_FATAL,
  2302. "slapd_get_tmp_dir",
  2303. "mkdir(%s, 00770) Error: %s\n",
  2304. tmpdir, strerror(errno));
  2305. }
  2306. }
  2307. return ( tmpdir );
  2308. }
  2309. SECKEYPrivateKey *
  2310. slapd_get_unlocked_key_for_cert(CERTCertificate *cert, void *pin_arg)
  2311. {
  2312. SECKEYPrivateKey *key = NULL;
  2313. PK11SlotListElement *sle;
  2314. PK11SlotList *slotlist = PK11_GetAllSlotsForCert(cert, NULL);
  2315. const char *certsubject = cert->subjectName ? cert->subjectName : "unknown cert";
  2316. if (!slotlist) {
  2317. PRErrorCode errcode = PR_GetError();
  2318. slapi_log_error(SLAPI_LOG_FATAL, "slapd_get_unlocked_key_for_cert",
  2319. "Error: cannot get slot list for certificate [%s] (%d: %s)\n",
  2320. certsubject, errcode, slapd_pr_strerror(errcode));
  2321. return key;
  2322. }
  2323. for (sle = slotlist->head; sle; sle = sle->next) {
  2324. PK11SlotInfo *slot = sle->slot;
  2325. const char *slotname = (slot && PK11_GetSlotName(slot)) ? PK11_GetSlotName(slot) : "unknown slot";
  2326. const char *tokenname = (slot && PK11_GetTokenName(slot)) ? PK11_GetTokenName(slot) : "unknown token";
  2327. if (!slot) {
  2328. slapi_log_error(SLAPI_LOG_TRACE, "slapd_get_unlocked_key_for_cert",
  2329. "Missing slot for slot list element for certificate [%s]\n",
  2330. certsubject);
  2331. } else if (!PK11_NeedLogin(slot) || PK11_IsLoggedIn(slot, pin_arg)) {
  2332. key = PK11_FindKeyByDERCert(slot, cert, pin_arg);
  2333. slapi_log_error(SLAPI_LOG_TRACE, "slapd_get_unlocked_key_for_cert",
  2334. "Found unlocked slot [%s] token [%s] for certificate [%s]\n",
  2335. slotname, tokenname, certsubject);
  2336. break;
  2337. } else {
  2338. PRErrorCode errcode = PR_GetError();
  2339. slapi_log_error(SLAPI_LOG_FATAL, "slapd_get_unlocked_key_for_cert",
  2340. "Skipping locked slot [%s] token [%s] for certificate [%s] (%d - %s)\n",
  2341. slotname, tokenname, certsubject, errcode, slapd_pr_strerror(errcode));
  2342. }
  2343. }
  2344. if (!key) {
  2345. slapi_log_error(SLAPI_LOG_FATAL, "slapd_get_unlocked_key_for_cert",
  2346. "Error: could not find any unlocked slots for certificate [%s]. "
  2347. "Please review your TLS/SSL configuration. The following slots were found:\n",
  2348. certsubject);
  2349. for (sle = slotlist->head; sle; sle = sle->next) {
  2350. PK11SlotInfo *slot = sle->slot;
  2351. const char *slotname = (slot && PK11_GetSlotName(slot)) ? PK11_GetSlotName(slot) : "unknown slot";
  2352. const char *tokenname = (slot && PK11_GetTokenName(slot)) ? PK11_GetTokenName(slot) : "unknown token";
  2353. slapi_log_error(SLAPI_LOG_FATAL, "slapd_get_unlocked_key_for_cert",
  2354. "Slot [%s] token [%s] was locked.\n",
  2355. slotname, tokenname);
  2356. }
  2357. }
  2358. PK11_FreeSlotList(slotlist);
  2359. return key;
  2360. }
  2361. /*
  2362. * Functions to extract key and cert from the NSS cert db.
  2363. */
  2364. #include <libgen.h>
  2365. #include <seccomon.h>
  2366. #include <secmodt.h>
  2367. #include <certt.h>
  2368. #include <base64.h>
  2369. #define DONOTEDIT "This file is auto-generated by 389-ds-base.\nDo not edit directly.\n"
  2370. #define NS_CERT_HEADER "-----BEGIN CERTIFICATE-----"
  2371. #define NS_CERT_TRAILER "-----END CERTIFICATE-----"
  2372. #define KEY_HEADER "-----BEGIN PRIVATE KEY-----"
  2373. #define KEY_TRAILER "-----END PRIVATE KEY-----"
  2374. #define ENCRYPTED_KEY_HEADER "-----BEGIN ENCRYPTED PRIVATE KEY-----"
  2375. #define ENCRYPTED_KEY_TRAILER "-----END ENCRYPTED PRIVATE KEY-----"
  2376. typedef struct {
  2377. enum {
  2378. PW_NONE = 0,
  2379. PW_FROMFILE = 1,
  2380. PW_PLAINTEXT = 2,
  2381. PW_EXTERNAL = 3
  2382. } source;
  2383. char *data;
  2384. } secuPWData;
  2385. static SECStatus
  2386. listCerts(CERTCertDBHandle *handle, CERTCertificate *cert, PK11SlotInfo *slot,
  2387. PRFileDesc *outfile, void *pwarg)
  2388. {
  2389. SECItem data;
  2390. SECStatus rv = SECFailure;
  2391. CERTCertList *certs;
  2392. CERTCertListNode *node;
  2393. CERTCertificate *the_cert = NULL;
  2394. char *name = NULL;
  2395. if (!cert) {
  2396. slapi_log_error(SLAPI_LOG_FATAL, "listCerts", "No cert given\n");
  2397. return rv;
  2398. }
  2399. name = cert->nickname;
  2400. if (!name) {
  2401. slapi_log_error(SLAPI_LOG_FATAL, "listCerts", "No cert nickname\n");
  2402. return rv;
  2403. }
  2404. the_cert = CERT_FindCertByNicknameOrEmailAddr(handle, name);
  2405. if (!the_cert) {
  2406. slapi_log_error(SLAPI_LOG_FATAL, "listCerts", "Could not find cert: %s\n", name);
  2407. return SECFailure;
  2408. }
  2409. PR_fprintf(outfile, "%s\n", DONOTEDIT);
  2410. /* Here, we have one cert with the desired nickname or email
  2411. * address. Now, we will attempt to get a list of ALL certs
  2412. * with the same subject name as the cert we have. That list
  2413. * should contain, at a minimum, the one cert we have already found.
  2414. * If the list of certs is empty (NULL), the libraries have failed.
  2415. */
  2416. certs = CERT_CreateSubjectCertList(NULL, handle, &the_cert->derSubject,
  2417. PR_Now(), PR_FALSE);
  2418. CERT_DestroyCertificate(the_cert);
  2419. if (!certs) {
  2420. slapi_log_error(SLAPI_LOG_FATAL, "listCerts", "problem printing certificates");
  2421. return SECFailure;
  2422. }
  2423. for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node,certs); node = CERT_LIST_NEXT(node)) {
  2424. the_cert = node->cert;
  2425. PR_fprintf(outfile, "Issuer: %s\n", the_cert->issuerName);
  2426. PR_fprintf(outfile, "Subject: %s\n", the_cert->subjectName);
  2427. /* now get the subjectList that matches this cert */
  2428. data.data = the_cert->derCert.data;
  2429. data.len = the_cert->derCert.len;
  2430. PR_fprintf(outfile, "\n%s\n%s\n%s\n", NS_CERT_HEADER,
  2431. BTOA_DataToAscii(data.data, data.len), NS_CERT_TRAILER);
  2432. rv = SECSuccess;
  2433. }
  2434. if (certs) {
  2435. CERT_DestroyCertList(certs);
  2436. }
  2437. if (rv) {
  2438. slapi_log_error(SLAPI_LOG_FATAL, "listCerts", "problem printing certificate nicknames");
  2439. return SECFailure;
  2440. }
  2441. return rv;
  2442. }
  2443. static char *
  2444. gen_pem_path(char *filename)
  2445. {
  2446. char *pem = NULL;
  2447. char *pempath = NULL;
  2448. char *dname = NULL;
  2449. char *bname = NULL;
  2450. char *certdir = config_get_certdir();
  2451. if (!filename) {
  2452. goto bail;
  2453. }
  2454. pem = PL_strstr(filename, PEMEXT);
  2455. if (pem) {
  2456. *pem = '\0';
  2457. }
  2458. bname = basename(filename);
  2459. dname = dirname(filename);
  2460. if (!PL_strcmp(dname, ".")) {
  2461. /* just a file name */
  2462. pempath = slapi_ch_smprintf("%s/%s%s", certdir, bname, PEMEXT);
  2463. } else if (*dname == '/') {
  2464. /* full path */
  2465. pempath = slapi_ch_smprintf("%s/%s%s", dname, bname, PEMEXT);
  2466. } else {
  2467. /* relative path */
  2468. pempath = slapi_ch_smprintf("%s/%s/%s%s", certdir, dname, bname, PEMEXT);
  2469. }
  2470. bail:
  2471. return pempath;
  2472. }
  2473. static int
  2474. slapd_extract_cert(Slapi_Entry *entry, int isCA)
  2475. {
  2476. CERTCertDBHandle *certHandle;
  2477. char *certdir = config_get_certdir();
  2478. CERTCertListNode *node;
  2479. CERTCertList *list = PK11_ListCerts(PK11CertListAll, NULL);
  2480. PRFileDesc *outFile = NULL;
  2481. SECStatus rv = SECFailure;
  2482. char *CertExtractFile = NULL;
  2483. char *certfile = NULL;
  2484. char *personality = NULL;
  2485. if (!entry) {
  2486. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_cert",
  2487. "No entry is given for %s Cert.\n", isCA?"CA":"Server");
  2488. goto bail;
  2489. }
  2490. /* Get CertExtractFile from given entry if any. */
  2491. if (isCA) {
  2492. CertExtractFile = slapi_entry_attr_get_charptr(entry, "CACertExtractFile");
  2493. } else {
  2494. CertExtractFile = slapi_entry_attr_get_charptr(entry, "ServerCertExtractFile");
  2495. personality = slapi_entry_attr_get_charptr(entry, "nsSSLPersonalitySSL" );
  2496. }
  2497. certfile = gen_pem_path(CertExtractFile);
  2498. if (isCA) {
  2499. slapi_ch_free_string(&CACertPemFile);
  2500. CACertPemFile = certfile;
  2501. }
  2502. certHandle = CERT_GetDefaultCertDB();
  2503. for (node = CERT_LIST_HEAD(list); !CERT_LIST_END(node, list);
  2504. node = CERT_LIST_NEXT(node)) {
  2505. CERTCertificate *cert = node->cert;
  2506. CERTCertTrust trust;
  2507. switch (isCA) {
  2508. case PR_TRUE:
  2509. if ((CERT_GetCertTrust(cert, &trust) == SECSuccess) &&
  2510. (trust.sslFlags & (CERTDB_VALID_CA|CERTDB_TRUSTED_CA|CERTDB_TRUSTED_CLIENT_CA))) {
  2511. /* default token "internal" */
  2512. PK11SlotInfo *slot = slapd_pk11_getInternalKeySlot();
  2513. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_cert", "CA CERT NAME: %s\n", cert->nickname);
  2514. if (!certfile) {
  2515. certfile = slapi_ch_smprintf("%s/%s%s", certdir, escape_string_for_filename(cert->nickname), PEMEXT);
  2516. entrySetValue(slapi_entry_get_sdn(entry), "CACertExtractFile", certfile);
  2517. slapi_set_cacertfile(certfile);
  2518. }
  2519. if (!outFile) {
  2520. outFile = PR_Open(certfile, PR_CREATE_FILE | PR_RDWR | PR_TRUNCATE, 00660);
  2521. }
  2522. if (!outFile) {
  2523. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_cert",
  2524. "Unable to open \"%s\" for writing (%d, %d).\n",
  2525. certfile, PR_GetError(), PR_GetOSError());
  2526. goto bail;
  2527. }
  2528. rv = listCerts(certHandle, cert, slot, outFile, NULL);
  2529. if (rv) {
  2530. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_cert", "listCerts failed\n");
  2531. break;
  2532. }
  2533. }
  2534. break;
  2535. default:
  2536. if (!PL_strcmp(cert->nickname, personality)) {
  2537. PK11SlotInfo *slot = slapd_pk11_getInternalKeySlot();
  2538. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_cert", "SERVER CERT NAME: %s\n", cert->nickname);
  2539. if (!certfile) {
  2540. certfile = slapi_ch_smprintf("%s/%s%s", certdir, escape_string_for_filename(cert->nickname), PEMEXT);
  2541. }
  2542. if (!outFile) {
  2543. outFile = PR_Open(certfile, PR_CREATE_FILE | PR_RDWR | PR_TRUNCATE, 00660);
  2544. }
  2545. if (!outFile) {
  2546. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_cert",
  2547. "Unable to open \"%s\" for writing (%d, %d).\n",
  2548. certfile, PR_GetError(), PR_GetOSError());
  2549. goto bail;
  2550. }
  2551. rv = listCerts(certHandle, cert, slot, outFile, NULL);
  2552. if (rv) {
  2553. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_cert", "listCerts failed\n");
  2554. }
  2555. PR_Close(outFile);
  2556. outFile = NULL;
  2557. break; /* One cert per one pem file. */
  2558. }
  2559. break;
  2560. }
  2561. }
  2562. rv = SECSuccess;
  2563. bail:
  2564. CERT_DestroyCertList(list);
  2565. slapi_ch_free_string(&CertExtractFile);
  2566. if (CACertPemFile != certfile) {
  2567. slapi_ch_free_string(&certfile);
  2568. }
  2569. slapi_ch_free_string(&personality);
  2570. if (outFile) {
  2571. PR_Close(outFile);
  2572. }
  2573. return rv;
  2574. }
  2575. /*
  2576. * Borrowed from keyutil.c (crypto-util)
  2577. *
  2578. * Extract the public and private keys and the subject
  2579. * distinguished from the cert with the given nickname
  2580. * in the given slot.
  2581. *
  2582. * @param nickname the certificate nickname
  2583. * @param slot the slot where keys it was loaded
  2584. * @param pwdat module authentication password
  2585. * @param privkey private key out
  2586. * @param pubkey public key out
  2587. * @param subject subject out
  2588. */
  2589. static SECStatus
  2590. extractRSAKeysAndSubject(
  2591. const char *nickname,
  2592. PK11SlotInfo *slot,
  2593. secuPWData *pwdata,
  2594. SECKEYPrivateKey **privkey,
  2595. SECKEYPublicKey **pubkey,
  2596. CERTName **subject)
  2597. {
  2598. PRErrorCode rv = SECFailure;
  2599. CERTCertificate *cert = PK11_FindCertFromNickname((char *)nickname, NULL);
  2600. if (!cert) {
  2601. rv = PR_GetError();
  2602. slapi_log_error(SLAPI_LOG_FATAL, "extractRSAKeysAndSubject",
  2603. "Failed extract cert with %s, (%d-%s, %d).\n",
  2604. nickname, rv, slapd_pr_strerror(rv), PR_GetOSError());
  2605. goto bail;
  2606. }
  2607. *pubkey = CERT_ExtractPublicKey(cert);
  2608. if (!*pubkey) {
  2609. rv = PR_GetError();
  2610. slapi_log_error(SLAPI_LOG_FATAL, "extractRSAKeysAndSubject",
  2611. "Could not get public key from cert for %s, (%d-%s, %d)\n",
  2612. nickname, rv, slapd_pr_strerror(rv), PR_GetOSError());
  2613. goto bail;
  2614. }
  2615. *privkey = PK11_FindKeyByDERCert(slot, cert, pwdata);
  2616. if (!*privkey) {
  2617. rv = PR_GetError();
  2618. slapi_log_error(SLAPI_LOG_FATAL, "extractRSAKeysAndSubject",
  2619. "Unable to find the key with PK11_FindKeyByDERCert for %s, (%d-%s, %d)\n",
  2620. nickname, rv, slapd_pr_strerror(rv), PR_GetOSError());
  2621. *privkey= PK11_FindKeyByAnyCert(cert, &pwdata);
  2622. if (!*privkey) {
  2623. rv = PR_GetError();
  2624. slapi_log_error(SLAPI_LOG_FATAL, "extractRSAKeysAndSubject",
  2625. "Unable to find the key with PK11_FindKeyByAnyCert for %s, (%d-%s, %d)\n",
  2626. nickname, rv, slapd_pr_strerror(rv), PR_GetOSError());
  2627. goto bail;
  2628. }
  2629. }
  2630. PR_ASSERT(((*privkey)->keyType) == rsaKey);
  2631. *subject = CERT_AsciiToName(cert->subjectName);
  2632. if (!*subject) {
  2633. slapi_log_error(SLAPI_LOG_FATAL, "extractRSAKeysAndSubject",
  2634. "Improperly formatted name: \"%s\"\n",
  2635. cert->subjectName);
  2636. goto bail;
  2637. }
  2638. rv = SECSuccess;
  2639. bail:
  2640. if (cert)
  2641. CERT_DestroyCertificate(cert);
  2642. return rv;
  2643. }
  2644. /*
  2645. * Decrypt the private key
  2646. */
  2647. SECStatus DecryptKey(
  2648. SECKEYEncryptedPrivateKeyInfo *epki,
  2649. SECOidTag algTag,
  2650. SECItem *pwitem,
  2651. secuPWData *pwdata,
  2652. SECItem *derPKI)
  2653. {
  2654. SECItem *cryptoParam = NULL;
  2655. PK11SymKey *symKey = NULL;
  2656. PK11Context *ctx = NULL;
  2657. SECStatus rv = SECFailure;
  2658. if (!pwitem) {
  2659. return rv;
  2660. }
  2661. do {
  2662. SECAlgorithmID algid = epki->algorithm;
  2663. CK_MECHANISM_TYPE cryptoMechType;
  2664. CK_ATTRIBUTE_TYPE operation = CKA_DECRYPT;
  2665. PK11SlotInfo *slot = NULL;
  2666. cryptoMechType = PK11_GetPBECryptoMechanism(&algid, &cryptoParam, pwitem);
  2667. if (cryptoMechType == CKM_INVALID_MECHANISM) {
  2668. break;
  2669. }
  2670. slot = PK11_GetBestSlot(cryptoMechType, NULL);
  2671. if (!slot) {
  2672. break;
  2673. }
  2674. symKey = PK11_PBEKeyGen(slot, &algid, pwitem, PR_FALSE, pwdata);
  2675. if (symKey == NULL) {
  2676. break;
  2677. }
  2678. ctx = PK11_CreateContextBySymKey(cryptoMechType, operation, symKey, cryptoParam);
  2679. if (ctx == NULL) {
  2680. break;
  2681. }
  2682. rv = PK11_CipherOp(ctx,
  2683. derPKI->data, /* out */
  2684. (int *)(&derPKI->len), /* out len */
  2685. (int)epki->encryptedData.len, /* max out */
  2686. epki->encryptedData.data, /* in */
  2687. (int)epki->encryptedData.len); /* in len */
  2688. PR_ASSERT(derPKI->len == epki->encryptedData.len);
  2689. PR_ASSERT(rv == SECSuccess);
  2690. rv = PK11_Finalize(ctx);
  2691. PR_ASSERT(rv == SECSuccess);
  2692. } while (0);
  2693. /* cleanup */
  2694. if (symKey) {
  2695. PK11_FreeSymKey(symKey);
  2696. }
  2697. if (cryptoParam) {
  2698. SECITEM_ZfreeItem(cryptoParam, PR_TRUE);
  2699. cryptoParam = NULL;
  2700. }
  2701. if (ctx) {
  2702. PK11_DestroyContext(ctx, PR_TRUE);
  2703. }
  2704. return rv;
  2705. }
  2706. /* #define ENCRYPTEDKEY 1 */
  2707. #define RAND_PASS_LEN 32
  2708. static int
  2709. slapd_extract_key(Slapi_Entry *entry, char *token, PK11SlotInfo *slot)
  2710. {
  2711. char *KeyExtractFile = NULL;
  2712. char *personality = NULL;
  2713. char *keyfile = NULL;
  2714. unsigned char randomPassword[RAND_PASS_LEN] = {0};
  2715. SECStatus rv = SECFailure;
  2716. SECItem pwitem = { 0, NULL, 0 };
  2717. SECItem clearKeyDER = { 0, NULL, 0 };
  2718. PRFileDesc *outFile = NULL;
  2719. SECKEYEncryptedPrivateKeyInfo *epki = NULL;
  2720. SECKEYPrivateKey *privkey = NULL;
  2721. SECKEYPublicKey *pubkey = NULL;
  2722. secuPWData pwdata = { PW_NONE, 0 };
  2723. CERTName *subject = NULL;
  2724. PLArenaPool *arenaForPKI = NULL;
  2725. char *b64 = NULL;
  2726. PRUint32 total = 0;
  2727. PRUint32 numBytes = 0;
  2728. char *certdir = config_get_certdir();
  2729. #if defined(ENCRYPTEDKEY)
  2730. char *keyEncPwd = NULL;
  2731. SVRCOREError err = SVRCORE_Success;
  2732. PRArenaPool *arenaForEPKI = NULL;
  2733. SVRCOREStdPinObj *StdPinObj;
  2734. SECItem *encryptedKeyDER = NULL;
  2735. #endif
  2736. if (!entry) {
  2737. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2738. "No entry is given for Server Key.\n");
  2739. goto bail;
  2740. }
  2741. #if defined(ENCRYPTEDKEY)
  2742. if (!token) {
  2743. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2744. "No token is given.\n");
  2745. goto bail;
  2746. }
  2747. StdPinObj = (SVRCOREStdPinObj *)SVRCORE_GetRegisteredPinObj();
  2748. if (!StdPinObj) {
  2749. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2750. "No entry is given for Server Key.\n");
  2751. goto bail;
  2752. }
  2753. err = SVRCORE_StdPinGetPin(&keyEncPwd, StdPinObj, token);
  2754. if (err || !keyEncPwd) {
  2755. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2756. "Failed to extract pw with token %s.\n", token);
  2757. goto bail;
  2758. }
  2759. pwitem.data = (unsigned char *)keyEncPwd;
  2760. pwitem.len = (unsigned int)strlen(keyEncPwd);
  2761. pwitem.type = siBuffer;
  2762. #else
  2763. /* Caller wants clear keys. Make up a dummy
  2764. * password to get NSS to export an encrypted
  2765. * key which we will decrypt.
  2766. */
  2767. rv = PK11_GenerateRandom(randomPassword, sizeof((const char *)randomPassword) - 1);
  2768. if (rv != SECSuccess) {
  2769. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key", "Failed to generate random.\n");
  2770. goto bail;
  2771. }
  2772. pwitem.data = randomPassword;
  2773. pwitem.len = strlen((const char *)randomPassword);
  2774. pwitem.type = siBuffer;
  2775. #endif
  2776. /* Get ServerKeyExtractFile from given entry if any. */
  2777. KeyExtractFile = slapi_entry_attr_get_charptr(entry, "ServerKeyExtractFile");
  2778. personality = slapi_entry_attr_get_charptr(entry, "nsSSLPersonalitySSL" );
  2779. if (!personality) {
  2780. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2781. "nsSSLPersonalitySSL value not found.\n");
  2782. goto bail;
  2783. }
  2784. keyfile = gen_pem_path(KeyExtractFile);
  2785. if (!keyfile) {
  2786. keyfile = slapi_ch_smprintf("%s/%s-Key%s", certdir, escape_string_for_filename(personality), PEMEXT);
  2787. }
  2788. outFile = PR_Open(keyfile, PR_CREATE_FILE | PR_RDWR | PR_TRUNCATE, 00660);
  2789. if (!outFile) {
  2790. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2791. "Unable to open \"%s\" for writing (%d, %d).\n",
  2792. keyfile, PR_GetError(), PR_GetOSError());
  2793. goto bail;
  2794. }
  2795. rv = extractRSAKeysAndSubject(personality, slot, &pwdata, &privkey, &pubkey, &subject);
  2796. if (rv != SECSuccess) {
  2797. #if defined(ENCRYPTEDKEY)
  2798. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2799. "Failed to extract keys for \"%s\".\n", token);
  2800. #else
  2801. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key", "Failed to extract keys for %s.\n", personality);
  2802. #endif
  2803. goto bail;
  2804. }
  2805. /*
  2806. * Borrowed the code from KeyOut in keyutil.c (crypto-util).
  2807. * Is it ok to hardcode the algorithm SEC_OID_DES_EDE3_CBC???
  2808. */
  2809. epki = PK11_ExportEncryptedPrivKeyInfo(NULL, SEC_OID_DES_EDE3_CBC, &pwitem, privkey, 1000, &pwdata);
  2810. if (!epki) {
  2811. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2812. "Unable to export encrypted private key (%d, %d).\n",
  2813. PR_GetError(), PR_GetOSError());
  2814. goto bail;
  2815. }
  2816. #if defined(ENCRYPTEDKEY)
  2817. arenaForEPKI = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
  2818. /* NULL dest to let it allocate memory for us */
  2819. encryptedKeyDER = SEC_ASN1EncodeItem(arenaForEPKI, NULL, epki, SECKEY_EncryptedPrivateKeyInfoTemplate);
  2820. if (!encryptedKeyDER) {
  2821. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2822. "SEC_ASN1EncodeItem failed. (%d, %d).\n", PR_GetError(), PR_GetOSError());
  2823. goto bail;
  2824. }
  2825. #else
  2826. /* Make a decrypted key the one to write out. */
  2827. arenaForPKI = PORT_NewArena(2048);
  2828. if (!arenaForPKI) {
  2829. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2830. "PORT_NewArena failed. (%d, %d).\n", PR_GetError(), PR_GetOSError());
  2831. goto bail;
  2832. }
  2833. clearKeyDER.data = PORT_ArenaAlloc(arenaForPKI, epki->encryptedData.len);
  2834. clearKeyDER.len = epki->encryptedData.len;
  2835. clearKeyDER.type = siBuffer;
  2836. rv = DecryptKey(epki, SEC_OID_DES_EDE3_CBC, &pwitem, &pwdata, &clearKeyDER);
  2837. if (rv != SECSuccess) {
  2838. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2839. "DekryptKey failed. (%d, %d).\n", PR_GetError(), PR_GetOSError());
  2840. goto bail;
  2841. }
  2842. #endif
  2843. /* we could be exporting a clear or encrypted key */
  2844. #if defined(ENCRYPTEDKEY)
  2845. b64 = BTOA_ConvertItemToAscii(encryptedKeyDER);
  2846. #else
  2847. b64 = BTOA_ConvertItemToAscii(&clearKeyDER);
  2848. #endif
  2849. if (!b64) {
  2850. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2851. "Failed to conver to the ASCII (%d, %d).\n",
  2852. PR_GetError(), PR_GetOSError());
  2853. goto bail;
  2854. }
  2855. total = PL_strlen(b64);
  2856. PR_fprintf(outFile, "%s\n", DONOTEDIT);
  2857. #if defined(ENCRYPTEDKEY)
  2858. PR_fprintf(outFile, "%s\n", ENCRYPTED_KEY_HEADER);
  2859. #else
  2860. PR_fprintf(outFile, "%s\n", KEY_HEADER);
  2861. #endif
  2862. numBytes = PR_Write(outFile, b64, total);
  2863. if (numBytes != total) {
  2864. slapi_log_error(SLAPI_LOG_FATAL, "slapd_extract_key",
  2865. "Failed to write to the file (%d, %d).\n",
  2866. PR_GetError(), PR_GetOSError());
  2867. goto bail;
  2868. }
  2869. #if defined(ENCRYPTEDKEY)
  2870. PR_fprintf(outFile, "\n%s\n", ENCRYPTED_KEY_TRAILER);
  2871. #else
  2872. PR_fprintf(outFile, "\n%s\n", KEY_TRAILER);
  2873. #endif
  2874. rv = SECSuccess;
  2875. bail:
  2876. slapi_ch_free_string(&certdir);
  2877. slapi_ch_free_string(&KeyExtractFile);
  2878. slapi_ch_free_string(&keyfile);
  2879. if (outFile) {
  2880. PR_Close(outFile);
  2881. }
  2882. #if defined(ENCRYPTEDKEY)
  2883. if (arenaForEPKI) {
  2884. PORT_FreeArena(arenaForEPKI, PR_FALSE);
  2885. }
  2886. if (pwitem.data) {
  2887. memset(pwitem.data, 0, pwitem.len);
  2888. PORT_Free(pwitem.data);
  2889. }
  2890. memset(&pwitem, 0, sizeof(SECItem));
  2891. #else
  2892. if (arenaForPKI) {
  2893. PORT_FreeArena(arenaForPKI, PR_FALSE);
  2894. }
  2895. memset(randomPassword, 0, strlen((const char *)randomPassword));
  2896. #endif
  2897. return rv;
  2898. }
  2899. const char *
  2900. slapi_get_cacertfile()
  2901. {
  2902. return CACertPemFile;
  2903. }
  2904. void
  2905. slapi_set_cacertfile(char *certfile)
  2906. {
  2907. slapi_ch_free_string(&CACertPemFile);
  2908. CACertPemFile = certfile;
  2909. }