tls_openssl.c 115 KB

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