tls_openssl.c 99 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038
  1. /*
  2. * SSL/TLS interface functions for OpenSSL
  3. * Copyright (c) 2004-2015, Jouni Malinen <j@w1.fi>
  4. *
  5. * This software may be distributed under the terms of the BSD license.
  6. * See README for more details.
  7. */
  8. #include "includes.h"
  9. #ifndef CONFIG_SMARTCARD
  10. #ifndef OPENSSL_NO_ENGINE
  11. #ifndef ANDROID
  12. #define OPENSSL_NO_ENGINE
  13. #endif
  14. #endif
  15. #endif
  16. #include <openssl/ssl.h>
  17. #include <openssl/err.h>
  18. #include <openssl/pkcs12.h>
  19. #include <openssl/x509v3.h>
  20. #ifndef OPENSSL_NO_ENGINE
  21. #include <openssl/engine.h>
  22. #endif /* OPENSSL_NO_ENGINE */
  23. #ifndef OPENSSL_NO_DSA
  24. #include <openssl/dsa.h>
  25. #endif
  26. #ifndef OPENSSL_NO_DH
  27. #include <openssl/dh.h>
  28. #endif
  29. #include "common.h"
  30. #include "crypto.h"
  31. #include "sha1.h"
  32. #include "sha256.h"
  33. #include "tls.h"
  34. #if OPENSSL_VERSION_NUMBER < 0x10000000L
  35. /* ERR_remove_thread_state replaces ERR_remove_state and the latter is
  36. * deprecated. However, OpenSSL 0.9.8 doesn't include
  37. * ERR_remove_thread_state. */
  38. #define ERR_remove_thread_state(tid) ERR_remove_state(0)
  39. #endif
  40. #if defined(OPENSSL_IS_BORINGSSL)
  41. /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
  42. typedef size_t stack_index_t;
  43. #else
  44. typedef int stack_index_t;
  45. #endif
  46. #ifdef SSL_set_tlsext_status_type
  47. #ifndef OPENSSL_NO_TLSEXT
  48. #define HAVE_OCSP
  49. #include <openssl/ocsp.h>
  50. #endif /* OPENSSL_NO_TLSEXT */
  51. #endif /* SSL_set_tlsext_status_type */
  52. #ifdef ANDROID
  53. #include <openssl/pem.h>
  54. #include <keystore/keystore_get.h>
  55. static BIO * BIO_from_keystore(const char *key)
  56. {
  57. BIO *bio = NULL;
  58. uint8_t *value = NULL;
  59. int length = keystore_get(key, strlen(key), &value);
  60. if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
  61. BIO_write(bio, value, length);
  62. free(value);
  63. return bio;
  64. }
  65. #endif /* ANDROID */
  66. static int tls_openssl_ref_count = 0;
  67. struct tls_context {
  68. void (*event_cb)(void *ctx, enum tls_event ev,
  69. union tls_event_data *data);
  70. void *cb_ctx;
  71. int cert_in_cb;
  72. char *ocsp_stapling_response;
  73. };
  74. static struct tls_context *tls_global = NULL;
  75. struct tls_data {
  76. SSL_CTX *ssl;
  77. };
  78. struct tls_connection {
  79. struct tls_context *context;
  80. SSL_CTX *ssl_ctx;
  81. SSL *ssl;
  82. BIO *ssl_in, *ssl_out;
  83. #ifndef OPENSSL_NO_ENGINE
  84. ENGINE *engine; /* functional reference to the engine */
  85. EVP_PKEY *private_key; /* the private key if using engine */
  86. #endif /* OPENSSL_NO_ENGINE */
  87. char *subject_match, *altsubject_match, *suffix_match, *domain_match;
  88. int read_alerts, write_alerts, failed;
  89. tls_session_ticket_cb session_ticket_cb;
  90. void *session_ticket_cb_ctx;
  91. /* SessionTicket received from OpenSSL hello_extension_cb (server) */
  92. u8 *session_ticket;
  93. size_t session_ticket_len;
  94. unsigned int ca_cert_verify:1;
  95. unsigned int cert_probe:1;
  96. unsigned int server_cert_only:1;
  97. unsigned int invalid_hb_used:1;
  98. u8 srv_cert_hash[32];
  99. unsigned int flags;
  100. X509 *peer_cert;
  101. X509 *peer_issuer;
  102. X509 *peer_issuer_issuer;
  103. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  104. unsigned char client_random[SSL3_RANDOM_SIZE];
  105. unsigned char server_random[SSL3_RANDOM_SIZE];
  106. #endif
  107. };
  108. static struct tls_context * tls_context_new(const struct tls_config *conf)
  109. {
  110. struct tls_context *context = os_zalloc(sizeof(*context));
  111. if (context == NULL)
  112. return NULL;
  113. if (conf) {
  114. context->event_cb = conf->event_cb;
  115. context->cb_ctx = conf->cb_ctx;
  116. context->cert_in_cb = conf->cert_in_cb;
  117. }
  118. return context;
  119. }
  120. #ifdef CONFIG_NO_STDOUT_DEBUG
  121. static void _tls_show_errors(void)
  122. {
  123. unsigned long err;
  124. while ((err = ERR_get_error())) {
  125. /* Just ignore the errors, since stdout is disabled */
  126. }
  127. }
  128. #define tls_show_errors(l, f, t) _tls_show_errors()
  129. #else /* CONFIG_NO_STDOUT_DEBUG */
  130. static void tls_show_errors(int level, const char *func, const char *txt)
  131. {
  132. unsigned long err;
  133. wpa_printf(level, "OpenSSL: %s - %s %s",
  134. func, txt, ERR_error_string(ERR_get_error(), NULL));
  135. while ((err = ERR_get_error())) {
  136. wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
  137. ERR_error_string(err, NULL));
  138. }
  139. }
  140. #endif /* CONFIG_NO_STDOUT_DEBUG */
  141. #ifdef CONFIG_NATIVE_WINDOWS
  142. /* Windows CryptoAPI and access to certificate stores */
  143. #include <wincrypt.h>
  144. #ifdef __MINGW32_VERSION
  145. /*
  146. * MinGW does not yet include all the needed definitions for CryptoAPI, so
  147. * define here whatever extra is needed.
  148. */
  149. #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
  150. #define CERT_STORE_READONLY_FLAG 0x00008000
  151. #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
  152. #endif /* __MINGW32_VERSION */
  153. struct cryptoapi_rsa_data {
  154. const CERT_CONTEXT *cert;
  155. HCRYPTPROV crypt_prov;
  156. DWORD key_spec;
  157. BOOL free_crypt_prov;
  158. };
  159. static void cryptoapi_error(const char *msg)
  160. {
  161. wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
  162. msg, (unsigned int) GetLastError());
  163. }
  164. static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
  165. unsigned char *to, RSA *rsa, int padding)
  166. {
  167. wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
  168. return 0;
  169. }
  170. static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
  171. unsigned char *to, RSA *rsa, int padding)
  172. {
  173. wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
  174. return 0;
  175. }
  176. static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
  177. unsigned char *to, RSA *rsa, int padding)
  178. {
  179. struct cryptoapi_rsa_data *priv =
  180. (struct cryptoapi_rsa_data *) rsa->meth->app_data;
  181. HCRYPTHASH hash;
  182. DWORD hash_size, len, i;
  183. unsigned char *buf = NULL;
  184. int ret = 0;
  185. if (priv == NULL) {
  186. RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
  187. ERR_R_PASSED_NULL_PARAMETER);
  188. return 0;
  189. }
  190. if (padding != RSA_PKCS1_PADDING) {
  191. RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
  192. RSA_R_UNKNOWN_PADDING_TYPE);
  193. return 0;
  194. }
  195. if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
  196. wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
  197. __func__);
  198. RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
  199. RSA_R_INVALID_MESSAGE_LENGTH);
  200. return 0;
  201. }
  202. if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
  203. {
  204. cryptoapi_error("CryptCreateHash failed");
  205. return 0;
  206. }
  207. len = sizeof(hash_size);
  208. if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
  209. 0)) {
  210. cryptoapi_error("CryptGetHashParam failed");
  211. goto err;
  212. }
  213. if ((int) hash_size != flen) {
  214. wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
  215. (unsigned) hash_size, flen);
  216. RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
  217. RSA_R_INVALID_MESSAGE_LENGTH);
  218. goto err;
  219. }
  220. if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
  221. cryptoapi_error("CryptSetHashParam failed");
  222. goto err;
  223. }
  224. len = RSA_size(rsa);
  225. buf = os_malloc(len);
  226. if (buf == NULL) {
  227. RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
  228. goto err;
  229. }
  230. if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
  231. cryptoapi_error("CryptSignHash failed");
  232. goto err;
  233. }
  234. for (i = 0; i < len; i++)
  235. to[i] = buf[len - i - 1];
  236. ret = len;
  237. err:
  238. os_free(buf);
  239. CryptDestroyHash(hash);
  240. return ret;
  241. }
  242. static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
  243. unsigned char *to, RSA *rsa, int padding)
  244. {
  245. wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
  246. return 0;
  247. }
  248. static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
  249. {
  250. if (priv == NULL)
  251. return;
  252. if (priv->crypt_prov && priv->free_crypt_prov)
  253. CryptReleaseContext(priv->crypt_prov, 0);
  254. if (priv->cert)
  255. CertFreeCertificateContext(priv->cert);
  256. os_free(priv);
  257. }
  258. static int cryptoapi_finish(RSA *rsa)
  259. {
  260. cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
  261. os_free((void *) rsa->meth);
  262. rsa->meth = NULL;
  263. return 1;
  264. }
  265. static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
  266. {
  267. HCERTSTORE cs;
  268. const CERT_CONTEXT *ret = NULL;
  269. cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
  270. store | CERT_STORE_OPEN_EXISTING_FLAG |
  271. CERT_STORE_READONLY_FLAG, L"MY");
  272. if (cs == NULL) {
  273. cryptoapi_error("Failed to open 'My system store'");
  274. return NULL;
  275. }
  276. if (strncmp(name, "cert://", 7) == 0) {
  277. unsigned short wbuf[255];
  278. MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
  279. ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
  280. PKCS_7_ASN_ENCODING,
  281. 0, CERT_FIND_SUBJECT_STR,
  282. wbuf, NULL);
  283. } else if (strncmp(name, "hash://", 7) == 0) {
  284. CRYPT_HASH_BLOB blob;
  285. int len;
  286. const char *hash = name + 7;
  287. unsigned char *buf;
  288. len = os_strlen(hash) / 2;
  289. buf = os_malloc(len);
  290. if (buf && hexstr2bin(hash, buf, len) == 0) {
  291. blob.cbData = len;
  292. blob.pbData = buf;
  293. ret = CertFindCertificateInStore(cs,
  294. X509_ASN_ENCODING |
  295. PKCS_7_ASN_ENCODING,
  296. 0, CERT_FIND_HASH,
  297. &blob, NULL);
  298. }
  299. os_free(buf);
  300. }
  301. CertCloseStore(cs, 0);
  302. return ret;
  303. }
  304. static int tls_cryptoapi_cert(SSL *ssl, const char *name)
  305. {
  306. X509 *cert = NULL;
  307. RSA *rsa = NULL, *pub_rsa;
  308. struct cryptoapi_rsa_data *priv;
  309. RSA_METHOD *rsa_meth;
  310. if (name == NULL ||
  311. (strncmp(name, "cert://", 7) != 0 &&
  312. strncmp(name, "hash://", 7) != 0))
  313. return -1;
  314. priv = os_zalloc(sizeof(*priv));
  315. rsa_meth = os_zalloc(sizeof(*rsa_meth));
  316. if (priv == NULL || rsa_meth == NULL) {
  317. wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
  318. "for CryptoAPI RSA method");
  319. os_free(priv);
  320. os_free(rsa_meth);
  321. return -1;
  322. }
  323. priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
  324. if (priv->cert == NULL) {
  325. priv->cert = cryptoapi_find_cert(
  326. name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
  327. }
  328. if (priv->cert == NULL) {
  329. wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
  330. "'%s'", name);
  331. goto err;
  332. }
  333. cert = d2i_X509(NULL,
  334. (const unsigned char **) &priv->cert->pbCertEncoded,
  335. priv->cert->cbCertEncoded);
  336. if (cert == NULL) {
  337. wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
  338. "encoding");
  339. goto err;
  340. }
  341. if (!CryptAcquireCertificatePrivateKey(priv->cert,
  342. CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
  343. NULL, &priv->crypt_prov,
  344. &priv->key_spec,
  345. &priv->free_crypt_prov)) {
  346. cryptoapi_error("Failed to acquire a private key for the "
  347. "certificate");
  348. goto err;
  349. }
  350. rsa_meth->name = "Microsoft CryptoAPI RSA Method";
  351. rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
  352. rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
  353. rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
  354. rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
  355. rsa_meth->finish = cryptoapi_finish;
  356. rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
  357. rsa_meth->app_data = (char *) priv;
  358. rsa = RSA_new();
  359. if (rsa == NULL) {
  360. SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
  361. ERR_R_MALLOC_FAILURE);
  362. goto err;
  363. }
  364. if (!SSL_use_certificate(ssl, cert)) {
  365. RSA_free(rsa);
  366. rsa = NULL;
  367. goto err;
  368. }
  369. pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
  370. X509_free(cert);
  371. cert = NULL;
  372. rsa->n = BN_dup(pub_rsa->n);
  373. rsa->e = BN_dup(pub_rsa->e);
  374. if (!RSA_set_method(rsa, rsa_meth))
  375. goto err;
  376. if (!SSL_use_RSAPrivateKey(ssl, rsa))
  377. goto err;
  378. RSA_free(rsa);
  379. return 0;
  380. err:
  381. if (cert)
  382. X509_free(cert);
  383. if (rsa)
  384. RSA_free(rsa);
  385. else {
  386. os_free(rsa_meth);
  387. cryptoapi_free_data(priv);
  388. }
  389. return -1;
  390. }
  391. static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
  392. {
  393. HCERTSTORE cs;
  394. PCCERT_CONTEXT ctx = NULL;
  395. X509 *cert;
  396. char buf[128];
  397. const char *store;
  398. #ifdef UNICODE
  399. WCHAR *wstore;
  400. #endif /* UNICODE */
  401. if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
  402. return -1;
  403. store = name + 13;
  404. #ifdef UNICODE
  405. wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
  406. if (wstore == NULL)
  407. return -1;
  408. wsprintf(wstore, L"%S", store);
  409. cs = CertOpenSystemStore(0, wstore);
  410. os_free(wstore);
  411. #else /* UNICODE */
  412. cs = CertOpenSystemStore(0, store);
  413. #endif /* UNICODE */
  414. if (cs == NULL) {
  415. wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
  416. "'%s': error=%d", __func__, store,
  417. (int) GetLastError());
  418. return -1;
  419. }
  420. while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
  421. cert = d2i_X509(NULL,
  422. (const unsigned char **) &ctx->pbCertEncoded,
  423. ctx->cbCertEncoded);
  424. if (cert == NULL) {
  425. wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
  426. "X509 DER encoding for CA cert");
  427. continue;
  428. }
  429. X509_NAME_oneline(X509_get_subject_name(cert), buf,
  430. sizeof(buf));
  431. wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
  432. "system certificate store: subject='%s'", buf);
  433. if (!X509_STORE_add_cert(ssl_ctx->cert_store, cert)) {
  434. tls_show_errors(MSG_WARNING, __func__,
  435. "Failed to add ca_cert to OpenSSL "
  436. "certificate store");
  437. }
  438. X509_free(cert);
  439. }
  440. if (!CertCloseStore(cs, 0)) {
  441. wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
  442. "'%s': error=%d", __func__, name + 13,
  443. (int) GetLastError());
  444. }
  445. return 0;
  446. }
  447. #else /* CONFIG_NATIVE_WINDOWS */
  448. static int tls_cryptoapi_cert(SSL *ssl, const char *name)
  449. {
  450. return -1;
  451. }
  452. #endif /* CONFIG_NATIVE_WINDOWS */
  453. static void ssl_info_cb(const SSL *ssl, int where, int ret)
  454. {
  455. const char *str;
  456. int w;
  457. wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
  458. w = where & ~SSL_ST_MASK;
  459. if (w & SSL_ST_CONNECT)
  460. str = "SSL_connect";
  461. else if (w & SSL_ST_ACCEPT)
  462. str = "SSL_accept";
  463. else
  464. str = "undefined";
  465. if (where & SSL_CB_LOOP) {
  466. wpa_printf(MSG_DEBUG, "SSL: %s:%s",
  467. str, SSL_state_string_long(ssl));
  468. } else if (where & SSL_CB_ALERT) {
  469. struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
  470. wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
  471. where & SSL_CB_READ ?
  472. "read (remote end reported an error)" :
  473. "write (local SSL3 detected an error)",
  474. SSL_alert_type_string_long(ret),
  475. SSL_alert_desc_string_long(ret));
  476. if ((ret >> 8) == SSL3_AL_FATAL) {
  477. if (where & SSL_CB_READ)
  478. conn->read_alerts++;
  479. else
  480. conn->write_alerts++;
  481. }
  482. if (conn->context->event_cb != NULL) {
  483. union tls_event_data ev;
  484. struct tls_context *context = conn->context;
  485. os_memset(&ev, 0, sizeof(ev));
  486. ev.alert.is_local = !(where & SSL_CB_READ);
  487. ev.alert.type = SSL_alert_type_string_long(ret);
  488. ev.alert.description = SSL_alert_desc_string_long(ret);
  489. context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
  490. }
  491. } else if (where & SSL_CB_EXIT && ret <= 0) {
  492. wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
  493. str, ret == 0 ? "failed" : "error",
  494. SSL_state_string_long(ssl));
  495. }
  496. }
  497. #ifndef OPENSSL_NO_ENGINE
  498. /**
  499. * tls_engine_load_dynamic_generic - load any openssl engine
  500. * @pre: an array of commands and values that load an engine initialized
  501. * in the engine specific function
  502. * @post: an array of commands and values that initialize an already loaded
  503. * engine (or %NULL if not required)
  504. * @id: the engine id of the engine to load (only required if post is not %NULL
  505. *
  506. * This function is a generic function that loads any openssl engine.
  507. *
  508. * Returns: 0 on success, -1 on failure
  509. */
  510. static int tls_engine_load_dynamic_generic(const char *pre[],
  511. const char *post[], const char *id)
  512. {
  513. ENGINE *engine;
  514. const char *dynamic_id = "dynamic";
  515. engine = ENGINE_by_id(id);
  516. if (engine) {
  517. ENGINE_free(engine);
  518. wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
  519. "available", id);
  520. return 0;
  521. }
  522. ERR_clear_error();
  523. engine = ENGINE_by_id(dynamic_id);
  524. if (engine == NULL) {
  525. wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
  526. dynamic_id,
  527. ERR_error_string(ERR_get_error(), NULL));
  528. return -1;
  529. }
  530. /* Perform the pre commands. This will load the engine. */
  531. while (pre && pre[0]) {
  532. wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
  533. if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
  534. wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
  535. "%s %s [%s]", pre[0], pre[1],
  536. ERR_error_string(ERR_get_error(), NULL));
  537. ENGINE_free(engine);
  538. return -1;
  539. }
  540. pre += 2;
  541. }
  542. /*
  543. * Free the reference to the "dynamic" engine. The loaded engine can
  544. * now be looked up using ENGINE_by_id().
  545. */
  546. ENGINE_free(engine);
  547. engine = ENGINE_by_id(id);
  548. if (engine == NULL) {
  549. wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
  550. id, ERR_error_string(ERR_get_error(), NULL));
  551. return -1;
  552. }
  553. while (post && post[0]) {
  554. wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
  555. if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
  556. wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
  557. " %s %s [%s]", post[0], post[1],
  558. ERR_error_string(ERR_get_error(), NULL));
  559. ENGINE_remove(engine);
  560. ENGINE_free(engine);
  561. return -1;
  562. }
  563. post += 2;
  564. }
  565. ENGINE_free(engine);
  566. return 0;
  567. }
  568. /**
  569. * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
  570. * @pkcs11_so_path: pksc11_so_path from the configuration
  571. * @pcks11_module_path: pkcs11_module_path from the configuration
  572. */
  573. static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
  574. const char *pkcs11_module_path)
  575. {
  576. char *engine_id = "pkcs11";
  577. const char *pre_cmd[] = {
  578. "SO_PATH", NULL /* pkcs11_so_path */,
  579. "ID", NULL /* engine_id */,
  580. "LIST_ADD", "1",
  581. /* "NO_VCHECK", "1", */
  582. "LOAD", NULL,
  583. NULL, NULL
  584. };
  585. const char *post_cmd[] = {
  586. "MODULE_PATH", NULL /* pkcs11_module_path */,
  587. NULL, NULL
  588. };
  589. if (!pkcs11_so_path)
  590. return 0;
  591. pre_cmd[1] = pkcs11_so_path;
  592. pre_cmd[3] = engine_id;
  593. if (pkcs11_module_path)
  594. post_cmd[1] = pkcs11_module_path;
  595. else
  596. post_cmd[0] = NULL;
  597. wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
  598. pkcs11_so_path);
  599. return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
  600. }
  601. /**
  602. * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
  603. * @opensc_so_path: opensc_so_path from the configuration
  604. */
  605. static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
  606. {
  607. char *engine_id = "opensc";
  608. const char *pre_cmd[] = {
  609. "SO_PATH", NULL /* opensc_so_path */,
  610. "ID", NULL /* engine_id */,
  611. "LIST_ADD", "1",
  612. "LOAD", NULL,
  613. NULL, NULL
  614. };
  615. if (!opensc_so_path)
  616. return 0;
  617. pre_cmd[1] = opensc_so_path;
  618. pre_cmd[3] = engine_id;
  619. wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
  620. opensc_so_path);
  621. return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
  622. }
  623. #endif /* OPENSSL_NO_ENGINE */
  624. void * tls_init(const struct tls_config *conf)
  625. {
  626. struct tls_data *data;
  627. SSL_CTX *ssl;
  628. struct tls_context *context;
  629. const char *ciphers;
  630. if (tls_openssl_ref_count == 0) {
  631. tls_global = context = tls_context_new(conf);
  632. if (context == NULL)
  633. return NULL;
  634. #ifdef CONFIG_FIPS
  635. #ifdef OPENSSL_FIPS
  636. if (conf && conf->fips_mode) {
  637. static int fips_enabled = 0;
  638. if (!fips_enabled && !FIPS_mode_set(1)) {
  639. wpa_printf(MSG_ERROR, "Failed to enable FIPS "
  640. "mode");
  641. ERR_load_crypto_strings();
  642. ERR_print_errors_fp(stderr);
  643. os_free(tls_global);
  644. tls_global = NULL;
  645. return NULL;
  646. } else {
  647. wpa_printf(MSG_INFO, "Running in FIPS mode");
  648. fips_enabled = 1;
  649. }
  650. }
  651. #else /* OPENSSL_FIPS */
  652. if (conf && conf->fips_mode) {
  653. wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
  654. "supported");
  655. os_free(tls_global);
  656. tls_global = NULL;
  657. return NULL;
  658. }
  659. #endif /* OPENSSL_FIPS */
  660. #endif /* CONFIG_FIPS */
  661. SSL_load_error_strings();
  662. SSL_library_init();
  663. #ifndef OPENSSL_NO_SHA256
  664. EVP_add_digest(EVP_sha256());
  665. #endif /* OPENSSL_NO_SHA256 */
  666. /* TODO: if /dev/urandom is available, PRNG is seeded
  667. * automatically. If this is not the case, random data should
  668. * be added here. */
  669. #ifdef PKCS12_FUNCS
  670. #ifndef OPENSSL_NO_RC2
  671. /*
  672. * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
  673. * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
  674. * versions, but it looks like OpenSSL 1.0.0 does not do that
  675. * anymore.
  676. */
  677. EVP_add_cipher(EVP_rc2_40_cbc());
  678. #endif /* OPENSSL_NO_RC2 */
  679. PKCS12_PBE_add();
  680. #endif /* PKCS12_FUNCS */
  681. } else {
  682. context = tls_context_new(conf);
  683. if (context == NULL)
  684. return NULL;
  685. }
  686. tls_openssl_ref_count++;
  687. data = os_zalloc(sizeof(*data));
  688. if (data)
  689. ssl = SSL_CTX_new(SSLv23_method());
  690. else
  691. ssl = NULL;
  692. if (ssl == NULL) {
  693. tls_openssl_ref_count--;
  694. if (context != tls_global)
  695. os_free(context);
  696. if (tls_openssl_ref_count == 0) {
  697. os_free(tls_global);
  698. tls_global = NULL;
  699. }
  700. return NULL;
  701. }
  702. data->ssl = ssl;
  703. SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
  704. SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
  705. SSL_CTX_set_info_callback(ssl, ssl_info_cb);
  706. SSL_CTX_set_app_data(ssl, context);
  707. #ifndef OPENSSL_NO_ENGINE
  708. wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
  709. ERR_load_ENGINE_strings();
  710. ENGINE_load_dynamic();
  711. if (conf &&
  712. (conf->opensc_engine_path || conf->pkcs11_engine_path ||
  713. conf->pkcs11_module_path)) {
  714. if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
  715. tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
  716. conf->pkcs11_module_path)) {
  717. tls_deinit(data);
  718. return NULL;
  719. }
  720. }
  721. #endif /* OPENSSL_NO_ENGINE */
  722. if (conf && conf->openssl_ciphers)
  723. ciphers = conf->openssl_ciphers;
  724. else
  725. ciphers = "DEFAULT:!EXP:!LOW";
  726. if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
  727. wpa_printf(MSG_ERROR,
  728. "OpenSSL: Failed to set cipher string '%s'",
  729. ciphers);
  730. tls_deinit(data);
  731. return NULL;
  732. }
  733. return data;
  734. }
  735. void tls_deinit(void *ssl_ctx)
  736. {
  737. struct tls_data *data = ssl_ctx;
  738. SSL_CTX *ssl = data->ssl;
  739. struct tls_context *context = SSL_CTX_get_app_data(ssl);
  740. if (context != tls_global)
  741. os_free(context);
  742. SSL_CTX_free(ssl);
  743. tls_openssl_ref_count--;
  744. if (tls_openssl_ref_count == 0) {
  745. #ifndef OPENSSL_NO_ENGINE
  746. ENGINE_cleanup();
  747. #endif /* OPENSSL_NO_ENGINE */
  748. CRYPTO_cleanup_all_ex_data();
  749. ERR_remove_thread_state(NULL);
  750. ERR_free_strings();
  751. EVP_cleanup();
  752. os_free(tls_global->ocsp_stapling_response);
  753. tls_global->ocsp_stapling_response = NULL;
  754. os_free(tls_global);
  755. tls_global = NULL;
  756. }
  757. os_free(data);
  758. }
  759. #ifndef OPENSSL_NO_ENGINE
  760. /* Cryptoki return values */
  761. #define CKR_PIN_INCORRECT 0x000000a0
  762. #define CKR_PIN_INVALID 0x000000a1
  763. #define CKR_PIN_LEN_RANGE 0x000000a2
  764. /* libp11 */
  765. #define ERR_LIB_PKCS11 ERR_LIB_USER
  766. static int tls_is_pin_error(unsigned int err)
  767. {
  768. return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
  769. (ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
  770. ERR_GET_REASON(err) == CKR_PIN_INVALID ||
  771. ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
  772. }
  773. #endif /* OPENSSL_NO_ENGINE */
  774. static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
  775. const char *pin, const char *key_id,
  776. const char *cert_id, const char *ca_cert_id)
  777. {
  778. #ifndef OPENSSL_NO_ENGINE
  779. int ret = -1;
  780. if (engine_id == NULL) {
  781. wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
  782. return -1;
  783. }
  784. ERR_clear_error();
  785. #ifdef ANDROID
  786. ENGINE_load_dynamic();
  787. #endif
  788. conn->engine = ENGINE_by_id(engine_id);
  789. if (!conn->engine) {
  790. wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
  791. engine_id, ERR_error_string(ERR_get_error(), NULL));
  792. goto err;
  793. }
  794. if (ENGINE_init(conn->engine) != 1) {
  795. wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
  796. "(engine: %s) [%s]", engine_id,
  797. ERR_error_string(ERR_get_error(), NULL));
  798. goto err;
  799. }
  800. wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
  801. #ifndef ANDROID
  802. if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
  803. wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
  804. ERR_error_string(ERR_get_error(), NULL));
  805. goto err;
  806. }
  807. #endif
  808. if (key_id) {
  809. /*
  810. * Ensure that the ENGINE does not attempt to use the OpenSSL
  811. * UI system to obtain a PIN, if we didn't provide one.
  812. */
  813. struct {
  814. const void *password;
  815. const char *prompt_info;
  816. } key_cb = { "", NULL };
  817. /* load private key first in-case PIN is required for cert */
  818. conn->private_key = ENGINE_load_private_key(conn->engine,
  819. key_id, NULL,
  820. &key_cb);
  821. if (!conn->private_key) {
  822. unsigned long err = ERR_get_error();
  823. wpa_printf(MSG_ERROR,
  824. "ENGINE: cannot load private key with id '%s' [%s]",
  825. key_id,
  826. ERR_error_string(err, NULL));
  827. if (tls_is_pin_error(err))
  828. ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
  829. else
  830. ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
  831. goto err;
  832. }
  833. }
  834. /* handle a certificate and/or CA certificate */
  835. if (cert_id || ca_cert_id) {
  836. const char *cmd_name = "LOAD_CERT_CTRL";
  837. /* test if the engine supports a LOAD_CERT_CTRL */
  838. if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
  839. 0, (void *)cmd_name, NULL)) {
  840. wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
  841. " loading certificates");
  842. ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
  843. goto err;
  844. }
  845. }
  846. return 0;
  847. err:
  848. if (conn->engine) {
  849. ENGINE_free(conn->engine);
  850. conn->engine = NULL;
  851. }
  852. if (conn->private_key) {
  853. EVP_PKEY_free(conn->private_key);
  854. conn->private_key = NULL;
  855. }
  856. return ret;
  857. #else /* OPENSSL_NO_ENGINE */
  858. return 0;
  859. #endif /* OPENSSL_NO_ENGINE */
  860. }
  861. static void tls_engine_deinit(struct tls_connection *conn)
  862. {
  863. #ifndef OPENSSL_NO_ENGINE
  864. wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
  865. if (conn->private_key) {
  866. EVP_PKEY_free(conn->private_key);
  867. conn->private_key = NULL;
  868. }
  869. if (conn->engine) {
  870. ENGINE_finish(conn->engine);
  871. conn->engine = NULL;
  872. }
  873. #endif /* OPENSSL_NO_ENGINE */
  874. }
  875. int tls_get_errors(void *ssl_ctx)
  876. {
  877. int count = 0;
  878. unsigned long err;
  879. while ((err = ERR_get_error())) {
  880. wpa_printf(MSG_INFO, "TLS - SSL error: %s",
  881. ERR_error_string(err, NULL));
  882. count++;
  883. }
  884. return count;
  885. }
  886. static void tls_msg_cb(int write_p, int version, int content_type,
  887. const void *buf, size_t len, SSL *ssl, void *arg)
  888. {
  889. struct tls_connection *conn = arg;
  890. const u8 *pos = buf;
  891. wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d",
  892. write_p ? "TX" : "RX", version, content_type);
  893. wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
  894. if (content_type == 24 && len >= 3 && pos[0] == 1) {
  895. size_t payload_len = WPA_GET_BE16(pos + 1);
  896. if (payload_len + 3 > len) {
  897. wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
  898. conn->invalid_hb_used = 1;
  899. }
  900. }
  901. }
  902. struct tls_connection * tls_connection_init(void *ssl_ctx)
  903. {
  904. struct tls_data *data = ssl_ctx;
  905. SSL_CTX *ssl = data->ssl;
  906. struct tls_connection *conn;
  907. long options;
  908. struct tls_context *context = SSL_CTX_get_app_data(ssl);
  909. conn = os_zalloc(sizeof(*conn));
  910. if (conn == NULL)
  911. return NULL;
  912. conn->ssl_ctx = ssl;
  913. conn->ssl = SSL_new(ssl);
  914. if (conn->ssl == NULL) {
  915. tls_show_errors(MSG_INFO, __func__,
  916. "Failed to initialize new SSL connection");
  917. os_free(conn);
  918. return NULL;
  919. }
  920. conn->context = context;
  921. SSL_set_app_data(conn->ssl, conn);
  922. SSL_set_msg_callback(conn->ssl, tls_msg_cb);
  923. SSL_set_msg_callback_arg(conn->ssl, conn);
  924. options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
  925. SSL_OP_SINGLE_DH_USE;
  926. #ifdef SSL_OP_NO_COMPRESSION
  927. options |= SSL_OP_NO_COMPRESSION;
  928. #endif /* SSL_OP_NO_COMPRESSION */
  929. SSL_set_options(conn->ssl, options);
  930. conn->ssl_in = BIO_new(BIO_s_mem());
  931. if (!conn->ssl_in) {
  932. tls_show_errors(MSG_INFO, __func__,
  933. "Failed to create a new BIO for ssl_in");
  934. SSL_free(conn->ssl);
  935. os_free(conn);
  936. return NULL;
  937. }
  938. conn->ssl_out = BIO_new(BIO_s_mem());
  939. if (!conn->ssl_out) {
  940. tls_show_errors(MSG_INFO, __func__,
  941. "Failed to create a new BIO for ssl_out");
  942. SSL_free(conn->ssl);
  943. BIO_free(conn->ssl_in);
  944. os_free(conn);
  945. return NULL;
  946. }
  947. SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
  948. return conn;
  949. }
  950. void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
  951. {
  952. if (conn == NULL)
  953. return;
  954. SSL_free(conn->ssl);
  955. tls_engine_deinit(conn);
  956. os_free(conn->subject_match);
  957. os_free(conn->altsubject_match);
  958. os_free(conn->suffix_match);
  959. os_free(conn->domain_match);
  960. os_free(conn->session_ticket);
  961. os_free(conn);
  962. }
  963. int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
  964. {
  965. return conn ? SSL_is_init_finished(conn->ssl) : 0;
  966. }
  967. int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
  968. {
  969. if (conn == NULL)
  970. return -1;
  971. /* Shutdown previous TLS connection without notifying the peer
  972. * because the connection was already terminated in practice
  973. * and "close notify" shutdown alert would confuse AS. */
  974. SSL_set_quiet_shutdown(conn->ssl, 1);
  975. SSL_shutdown(conn->ssl);
  976. return SSL_clear(conn->ssl) == 1 ? 0 : -1;
  977. }
  978. static int tls_match_altsubject_component(X509 *cert, int type,
  979. const char *value, size_t len)
  980. {
  981. GENERAL_NAME *gen;
  982. void *ext;
  983. int found = 0;
  984. stack_index_t i;
  985. ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
  986. for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
  987. gen = sk_GENERAL_NAME_value(ext, i);
  988. if (gen->type != type)
  989. continue;
  990. if (os_strlen((char *) gen->d.ia5->data) == len &&
  991. os_memcmp(value, gen->d.ia5->data, len) == 0)
  992. found++;
  993. }
  994. return found;
  995. }
  996. static int tls_match_altsubject(X509 *cert, const char *match)
  997. {
  998. int type;
  999. const char *pos, *end;
  1000. size_t len;
  1001. pos = match;
  1002. do {
  1003. if (os_strncmp(pos, "EMAIL:", 6) == 0) {
  1004. type = GEN_EMAIL;
  1005. pos += 6;
  1006. } else if (os_strncmp(pos, "DNS:", 4) == 0) {
  1007. type = GEN_DNS;
  1008. pos += 4;
  1009. } else if (os_strncmp(pos, "URI:", 4) == 0) {
  1010. type = GEN_URI;
  1011. pos += 4;
  1012. } else {
  1013. wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
  1014. "match '%s'", pos);
  1015. return 0;
  1016. }
  1017. end = os_strchr(pos, ';');
  1018. while (end) {
  1019. if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
  1020. os_strncmp(end + 1, "DNS:", 4) == 0 ||
  1021. os_strncmp(end + 1, "URI:", 4) == 0)
  1022. break;
  1023. end = os_strchr(end + 1, ';');
  1024. }
  1025. if (end)
  1026. len = end - pos;
  1027. else
  1028. len = os_strlen(pos);
  1029. if (tls_match_altsubject_component(cert, type, pos, len) > 0)
  1030. return 1;
  1031. pos = end + 1;
  1032. } while (end);
  1033. return 0;
  1034. }
  1035. #ifndef CONFIG_NATIVE_WINDOWS
  1036. static int domain_suffix_match(const u8 *val, size_t len, const char *match,
  1037. int full)
  1038. {
  1039. size_t i, match_len;
  1040. /* Check for embedded nuls that could mess up suffix matching */
  1041. for (i = 0; i < len; i++) {
  1042. if (val[i] == '\0') {
  1043. wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
  1044. return 0;
  1045. }
  1046. }
  1047. match_len = os_strlen(match);
  1048. if (match_len > len || (full && match_len != len))
  1049. return 0;
  1050. if (os_strncasecmp((const char *) val + len - match_len, match,
  1051. match_len) != 0)
  1052. return 0; /* no match */
  1053. if (match_len == len)
  1054. return 1; /* exact match */
  1055. if (val[len - match_len - 1] == '.')
  1056. return 1; /* full label match completes suffix match */
  1057. wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
  1058. return 0;
  1059. }
  1060. #endif /* CONFIG_NATIVE_WINDOWS */
  1061. static int tls_match_suffix(X509 *cert, const char *match, int full)
  1062. {
  1063. #ifdef CONFIG_NATIVE_WINDOWS
  1064. /* wincrypt.h has conflicting X509_NAME definition */
  1065. return -1;
  1066. #else /* CONFIG_NATIVE_WINDOWS */
  1067. GENERAL_NAME *gen;
  1068. void *ext;
  1069. int i;
  1070. stack_index_t j;
  1071. int dns_name = 0;
  1072. X509_NAME *name;
  1073. wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
  1074. full ? "": "suffix ", match);
  1075. ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
  1076. for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
  1077. gen = sk_GENERAL_NAME_value(ext, j);
  1078. if (gen->type != GEN_DNS)
  1079. continue;
  1080. dns_name++;
  1081. wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
  1082. gen->d.dNSName->data,
  1083. gen->d.dNSName->length);
  1084. if (domain_suffix_match(gen->d.dNSName->data,
  1085. gen->d.dNSName->length, match, full) ==
  1086. 1) {
  1087. wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
  1088. full ? "Match" : "Suffix match");
  1089. return 1;
  1090. }
  1091. }
  1092. if (dns_name) {
  1093. wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
  1094. return 0;
  1095. }
  1096. name = X509_get_subject_name(cert);
  1097. i = -1;
  1098. for (;;) {
  1099. X509_NAME_ENTRY *e;
  1100. ASN1_STRING *cn;
  1101. i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
  1102. if (i == -1)
  1103. break;
  1104. e = X509_NAME_get_entry(name, i);
  1105. if (e == NULL)
  1106. continue;
  1107. cn = X509_NAME_ENTRY_get_data(e);
  1108. if (cn == NULL)
  1109. continue;
  1110. wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
  1111. cn->data, cn->length);
  1112. if (domain_suffix_match(cn->data, cn->length, match, full) == 1)
  1113. {
  1114. wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
  1115. full ? "Match" : "Suffix match");
  1116. return 1;
  1117. }
  1118. }
  1119. wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
  1120. full ? "": "suffix ");
  1121. return 0;
  1122. #endif /* CONFIG_NATIVE_WINDOWS */
  1123. }
  1124. static enum tls_fail_reason openssl_tls_fail_reason(int err)
  1125. {
  1126. switch (err) {
  1127. case X509_V_ERR_CERT_REVOKED:
  1128. return TLS_FAIL_REVOKED;
  1129. case X509_V_ERR_CERT_NOT_YET_VALID:
  1130. case X509_V_ERR_CRL_NOT_YET_VALID:
  1131. return TLS_FAIL_NOT_YET_VALID;
  1132. case X509_V_ERR_CERT_HAS_EXPIRED:
  1133. case X509_V_ERR_CRL_HAS_EXPIRED:
  1134. return TLS_FAIL_EXPIRED;
  1135. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
  1136. case X509_V_ERR_UNABLE_TO_GET_CRL:
  1137. case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
  1138. case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
  1139. case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
  1140. case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
  1141. case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
  1142. case X509_V_ERR_CERT_CHAIN_TOO_LONG:
  1143. case X509_V_ERR_PATH_LENGTH_EXCEEDED:
  1144. case X509_V_ERR_INVALID_CA:
  1145. return TLS_FAIL_UNTRUSTED;
  1146. case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
  1147. case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
  1148. case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
  1149. case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
  1150. case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
  1151. case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
  1152. case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
  1153. case X509_V_ERR_CERT_UNTRUSTED:
  1154. case X509_V_ERR_CERT_REJECTED:
  1155. return TLS_FAIL_BAD_CERTIFICATE;
  1156. default:
  1157. return TLS_FAIL_UNSPECIFIED;
  1158. }
  1159. }
  1160. static struct wpabuf * get_x509_cert(X509 *cert)
  1161. {
  1162. struct wpabuf *buf;
  1163. u8 *tmp;
  1164. int cert_len = i2d_X509(cert, NULL);
  1165. if (cert_len <= 0)
  1166. return NULL;
  1167. buf = wpabuf_alloc(cert_len);
  1168. if (buf == NULL)
  1169. return NULL;
  1170. tmp = wpabuf_put(buf, cert_len);
  1171. i2d_X509(cert, &tmp);
  1172. return buf;
  1173. }
  1174. static void openssl_tls_fail_event(struct tls_connection *conn,
  1175. X509 *err_cert, int err, int depth,
  1176. const char *subject, const char *err_str,
  1177. enum tls_fail_reason reason)
  1178. {
  1179. union tls_event_data ev;
  1180. struct wpabuf *cert = NULL;
  1181. struct tls_context *context = conn->context;
  1182. if (context->event_cb == NULL)
  1183. return;
  1184. cert = get_x509_cert(err_cert);
  1185. os_memset(&ev, 0, sizeof(ev));
  1186. ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
  1187. reason : openssl_tls_fail_reason(err);
  1188. ev.cert_fail.depth = depth;
  1189. ev.cert_fail.subject = subject;
  1190. ev.cert_fail.reason_txt = err_str;
  1191. ev.cert_fail.cert = cert;
  1192. context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
  1193. wpabuf_free(cert);
  1194. }
  1195. static void openssl_tls_cert_event(struct tls_connection *conn,
  1196. X509 *err_cert, int depth,
  1197. const char *subject)
  1198. {
  1199. struct wpabuf *cert = NULL;
  1200. union tls_event_data ev;
  1201. struct tls_context *context = conn->context;
  1202. char *altsubject[TLS_MAX_ALT_SUBJECT];
  1203. int alt, num_altsubject = 0;
  1204. GENERAL_NAME *gen;
  1205. void *ext;
  1206. stack_index_t i;
  1207. #ifdef CONFIG_SHA256
  1208. u8 hash[32];
  1209. #endif /* CONFIG_SHA256 */
  1210. if (context->event_cb == NULL)
  1211. return;
  1212. os_memset(&ev, 0, sizeof(ev));
  1213. if (conn->cert_probe || context->cert_in_cb) {
  1214. cert = get_x509_cert(err_cert);
  1215. ev.peer_cert.cert = cert;
  1216. }
  1217. #ifdef CONFIG_SHA256
  1218. if (cert) {
  1219. const u8 *addr[1];
  1220. size_t len[1];
  1221. addr[0] = wpabuf_head(cert);
  1222. len[0] = wpabuf_len(cert);
  1223. if (sha256_vector(1, addr, len, hash) == 0) {
  1224. ev.peer_cert.hash = hash;
  1225. ev.peer_cert.hash_len = sizeof(hash);
  1226. }
  1227. }
  1228. #endif /* CONFIG_SHA256 */
  1229. ev.peer_cert.depth = depth;
  1230. ev.peer_cert.subject = subject;
  1231. ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
  1232. for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
  1233. char *pos;
  1234. if (num_altsubject == TLS_MAX_ALT_SUBJECT)
  1235. break;
  1236. gen = sk_GENERAL_NAME_value(ext, i);
  1237. if (gen->type != GEN_EMAIL &&
  1238. gen->type != GEN_DNS &&
  1239. gen->type != GEN_URI)
  1240. continue;
  1241. pos = os_malloc(10 + gen->d.ia5->length + 1);
  1242. if (pos == NULL)
  1243. break;
  1244. altsubject[num_altsubject++] = pos;
  1245. switch (gen->type) {
  1246. case GEN_EMAIL:
  1247. os_memcpy(pos, "EMAIL:", 6);
  1248. pos += 6;
  1249. break;
  1250. case GEN_DNS:
  1251. os_memcpy(pos, "DNS:", 4);
  1252. pos += 4;
  1253. break;
  1254. case GEN_URI:
  1255. os_memcpy(pos, "URI:", 4);
  1256. pos += 4;
  1257. break;
  1258. }
  1259. os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
  1260. pos += gen->d.ia5->length;
  1261. *pos = '\0';
  1262. }
  1263. for (alt = 0; alt < num_altsubject; alt++)
  1264. ev.peer_cert.altsubject[alt] = altsubject[alt];
  1265. ev.peer_cert.num_altsubject = num_altsubject;
  1266. context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
  1267. wpabuf_free(cert);
  1268. for (alt = 0; alt < num_altsubject; alt++)
  1269. os_free(altsubject[alt]);
  1270. }
  1271. static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
  1272. {
  1273. char buf[256];
  1274. X509 *err_cert;
  1275. int err, depth;
  1276. SSL *ssl;
  1277. struct tls_connection *conn;
  1278. struct tls_context *context;
  1279. char *match, *altmatch, *suffix_match, *domain_match;
  1280. const char *err_str;
  1281. err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
  1282. if (!err_cert)
  1283. return 0;
  1284. err = X509_STORE_CTX_get_error(x509_ctx);
  1285. depth = X509_STORE_CTX_get_error_depth(x509_ctx);
  1286. ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
  1287. SSL_get_ex_data_X509_STORE_CTX_idx());
  1288. X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
  1289. conn = SSL_get_app_data(ssl);
  1290. if (conn == NULL)
  1291. return 0;
  1292. if (depth == 0)
  1293. conn->peer_cert = err_cert;
  1294. else if (depth == 1)
  1295. conn->peer_issuer = err_cert;
  1296. else if (depth == 2)
  1297. conn->peer_issuer_issuer = err_cert;
  1298. context = conn->context;
  1299. match = conn->subject_match;
  1300. altmatch = conn->altsubject_match;
  1301. suffix_match = conn->suffix_match;
  1302. domain_match = conn->domain_match;
  1303. if (!preverify_ok && !conn->ca_cert_verify)
  1304. preverify_ok = 1;
  1305. if (!preverify_ok && depth > 0 && conn->server_cert_only)
  1306. preverify_ok = 1;
  1307. if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
  1308. (err == X509_V_ERR_CERT_HAS_EXPIRED ||
  1309. err == X509_V_ERR_CERT_NOT_YET_VALID)) {
  1310. wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
  1311. "time mismatch");
  1312. preverify_ok = 1;
  1313. }
  1314. err_str = X509_verify_cert_error_string(err);
  1315. #ifdef CONFIG_SHA256
  1316. /*
  1317. * Do not require preverify_ok so we can explicity allow otherwise
  1318. * invalid pinned server certificates.
  1319. */
  1320. if (depth == 0 && conn->server_cert_only) {
  1321. struct wpabuf *cert;
  1322. cert = get_x509_cert(err_cert);
  1323. if (!cert) {
  1324. wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
  1325. "server certificate data");
  1326. preverify_ok = 0;
  1327. } else {
  1328. u8 hash[32];
  1329. const u8 *addr[1];
  1330. size_t len[1];
  1331. addr[0] = wpabuf_head(cert);
  1332. len[0] = wpabuf_len(cert);
  1333. if (sha256_vector(1, addr, len, hash) < 0 ||
  1334. os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
  1335. err_str = "Server certificate mismatch";
  1336. err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
  1337. preverify_ok = 0;
  1338. } else if (!preverify_ok) {
  1339. /*
  1340. * Certificate matches pinned certificate, allow
  1341. * regardless of other problems.
  1342. */
  1343. wpa_printf(MSG_DEBUG,
  1344. "OpenSSL: Ignore validation issues for a pinned server certificate");
  1345. preverify_ok = 1;
  1346. }
  1347. wpabuf_free(cert);
  1348. }
  1349. }
  1350. #endif /* CONFIG_SHA256 */
  1351. if (!preverify_ok) {
  1352. wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
  1353. " error %d (%s) depth %d for '%s'", err, err_str,
  1354. depth, buf);
  1355. openssl_tls_fail_event(conn, err_cert, err, depth, buf,
  1356. err_str, TLS_FAIL_UNSPECIFIED);
  1357. return preverify_ok;
  1358. }
  1359. wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
  1360. "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
  1361. preverify_ok, err, err_str,
  1362. conn->ca_cert_verify, depth, buf);
  1363. if (depth == 0 && match && os_strstr(buf, match) == NULL) {
  1364. wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
  1365. "match with '%s'", buf, match);
  1366. preverify_ok = 0;
  1367. openssl_tls_fail_event(conn, err_cert, err, depth, buf,
  1368. "Subject mismatch",
  1369. TLS_FAIL_SUBJECT_MISMATCH);
  1370. } else if (depth == 0 && altmatch &&
  1371. !tls_match_altsubject(err_cert, altmatch)) {
  1372. wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
  1373. "'%s' not found", altmatch);
  1374. preverify_ok = 0;
  1375. openssl_tls_fail_event(conn, err_cert, err, depth, buf,
  1376. "AltSubject mismatch",
  1377. TLS_FAIL_ALTSUBJECT_MISMATCH);
  1378. } else if (depth == 0 && suffix_match &&
  1379. !tls_match_suffix(err_cert, suffix_match, 0)) {
  1380. wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
  1381. suffix_match);
  1382. preverify_ok = 0;
  1383. openssl_tls_fail_event(conn, err_cert, err, depth, buf,
  1384. "Domain suffix mismatch",
  1385. TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
  1386. } else if (depth == 0 && domain_match &&
  1387. !tls_match_suffix(err_cert, domain_match, 1)) {
  1388. wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
  1389. domain_match);
  1390. preverify_ok = 0;
  1391. openssl_tls_fail_event(conn, err_cert, err, depth, buf,
  1392. "Domain mismatch",
  1393. TLS_FAIL_DOMAIN_MISMATCH);
  1394. } else
  1395. openssl_tls_cert_event(conn, err_cert, depth, buf);
  1396. if (conn->cert_probe && preverify_ok && depth == 0) {
  1397. wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
  1398. "on probe-only run");
  1399. preverify_ok = 0;
  1400. openssl_tls_fail_event(conn, err_cert, err, depth, buf,
  1401. "Server certificate chain probe",
  1402. TLS_FAIL_SERVER_CHAIN_PROBE);
  1403. }
  1404. if (preverify_ok && context->event_cb != NULL)
  1405. context->event_cb(context->cb_ctx,
  1406. TLS_CERT_CHAIN_SUCCESS, NULL);
  1407. return preverify_ok;
  1408. }
  1409. #ifndef OPENSSL_NO_STDIO
  1410. static int tls_load_ca_der(struct tls_data *data, const char *ca_cert)
  1411. {
  1412. SSL_CTX *ssl_ctx = data->ssl;
  1413. X509_LOOKUP *lookup;
  1414. int ret = 0;
  1415. lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
  1416. X509_LOOKUP_file());
  1417. if (lookup == NULL) {
  1418. tls_show_errors(MSG_WARNING, __func__,
  1419. "Failed add lookup for X509 store");
  1420. return -1;
  1421. }
  1422. if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
  1423. unsigned long err = ERR_peek_error();
  1424. tls_show_errors(MSG_WARNING, __func__,
  1425. "Failed load CA in DER format");
  1426. if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
  1427. ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  1428. wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
  1429. "cert already in hash table error",
  1430. __func__);
  1431. } else
  1432. ret = -1;
  1433. }
  1434. return ret;
  1435. }
  1436. #endif /* OPENSSL_NO_STDIO */
  1437. static int tls_connection_ca_cert(struct tls_data *data,
  1438. struct tls_connection *conn,
  1439. const char *ca_cert, const u8 *ca_cert_blob,
  1440. size_t ca_cert_blob_len, const char *ca_path)
  1441. {
  1442. SSL_CTX *ssl_ctx = data->ssl;
  1443. X509_STORE *store;
  1444. /*
  1445. * Remove previously configured trusted CA certificates before adding
  1446. * new ones.
  1447. */
  1448. store = X509_STORE_new();
  1449. if (store == NULL) {
  1450. wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
  1451. "certificate store", __func__);
  1452. return -1;
  1453. }
  1454. SSL_CTX_set_cert_store(ssl_ctx, store);
  1455. SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
  1456. conn->ca_cert_verify = 1;
  1457. if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
  1458. wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
  1459. "chain");
  1460. conn->cert_probe = 1;
  1461. conn->ca_cert_verify = 0;
  1462. return 0;
  1463. }
  1464. if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
  1465. #ifdef CONFIG_SHA256
  1466. const char *pos = ca_cert + 7;
  1467. if (os_strncmp(pos, "server/sha256/", 14) != 0) {
  1468. wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
  1469. "hash value '%s'", ca_cert);
  1470. return -1;
  1471. }
  1472. pos += 14;
  1473. if (os_strlen(pos) != 32 * 2) {
  1474. wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
  1475. "hash length in ca_cert '%s'", ca_cert);
  1476. return -1;
  1477. }
  1478. if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
  1479. wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
  1480. "value in ca_cert '%s'", ca_cert);
  1481. return -1;
  1482. }
  1483. conn->server_cert_only = 1;
  1484. wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
  1485. "certificate match");
  1486. return 0;
  1487. #else /* CONFIG_SHA256 */
  1488. wpa_printf(MSG_INFO, "No SHA256 included in the build - "
  1489. "cannot validate server certificate hash");
  1490. return -1;
  1491. #endif /* CONFIG_SHA256 */
  1492. }
  1493. if (ca_cert_blob) {
  1494. X509 *cert = d2i_X509(NULL,
  1495. (const unsigned char **) &ca_cert_blob,
  1496. ca_cert_blob_len);
  1497. if (cert == NULL) {
  1498. tls_show_errors(MSG_WARNING, __func__,
  1499. "Failed to parse ca_cert_blob");
  1500. return -1;
  1501. }
  1502. if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
  1503. cert)) {
  1504. unsigned long err = ERR_peek_error();
  1505. tls_show_errors(MSG_WARNING, __func__,
  1506. "Failed to add ca_cert_blob to "
  1507. "certificate store");
  1508. if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
  1509. ERR_GET_REASON(err) ==
  1510. X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  1511. wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
  1512. "cert already in hash table error",
  1513. __func__);
  1514. } else {
  1515. X509_free(cert);
  1516. return -1;
  1517. }
  1518. }
  1519. X509_free(cert);
  1520. wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
  1521. "to certificate store", __func__);
  1522. return 0;
  1523. }
  1524. #ifdef ANDROID
  1525. if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
  1526. BIO *bio = BIO_from_keystore(&ca_cert[11]);
  1527. STACK_OF(X509_INFO) *stack = NULL;
  1528. stack_index_t i;
  1529. if (bio) {
  1530. stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
  1531. BIO_free(bio);
  1532. }
  1533. if (!stack)
  1534. return -1;
  1535. for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
  1536. X509_INFO *info = sk_X509_INFO_value(stack, i);
  1537. if (info->x509) {
  1538. X509_STORE_add_cert(ssl_ctx->cert_store,
  1539. info->x509);
  1540. }
  1541. if (info->crl) {
  1542. X509_STORE_add_crl(ssl_ctx->cert_store,
  1543. info->crl);
  1544. }
  1545. }
  1546. sk_X509_INFO_pop_free(stack, X509_INFO_free);
  1547. SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
  1548. return 0;
  1549. }
  1550. #endif /* ANDROID */
  1551. #ifdef CONFIG_NATIVE_WINDOWS
  1552. if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
  1553. 0) {
  1554. wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
  1555. "system certificate store");
  1556. return 0;
  1557. }
  1558. #endif /* CONFIG_NATIVE_WINDOWS */
  1559. if (ca_cert || ca_path) {
  1560. #ifndef OPENSSL_NO_STDIO
  1561. if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
  1562. 1) {
  1563. tls_show_errors(MSG_WARNING, __func__,
  1564. "Failed to load root certificates");
  1565. if (ca_cert &&
  1566. tls_load_ca_der(data, ca_cert) == 0) {
  1567. wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
  1568. "DER format CA certificate",
  1569. __func__);
  1570. } else
  1571. return -1;
  1572. } else {
  1573. wpa_printf(MSG_DEBUG, "TLS: Trusted root "
  1574. "certificate(s) loaded");
  1575. tls_get_errors(data);
  1576. }
  1577. #else /* OPENSSL_NO_STDIO */
  1578. wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
  1579. __func__);
  1580. return -1;
  1581. #endif /* OPENSSL_NO_STDIO */
  1582. } else {
  1583. /* No ca_cert configured - do not try to verify server
  1584. * certificate */
  1585. conn->ca_cert_verify = 0;
  1586. }
  1587. return 0;
  1588. }
  1589. static int tls_global_ca_cert(struct tls_data *data, const char *ca_cert)
  1590. {
  1591. SSL_CTX *ssl_ctx = data->ssl;
  1592. if (ca_cert) {
  1593. if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
  1594. {
  1595. tls_show_errors(MSG_WARNING, __func__,
  1596. "Failed to load root certificates");
  1597. return -1;
  1598. }
  1599. wpa_printf(MSG_DEBUG, "TLS: Trusted root "
  1600. "certificate(s) loaded");
  1601. #ifndef OPENSSL_NO_STDIO
  1602. /* Add the same CAs to the client certificate requests */
  1603. SSL_CTX_set_client_CA_list(ssl_ctx,
  1604. SSL_load_client_CA_file(ca_cert));
  1605. #endif /* OPENSSL_NO_STDIO */
  1606. }
  1607. return 0;
  1608. }
  1609. int tls_global_set_verify(void *ssl_ctx, int check_crl)
  1610. {
  1611. int flags;
  1612. if (check_crl) {
  1613. struct tls_data *data = ssl_ctx;
  1614. X509_STORE *cs = SSL_CTX_get_cert_store(data->ssl);
  1615. if (cs == NULL) {
  1616. tls_show_errors(MSG_INFO, __func__, "Failed to get "
  1617. "certificate store when enabling "
  1618. "check_crl");
  1619. return -1;
  1620. }
  1621. flags = X509_V_FLAG_CRL_CHECK;
  1622. if (check_crl == 2)
  1623. flags |= X509_V_FLAG_CRL_CHECK_ALL;
  1624. X509_STORE_set_flags(cs, flags);
  1625. }
  1626. return 0;
  1627. }
  1628. static int tls_connection_set_subject_match(struct tls_connection *conn,
  1629. const char *subject_match,
  1630. const char *altsubject_match,
  1631. const char *suffix_match,
  1632. const char *domain_match)
  1633. {
  1634. os_free(conn->subject_match);
  1635. conn->subject_match = NULL;
  1636. if (subject_match) {
  1637. conn->subject_match = os_strdup(subject_match);
  1638. if (conn->subject_match == NULL)
  1639. return -1;
  1640. }
  1641. os_free(conn->altsubject_match);
  1642. conn->altsubject_match = NULL;
  1643. if (altsubject_match) {
  1644. conn->altsubject_match = os_strdup(altsubject_match);
  1645. if (conn->altsubject_match == NULL)
  1646. return -1;
  1647. }
  1648. os_free(conn->suffix_match);
  1649. conn->suffix_match = NULL;
  1650. if (suffix_match) {
  1651. conn->suffix_match = os_strdup(suffix_match);
  1652. if (conn->suffix_match == NULL)
  1653. return -1;
  1654. }
  1655. os_free(conn->domain_match);
  1656. conn->domain_match = NULL;
  1657. if (domain_match) {
  1658. conn->domain_match = os_strdup(domain_match);
  1659. if (conn->domain_match == NULL)
  1660. return -1;
  1661. }
  1662. return 0;
  1663. }
  1664. static void tls_set_conn_flags(SSL *ssl, unsigned int flags)
  1665. {
  1666. #ifdef SSL_OP_NO_TICKET
  1667. if (flags & TLS_CONN_DISABLE_SESSION_TICKET)
  1668. SSL_set_options(ssl, SSL_OP_NO_TICKET);
  1669. #ifdef SSL_clear_options
  1670. else
  1671. SSL_clear_options(ssl, SSL_OP_NO_TICKET);
  1672. #endif /* SSL_clear_options */
  1673. #endif /* SSL_OP_NO_TICKET */
  1674. #ifdef SSL_OP_NO_TLSv1
  1675. if (flags & TLS_CONN_DISABLE_TLSv1_0)
  1676. SSL_set_options(ssl, SSL_OP_NO_TLSv1);
  1677. else
  1678. SSL_clear_options(ssl, SSL_OP_NO_TLSv1);
  1679. #endif /* SSL_OP_NO_TLSv1 */
  1680. #ifdef SSL_OP_NO_TLSv1_1
  1681. if (flags & TLS_CONN_DISABLE_TLSv1_1)
  1682. SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
  1683. else
  1684. SSL_clear_options(ssl, SSL_OP_NO_TLSv1_1);
  1685. #endif /* SSL_OP_NO_TLSv1_1 */
  1686. #ifdef SSL_OP_NO_TLSv1_2
  1687. if (flags & TLS_CONN_DISABLE_TLSv1_2)
  1688. SSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
  1689. else
  1690. SSL_clear_options(ssl, SSL_OP_NO_TLSv1_2);
  1691. #endif /* SSL_OP_NO_TLSv1_2 */
  1692. }
  1693. int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
  1694. int verify_peer, unsigned int flags,
  1695. const u8 *session_ctx, size_t session_ctx_len)
  1696. {
  1697. static int counter = 0;
  1698. if (conn == NULL)
  1699. return -1;
  1700. if (verify_peer) {
  1701. conn->ca_cert_verify = 1;
  1702. SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
  1703. SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
  1704. SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
  1705. } else {
  1706. conn->ca_cert_verify = 0;
  1707. SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
  1708. }
  1709. tls_set_conn_flags(conn->ssl, flags);
  1710. conn->flags = flags;
  1711. SSL_set_accept_state(conn->ssl);
  1712. /*
  1713. * Set session id context in order to avoid fatal errors when client
  1714. * tries to resume a session. However, set the context to a unique
  1715. * value in order to effectively disable session resumption for now
  1716. * since not all areas of the server code are ready for it (e.g.,
  1717. * EAP-TTLS needs special handling for Phase 2 after abbreviated TLS
  1718. * handshake).
  1719. */
  1720. counter++;
  1721. SSL_set_session_id_context(conn->ssl,
  1722. (const unsigned char *) &counter,
  1723. sizeof(counter));
  1724. return 0;
  1725. }
  1726. static int tls_connection_client_cert(struct tls_connection *conn,
  1727. const char *client_cert,
  1728. const u8 *client_cert_blob,
  1729. size_t client_cert_blob_len)
  1730. {
  1731. if (client_cert == NULL && client_cert_blob == NULL)
  1732. return 0;
  1733. if (client_cert_blob &&
  1734. SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
  1735. client_cert_blob_len) == 1) {
  1736. wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
  1737. "OK");
  1738. return 0;
  1739. } else if (client_cert_blob) {
  1740. tls_show_errors(MSG_DEBUG, __func__,
  1741. "SSL_use_certificate_ASN1 failed");
  1742. }
  1743. if (client_cert == NULL)
  1744. return -1;
  1745. #ifdef ANDROID
  1746. if (os_strncmp("keystore://", client_cert, 11) == 0) {
  1747. BIO *bio = BIO_from_keystore(&client_cert[11]);
  1748. X509 *x509 = NULL;
  1749. int ret = -1;
  1750. if (bio) {
  1751. x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
  1752. BIO_free(bio);
  1753. }
  1754. if (x509) {
  1755. if (SSL_use_certificate(conn->ssl, x509) == 1)
  1756. ret = 0;
  1757. X509_free(x509);
  1758. }
  1759. return ret;
  1760. }
  1761. #endif /* ANDROID */
  1762. #ifndef OPENSSL_NO_STDIO
  1763. if (SSL_use_certificate_file(conn->ssl, client_cert,
  1764. SSL_FILETYPE_ASN1) == 1) {
  1765. wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
  1766. " --> OK");
  1767. return 0;
  1768. }
  1769. if (SSL_use_certificate_file(conn->ssl, client_cert,
  1770. SSL_FILETYPE_PEM) == 1) {
  1771. ERR_clear_error();
  1772. wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
  1773. " --> OK");
  1774. return 0;
  1775. }
  1776. tls_show_errors(MSG_DEBUG, __func__,
  1777. "SSL_use_certificate_file failed");
  1778. #else /* OPENSSL_NO_STDIO */
  1779. wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
  1780. #endif /* OPENSSL_NO_STDIO */
  1781. return -1;
  1782. }
  1783. static int tls_global_client_cert(struct tls_data *data,
  1784. const char *client_cert)
  1785. {
  1786. #ifndef OPENSSL_NO_STDIO
  1787. SSL_CTX *ssl_ctx = data->ssl;
  1788. if (client_cert == NULL)
  1789. return 0;
  1790. if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
  1791. SSL_FILETYPE_ASN1) != 1 &&
  1792. SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
  1793. SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
  1794. SSL_FILETYPE_PEM) != 1) {
  1795. tls_show_errors(MSG_INFO, __func__,
  1796. "Failed to load client certificate");
  1797. return -1;
  1798. }
  1799. return 0;
  1800. #else /* OPENSSL_NO_STDIO */
  1801. if (client_cert == NULL)
  1802. return 0;
  1803. wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
  1804. return -1;
  1805. #endif /* OPENSSL_NO_STDIO */
  1806. }
  1807. static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
  1808. {
  1809. if (password == NULL) {
  1810. return 0;
  1811. }
  1812. os_strlcpy(buf, (char *) password, size);
  1813. return os_strlen(buf);
  1814. }
  1815. #ifdef PKCS12_FUNCS
  1816. static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
  1817. const char *passwd)
  1818. {
  1819. EVP_PKEY *pkey;
  1820. X509 *cert;
  1821. STACK_OF(X509) *certs;
  1822. int res = 0;
  1823. char buf[256];
  1824. pkey = NULL;
  1825. cert = NULL;
  1826. certs = NULL;
  1827. if (!passwd)
  1828. passwd = "";
  1829. if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
  1830. tls_show_errors(MSG_DEBUG, __func__,
  1831. "Failed to parse PKCS12 file");
  1832. PKCS12_free(p12);
  1833. return -1;
  1834. }
  1835. wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
  1836. if (cert) {
  1837. X509_NAME_oneline(X509_get_subject_name(cert), buf,
  1838. sizeof(buf));
  1839. wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
  1840. "subject='%s'", buf);
  1841. if (ssl) {
  1842. if (SSL_use_certificate(ssl, cert) != 1)
  1843. res = -1;
  1844. } else {
  1845. if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
  1846. res = -1;
  1847. }
  1848. X509_free(cert);
  1849. }
  1850. if (pkey) {
  1851. wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
  1852. if (ssl) {
  1853. if (SSL_use_PrivateKey(ssl, pkey) != 1)
  1854. res = -1;
  1855. } else {
  1856. if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
  1857. res = -1;
  1858. }
  1859. EVP_PKEY_free(pkey);
  1860. }
  1861. if (certs) {
  1862. #if OPENSSL_VERSION_NUMBER >= 0x10002000L
  1863. SSL_clear_chain_certs(ssl);
  1864. while ((cert = sk_X509_pop(certs)) != NULL) {
  1865. X509_NAME_oneline(X509_get_subject_name(cert), buf,
  1866. sizeof(buf));
  1867. wpa_printf(MSG_DEBUG, "TLS: additional certificate"
  1868. " from PKCS12: subject='%s'", buf);
  1869. if (SSL_add1_chain_cert(ssl, cert) != 1) {
  1870. res = -1;
  1871. break;
  1872. }
  1873. }
  1874. sk_X509_free(certs);
  1875. #ifndef OPENSSL_IS_BORINGSSL
  1876. res = SSL_build_cert_chain(ssl,
  1877. SSL_BUILD_CHAIN_FLAG_CHECK |
  1878. SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
  1879. if (!res) {
  1880. tls_show_errors(MSG_DEBUG, __func__,
  1881. "Failed to build certificate chain");
  1882. } else if (res == 2) {
  1883. wpa_printf(MSG_DEBUG,
  1884. "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
  1885. }
  1886. #endif /* OPENSSL_IS_BORINGSSL */
  1887. /*
  1888. * Try to continue regardless of result since it is possible for
  1889. * the extra certificates not to be required.
  1890. */
  1891. res = 0;
  1892. #else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
  1893. #if OPENSSL_VERSION_NUMBER >= 0x10001000L
  1894. SSL_CTX_clear_extra_chain_certs(data->ssl);
  1895. #endif /* OPENSSL_VERSION_NUMBER >= 0x10001000L */
  1896. while ((cert = sk_X509_pop(certs)) != NULL) {
  1897. X509_NAME_oneline(X509_get_subject_name(cert), buf,
  1898. sizeof(buf));
  1899. wpa_printf(MSG_DEBUG, "TLS: additional certificate"
  1900. " from PKCS12: subject='%s'", buf);
  1901. /*
  1902. * There is no SSL equivalent for the chain cert - so
  1903. * always add it to the context...
  1904. */
  1905. if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
  1906. {
  1907. res = -1;
  1908. break;
  1909. }
  1910. }
  1911. sk_X509_free(certs);
  1912. #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
  1913. }
  1914. PKCS12_free(p12);
  1915. if (res < 0)
  1916. tls_get_errors(data);
  1917. return res;
  1918. }
  1919. #endif /* PKCS12_FUNCS */
  1920. static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
  1921. const char *private_key, const char *passwd)
  1922. {
  1923. #ifdef PKCS12_FUNCS
  1924. FILE *f;
  1925. PKCS12 *p12;
  1926. f = fopen(private_key, "rb");
  1927. if (f == NULL)
  1928. return -1;
  1929. p12 = d2i_PKCS12_fp(f, NULL);
  1930. fclose(f);
  1931. if (p12 == NULL) {
  1932. tls_show_errors(MSG_INFO, __func__,
  1933. "Failed to use PKCS#12 file");
  1934. return -1;
  1935. }
  1936. return tls_parse_pkcs12(data, ssl, p12, passwd);
  1937. #else /* PKCS12_FUNCS */
  1938. wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
  1939. "p12/pfx files");
  1940. return -1;
  1941. #endif /* PKCS12_FUNCS */
  1942. }
  1943. static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
  1944. const u8 *blob, size_t len, const char *passwd)
  1945. {
  1946. #ifdef PKCS12_FUNCS
  1947. PKCS12 *p12;
  1948. p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
  1949. if (p12 == NULL) {
  1950. tls_show_errors(MSG_INFO, __func__,
  1951. "Failed to use PKCS#12 blob");
  1952. return -1;
  1953. }
  1954. return tls_parse_pkcs12(data, ssl, p12, passwd);
  1955. #else /* PKCS12_FUNCS */
  1956. wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
  1957. "p12/pfx blobs");
  1958. return -1;
  1959. #endif /* PKCS12_FUNCS */
  1960. }
  1961. #ifndef OPENSSL_NO_ENGINE
  1962. static int tls_engine_get_cert(struct tls_connection *conn,
  1963. const char *cert_id,
  1964. X509 **cert)
  1965. {
  1966. /* this runs after the private key is loaded so no PIN is required */
  1967. struct {
  1968. const char *cert_id;
  1969. X509 *cert;
  1970. } params;
  1971. params.cert_id = cert_id;
  1972. params.cert = NULL;
  1973. if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
  1974. 0, &params, NULL, 1)) {
  1975. unsigned long err = ERR_get_error();
  1976. wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
  1977. " '%s' [%s]", cert_id,
  1978. ERR_error_string(err, NULL));
  1979. if (tls_is_pin_error(err))
  1980. return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
  1981. return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
  1982. }
  1983. if (!params.cert) {
  1984. wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
  1985. " '%s'", cert_id);
  1986. return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
  1987. }
  1988. *cert = params.cert;
  1989. return 0;
  1990. }
  1991. #endif /* OPENSSL_NO_ENGINE */
  1992. static int tls_connection_engine_client_cert(struct tls_connection *conn,
  1993. const char *cert_id)
  1994. {
  1995. #ifndef OPENSSL_NO_ENGINE
  1996. X509 *cert;
  1997. if (tls_engine_get_cert(conn, cert_id, &cert))
  1998. return -1;
  1999. if (!SSL_use_certificate(conn->ssl, cert)) {
  2000. tls_show_errors(MSG_ERROR, __func__,
  2001. "SSL_use_certificate failed");
  2002. X509_free(cert);
  2003. return -1;
  2004. }
  2005. X509_free(cert);
  2006. wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
  2007. "OK");
  2008. return 0;
  2009. #else /* OPENSSL_NO_ENGINE */
  2010. return -1;
  2011. #endif /* OPENSSL_NO_ENGINE */
  2012. }
  2013. static int tls_connection_engine_ca_cert(struct tls_data *data,
  2014. struct tls_connection *conn,
  2015. const char *ca_cert_id)
  2016. {
  2017. #ifndef OPENSSL_NO_ENGINE
  2018. X509 *cert;
  2019. SSL_CTX *ssl_ctx = data->ssl;
  2020. X509_STORE *store;
  2021. if (tls_engine_get_cert(conn, ca_cert_id, &cert))
  2022. return -1;
  2023. /* start off the same as tls_connection_ca_cert */
  2024. store = X509_STORE_new();
  2025. if (store == NULL) {
  2026. wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
  2027. "certificate store", __func__);
  2028. X509_free(cert);
  2029. return -1;
  2030. }
  2031. SSL_CTX_set_cert_store(ssl_ctx, store);
  2032. if (!X509_STORE_add_cert(store, cert)) {
  2033. unsigned long err = ERR_peek_error();
  2034. tls_show_errors(MSG_WARNING, __func__,
  2035. "Failed to add CA certificate from engine "
  2036. "to certificate store");
  2037. if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
  2038. ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
  2039. wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
  2040. " already in hash table error",
  2041. __func__);
  2042. } else {
  2043. X509_free(cert);
  2044. return -1;
  2045. }
  2046. }
  2047. X509_free(cert);
  2048. wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
  2049. "to certificate store", __func__);
  2050. SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
  2051. conn->ca_cert_verify = 1;
  2052. return 0;
  2053. #else /* OPENSSL_NO_ENGINE */
  2054. return -1;
  2055. #endif /* OPENSSL_NO_ENGINE */
  2056. }
  2057. static int tls_connection_engine_private_key(struct tls_connection *conn)
  2058. {
  2059. #ifndef OPENSSL_NO_ENGINE
  2060. if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
  2061. tls_show_errors(MSG_ERROR, __func__,
  2062. "ENGINE: cannot use private key for TLS");
  2063. return -1;
  2064. }
  2065. if (!SSL_check_private_key(conn->ssl)) {
  2066. tls_show_errors(MSG_INFO, __func__,
  2067. "Private key failed verification");
  2068. return -1;
  2069. }
  2070. return 0;
  2071. #else /* OPENSSL_NO_ENGINE */
  2072. wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
  2073. "engine support was not compiled in");
  2074. return -1;
  2075. #endif /* OPENSSL_NO_ENGINE */
  2076. }
  2077. static int tls_connection_private_key(struct tls_data *data,
  2078. struct tls_connection *conn,
  2079. const char *private_key,
  2080. const char *private_key_passwd,
  2081. const u8 *private_key_blob,
  2082. size_t private_key_blob_len)
  2083. {
  2084. SSL_CTX *ssl_ctx = data->ssl;
  2085. char *passwd;
  2086. int ok;
  2087. if (private_key == NULL && private_key_blob == NULL)
  2088. return 0;
  2089. if (private_key_passwd) {
  2090. passwd = os_strdup(private_key_passwd);
  2091. if (passwd == NULL)
  2092. return -1;
  2093. } else
  2094. passwd = NULL;
  2095. SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
  2096. SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
  2097. ok = 0;
  2098. while (private_key_blob) {
  2099. if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
  2100. (u8 *) private_key_blob,
  2101. private_key_blob_len) == 1) {
  2102. wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
  2103. "ASN1(EVP_PKEY_RSA) --> OK");
  2104. ok = 1;
  2105. break;
  2106. }
  2107. if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
  2108. (u8 *) private_key_blob,
  2109. private_key_blob_len) == 1) {
  2110. wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
  2111. "ASN1(EVP_PKEY_DSA) --> OK");
  2112. ok = 1;
  2113. break;
  2114. }
  2115. if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
  2116. (u8 *) private_key_blob,
  2117. private_key_blob_len) == 1) {
  2118. wpa_printf(MSG_DEBUG, "OpenSSL: "
  2119. "SSL_use_RSAPrivateKey_ASN1 --> OK");
  2120. ok = 1;
  2121. break;
  2122. }
  2123. if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
  2124. private_key_blob_len, passwd) == 0) {
  2125. wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
  2126. "OK");
  2127. ok = 1;
  2128. break;
  2129. }
  2130. break;
  2131. }
  2132. while (!ok && private_key) {
  2133. #ifndef OPENSSL_NO_STDIO
  2134. if (SSL_use_PrivateKey_file(conn->ssl, private_key,
  2135. SSL_FILETYPE_ASN1) == 1) {
  2136. wpa_printf(MSG_DEBUG, "OpenSSL: "
  2137. "SSL_use_PrivateKey_File (DER) --> OK");
  2138. ok = 1;
  2139. break;
  2140. }
  2141. if (SSL_use_PrivateKey_file(conn->ssl, private_key,
  2142. SSL_FILETYPE_PEM) == 1) {
  2143. wpa_printf(MSG_DEBUG, "OpenSSL: "
  2144. "SSL_use_PrivateKey_File (PEM) --> OK");
  2145. ok = 1;
  2146. break;
  2147. }
  2148. #else /* OPENSSL_NO_STDIO */
  2149. wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
  2150. __func__);
  2151. #endif /* OPENSSL_NO_STDIO */
  2152. if (tls_read_pkcs12(data, conn->ssl, private_key, passwd)
  2153. == 0) {
  2154. wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
  2155. "--> OK");
  2156. ok = 1;
  2157. break;
  2158. }
  2159. if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
  2160. wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
  2161. "access certificate store --> OK");
  2162. ok = 1;
  2163. break;
  2164. }
  2165. break;
  2166. }
  2167. if (!ok) {
  2168. tls_show_errors(MSG_INFO, __func__,
  2169. "Failed to load private key");
  2170. os_free(passwd);
  2171. return -1;
  2172. }
  2173. ERR_clear_error();
  2174. SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
  2175. os_free(passwd);
  2176. if (!SSL_check_private_key(conn->ssl)) {
  2177. tls_show_errors(MSG_INFO, __func__, "Private key failed "
  2178. "verification");
  2179. return -1;
  2180. }
  2181. wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
  2182. return 0;
  2183. }
  2184. static int tls_global_private_key(struct tls_data *data,
  2185. const char *private_key,
  2186. const char *private_key_passwd)
  2187. {
  2188. SSL_CTX *ssl_ctx = data->ssl;
  2189. char *passwd;
  2190. if (private_key == NULL)
  2191. return 0;
  2192. if (private_key_passwd) {
  2193. passwd = os_strdup(private_key_passwd);
  2194. if (passwd == NULL)
  2195. return -1;
  2196. } else
  2197. passwd = NULL;
  2198. SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
  2199. SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
  2200. if (
  2201. #ifndef OPENSSL_NO_STDIO
  2202. SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
  2203. SSL_FILETYPE_ASN1) != 1 &&
  2204. SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
  2205. SSL_FILETYPE_PEM) != 1 &&
  2206. #endif /* OPENSSL_NO_STDIO */
  2207. tls_read_pkcs12(data, NULL, private_key, passwd)) {
  2208. tls_show_errors(MSG_INFO, __func__,
  2209. "Failed to load private key");
  2210. os_free(passwd);
  2211. ERR_clear_error();
  2212. return -1;
  2213. }
  2214. os_free(passwd);
  2215. ERR_clear_error();
  2216. SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
  2217. if (!SSL_CTX_check_private_key(ssl_ctx)) {
  2218. tls_show_errors(MSG_INFO, __func__,
  2219. "Private key failed verification");
  2220. return -1;
  2221. }
  2222. return 0;
  2223. }
  2224. static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
  2225. {
  2226. #ifdef OPENSSL_NO_DH
  2227. if (dh_file == NULL)
  2228. return 0;
  2229. wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
  2230. "dh_file specified");
  2231. return -1;
  2232. #else /* OPENSSL_NO_DH */
  2233. DH *dh;
  2234. BIO *bio;
  2235. /* TODO: add support for dh_blob */
  2236. if (dh_file == NULL)
  2237. return 0;
  2238. if (conn == NULL)
  2239. return -1;
  2240. bio = BIO_new_file(dh_file, "r");
  2241. if (bio == NULL) {
  2242. wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
  2243. dh_file, ERR_error_string(ERR_get_error(), NULL));
  2244. return -1;
  2245. }
  2246. dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  2247. BIO_free(bio);
  2248. #ifndef OPENSSL_NO_DSA
  2249. while (dh == NULL) {
  2250. DSA *dsa;
  2251. wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
  2252. " trying to parse as DSA params", dh_file,
  2253. ERR_error_string(ERR_get_error(), NULL));
  2254. bio = BIO_new_file(dh_file, "r");
  2255. if (bio == NULL)
  2256. break;
  2257. dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
  2258. BIO_free(bio);
  2259. if (!dsa) {
  2260. wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
  2261. "'%s': %s", dh_file,
  2262. ERR_error_string(ERR_get_error(), NULL));
  2263. break;
  2264. }
  2265. wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
  2266. dh = DSA_dup_DH(dsa);
  2267. DSA_free(dsa);
  2268. if (dh == NULL) {
  2269. wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
  2270. "params into DH params");
  2271. break;
  2272. }
  2273. break;
  2274. }
  2275. #endif /* !OPENSSL_NO_DSA */
  2276. if (dh == NULL) {
  2277. wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
  2278. "'%s'", dh_file);
  2279. return -1;
  2280. }
  2281. if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
  2282. wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
  2283. "%s", dh_file,
  2284. ERR_error_string(ERR_get_error(), NULL));
  2285. DH_free(dh);
  2286. return -1;
  2287. }
  2288. DH_free(dh);
  2289. return 0;
  2290. #endif /* OPENSSL_NO_DH */
  2291. }
  2292. static int tls_global_dh(struct tls_data *data, const char *dh_file)
  2293. {
  2294. #ifdef OPENSSL_NO_DH
  2295. if (dh_file == NULL)
  2296. return 0;
  2297. wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
  2298. "dh_file specified");
  2299. return -1;
  2300. #else /* OPENSSL_NO_DH */
  2301. SSL_CTX *ssl_ctx = data->ssl;
  2302. DH *dh;
  2303. BIO *bio;
  2304. /* TODO: add support for dh_blob */
  2305. if (dh_file == NULL)
  2306. return 0;
  2307. if (ssl_ctx == NULL)
  2308. return -1;
  2309. bio = BIO_new_file(dh_file, "r");
  2310. if (bio == NULL) {
  2311. wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
  2312. dh_file, ERR_error_string(ERR_get_error(), NULL));
  2313. return -1;
  2314. }
  2315. dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
  2316. BIO_free(bio);
  2317. #ifndef OPENSSL_NO_DSA
  2318. while (dh == NULL) {
  2319. DSA *dsa;
  2320. wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
  2321. " trying to parse as DSA params", dh_file,
  2322. ERR_error_string(ERR_get_error(), NULL));
  2323. bio = BIO_new_file(dh_file, "r");
  2324. if (bio == NULL)
  2325. break;
  2326. dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
  2327. BIO_free(bio);
  2328. if (!dsa) {
  2329. wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
  2330. "'%s': %s", dh_file,
  2331. ERR_error_string(ERR_get_error(), NULL));
  2332. break;
  2333. }
  2334. wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
  2335. dh = DSA_dup_DH(dsa);
  2336. DSA_free(dsa);
  2337. if (dh == NULL) {
  2338. wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
  2339. "params into DH params");
  2340. break;
  2341. }
  2342. break;
  2343. }
  2344. #endif /* !OPENSSL_NO_DSA */
  2345. if (dh == NULL) {
  2346. wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
  2347. "'%s'", dh_file);
  2348. return -1;
  2349. }
  2350. if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
  2351. wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
  2352. "%s", dh_file,
  2353. ERR_error_string(ERR_get_error(), NULL));
  2354. DH_free(dh);
  2355. return -1;
  2356. }
  2357. DH_free(dh);
  2358. return 0;
  2359. #endif /* OPENSSL_NO_DH */
  2360. }
  2361. int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
  2362. struct tls_random *keys)
  2363. {
  2364. SSL *ssl;
  2365. if (conn == NULL || keys == NULL)
  2366. return -1;
  2367. ssl = conn->ssl;
  2368. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  2369. if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL)
  2370. return -1;
  2371. os_memset(keys, 0, sizeof(*keys));
  2372. keys->client_random = ssl->s3->client_random;
  2373. keys->client_random_len = SSL3_RANDOM_SIZE;
  2374. keys->server_random = ssl->s3->server_random;
  2375. keys->server_random_len = SSL3_RANDOM_SIZE;
  2376. #else
  2377. if (ssl == NULL)
  2378. return -1;
  2379. os_memset(keys, 0, sizeof(*keys));
  2380. keys->client_random = conn->client_random;
  2381. keys->client_random_len = SSL_get_client_random(
  2382. ssl, conn->client_random, sizeof(conn->client_random));
  2383. keys->server_random = conn->server_random;
  2384. keys->server_random_len = SSL_get_server_random(
  2385. ssl, conn->server_random, sizeof(conn->server_random));
  2386. #endif
  2387. return 0;
  2388. }
  2389. #ifndef CONFIG_FIPS
  2390. static int openssl_get_keyblock_size(SSL *ssl)
  2391. {
  2392. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  2393. const EVP_CIPHER *c;
  2394. const EVP_MD *h;
  2395. int md_size;
  2396. if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
  2397. ssl->read_hash == NULL)
  2398. return -1;
  2399. c = ssl->enc_read_ctx->cipher;
  2400. #if OPENSSL_VERSION_NUMBER >= 0x00909000L
  2401. h = EVP_MD_CTX_md(ssl->read_hash);
  2402. #else
  2403. h = ssl->read_hash;
  2404. #endif
  2405. if (h)
  2406. md_size = EVP_MD_size(h);
  2407. #if OPENSSL_VERSION_NUMBER >= 0x10000000L
  2408. else if (ssl->s3)
  2409. md_size = ssl->s3->tmp.new_mac_secret_size;
  2410. #endif
  2411. else
  2412. return -1;
  2413. wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
  2414. "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
  2415. EVP_CIPHER_iv_length(c));
  2416. return 2 * (EVP_CIPHER_key_length(c) +
  2417. md_size +
  2418. EVP_CIPHER_iv_length(c));
  2419. #else
  2420. const SSL_CIPHER *ssl_cipher;
  2421. int cipher, digest;
  2422. const EVP_CIPHER *c;
  2423. const EVP_MD *h;
  2424. ssl_cipher = SSL_get_current_cipher(ssl);
  2425. if (!ssl_cipher)
  2426. return -1;
  2427. cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
  2428. digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
  2429. wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
  2430. cipher, digest);
  2431. if (cipher < 0 || digest < 0)
  2432. return -1;
  2433. c = EVP_get_cipherbynid(cipher);
  2434. h = EVP_get_digestbynid(digest);
  2435. if (!c || !h)
  2436. return -1;
  2437. wpa_printf(MSG_DEBUG,
  2438. "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
  2439. EVP_CIPHER_key_length(c), EVP_MD_size(h),
  2440. EVP_CIPHER_iv_length(c));
  2441. return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
  2442. EVP_CIPHER_iv_length(c));
  2443. #endif
  2444. }
  2445. #endif /* CONFIG_FIPS */
  2446. static int openssl_tls_prf(struct tls_connection *conn,
  2447. const char *label, int server_random_first,
  2448. int skip_keyblock, u8 *out, size_t out_len)
  2449. {
  2450. #ifdef CONFIG_FIPS
  2451. wpa_printf(MSG_ERROR, "OpenSSL: TLS keys cannot be exported in FIPS "
  2452. "mode");
  2453. return -1;
  2454. #else /* CONFIG_FIPS */
  2455. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  2456. SSL *ssl;
  2457. u8 *rnd;
  2458. int ret = -1;
  2459. int skip = 0;
  2460. u8 *tmp_out = NULL;
  2461. u8 *_out = out;
  2462. const char *ver;
  2463. /*
  2464. * TLS library did not support key generation, so get the needed TLS
  2465. * session parameters and use an internal implementation of TLS PRF to
  2466. * derive the key.
  2467. */
  2468. if (conn == NULL)
  2469. return -1;
  2470. ssl = conn->ssl;
  2471. if (ssl == NULL || ssl->s3 == NULL || ssl->session == NULL ||
  2472. ssl->session->master_key_length <= 0)
  2473. return -1;
  2474. ver = SSL_get_version(ssl);
  2475. if (skip_keyblock) {
  2476. skip = openssl_get_keyblock_size(ssl);
  2477. if (skip < 0)
  2478. return -1;
  2479. tmp_out = os_malloc(skip + out_len);
  2480. if (!tmp_out)
  2481. return -1;
  2482. _out = tmp_out;
  2483. }
  2484. rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
  2485. if (!rnd) {
  2486. os_free(tmp_out);
  2487. return -1;
  2488. }
  2489. if (server_random_first) {
  2490. os_memcpy(rnd, ssl->s3->server_random, SSL3_RANDOM_SIZE);
  2491. os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->client_random,
  2492. SSL3_RANDOM_SIZE);
  2493. } else {
  2494. os_memcpy(rnd, ssl->s3->client_random, SSL3_RANDOM_SIZE);
  2495. os_memcpy(rnd + SSL3_RANDOM_SIZE, ssl->s3->server_random,
  2496. SSL3_RANDOM_SIZE);
  2497. }
  2498. if (os_strcmp(ver, "TLSv1.2") == 0) {
  2499. tls_prf_sha256(ssl->session->master_key,
  2500. ssl->session->master_key_length,
  2501. label, rnd, 2 * SSL3_RANDOM_SIZE,
  2502. _out, skip + out_len);
  2503. ret = 0;
  2504. } else if (tls_prf_sha1_md5(ssl->session->master_key,
  2505. ssl->session->master_key_length,
  2506. label, rnd, 2 * SSL3_RANDOM_SIZE,
  2507. _out, skip + out_len) == 0) {
  2508. ret = 0;
  2509. }
  2510. os_free(rnd);
  2511. if (ret == 0 && skip_keyblock)
  2512. os_memcpy(out, _out + skip, out_len);
  2513. bin_clear_free(tmp_out, skip);
  2514. return ret;
  2515. #else
  2516. SSL *ssl;
  2517. SSL_SESSION *sess;
  2518. u8 *rnd;
  2519. int ret = -1;
  2520. int skip = 0;
  2521. u8 *tmp_out = NULL;
  2522. u8 *_out = out;
  2523. unsigned char client_random[SSL3_RANDOM_SIZE];
  2524. unsigned char server_random[SSL3_RANDOM_SIZE];
  2525. unsigned char master_key[64];
  2526. size_t master_key_len;
  2527. const char *ver;
  2528. /*
  2529. * TLS library did not support key generation, so get the needed TLS
  2530. * session parameters and use an internal implementation of TLS PRF to
  2531. * derive the key.
  2532. */
  2533. if (conn == NULL)
  2534. return -1;
  2535. ssl = conn->ssl;
  2536. if (ssl == NULL)
  2537. return -1;
  2538. ver = SSL_get_version(ssl);
  2539. sess = SSL_get_session(ssl);
  2540. if (!ver || !sess)
  2541. return -1;
  2542. if (skip_keyblock) {
  2543. skip = openssl_get_keyblock_size(ssl);
  2544. if (skip < 0)
  2545. return -1;
  2546. tmp_out = os_malloc(skip + out_len);
  2547. if (!tmp_out)
  2548. return -1;
  2549. _out = tmp_out;
  2550. }
  2551. rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
  2552. if (!rnd) {
  2553. os_free(tmp_out);
  2554. return -1;
  2555. }
  2556. SSL_get_client_random(ssl, client_random, sizeof(client_random));
  2557. SSL_get_server_random(ssl, server_random, sizeof(server_random));
  2558. master_key_len = SSL_SESSION_get_master_key(sess, master_key,
  2559. sizeof(master_key));
  2560. if (server_random_first) {
  2561. os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
  2562. os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random,
  2563. SSL3_RANDOM_SIZE);
  2564. } else {
  2565. os_memcpy(rnd, client_random, SSL3_RANDOM_SIZE);
  2566. os_memcpy(rnd + SSL3_RANDOM_SIZE, server_random,
  2567. SSL3_RANDOM_SIZE);
  2568. }
  2569. if (os_strcmp(ver, "TLSv1.2") == 0) {
  2570. tls_prf_sha256(master_key, master_key_len,
  2571. label, rnd, 2 * SSL3_RANDOM_SIZE,
  2572. _out, skip + out_len);
  2573. ret = 0;
  2574. } else if (tls_prf_sha1_md5(master_key, master_key_len,
  2575. label, rnd, 2 * SSL3_RANDOM_SIZE,
  2576. _out, skip + out_len) == 0) {
  2577. ret = 0;
  2578. }
  2579. os_memset(master_key, 0, sizeof(master_key));
  2580. os_free(rnd);
  2581. if (ret == 0 && skip_keyblock)
  2582. os_memcpy(out, _out + skip, out_len);
  2583. bin_clear_free(tmp_out, skip);
  2584. return ret;
  2585. #endif
  2586. #endif /* CONFIG_FIPS */
  2587. }
  2588. int tls_connection_prf(void *tls_ctx, struct tls_connection *conn,
  2589. const char *label, int server_random_first,
  2590. int skip_keyblock, u8 *out, size_t out_len)
  2591. {
  2592. #if OPENSSL_VERSION_NUMBER >= 0x10001000L
  2593. SSL *ssl;
  2594. if (conn == NULL)
  2595. return -1;
  2596. if (server_random_first || skip_keyblock)
  2597. return openssl_tls_prf(conn, label,
  2598. server_random_first, skip_keyblock,
  2599. out, out_len);
  2600. ssl = conn->ssl;
  2601. if (SSL_export_keying_material(ssl, out, out_len, label,
  2602. os_strlen(label), NULL, 0, 0) == 1) {
  2603. wpa_printf(MSG_DEBUG, "OpenSSL: Using internal PRF");
  2604. return 0;
  2605. }
  2606. #endif
  2607. return openssl_tls_prf(conn, label, server_random_first,
  2608. skip_keyblock, out, out_len);
  2609. }
  2610. static struct wpabuf *
  2611. openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
  2612. int server)
  2613. {
  2614. int res;
  2615. struct wpabuf *out_data;
  2616. /*
  2617. * Give TLS handshake data from the server (if available) to OpenSSL
  2618. * for processing.
  2619. */
  2620. if (in_data && wpabuf_len(in_data) > 0 &&
  2621. BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
  2622. < 0) {
  2623. tls_show_errors(MSG_INFO, __func__,
  2624. "Handshake failed - BIO_write");
  2625. return NULL;
  2626. }
  2627. /* Initiate TLS handshake or continue the existing handshake */
  2628. if (server)
  2629. res = SSL_accept(conn->ssl);
  2630. else
  2631. res = SSL_connect(conn->ssl);
  2632. if (res != 1) {
  2633. int err = SSL_get_error(conn->ssl, res);
  2634. if (err == SSL_ERROR_WANT_READ)
  2635. wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
  2636. "more data");
  2637. else if (err == SSL_ERROR_WANT_WRITE)
  2638. wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
  2639. "write");
  2640. else {
  2641. tls_show_errors(MSG_INFO, __func__, "SSL_connect");
  2642. conn->failed++;
  2643. }
  2644. }
  2645. /* Get the TLS handshake data to be sent to the server */
  2646. res = BIO_ctrl_pending(conn->ssl_out);
  2647. wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
  2648. out_data = wpabuf_alloc(res);
  2649. if (out_data == NULL) {
  2650. wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
  2651. "handshake output (%d bytes)", res);
  2652. if (BIO_reset(conn->ssl_out) < 0) {
  2653. tls_show_errors(MSG_INFO, __func__,
  2654. "BIO_reset failed");
  2655. }
  2656. return NULL;
  2657. }
  2658. res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
  2659. res);
  2660. if (res < 0) {
  2661. tls_show_errors(MSG_INFO, __func__,
  2662. "Handshake failed - BIO_read");
  2663. if (BIO_reset(conn->ssl_out) < 0) {
  2664. tls_show_errors(MSG_INFO, __func__,
  2665. "BIO_reset failed");
  2666. }
  2667. wpabuf_free(out_data);
  2668. return NULL;
  2669. }
  2670. wpabuf_put(out_data, res);
  2671. return out_data;
  2672. }
  2673. static struct wpabuf *
  2674. openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
  2675. {
  2676. struct wpabuf *appl_data;
  2677. int res;
  2678. appl_data = wpabuf_alloc(max_len + 100);
  2679. if (appl_data == NULL)
  2680. return NULL;
  2681. res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
  2682. wpabuf_size(appl_data));
  2683. if (res < 0) {
  2684. int err = SSL_get_error(conn->ssl, res);
  2685. if (err == SSL_ERROR_WANT_READ ||
  2686. err == SSL_ERROR_WANT_WRITE) {
  2687. wpa_printf(MSG_DEBUG, "SSL: No Application Data "
  2688. "included");
  2689. } else {
  2690. tls_show_errors(MSG_INFO, __func__,
  2691. "Failed to read possible "
  2692. "Application Data");
  2693. }
  2694. wpabuf_free(appl_data);
  2695. return NULL;
  2696. }
  2697. wpabuf_put(appl_data, res);
  2698. wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
  2699. "message", appl_data);
  2700. return appl_data;
  2701. }
  2702. static struct wpabuf *
  2703. openssl_connection_handshake(struct tls_connection *conn,
  2704. const struct wpabuf *in_data,
  2705. struct wpabuf **appl_data, int server)
  2706. {
  2707. struct wpabuf *out_data;
  2708. if (appl_data)
  2709. *appl_data = NULL;
  2710. out_data = openssl_handshake(conn, in_data, server);
  2711. if (out_data == NULL)
  2712. return NULL;
  2713. if (conn->invalid_hb_used) {
  2714. wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
  2715. wpabuf_free(out_data);
  2716. return NULL;
  2717. }
  2718. if (SSL_is_init_finished(conn->ssl)) {
  2719. wpa_printf(MSG_DEBUG,
  2720. "OpenSSL: Handshake finished - resumed=%d",
  2721. tls_connection_resumed(conn->ssl_ctx, conn));
  2722. if (appl_data && in_data)
  2723. *appl_data = openssl_get_appl_data(conn,
  2724. wpabuf_len(in_data));
  2725. }
  2726. if (conn->invalid_hb_used) {
  2727. wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
  2728. if (appl_data) {
  2729. wpabuf_free(*appl_data);
  2730. *appl_data = NULL;
  2731. }
  2732. wpabuf_free(out_data);
  2733. return NULL;
  2734. }
  2735. return out_data;
  2736. }
  2737. struct wpabuf *
  2738. tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
  2739. const struct wpabuf *in_data,
  2740. struct wpabuf **appl_data)
  2741. {
  2742. return openssl_connection_handshake(conn, in_data, appl_data, 0);
  2743. }
  2744. struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
  2745. struct tls_connection *conn,
  2746. const struct wpabuf *in_data,
  2747. struct wpabuf **appl_data)
  2748. {
  2749. return openssl_connection_handshake(conn, in_data, appl_data, 1);
  2750. }
  2751. struct wpabuf * tls_connection_encrypt(void *tls_ctx,
  2752. struct tls_connection *conn,
  2753. const struct wpabuf *in_data)
  2754. {
  2755. int res;
  2756. struct wpabuf *buf;
  2757. if (conn == NULL)
  2758. return NULL;
  2759. /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
  2760. if ((res = BIO_reset(conn->ssl_in)) < 0 ||
  2761. (res = BIO_reset(conn->ssl_out)) < 0) {
  2762. tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
  2763. return NULL;
  2764. }
  2765. res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
  2766. if (res < 0) {
  2767. tls_show_errors(MSG_INFO, __func__,
  2768. "Encryption failed - SSL_write");
  2769. return NULL;
  2770. }
  2771. /* Read encrypted data to be sent to the server */
  2772. buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
  2773. if (buf == NULL)
  2774. return NULL;
  2775. res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
  2776. if (res < 0) {
  2777. tls_show_errors(MSG_INFO, __func__,
  2778. "Encryption failed - BIO_read");
  2779. wpabuf_free(buf);
  2780. return NULL;
  2781. }
  2782. wpabuf_put(buf, res);
  2783. return buf;
  2784. }
  2785. struct wpabuf * tls_connection_decrypt(void *tls_ctx,
  2786. struct tls_connection *conn,
  2787. const struct wpabuf *in_data)
  2788. {
  2789. int res;
  2790. struct wpabuf *buf;
  2791. /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
  2792. res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
  2793. wpabuf_len(in_data));
  2794. if (res < 0) {
  2795. tls_show_errors(MSG_INFO, __func__,
  2796. "Decryption failed - BIO_write");
  2797. return NULL;
  2798. }
  2799. if (BIO_reset(conn->ssl_out) < 0) {
  2800. tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
  2801. return NULL;
  2802. }
  2803. /* Read decrypted data for further processing */
  2804. /*
  2805. * Even though we try to disable TLS compression, it is possible that
  2806. * this cannot be done with all TLS libraries. Add extra buffer space
  2807. * to handle the possibility of the decrypted data being longer than
  2808. * input data.
  2809. */
  2810. buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
  2811. if (buf == NULL)
  2812. return NULL;
  2813. res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
  2814. if (res < 0) {
  2815. tls_show_errors(MSG_INFO, __func__,
  2816. "Decryption failed - SSL_read");
  2817. wpabuf_free(buf);
  2818. return NULL;
  2819. }
  2820. wpabuf_put(buf, res);
  2821. if (conn->invalid_hb_used) {
  2822. wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
  2823. wpabuf_free(buf);
  2824. return NULL;
  2825. }
  2826. return buf;
  2827. }
  2828. int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
  2829. {
  2830. #if OPENSSL_VERSION_NUMBER >= 0x10001000L
  2831. return conn ? SSL_cache_hit(conn->ssl) : 0;
  2832. #else
  2833. return conn ? conn->ssl->hit : 0;
  2834. #endif
  2835. }
  2836. int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
  2837. u8 *ciphers)
  2838. {
  2839. char buf[100], *pos, *end;
  2840. u8 *c;
  2841. int ret;
  2842. if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
  2843. return -1;
  2844. buf[0] = '\0';
  2845. pos = buf;
  2846. end = pos + sizeof(buf);
  2847. c = ciphers;
  2848. while (*c != TLS_CIPHER_NONE) {
  2849. const char *suite;
  2850. switch (*c) {
  2851. case TLS_CIPHER_RC4_SHA:
  2852. suite = "RC4-SHA";
  2853. break;
  2854. case TLS_CIPHER_AES128_SHA:
  2855. suite = "AES128-SHA";
  2856. break;
  2857. case TLS_CIPHER_RSA_DHE_AES128_SHA:
  2858. suite = "DHE-RSA-AES128-SHA";
  2859. break;
  2860. case TLS_CIPHER_ANON_DH_AES128_SHA:
  2861. suite = "ADH-AES128-SHA";
  2862. break;
  2863. default:
  2864. wpa_printf(MSG_DEBUG, "TLS: Unsupported "
  2865. "cipher selection: %d", *c);
  2866. return -1;
  2867. }
  2868. ret = os_snprintf(pos, end - pos, ":%s", suite);
  2869. if (os_snprintf_error(end - pos, ret))
  2870. break;
  2871. pos += ret;
  2872. c++;
  2873. }
  2874. wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
  2875. #if OPENSSL_VERSION_NUMBER >= 0x10100000L
  2876. #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
  2877. if (os_strstr(buf, ":ADH-")) {
  2878. /*
  2879. * Need to drop to security level 0 to allow anonymous
  2880. * cipher suites for EAP-FAST.
  2881. */
  2882. SSL_set_security_level(conn->ssl, 0);
  2883. } else if (SSL_get_security_level(conn->ssl) == 0) {
  2884. /* Force at least security level 1 */
  2885. SSL_set_security_level(conn->ssl, 1);
  2886. }
  2887. #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
  2888. #endif
  2889. if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
  2890. tls_show_errors(MSG_INFO, __func__,
  2891. "Cipher suite configuration failed");
  2892. return -1;
  2893. }
  2894. return 0;
  2895. }
  2896. int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
  2897. char *buf, size_t buflen)
  2898. {
  2899. const char *name;
  2900. if (conn == NULL || conn->ssl == NULL)
  2901. return -1;
  2902. name = SSL_get_version(conn->ssl);
  2903. if (name == NULL)
  2904. return -1;
  2905. os_strlcpy(buf, name, buflen);
  2906. return 0;
  2907. }
  2908. int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
  2909. char *buf, size_t buflen)
  2910. {
  2911. const char *name;
  2912. if (conn == NULL || conn->ssl == NULL)
  2913. return -1;
  2914. name = SSL_get_cipher(conn->ssl);
  2915. if (name == NULL)
  2916. return -1;
  2917. os_strlcpy(buf, name, buflen);
  2918. return 0;
  2919. }
  2920. int tls_connection_enable_workaround(void *ssl_ctx,
  2921. struct tls_connection *conn)
  2922. {
  2923. SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
  2924. return 0;
  2925. }
  2926. #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
  2927. /* ClientHello TLS extensions require a patch to openssl, so this function is
  2928. * commented out unless explicitly needed for EAP-FAST in order to be able to
  2929. * build this file with unmodified openssl. */
  2930. int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
  2931. int ext_type, const u8 *data,
  2932. size_t data_len)
  2933. {
  2934. if (conn == NULL || conn->ssl == NULL || ext_type != 35)
  2935. return -1;
  2936. if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
  2937. data_len) != 1)
  2938. return -1;
  2939. return 0;
  2940. }
  2941. #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
  2942. int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
  2943. {
  2944. if (conn == NULL)
  2945. return -1;
  2946. return conn->failed;
  2947. }
  2948. int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
  2949. {
  2950. if (conn == NULL)
  2951. return -1;
  2952. return conn->read_alerts;
  2953. }
  2954. int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
  2955. {
  2956. if (conn == NULL)
  2957. return -1;
  2958. return conn->write_alerts;
  2959. }
  2960. #ifdef HAVE_OCSP
  2961. static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
  2962. {
  2963. #ifndef CONFIG_NO_STDOUT_DEBUG
  2964. BIO *out;
  2965. size_t rlen;
  2966. char *txt;
  2967. int res;
  2968. if (wpa_debug_level > MSG_DEBUG)
  2969. return;
  2970. out = BIO_new(BIO_s_mem());
  2971. if (!out)
  2972. return;
  2973. OCSP_RESPONSE_print(out, rsp, 0);
  2974. rlen = BIO_ctrl_pending(out);
  2975. txt = os_malloc(rlen + 1);
  2976. if (!txt) {
  2977. BIO_free(out);
  2978. return;
  2979. }
  2980. res = BIO_read(out, txt, rlen);
  2981. if (res > 0) {
  2982. txt[res] = '\0';
  2983. wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
  2984. }
  2985. os_free(txt);
  2986. BIO_free(out);
  2987. #endif /* CONFIG_NO_STDOUT_DEBUG */
  2988. }
  2989. static void debug_print_cert(X509 *cert, const char *title)
  2990. {
  2991. #ifndef CONFIG_NO_STDOUT_DEBUG
  2992. BIO *out;
  2993. size_t rlen;
  2994. char *txt;
  2995. int res;
  2996. if (wpa_debug_level > MSG_DEBUG)
  2997. return;
  2998. out = BIO_new(BIO_s_mem());
  2999. if (!out)
  3000. return;
  3001. X509_print(out, cert);
  3002. rlen = BIO_ctrl_pending(out);
  3003. txt = os_malloc(rlen + 1);
  3004. if (!txt) {
  3005. BIO_free(out);
  3006. return;
  3007. }
  3008. res = BIO_read(out, txt, rlen);
  3009. if (res > 0) {
  3010. txt[res] = '\0';
  3011. wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
  3012. }
  3013. os_free(txt);
  3014. BIO_free(out);
  3015. #endif /* CONFIG_NO_STDOUT_DEBUG */
  3016. }
  3017. static int ocsp_resp_cb(SSL *s, void *arg)
  3018. {
  3019. struct tls_connection *conn = arg;
  3020. const unsigned char *p;
  3021. int len, status, reason;
  3022. OCSP_RESPONSE *rsp;
  3023. OCSP_BASICRESP *basic;
  3024. OCSP_CERTID *id;
  3025. ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
  3026. X509_STORE *store;
  3027. STACK_OF(X509) *certs = NULL;
  3028. len = SSL_get_tlsext_status_ocsp_resp(s, &p);
  3029. if (!p) {
  3030. wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
  3031. return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
  3032. }
  3033. wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
  3034. rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
  3035. if (!rsp) {
  3036. wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
  3037. return 0;
  3038. }
  3039. ocsp_debug_print_resp(rsp);
  3040. status = OCSP_response_status(rsp);
  3041. if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
  3042. wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
  3043. status, OCSP_response_status_str(status));
  3044. return 0;
  3045. }
  3046. basic = OCSP_response_get1_basic(rsp);
  3047. if (!basic) {
  3048. wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
  3049. return 0;
  3050. }
  3051. store = SSL_CTX_get_cert_store(conn->ssl_ctx);
  3052. if (conn->peer_issuer) {
  3053. debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
  3054. if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
  3055. tls_show_errors(MSG_INFO, __func__,
  3056. "OpenSSL: Could not add issuer to certificate store");
  3057. }
  3058. certs = sk_X509_new_null();
  3059. if (certs) {
  3060. X509 *cert;
  3061. cert = X509_dup(conn->peer_issuer);
  3062. if (cert && !sk_X509_push(certs, cert)) {
  3063. tls_show_errors(
  3064. MSG_INFO, __func__,
  3065. "OpenSSL: Could not add issuer to OCSP responder trust store");
  3066. X509_free(cert);
  3067. sk_X509_free(certs);
  3068. certs = NULL;
  3069. }
  3070. if (certs && conn->peer_issuer_issuer) {
  3071. cert = X509_dup(conn->peer_issuer_issuer);
  3072. if (cert && !sk_X509_push(certs, cert)) {
  3073. tls_show_errors(
  3074. MSG_INFO, __func__,
  3075. "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
  3076. X509_free(cert);
  3077. }
  3078. }
  3079. }
  3080. }
  3081. status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
  3082. sk_X509_pop_free(certs, X509_free);
  3083. if (status <= 0) {
  3084. tls_show_errors(MSG_INFO, __func__,
  3085. "OpenSSL: OCSP response failed verification");
  3086. OCSP_BASICRESP_free(basic);
  3087. OCSP_RESPONSE_free(rsp);
  3088. return 0;
  3089. }
  3090. wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
  3091. if (!conn->peer_cert) {
  3092. wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
  3093. OCSP_BASICRESP_free(basic);
  3094. OCSP_RESPONSE_free(rsp);
  3095. return 0;
  3096. }
  3097. if (!conn->peer_issuer) {
  3098. wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
  3099. OCSP_BASICRESP_free(basic);
  3100. OCSP_RESPONSE_free(rsp);
  3101. return 0;
  3102. }
  3103. id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
  3104. if (!id) {
  3105. wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
  3106. OCSP_BASICRESP_free(basic);
  3107. OCSP_RESPONSE_free(rsp);
  3108. return 0;
  3109. }
  3110. if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
  3111. &this_update, &next_update)) {
  3112. wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
  3113. (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
  3114. " (OCSP not required)");
  3115. OCSP_BASICRESP_free(basic);
  3116. OCSP_RESPONSE_free(rsp);
  3117. return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
  3118. }
  3119. if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
  3120. tls_show_errors(MSG_INFO, __func__,
  3121. "OpenSSL: OCSP status times invalid");
  3122. OCSP_BASICRESP_free(basic);
  3123. OCSP_RESPONSE_free(rsp);
  3124. return 0;
  3125. }
  3126. OCSP_BASICRESP_free(basic);
  3127. OCSP_RESPONSE_free(rsp);
  3128. wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
  3129. OCSP_cert_status_str(status));
  3130. if (status == V_OCSP_CERTSTATUS_GOOD)
  3131. return 1;
  3132. if (status == V_OCSP_CERTSTATUS_REVOKED)
  3133. return 0;
  3134. if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
  3135. wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
  3136. return 0;
  3137. }
  3138. wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
  3139. return 1;
  3140. }
  3141. static int ocsp_status_cb(SSL *s, void *arg)
  3142. {
  3143. char *tmp;
  3144. char *resp;
  3145. size_t len;
  3146. if (tls_global->ocsp_stapling_response == NULL) {
  3147. wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
  3148. return SSL_TLSEXT_ERR_OK;
  3149. }
  3150. resp = os_readfile(tls_global->ocsp_stapling_response, &len);
  3151. if (resp == NULL) {
  3152. wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
  3153. /* TODO: Build OCSPResponse with responseStatus = internalError
  3154. */
  3155. return SSL_TLSEXT_ERR_OK;
  3156. }
  3157. wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
  3158. tmp = OPENSSL_malloc(len);
  3159. if (tmp == NULL) {
  3160. os_free(resp);
  3161. return SSL_TLSEXT_ERR_ALERT_FATAL;
  3162. }
  3163. os_memcpy(tmp, resp, len);
  3164. os_free(resp);
  3165. SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
  3166. return SSL_TLSEXT_ERR_OK;
  3167. }
  3168. #endif /* HAVE_OCSP */
  3169. int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
  3170. const struct tls_connection_params *params)
  3171. {
  3172. struct tls_data *data = tls_ctx;
  3173. int ret;
  3174. unsigned long err;
  3175. int can_pkcs11 = 0;
  3176. const char *key_id = params->key_id;
  3177. const char *cert_id = params->cert_id;
  3178. const char *ca_cert_id = params->ca_cert_id;
  3179. const char *engine_id = params->engine ? params->engine_id : NULL;
  3180. if (conn == NULL)
  3181. return -1;
  3182. /*
  3183. * If the engine isn't explicitly configured, and any of the
  3184. * cert/key fields are actually PKCS#11 URIs, then automatically
  3185. * use the PKCS#11 ENGINE.
  3186. */
  3187. if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
  3188. can_pkcs11 = 1;
  3189. if (!key_id && params->private_key && can_pkcs11 &&
  3190. os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
  3191. can_pkcs11 = 2;
  3192. key_id = params->private_key;
  3193. }
  3194. if (!cert_id && params->client_cert && can_pkcs11 &&
  3195. os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
  3196. can_pkcs11 = 2;
  3197. cert_id = params->client_cert;
  3198. }
  3199. if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
  3200. os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
  3201. can_pkcs11 = 2;
  3202. ca_cert_id = params->ca_cert;
  3203. }
  3204. /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
  3205. if (can_pkcs11 == 2 && !engine_id)
  3206. engine_id = "pkcs11";
  3207. #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
  3208. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  3209. if (params->flags & TLS_CONN_EAP_FAST) {
  3210. wpa_printf(MSG_DEBUG,
  3211. "OpenSSL: Use TLSv1_method() for EAP-FAST");
  3212. if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
  3213. tls_show_errors(MSG_INFO, __func__,
  3214. "Failed to set TLSv1_method() for EAP-FAST");
  3215. return -1;
  3216. }
  3217. }
  3218. #endif
  3219. #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
  3220. while ((err = ERR_get_error())) {
  3221. wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
  3222. __func__, ERR_error_string(err, NULL));
  3223. }
  3224. if (engine_id) {
  3225. wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
  3226. ret = tls_engine_init(conn, engine_id, params->pin,
  3227. key_id, cert_id, ca_cert_id);
  3228. if (ret)
  3229. return ret;
  3230. }
  3231. if (tls_connection_set_subject_match(conn,
  3232. params->subject_match,
  3233. params->altsubject_match,
  3234. params->suffix_match,
  3235. params->domain_match))
  3236. return -1;
  3237. if (engine_id && ca_cert_id) {
  3238. if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
  3239. return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
  3240. } else if (tls_connection_ca_cert(data, conn, params->ca_cert,
  3241. params->ca_cert_blob,
  3242. params->ca_cert_blob_len,
  3243. params->ca_path))
  3244. return -1;
  3245. if (engine_id && cert_id) {
  3246. if (tls_connection_engine_client_cert(conn, cert_id))
  3247. return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
  3248. } else if (tls_connection_client_cert(conn, params->client_cert,
  3249. params->client_cert_blob,
  3250. params->client_cert_blob_len))
  3251. return -1;
  3252. if (engine_id && key_id) {
  3253. wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
  3254. if (tls_connection_engine_private_key(conn))
  3255. return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
  3256. } else if (tls_connection_private_key(data, conn,
  3257. params->private_key,
  3258. params->private_key_passwd,
  3259. params->private_key_blob,
  3260. params->private_key_blob_len)) {
  3261. wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
  3262. params->private_key);
  3263. return -1;
  3264. }
  3265. if (tls_connection_dh(conn, params->dh_file)) {
  3266. wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
  3267. params->dh_file);
  3268. return -1;
  3269. }
  3270. if (params->openssl_ciphers &&
  3271. SSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
  3272. wpa_printf(MSG_INFO,
  3273. "OpenSSL: Failed to set cipher string '%s'",
  3274. params->openssl_ciphers);
  3275. return -1;
  3276. }
  3277. tls_set_conn_flags(conn->ssl, params->flags);
  3278. #ifdef HAVE_OCSP
  3279. if (params->flags & TLS_CONN_REQUEST_OCSP) {
  3280. SSL_CTX *ssl_ctx = data->ssl;
  3281. SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
  3282. SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
  3283. SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
  3284. }
  3285. #else /* HAVE_OCSP */
  3286. if (params->flags & TLS_CONN_REQUIRE_OCSP) {
  3287. wpa_printf(MSG_INFO,
  3288. "OpenSSL: No OCSP support included - reject configuration");
  3289. return -1;
  3290. }
  3291. if (params->flags & TLS_CONN_REQUEST_OCSP) {
  3292. wpa_printf(MSG_DEBUG,
  3293. "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
  3294. }
  3295. #endif /* HAVE_OCSP */
  3296. conn->flags = params->flags;
  3297. tls_get_errors(data);
  3298. return 0;
  3299. }
  3300. int tls_global_set_params(void *tls_ctx,
  3301. const struct tls_connection_params *params)
  3302. {
  3303. struct tls_data *data = tls_ctx;
  3304. SSL_CTX *ssl_ctx = data->ssl;
  3305. unsigned long err;
  3306. while ((err = ERR_get_error())) {
  3307. wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
  3308. __func__, ERR_error_string(err, NULL));
  3309. }
  3310. if (tls_global_ca_cert(data, params->ca_cert) ||
  3311. tls_global_client_cert(data, params->client_cert) ||
  3312. tls_global_private_key(data, params->private_key,
  3313. params->private_key_passwd) ||
  3314. tls_global_dh(data, params->dh_file)) {
  3315. wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
  3316. return -1;
  3317. }
  3318. if (params->openssl_ciphers &&
  3319. SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
  3320. wpa_printf(MSG_INFO,
  3321. "OpenSSL: Failed to set cipher string '%s'",
  3322. params->openssl_ciphers);
  3323. return -1;
  3324. }
  3325. #ifdef SSL_OP_NO_TICKET
  3326. if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
  3327. SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
  3328. #ifdef SSL_CTX_clear_options
  3329. else
  3330. SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
  3331. #endif /* SSL_clear_options */
  3332. #endif /* SSL_OP_NO_TICKET */
  3333. #ifdef HAVE_OCSP
  3334. SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
  3335. SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
  3336. os_free(tls_global->ocsp_stapling_response);
  3337. if (params->ocsp_stapling_response)
  3338. tls_global->ocsp_stapling_response =
  3339. os_strdup(params->ocsp_stapling_response);
  3340. else
  3341. tls_global->ocsp_stapling_response = NULL;
  3342. #endif /* HAVE_OCSP */
  3343. return 0;
  3344. }
  3345. #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
  3346. /* Pre-shared secred requires a patch to openssl, so this function is
  3347. * commented out unless explicitly needed for EAP-FAST in order to be able to
  3348. * build this file with unmodified openssl. */
  3349. #ifdef OPENSSL_IS_BORINGSSL
  3350. static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
  3351. STACK_OF(SSL_CIPHER) *peer_ciphers,
  3352. const SSL_CIPHER **cipher, void *arg)
  3353. #else /* OPENSSL_IS_BORINGSSL */
  3354. static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
  3355. STACK_OF(SSL_CIPHER) *peer_ciphers,
  3356. SSL_CIPHER **cipher, void *arg)
  3357. #endif /* OPENSSL_IS_BORINGSSL */
  3358. {
  3359. struct tls_connection *conn = arg;
  3360. int ret;
  3361. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  3362. if (conn == NULL || conn->session_ticket_cb == NULL)
  3363. return 0;
  3364. ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
  3365. conn->session_ticket,
  3366. conn->session_ticket_len,
  3367. s->s3->client_random,
  3368. s->s3->server_random, secret);
  3369. #else
  3370. unsigned char client_random[SSL3_RANDOM_SIZE];
  3371. unsigned char server_random[SSL3_RANDOM_SIZE];
  3372. if (conn == NULL || conn->session_ticket_cb == NULL)
  3373. return 0;
  3374. SSL_get_client_random(s, client_random, sizeof(client_random));
  3375. SSL_get_server_random(s, server_random, sizeof(server_random));
  3376. ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
  3377. conn->session_ticket,
  3378. conn->session_ticket_len,
  3379. client_random,
  3380. server_random, secret);
  3381. #endif
  3382. os_free(conn->session_ticket);
  3383. conn->session_ticket = NULL;
  3384. if (ret <= 0)
  3385. return 0;
  3386. *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
  3387. return 1;
  3388. }
  3389. static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
  3390. int len, void *arg)
  3391. {
  3392. struct tls_connection *conn = arg;
  3393. if (conn == NULL || conn->session_ticket_cb == NULL)
  3394. return 0;
  3395. wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
  3396. os_free(conn->session_ticket);
  3397. conn->session_ticket = NULL;
  3398. wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
  3399. "extension", data, len);
  3400. conn->session_ticket = os_malloc(len);
  3401. if (conn->session_ticket == NULL)
  3402. return 0;
  3403. os_memcpy(conn->session_ticket, data, len);
  3404. conn->session_ticket_len = len;
  3405. return 1;
  3406. }
  3407. #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
  3408. int tls_connection_set_session_ticket_cb(void *tls_ctx,
  3409. struct tls_connection *conn,
  3410. tls_session_ticket_cb cb,
  3411. void *ctx)
  3412. {
  3413. #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
  3414. conn->session_ticket_cb = cb;
  3415. conn->session_ticket_cb_ctx = ctx;
  3416. if (cb) {
  3417. if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
  3418. conn) != 1)
  3419. return -1;
  3420. SSL_set_session_ticket_ext_cb(conn->ssl,
  3421. tls_session_ticket_ext_cb, conn);
  3422. } else {
  3423. if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
  3424. return -1;
  3425. SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
  3426. }
  3427. return 0;
  3428. #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
  3429. return -1;
  3430. #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
  3431. }
  3432. int tls_get_library_version(char *buf, size_t buf_len)
  3433. {
  3434. return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
  3435. OPENSSL_VERSION_TEXT,
  3436. SSLeay_version(SSLEAY_VERSION));
  3437. }
  3438. void tls_connection_set_success_data(struct tls_connection *conn,
  3439. struct wpabuf *data)
  3440. {
  3441. }
  3442. void tls_connection_set_success_data_resumed(struct tls_connection *conn)
  3443. {
  3444. }
  3445. const struct wpabuf *
  3446. tls_connection_get_success_data(struct tls_connection *conn)
  3447. {
  3448. return NULL;
  3449. }
  3450. void tls_connection_remove_session(struct tls_connection *conn)
  3451. {
  3452. }