sectransp.c 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. * Copyright (C) Nick Zitzmann, <nickzman@gmail.com>.
  10. *
  11. * This software is licensed as described in the file COPYING, which
  12. * you should have received as part of this distribution. The terms
  13. * are also available at https://curl.se/docs/copyright.html.
  14. *
  15. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  16. * copies of the Software, and permit persons to whom the Software is
  17. * furnished to do so, under the terms of the COPYING file.
  18. *
  19. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  20. * KIND, either express or implied.
  21. *
  22. * SPDX-License-Identifier: curl
  23. *
  24. ***************************************************************************/
  25. /*
  26. * Source file for all iOS and macOS Secure Transport-specific code for the
  27. * TLS/SSL layer. No code but vtls.c should ever call or use these functions.
  28. */
  29. #include "curl_setup.h"
  30. #ifdef USE_SECTRANSP
  31. #include "urldata.h" /* for the Curl_easy definition */
  32. #include "curl_base64.h"
  33. #include "strtok.h"
  34. #include "multiif.h"
  35. #include "strcase.h"
  36. #include "x509asn1.h"
  37. #include "strerror.h"
  38. #include "cipher_suite.h"
  39. #ifdef __clang__
  40. #pragma clang diagnostic push
  41. #pragma clang diagnostic ignored "-Wunreachable-code"
  42. #endif /* __clang__ */
  43. #ifdef __GNUC__
  44. #pragma GCC diagnostic push
  45. #pragma GCC diagnostic ignored "-Waddress"
  46. #endif
  47. #include <limits.h>
  48. #include <Security/Security.h>
  49. /* For some reason, when building for iOS, the omnibus header above does
  50. * not include SecureTransport.h as of iOS SDK 5.1. */
  51. #include <Security/SecureTransport.h>
  52. #include <CoreFoundation/CoreFoundation.h>
  53. #include <CommonCrypto/CommonDigest.h>
  54. /* The Security framework has changed greatly between iOS and different macOS
  55. versions, and we will try to support as many of them as we can (back to
  56. Leopard and iOS 5) by using macros and weak-linking.
  57. In general, you want to build this using the most recent OS SDK, since some
  58. features require curl to be built against the latest SDK. TLS 1.1 and 1.2
  59. support, for instance, require the macOS 10.8 SDK or later. TLS 1.3
  60. requires the macOS 10.13 or iOS 11 SDK or later. */
  61. #if (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE))
  62. #if MAC_OS_X_VERSION_MAX_ALLOWED < 1050
  63. #error "The Secure Transport backend requires Leopard or later."
  64. #endif /* MAC_OS_X_VERSION_MAX_ALLOWED < 1050 */
  65. #define CURL_BUILD_IOS 0
  66. #define CURL_BUILD_IOS_7 0
  67. #define CURL_BUILD_IOS_9 0
  68. #define CURL_BUILD_IOS_11 0
  69. #define CURL_BUILD_IOS_13 0
  70. #define CURL_BUILD_MAC 1
  71. /* This is the maximum API level we are allowed to use when building: */
  72. #define CURL_BUILD_MAC_10_5 MAC_OS_X_VERSION_MAX_ALLOWED >= 1050
  73. #define CURL_BUILD_MAC_10_6 MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
  74. #define CURL_BUILD_MAC_10_7 MAC_OS_X_VERSION_MAX_ALLOWED >= 1070
  75. #define CURL_BUILD_MAC_10_8 MAC_OS_X_VERSION_MAX_ALLOWED >= 1080
  76. #define CURL_BUILD_MAC_10_9 MAC_OS_X_VERSION_MAX_ALLOWED >= 1090
  77. #define CURL_BUILD_MAC_10_11 MAC_OS_X_VERSION_MAX_ALLOWED >= 101100
  78. #define CURL_BUILD_MAC_10_13 MAC_OS_X_VERSION_MAX_ALLOWED >= 101300
  79. #define CURL_BUILD_MAC_10_15 MAC_OS_X_VERSION_MAX_ALLOWED >= 101500
  80. /* These macros mean "the following code is present to allow runtime backward
  81. compatibility with at least this cat or earlier":
  82. (You set this at build-time using the compiler command line option
  83. "-mmacosx-version-min.") */
  84. #define CURL_SUPPORT_MAC_10_5 MAC_OS_X_VERSION_MIN_REQUIRED <= 1050
  85. #define CURL_SUPPORT_MAC_10_6 MAC_OS_X_VERSION_MIN_REQUIRED <= 1060
  86. #define CURL_SUPPORT_MAC_10_7 MAC_OS_X_VERSION_MIN_REQUIRED <= 1070
  87. #define CURL_SUPPORT_MAC_10_8 MAC_OS_X_VERSION_MIN_REQUIRED <= 1080
  88. #define CURL_SUPPORT_MAC_10_9 MAC_OS_X_VERSION_MIN_REQUIRED <= 1090
  89. #elif TARGET_OS_EMBEDDED || TARGET_OS_IPHONE
  90. #define CURL_BUILD_IOS 1
  91. #define CURL_BUILD_IOS_7 __IPHONE_OS_VERSION_MAX_ALLOWED >= 70000
  92. #define CURL_BUILD_IOS_9 __IPHONE_OS_VERSION_MAX_ALLOWED >= 90000
  93. #define CURL_BUILD_IOS_11 __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000
  94. #define CURL_BUILD_IOS_13 __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000
  95. #define CURL_BUILD_MAC 0
  96. #define CURL_BUILD_MAC_10_5 0
  97. #define CURL_BUILD_MAC_10_6 0
  98. #define CURL_BUILD_MAC_10_7 0
  99. #define CURL_BUILD_MAC_10_8 0
  100. #define CURL_BUILD_MAC_10_9 0
  101. #define CURL_BUILD_MAC_10_11 0
  102. #define CURL_BUILD_MAC_10_13 0
  103. #define CURL_BUILD_MAC_10_15 0
  104. #define CURL_SUPPORT_MAC_10_5 0
  105. #define CURL_SUPPORT_MAC_10_6 0
  106. #define CURL_SUPPORT_MAC_10_7 0
  107. #define CURL_SUPPORT_MAC_10_8 0
  108. #define CURL_SUPPORT_MAC_10_9 0
  109. #else
  110. #error "The Secure Transport backend requires iOS or macOS."
  111. #endif /* (TARGET_OS_MAC && !(TARGET_OS_EMBEDDED || TARGET_OS_IPHONE)) */
  112. #if CURL_BUILD_MAC
  113. #include <sys/sysctl.h>
  114. #endif /* CURL_BUILD_MAC */
  115. #include "sendf.h"
  116. #include "inet_pton.h"
  117. #include "connect.h"
  118. #include "select.h"
  119. #include "vtls.h"
  120. #include "vtls_int.h"
  121. #include "sectransp.h"
  122. #include "curl_printf.h"
  123. #include "strdup.h"
  124. #include "curl_memory.h"
  125. /* The last #include file should be: */
  126. #include "memdebug.h"
  127. /* From MacTypes.h (which we cannot include because it is not present in
  128. iOS: */
  129. #define ioErr -36
  130. #define paramErr -50
  131. struct st_ssl_backend_data {
  132. SSLContextRef ssl_ctx;
  133. bool ssl_direction; /* true if writing, false if reading */
  134. size_t ssl_write_buffered_length;
  135. BIT(sent_shutdown);
  136. };
  137. /* Create the list of default ciphers to use by making an intersection of the
  138. * ciphers supported by Secure Transport and the list below, using the order
  139. * of the former.
  140. * This list is based on TLS recommendations by Mozilla, balancing between
  141. * security and wide compatibility: "Most ciphers that are not clearly broken
  142. * and dangerous to use are supported"
  143. */
  144. static const uint16_t default_ciphers[] = {
  145. TLS_RSA_WITH_3DES_EDE_CBC_SHA, /* 0x000A */
  146. TLS_RSA_WITH_AES_128_CBC_SHA, /* 0x002F */
  147. TLS_RSA_WITH_AES_256_CBC_SHA, /* 0x0035 */
  148. #if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS
  149. TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, /* 0xC009 */
  150. TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, /* 0xC00A */
  151. TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, /* 0xC013 */
  152. TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, /* 0xC014 */
  153. #endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */
  154. #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
  155. TLS_RSA_WITH_AES_128_CBC_SHA256, /* 0x003C */
  156. TLS_RSA_WITH_AES_256_CBC_SHA256, /* 0x003D */
  157. TLS_DHE_RSA_WITH_AES_128_CBC_SHA256, /* 0x0067 */
  158. TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, /* 0x006B */
  159. TLS_RSA_WITH_AES_128_GCM_SHA256, /* 0x009C */
  160. TLS_RSA_WITH_AES_256_GCM_SHA384, /* 0x009D */
  161. TLS_DHE_RSA_WITH_AES_128_GCM_SHA256, /* 0x009E */
  162. TLS_DHE_RSA_WITH_AES_256_GCM_SHA384, /* 0x009F */
  163. TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, /* 0xC023 */
  164. TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384, /* 0xC024 */
  165. TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, /* 0xC027 */
  166. TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384, /* 0xC028 */
  167. TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, /* 0xC02B */
  168. TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, /* 0xC02C */
  169. TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, /* 0xC02F */
  170. TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, /* 0xC030 */
  171. #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */
  172. #if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11
  173. TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA8 */
  174. TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, /* 0xCCA9 */
  175. /* TLSv1.3 is not supported by Secure Transport, but there is also other
  176. * code referencing TLSv1.3, like: kTLSProtocol13 ? */
  177. TLS_AES_128_GCM_SHA256, /* 0x1301 */
  178. TLS_AES_256_GCM_SHA384, /* 0x1302 */
  179. TLS_CHACHA20_POLY1305_SHA256, /* 0x1303 */
  180. #endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */
  181. };
  182. #define DEFAULT_CIPHERS_LEN sizeof(default_ciphers)/sizeof(default_ciphers[0])
  183. /* pinned public key support tests */
  184. /* version 1 supports macOS 10.12+ and iOS 10+ */
  185. #if ((TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MIN_REQUIRED >= 100000) || \
  186. (!TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200))
  187. #define SECTRANSP_PINNEDPUBKEY_V1 1
  188. #endif
  189. /* version 2 supports macOS 10.7+ */
  190. #if (!TARGET_OS_IPHONE && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070)
  191. #define SECTRANSP_PINNEDPUBKEY_V2 1
  192. #endif
  193. #if defined(SECTRANSP_PINNEDPUBKEY_V1) || defined(SECTRANSP_PINNEDPUBKEY_V2)
  194. /* this backend supports CURLOPT_PINNEDPUBLICKEY */
  195. #define SECTRANSP_PINNEDPUBKEY 1
  196. #endif /* SECTRANSP_PINNEDPUBKEY */
  197. #ifdef SECTRANSP_PINNEDPUBKEY
  198. /* both new and old APIs return rsa keys missing the spki header (not DER) */
  199. static const unsigned char rsa4096SpkiHeader[] = {
  200. 0x30, 0x82, 0x02, 0x22, 0x30, 0x0d,
  201. 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
  202. 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05,
  203. 0x00, 0x03, 0x82, 0x02, 0x0f, 0x00};
  204. static const unsigned char rsa2048SpkiHeader[] = {
  205. 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d,
  206. 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
  207. 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05,
  208. 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00};
  209. #ifdef SECTRANSP_PINNEDPUBKEY_V1
  210. /* the *new* version does not return DER encoded ecdsa certs like the old... */
  211. static const unsigned char ecDsaSecp256r1SpkiHeader[] = {
  212. 0x30, 0x59, 0x30, 0x13, 0x06, 0x07,
  213. 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
  214. 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48,
  215. 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03,
  216. 0x42, 0x00};
  217. static const unsigned char ecDsaSecp384r1SpkiHeader[] = {
  218. 0x30, 0x76, 0x30, 0x10, 0x06, 0x07,
  219. 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02,
  220. 0x01, 0x06, 0x05, 0x2b, 0x81, 0x04,
  221. 0x00, 0x22, 0x03, 0x62, 0x00};
  222. #endif /* SECTRANSP_PINNEDPUBKEY_V1 */
  223. #endif /* SECTRANSP_PINNEDPUBKEY */
  224. static OSStatus sectransp_bio_cf_in_read(SSLConnectionRef connection,
  225. void *buf,
  226. size_t *dataLength) /* IN/OUT */
  227. {
  228. struct Curl_cfilter *cf = (struct Curl_cfilter *)connection;
  229. struct ssl_connect_data *connssl = cf->ctx;
  230. struct st_ssl_backend_data *backend =
  231. (struct st_ssl_backend_data *)connssl->backend;
  232. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  233. ssize_t nread;
  234. CURLcode result;
  235. OSStatus rtn = noErr;
  236. DEBUGASSERT(data);
  237. nread = Curl_conn_cf_recv(cf->next, data, buf, *dataLength, &result);
  238. CURL_TRC_CF(data, cf, "bio_read(len=%zu) -> %zd, result=%d",
  239. *dataLength, nread, result);
  240. if(nread < 0) {
  241. switch(result) {
  242. case CURLE_OK:
  243. case CURLE_AGAIN:
  244. rtn = errSSLWouldBlock;
  245. backend->ssl_direction = FALSE;
  246. break;
  247. default:
  248. rtn = ioErr;
  249. break;
  250. }
  251. nread = 0;
  252. }
  253. else if(nread == 0) {
  254. rtn = errSSLClosedGraceful;
  255. }
  256. else if((size_t)nread < *dataLength) {
  257. rtn = errSSLWouldBlock;
  258. }
  259. *dataLength = nread;
  260. return rtn;
  261. }
  262. static OSStatus sectransp_bio_cf_out_write(SSLConnectionRef connection,
  263. const void *buf,
  264. size_t *dataLength) /* IN/OUT */
  265. {
  266. struct Curl_cfilter *cf = (struct Curl_cfilter *)connection;
  267. struct ssl_connect_data *connssl = cf->ctx;
  268. struct st_ssl_backend_data *backend =
  269. (struct st_ssl_backend_data *)connssl->backend;
  270. struct Curl_easy *data = CF_DATA_CURRENT(cf);
  271. ssize_t nwritten;
  272. CURLcode result;
  273. OSStatus rtn = noErr;
  274. DEBUGASSERT(data);
  275. nwritten = Curl_conn_cf_send(cf->next, data, buf, *dataLength, FALSE,
  276. &result);
  277. CURL_TRC_CF(data, cf, "bio_send(len=%zu) -> %zd, result=%d",
  278. *dataLength, nwritten, result);
  279. if(nwritten <= 0) {
  280. if(result == CURLE_AGAIN) {
  281. rtn = errSSLWouldBlock;
  282. backend->ssl_direction = TRUE;
  283. }
  284. else {
  285. rtn = ioErr;
  286. }
  287. nwritten = 0;
  288. }
  289. else if((size_t)nwritten < *dataLength) {
  290. rtn = errSSLWouldBlock;
  291. }
  292. *dataLength = nwritten;
  293. return rtn;
  294. }
  295. #if CURL_BUILD_MAC
  296. CF_INLINE void GetDarwinVersionNumber(int *major, int *minor)
  297. {
  298. int mib[2];
  299. char *os_version;
  300. size_t os_version_len;
  301. char *os_version_major, *os_version_minor;
  302. char *tok_buf;
  303. /* Get the Darwin kernel version from the kernel using sysctl(): */
  304. mib[0] = CTL_KERN;
  305. mib[1] = KERN_OSRELEASE;
  306. if(sysctl(mib, 2, NULL, &os_version_len, NULL, 0) == -1)
  307. return;
  308. os_version = malloc(os_version_len*sizeof(char));
  309. if(!os_version)
  310. return;
  311. if(sysctl(mib, 2, os_version, &os_version_len, NULL, 0) == -1) {
  312. free(os_version);
  313. return;
  314. }
  315. /* Parse the version: */
  316. os_version_major = strtok_r(os_version, ".", &tok_buf);
  317. os_version_minor = strtok_r(NULL, ".", &tok_buf);
  318. *major = atoi(os_version_major);
  319. *minor = atoi(os_version_minor);
  320. free(os_version);
  321. }
  322. #endif /* CURL_BUILD_MAC */
  323. /* Apple provides a myriad of ways of getting information about a certificate
  324. into a string. Some are not available under iOS or newer cats. Here's a
  325. unified function for getting a string describing the certificate that ought
  326. to work in all cats starting with Leopard. */
  327. CF_INLINE CFStringRef getsubject(SecCertificateRef cert)
  328. {
  329. CFStringRef server_cert_summary = CFSTR("(null)");
  330. #if CURL_BUILD_IOS
  331. /* iOS: There is only one way to do this. */
  332. server_cert_summary = SecCertificateCopySubjectSummary(cert);
  333. #else
  334. #if CURL_BUILD_MAC_10_7
  335. /* Lion & later: Get the long description if we can. */
  336. if(&SecCertificateCopyLongDescription)
  337. server_cert_summary =
  338. SecCertificateCopyLongDescription(NULL, cert, NULL);
  339. else
  340. #endif /* CURL_BUILD_MAC_10_7 */
  341. #if CURL_BUILD_MAC_10_6
  342. /* Snow Leopard: Get the certificate summary. */
  343. if(&SecCertificateCopySubjectSummary)
  344. server_cert_summary = SecCertificateCopySubjectSummary(cert);
  345. else
  346. #endif /* CURL_BUILD_MAC_10_6 */
  347. /* Leopard is as far back as we go... */
  348. (void)SecCertificateCopyCommonName(cert, &server_cert_summary);
  349. #endif /* CURL_BUILD_IOS */
  350. return server_cert_summary;
  351. }
  352. static CURLcode CopyCertSubject(struct Curl_easy *data,
  353. SecCertificateRef cert, char **certp)
  354. {
  355. CFStringRef c = getsubject(cert);
  356. CURLcode result = CURLE_OK;
  357. const char *direct;
  358. char *cbuf = NULL;
  359. *certp = NULL;
  360. if(!c) {
  361. failf(data, "SSL: invalid CA certificate subject");
  362. return CURLE_PEER_FAILED_VERIFICATION;
  363. }
  364. /* If the subject is already available as UTF-8 encoded (ie 'direct') then
  365. use that, else convert it. */
  366. direct = CFStringGetCStringPtr(c, kCFStringEncodingUTF8);
  367. if(direct) {
  368. *certp = strdup(direct);
  369. if(!*certp) {
  370. failf(data, "SSL: out of memory");
  371. result = CURLE_OUT_OF_MEMORY;
  372. }
  373. }
  374. else {
  375. size_t cbuf_size = ((size_t)CFStringGetLength(c) * 4) + 1;
  376. cbuf = calloc(1, cbuf_size);
  377. if(cbuf) {
  378. if(!CFStringGetCString(c, cbuf, (CFIndex)cbuf_size,
  379. kCFStringEncodingUTF8)) {
  380. failf(data, "SSL: invalid CA certificate subject");
  381. result = CURLE_PEER_FAILED_VERIFICATION;
  382. }
  383. else
  384. /* pass back the buffer */
  385. *certp = cbuf;
  386. }
  387. else {
  388. failf(data, "SSL: could not allocate %zu bytes of memory", cbuf_size);
  389. result = CURLE_OUT_OF_MEMORY;
  390. }
  391. }
  392. if(result)
  393. free(cbuf);
  394. CFRelease(c);
  395. return result;
  396. }
  397. #if CURL_SUPPORT_MAC_10_6
  398. /* The SecKeychainSearch API was deprecated in Lion, and using it will raise
  399. deprecation warnings, so let's not compile this unless it is necessary: */
  400. static OSStatus CopyIdentityWithLabelOldSchool(char *label,
  401. SecIdentityRef *out_c_a_k)
  402. {
  403. OSStatus status = errSecItemNotFound;
  404. SecKeychainAttributeList attr_list;
  405. SecKeychainAttribute attr;
  406. SecKeychainSearchRef search = NULL;
  407. SecCertificateRef cert = NULL;
  408. /* Set up the attribute list: */
  409. attr_list.count = 1L;
  410. attr_list.attr = &attr;
  411. /* Set up our lone search criterion: */
  412. attr.tag = kSecLabelItemAttr;
  413. attr.data = label;
  414. attr.length = (UInt32)strlen(label);
  415. /* Start searching: */
  416. status = SecKeychainSearchCreateFromAttributes(NULL,
  417. kSecCertificateItemClass,
  418. &attr_list,
  419. &search);
  420. if(status == noErr) {
  421. status = SecKeychainSearchCopyNext(search,
  422. (SecKeychainItemRef *)&cert);
  423. if(status == noErr && cert) {
  424. /* If we found a certificate, does it have a private key? */
  425. status = SecIdentityCreateWithCertificate(NULL, cert, out_c_a_k);
  426. CFRelease(cert);
  427. }
  428. }
  429. if(search)
  430. CFRelease(search);
  431. return status;
  432. }
  433. #endif /* CURL_SUPPORT_MAC_10_6 */
  434. static OSStatus CopyIdentityWithLabel(char *label,
  435. SecIdentityRef *out_cert_and_key)
  436. {
  437. OSStatus status = errSecItemNotFound;
  438. #if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS
  439. CFArrayRef keys_list;
  440. CFIndex keys_list_count;
  441. CFIndex i;
  442. /* SecItemCopyMatching() was introduced in iOS and Snow Leopard.
  443. kSecClassIdentity was introduced in Lion. If both exist, let's use them
  444. to find the certificate. */
  445. if(&SecItemCopyMatching && kSecClassIdentity) {
  446. CFTypeRef keys[5];
  447. CFTypeRef values[5];
  448. CFDictionaryRef query_dict;
  449. CFStringRef label_cf = CFStringCreateWithCString(NULL, label,
  450. kCFStringEncodingUTF8);
  451. /* Set up our search criteria and expected results: */
  452. values[0] = kSecClassIdentity; /* we want a certificate and a key */
  453. keys[0] = kSecClass;
  454. values[1] = kCFBooleanTrue; /* we want a reference */
  455. keys[1] = kSecReturnRef;
  456. values[2] = kSecMatchLimitAll; /* kSecMatchLimitOne would be better if the
  457. * label matching below worked correctly */
  458. keys[2] = kSecMatchLimit;
  459. /* identity searches need a SecPolicyRef in order to work */
  460. values[3] = SecPolicyCreateSSL(FALSE, NULL);
  461. keys[3] = kSecMatchPolicy;
  462. /* match the name of the certificate (does not work in macOS 10.12.1) */
  463. values[4] = label_cf;
  464. keys[4] = kSecAttrLabel;
  465. query_dict = CFDictionaryCreate(NULL, (const void **)keys,
  466. (const void **)values, 5L,
  467. &kCFCopyStringDictionaryKeyCallBacks,
  468. &kCFTypeDictionaryValueCallBacks);
  469. CFRelease(values[3]);
  470. /* Do we have a match? */
  471. status = SecItemCopyMatching(query_dict, (CFTypeRef *) &keys_list);
  472. /* Because kSecAttrLabel matching does not work with kSecClassIdentity,
  473. * we need to find the correct identity ourselves */
  474. if(status == noErr) {
  475. keys_list_count = CFArrayGetCount(keys_list);
  476. *out_cert_and_key = NULL;
  477. status = 1;
  478. for(i = 0; i < keys_list_count; i++) {
  479. OSStatus err = noErr;
  480. SecCertificateRef cert = NULL;
  481. SecIdentityRef identity =
  482. (SecIdentityRef) CFArrayGetValueAtIndex(keys_list, i);
  483. err = SecIdentityCopyCertificate(identity, &cert);
  484. if(err == noErr) {
  485. CFStringRef common_name = NULL;
  486. OSStatus copy_status = noErr;
  487. #if CURL_BUILD_IOS
  488. common_name = SecCertificateCopySubjectSummary(cert);
  489. #elif CURL_BUILD_MAC_10_7
  490. copy_status = SecCertificateCopyCommonName(cert, &common_name);
  491. #endif
  492. if(copy_status == noErr &&
  493. CFStringCompare(common_name, label_cf, 0) == kCFCompareEqualTo) {
  494. CFRelease(cert);
  495. CFRelease(common_name);
  496. CFRetain(identity);
  497. *out_cert_and_key = identity;
  498. status = noErr;
  499. break;
  500. }
  501. if(common_name)
  502. CFRelease(common_name);
  503. }
  504. CFRelease(cert);
  505. }
  506. }
  507. if(keys_list)
  508. CFRelease(keys_list);
  509. CFRelease(query_dict);
  510. CFRelease(label_cf);
  511. }
  512. else {
  513. #if CURL_SUPPORT_MAC_10_6
  514. /* On Leopard and Snow Leopard, fall back to SecKeychainSearch. */
  515. status = CopyIdentityWithLabelOldSchool(label, out_cert_and_key);
  516. #endif /* CURL_SUPPORT_MAC_10_6 */
  517. }
  518. #elif CURL_SUPPORT_MAC_10_6
  519. /* For developers building on older cats, we have no choice but to fall back
  520. to SecKeychainSearch. */
  521. status = CopyIdentityWithLabelOldSchool(label, out_cert_and_key);
  522. #endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */
  523. return status;
  524. }
  525. static OSStatus CopyIdentityFromPKCS12File(const char *cPath,
  526. const struct curl_blob *blob,
  527. const char *cPassword,
  528. SecIdentityRef *out_cert_and_key)
  529. {
  530. OSStatus status = errSecItemNotFound;
  531. CFURLRef pkcs_url = NULL;
  532. CFStringRef password = cPassword ? CFStringCreateWithCString(NULL,
  533. cPassword, kCFStringEncodingUTF8) : NULL;
  534. CFDataRef pkcs_data = NULL;
  535. /* We can import P12 files on iOS or macOS 10.7 or later: */
  536. /* These constants are documented as having first appeared in 10.6 but they
  537. raise linker errors when used on that cat for some reason. */
  538. #if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS
  539. bool resource_imported;
  540. if(blob) {
  541. pkcs_data = CFDataCreate(kCFAllocatorDefault,
  542. (const unsigned char *)blob->data,
  543. (CFIndex)blob->len);
  544. status = (pkcs_data != NULL) ? errSecSuccess : errSecAllocate;
  545. resource_imported = (pkcs_data != NULL);
  546. }
  547. else {
  548. pkcs_url =
  549. CFURLCreateFromFileSystemRepresentation(NULL,
  550. (const UInt8 *)cPath,
  551. (CFIndex)strlen(cPath), FALSE);
  552. resource_imported =
  553. CFURLCreateDataAndPropertiesFromResource(NULL,
  554. pkcs_url, &pkcs_data,
  555. NULL, NULL, &status);
  556. }
  557. if(resource_imported) {
  558. CFArrayRef items = NULL;
  559. /* On iOS SecPKCS12Import will never add the client certificate to the
  560. * Keychain.
  561. *
  562. * It gives us back a SecIdentityRef that we can use directly. */
  563. #if CURL_BUILD_IOS
  564. const void *cKeys[] = {kSecImportExportPassphrase};
  565. const void *cValues[] = {password};
  566. CFDictionaryRef options = CFDictionaryCreate(NULL, cKeys, cValues,
  567. password ? 1L : 0L, NULL, NULL);
  568. if(options) {
  569. status = SecPKCS12Import(pkcs_data, options, &items);
  570. CFRelease(options);
  571. }
  572. /* On macOS SecPKCS12Import will always add the client certificate to
  573. * the Keychain.
  574. *
  575. * As this does not match iOS, and apps may not want to see their client
  576. * certificate saved in the user's keychain, we use SecItemImport
  577. * with a NULL keychain to avoid importing it.
  578. *
  579. * This returns a SecCertificateRef from which we can construct a
  580. * SecIdentityRef.
  581. */
  582. #elif CURL_BUILD_MAC_10_7
  583. SecItemImportExportKeyParameters keyParams;
  584. SecExternalFormat inputFormat = kSecFormatPKCS12;
  585. SecExternalItemType inputType = kSecItemTypeCertificate;
  586. memset(&keyParams, 0x00, sizeof(keyParams));
  587. keyParams.version = SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION;
  588. keyParams.passphrase = password;
  589. status = SecItemImport(pkcs_data, NULL, &inputFormat, &inputType,
  590. 0, &keyParams, NULL, &items);
  591. #endif
  592. /* Extract the SecIdentityRef */
  593. if(status == errSecSuccess && items && CFArrayGetCount(items)) {
  594. CFIndex i, count;
  595. count = CFArrayGetCount(items);
  596. for(i = 0; i < count; i++) {
  597. CFTypeRef item = (CFTypeRef) CFArrayGetValueAtIndex(items, i);
  598. CFTypeID itemID = CFGetTypeID(item);
  599. if(itemID == CFDictionaryGetTypeID()) {
  600. CFTypeRef identity = (CFTypeRef) CFDictionaryGetValue(
  601. (CFDictionaryRef) item,
  602. kSecImportItemIdentity);
  603. CFRetain(identity);
  604. *out_cert_and_key = (SecIdentityRef) identity;
  605. break;
  606. }
  607. #if CURL_BUILD_MAC_10_7
  608. else if(itemID == SecCertificateGetTypeID()) {
  609. status = SecIdentityCreateWithCertificate(NULL,
  610. (SecCertificateRef) item,
  611. out_cert_and_key);
  612. break;
  613. }
  614. #endif
  615. }
  616. }
  617. if(items)
  618. CFRelease(items);
  619. CFRelease(pkcs_data);
  620. }
  621. #endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */
  622. if(password)
  623. CFRelease(password);
  624. if(pkcs_url)
  625. CFRelease(pkcs_url);
  626. return status;
  627. }
  628. /* This code was borrowed from nss.c, with some modifications:
  629. * Determine whether the nickname passed in is a filename that needs to
  630. * be loaded as a PEM or a nickname.
  631. *
  632. * returns 1 for a file
  633. * returns 0 for not a file
  634. */
  635. CF_INLINE bool is_file(const char *filename)
  636. {
  637. struct_stat st;
  638. if(!filename)
  639. return FALSE;
  640. if(stat(filename, &st) == 0)
  641. return S_ISREG(st.st_mode);
  642. return FALSE;
  643. }
  644. static CURLcode
  645. sectransp_set_ssl_version_min_max(struct Curl_easy *data,
  646. struct st_ssl_backend_data *backend,
  647. struct ssl_primary_config *conn_config)
  648. {
  649. #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
  650. OSStatus err;
  651. SSLProtocol ver_min;
  652. SSLProtocol ver_max;
  653. #if CURL_SUPPORT_MAC_10_7
  654. if(!&SSLSetProtocolVersionMax)
  655. goto legacy;
  656. #endif
  657. switch(conn_config->version) {
  658. case CURL_SSLVERSION_DEFAULT:
  659. case CURL_SSLVERSION_TLSv1:
  660. case CURL_SSLVERSION_TLSv1_0:
  661. ver_min = kTLSProtocol1;
  662. break;
  663. case CURL_SSLVERSION_TLSv1_1:
  664. ver_min = kTLSProtocol11;
  665. break;
  666. case CURL_SSLVERSION_TLSv1_2:
  667. ver_min = kTLSProtocol12;
  668. break;
  669. case CURL_SSLVERSION_TLSv1_3:
  670. default:
  671. failf(data, "SSL: unsupported minimum TLS version value");
  672. return CURLE_SSL_CONNECT_ERROR;
  673. }
  674. switch(conn_config->version_max) {
  675. case CURL_SSLVERSION_MAX_DEFAULT:
  676. case CURL_SSLVERSION_MAX_NONE:
  677. case CURL_SSLVERSION_MAX_TLSv1_3:
  678. case CURL_SSLVERSION_MAX_TLSv1_2:
  679. ver_max = kTLSProtocol12;
  680. break;
  681. case CURL_SSLVERSION_MAX_TLSv1_1:
  682. ver_max = kTLSProtocol11;
  683. break;
  684. case CURL_SSLVERSION_MAX_TLSv1_0:
  685. ver_max = kTLSProtocol1;
  686. break;
  687. default:
  688. failf(data, "SSL: unsupported maximum TLS version value");
  689. return CURLE_SSL_CONNECT_ERROR;
  690. }
  691. err = SSLSetProtocolVersionMin(backend->ssl_ctx, ver_min);
  692. if(err != noErr) {
  693. failf(data, "SSL: failed to set minimum TLS version");
  694. return CURLE_SSL_CONNECT_ERROR;
  695. }
  696. err = SSLSetProtocolVersionMax(backend->ssl_ctx, ver_max);
  697. if(err != noErr) {
  698. failf(data, "SSL: failed to set maximum TLS version");
  699. return CURLE_SSL_CONNECT_ERROR;
  700. }
  701. return CURLE_OK;
  702. #endif
  703. #if CURL_SUPPORT_MAC_10_7
  704. goto legacy;
  705. legacy:
  706. switch(conn_config->version) {
  707. case CURL_SSLVERSION_DEFAULT:
  708. case CURL_SSLVERSION_TLSv1:
  709. case CURL_SSLVERSION_TLSv1_0:
  710. break;
  711. default:
  712. failf(data, "SSL: unsupported minimum TLS version value");
  713. return CURLE_SSL_CONNECT_ERROR;
  714. }
  715. /* only TLS 1.0 is supported, disable SSL 3.0 and SSL 2.0 */
  716. SSLSetProtocolVersionEnabled(backend->ssl_ctx, kSSLProtocolAll, FALSE);
  717. SSLSetProtocolVersionEnabled(backend->ssl_ctx, kTLSProtocol1, TRUE);
  718. return CURLE_OK;
  719. #endif
  720. }
  721. static int sectransp_cipher_suite_get_str(uint16_t id, char *buf,
  722. size_t buf_size, bool prefer_rfc)
  723. {
  724. /* are these fortezza suites even supported ? */
  725. if(id == SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA)
  726. msnprintf(buf, buf_size, "%s", "SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA");
  727. else if(id == SSL_FORTEZZA_DMS_WITH_NULL_SHA)
  728. msnprintf(buf, buf_size, "%s", "SSL_FORTEZZA_DMS_WITH_NULL_SHA");
  729. /* can TLS_EMPTY_RENEGOTIATION_INFO_SCSV even be set ? */
  730. else if(id == TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
  731. msnprintf(buf, buf_size, "%s", "TLS_EMPTY_RENEGOTIATION_INFO_SCSV");
  732. /* do we still need to support these SSL2-only ciphers ? */
  733. else if(id == SSL_RSA_WITH_RC2_CBC_MD5)
  734. msnprintf(buf, buf_size, "%s", "SSL_RSA_WITH_RC2_CBC_MD5");
  735. else if(id == SSL_RSA_WITH_IDEA_CBC_MD5)
  736. msnprintf(buf, buf_size, "%s", "SSL_RSA_WITH_IDEA_CBC_MD5");
  737. else if(id == SSL_RSA_WITH_DES_CBC_MD5)
  738. msnprintf(buf, buf_size, "%s", "SSL_RSA_WITH_DES_CBC_MD5");
  739. else if(id == SSL_RSA_WITH_3DES_EDE_CBC_MD5)
  740. msnprintf(buf, buf_size, "%s", "SSL_RSA_WITH_3DES_EDE_CBC_MD5");
  741. else
  742. return Curl_cipher_suite_get_str(id, buf, buf_size, prefer_rfc);
  743. return 0;
  744. }
  745. static uint16_t sectransp_cipher_suite_walk_str(const char **str,
  746. const char **end)
  747. {
  748. uint16_t id = Curl_cipher_suite_walk_str(str, end);
  749. size_t len = *end - *str;
  750. if(!id) {
  751. /* are these fortezza suites even supported ? */
  752. if(strncasecompare("SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA", *str, len))
  753. id = SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA;
  754. else if(strncasecompare("SSL_FORTEZZA_DMS_WITH_NULL_SHA", *str, len))
  755. id = SSL_FORTEZZA_DMS_WITH_NULL_SHA;
  756. /* can TLS_EMPTY_RENEGOTIATION_INFO_SCSV even be set ? */
  757. else if(strncasecompare("TLS_EMPTY_RENEGOTIATION_INFO_SCSV", *str, len))
  758. id = TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
  759. /* do we still need to support these SSL2-only ciphers ? */
  760. else if(strncasecompare("SSL_RSA_WITH_RC2_CBC_MD5", *str, len))
  761. id = SSL_RSA_WITH_RC2_CBC_MD5;
  762. else if(strncasecompare("SSL_RSA_WITH_IDEA_CBC_MD5", *str, len))
  763. id = SSL_RSA_WITH_IDEA_CBC_MD5;
  764. else if(strncasecompare("SSL_RSA_WITH_DES_CBC_MD5", *str, len))
  765. id = SSL_RSA_WITH_DES_CBC_MD5;
  766. else if(strncasecompare("SSL_RSA_WITH_3DES_EDE_CBC_MD5", *str, len))
  767. id = SSL_RSA_WITH_3DES_EDE_CBC_MD5;
  768. }
  769. return id;
  770. }
  771. /* allocated memory must be freed */
  772. static SSLCipherSuite * sectransp_get_supported_ciphers(SSLContextRef ssl_ctx,
  773. size_t *len)
  774. {
  775. SSLCipherSuite *ciphers = NULL;
  776. OSStatus err = noErr;
  777. *len = 0;
  778. err = SSLGetNumberSupportedCiphers(ssl_ctx, len);
  779. if(err != noErr)
  780. goto failed;
  781. ciphers = malloc(*len * sizeof(SSLCipherSuite));
  782. if(!ciphers)
  783. goto failed;
  784. err = SSLGetSupportedCiphers(ssl_ctx, ciphers, len);
  785. if(err != noErr)
  786. goto failed;
  787. #if CURL_BUILD_MAC
  788. {
  789. int maj = 0, min = 0;
  790. GetDarwinVersionNumber(&maj, &min);
  791. /* There is a known bug in early versions of Mountain Lion where ST's ECC
  792. ciphers (cipher suite 0xC001 through 0xC032) simply do not work.
  793. Work around the problem here by disabling those ciphers if we are
  794. running in an affected version of macOS. */
  795. if(maj == 12 && min <= 3) {
  796. size_t i = 0, j = 0;
  797. for(; i < *len; i++) {
  798. if(ciphers[i] >= 0xC001 && ciphers[i] <= 0xC032)
  799. continue;
  800. ciphers[j++] = ciphers[i];
  801. }
  802. *len = j;
  803. }
  804. }
  805. #endif
  806. return ciphers;
  807. failed:
  808. *len = 0;
  809. Curl_safefree(ciphers);
  810. return NULL;
  811. }
  812. static CURLcode sectransp_set_default_ciphers(struct Curl_easy *data,
  813. SSLContextRef ssl_ctx)
  814. {
  815. CURLcode ret = CURLE_SSL_CIPHER;
  816. size_t count = 0, i, j;
  817. OSStatus err;
  818. size_t supported_len;
  819. SSLCipherSuite *ciphers = NULL;
  820. ciphers = sectransp_get_supported_ciphers(ssl_ctx, &supported_len);
  821. if(!ciphers) {
  822. failf(data, "SSL: Failed to get supported ciphers");
  823. goto failed;
  824. }
  825. /* Intersect the ciphers supported by Secure Transport with the default
  826. * ciphers, using the order of the former. */
  827. for(i = 0; i < supported_len; i++) {
  828. for(j = 0; j < DEFAULT_CIPHERS_LEN; j++) {
  829. if(default_ciphers[j] == ciphers[i]) {
  830. ciphers[count++] = ciphers[i];
  831. break;
  832. }
  833. }
  834. }
  835. if(count == 0) {
  836. failf(data, "SSL: no supported default ciphers");
  837. goto failed;
  838. }
  839. err = SSLSetEnabledCiphers(ssl_ctx, ciphers, count);
  840. if(err != noErr) {
  841. failf(data, "SSL: SSLSetEnabledCiphers() failed: OSStatus %d", err);
  842. goto failed;
  843. }
  844. ret = CURLE_OK;
  845. failed:
  846. Curl_safefree(ciphers);
  847. return ret;
  848. }
  849. static CURLcode sectransp_set_selected_ciphers(struct Curl_easy *data,
  850. SSLContextRef ssl_ctx,
  851. const char *ciphers)
  852. {
  853. CURLcode ret = CURLE_SSL_CIPHER;
  854. size_t count = 0, i;
  855. const char *ptr, *end;
  856. OSStatus err;
  857. size_t supported_len;
  858. SSLCipherSuite *supported = NULL;
  859. SSLCipherSuite *selected = NULL;
  860. supported = sectransp_get_supported_ciphers(ssl_ctx, &supported_len);
  861. if(!supported) {
  862. failf(data, "SSL: Failed to get supported ciphers");
  863. goto failed;
  864. }
  865. selected = malloc(supported_len * sizeof(SSLCipherSuite));
  866. if(!selected) {
  867. failf(data, "SSL: Failed to allocate memory");
  868. goto failed;
  869. }
  870. for(ptr = ciphers; ptr[0] != '\0' && count < supported_len; ptr = end) {
  871. uint16_t id = sectransp_cipher_suite_walk_str(&ptr, &end);
  872. /* Check if cipher is supported */
  873. if(id) {
  874. for(i = 0; i < supported_len && supported[i] != id; i++);
  875. if(i == supported_len)
  876. id = 0;
  877. }
  878. if(!id) {
  879. if(ptr[0] != '\0')
  880. infof(data, "SSL: unknown cipher in list: \"%.*s\"", (int) (end - ptr),
  881. ptr);
  882. continue;
  883. }
  884. /* No duplicates allowed (so selected cannot overflow) */
  885. for(i = 0; i < count && selected[i] != id; i++);
  886. if(i < count) {
  887. infof(data, "SSL: duplicate cipher in list: \"%.*s\"", (int) (end - ptr),
  888. ptr);
  889. continue;
  890. }
  891. selected[count++] = id;
  892. }
  893. if(count == 0) {
  894. failf(data, "SSL: no supported cipher in list");
  895. goto failed;
  896. }
  897. err = SSLSetEnabledCiphers(ssl_ctx, selected, count);
  898. if(err != noErr) {
  899. failf(data, "SSL: SSLSetEnabledCiphers() failed: OSStatus %d", err);
  900. goto failed;
  901. }
  902. ret = CURLE_OK;
  903. failed:
  904. Curl_safefree(supported);
  905. Curl_safefree(selected);
  906. return ret;
  907. }
  908. static void sectransp_session_free(void *sessionid, size_t idsize)
  909. {
  910. /* ST, as of iOS 5 and Mountain Lion, has no public method of deleting a
  911. cached session ID inside the Security framework. There is a private
  912. function that does this, but I do not want to have to explain to you why I
  913. got your application rejected from the App Store due to the use of a
  914. private API, so the best we can do is free up our own char array that we
  915. created way back in sectransp_connect_step1... */
  916. (void)idsize;
  917. Curl_safefree(sessionid);
  918. }
  919. static CURLcode sectransp_connect_step1(struct Curl_cfilter *cf,
  920. struct Curl_easy *data)
  921. {
  922. struct ssl_connect_data *connssl = cf->ctx;
  923. struct st_ssl_backend_data *backend =
  924. (struct st_ssl_backend_data *)connssl->backend;
  925. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  926. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  927. const struct curl_blob *ssl_cablob = conn_config->ca_info_blob;
  928. const char * const ssl_cafile =
  929. /* CURLOPT_CAINFO_BLOB overrides CURLOPT_CAINFO */
  930. (ssl_cablob ? NULL : conn_config->CAfile);
  931. const bool verifypeer = conn_config->verifypeer;
  932. char * const ssl_cert = ssl_config->primary.clientcert;
  933. const struct curl_blob *ssl_cert_blob = ssl_config->primary.cert_blob;
  934. char *ciphers;
  935. OSStatus err = noErr;
  936. CURLcode result;
  937. #if CURL_BUILD_MAC
  938. int darwinver_maj = 0, darwinver_min = 0;
  939. DEBUGASSERT(backend);
  940. CURL_TRC_CF(data, cf, "connect_step1");
  941. GetDarwinVersionNumber(&darwinver_maj, &darwinver_min);
  942. #endif /* CURL_BUILD_MAC */
  943. #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
  944. if(&SSLCreateContext) { /* use the newer API if available */
  945. if(backend->ssl_ctx)
  946. CFRelease(backend->ssl_ctx);
  947. backend->ssl_ctx = SSLCreateContext(NULL, kSSLClientSide, kSSLStreamType);
  948. if(!backend->ssl_ctx) {
  949. failf(data, "SSL: could not create a context");
  950. return CURLE_OUT_OF_MEMORY;
  951. }
  952. }
  953. else {
  954. /* The old ST API does not exist under iOS, so do not compile it: */
  955. #if CURL_SUPPORT_MAC_10_8
  956. if(backend->ssl_ctx)
  957. (void)SSLDisposeContext(backend->ssl_ctx);
  958. err = SSLNewContext(FALSE, &(backend->ssl_ctx));
  959. if(err != noErr) {
  960. failf(data, "SSL: could not create a context: OSStatus %d", err);
  961. return CURLE_OUT_OF_MEMORY;
  962. }
  963. #endif /* CURL_SUPPORT_MAC_10_8 */
  964. }
  965. #else
  966. if(backend->ssl_ctx)
  967. (void)SSLDisposeContext(backend->ssl_ctx);
  968. err = SSLNewContext(FALSE, &(backend->ssl_ctx));
  969. if(err != noErr) {
  970. failf(data, "SSL: could not create a context: OSStatus %d", err);
  971. return CURLE_OUT_OF_MEMORY;
  972. }
  973. #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */
  974. backend->ssl_write_buffered_length = 0UL; /* reset buffered write length */
  975. result = sectransp_set_ssl_version_min_max(data, backend, conn_config);
  976. if(result != CURLE_OK)
  977. return result;
  978. #if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && \
  979. defined(HAVE_BUILTIN_AVAILABLE)
  980. if(connssl->alpn) {
  981. if(__builtin_available(macOS 10.13.4, iOS 11, tvOS 11, *)) {
  982. struct alpn_proto_buf proto;
  983. size_t i;
  984. CFStringRef cstr;
  985. CFMutableArrayRef alpnArr = CFArrayCreateMutable(NULL, 0,
  986. &kCFTypeArrayCallBacks);
  987. for(i = 0; i < connssl->alpn->count; ++i) {
  988. cstr = CFStringCreateWithCString(NULL, connssl->alpn->entries[i],
  989. kCFStringEncodingUTF8);
  990. if(!cstr)
  991. return CURLE_OUT_OF_MEMORY;
  992. CFArrayAppendValue(alpnArr, cstr);
  993. CFRelease(cstr);
  994. }
  995. err = SSLSetALPNProtocols(backend->ssl_ctx, alpnArr);
  996. if(err != noErr)
  997. infof(data, "WARNING: failed to set ALPN protocols; OSStatus %d",
  998. err);
  999. CFRelease(alpnArr);
  1000. Curl_alpn_to_proto_str(&proto, connssl->alpn);
  1001. infof(data, VTLS_INFOF_ALPN_OFFER_1STR, proto.data);
  1002. }
  1003. }
  1004. #endif
  1005. if(ssl_config->key) {
  1006. infof(data, "WARNING: SSL: CURLOPT_SSLKEY is ignored by Secure "
  1007. "Transport. The private key must be in the Keychain.");
  1008. }
  1009. if(ssl_cert || ssl_cert_blob) {
  1010. bool is_cert_data = ssl_cert_blob != NULL;
  1011. bool is_cert_file = (!is_cert_data) && is_file(ssl_cert);
  1012. SecIdentityRef cert_and_key = NULL;
  1013. /* User wants to authenticate with a client cert. Look for it. Assume that
  1014. the user wants to use an identity loaded from the Keychain. If not, try
  1015. it as a file on disk */
  1016. if(!is_cert_data)
  1017. err = CopyIdentityWithLabel(ssl_cert, &cert_and_key);
  1018. else
  1019. err = !noErr;
  1020. if((err != noErr) && (is_cert_file || is_cert_data)) {
  1021. if(!ssl_config->cert_type)
  1022. infof(data, "SSL: Certificate type not set, assuming "
  1023. "PKCS#12 format.");
  1024. else if(!strcasecompare(ssl_config->cert_type, "P12")) {
  1025. failf(data, "SSL: The Security framework only supports "
  1026. "loading identities that are in PKCS#12 format.");
  1027. return CURLE_SSL_CERTPROBLEM;
  1028. }
  1029. err = CopyIdentityFromPKCS12File(ssl_cert, ssl_cert_blob,
  1030. ssl_config->key_passwd,
  1031. &cert_and_key);
  1032. }
  1033. if(err == noErr && cert_and_key) {
  1034. SecCertificateRef cert = NULL;
  1035. CFTypeRef certs_c[1];
  1036. CFArrayRef certs;
  1037. /* If we found one, print it out: */
  1038. err = SecIdentityCopyCertificate(cert_and_key, &cert);
  1039. if(err == noErr) {
  1040. char *certp;
  1041. result = CopyCertSubject(data, cert, &certp);
  1042. if(!result) {
  1043. infof(data, "Client certificate: %s", certp);
  1044. free(certp);
  1045. }
  1046. CFRelease(cert);
  1047. if(result == CURLE_PEER_FAILED_VERIFICATION)
  1048. return CURLE_SSL_CERTPROBLEM;
  1049. if(result)
  1050. return result;
  1051. }
  1052. certs_c[0] = cert_and_key;
  1053. certs = CFArrayCreate(NULL, (const void **)certs_c, 1L,
  1054. &kCFTypeArrayCallBacks);
  1055. err = SSLSetCertificate(backend->ssl_ctx, certs);
  1056. if(certs)
  1057. CFRelease(certs);
  1058. if(err != noErr) {
  1059. failf(data, "SSL: SSLSetCertificate() failed: OSStatus %d", err);
  1060. return CURLE_SSL_CERTPROBLEM;
  1061. }
  1062. CFRelease(cert_and_key);
  1063. }
  1064. else {
  1065. const char *cert_showfilename_error =
  1066. is_cert_data ? "(memory blob)" : ssl_cert;
  1067. switch(err) {
  1068. case errSecAuthFailed: case -25264: /* errSecPkcs12VerifyFailure */
  1069. failf(data, "SSL: Incorrect password for the certificate \"%s\" "
  1070. "and its private key.", cert_showfilename_error);
  1071. break;
  1072. case -26275: /* errSecDecode */ case -25257: /* errSecUnknownFormat */
  1073. failf(data, "SSL: Couldn't make sense of the data in the "
  1074. "certificate \"%s\" and its private key.",
  1075. cert_showfilename_error);
  1076. break;
  1077. case -25260: /* errSecPassphraseRequired */
  1078. failf(data, "SSL The certificate \"%s\" requires a password.",
  1079. cert_showfilename_error);
  1080. break;
  1081. case errSecItemNotFound:
  1082. failf(data, "SSL: cannot find the certificate \"%s\" and its private "
  1083. "key in the Keychain.", cert_showfilename_error);
  1084. break;
  1085. default:
  1086. failf(data, "SSL: cannot load the certificate \"%s\" and its private "
  1087. "key: OSStatus %d", cert_showfilename_error, err);
  1088. break;
  1089. }
  1090. return CURLE_SSL_CERTPROBLEM;
  1091. }
  1092. }
  1093. /* SSL always tries to verify the peer, this only says whether it should
  1094. * fail to connect if the verification fails, or if it should continue
  1095. * anyway. In the latter case the result of the verification is checked with
  1096. * SSL_get_verify_result() below. */
  1097. #if CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS
  1098. /* Snow Leopard introduced the SSLSetSessionOption() function, but due to
  1099. a library bug with the way the kSSLSessionOptionBreakOnServerAuth flag
  1100. works, it does not work as expected under Snow Leopard, Lion or
  1101. Mountain Lion.
  1102. So we need to call SSLSetEnableCertVerify() on those older cats in order
  1103. to disable certificate validation if the user turned that off.
  1104. (Secure Transport always validates the certificate chain by default.)
  1105. Note:
  1106. Darwin 11.x.x is Lion (10.7)
  1107. Darwin 12.x.x is Mountain Lion (10.8)
  1108. Darwin 13.x.x is Mavericks (10.9)
  1109. Darwin 14.x.x is Yosemite (10.10)
  1110. Darwin 15.x.x is El Capitan (10.11)
  1111. */
  1112. #if CURL_BUILD_MAC
  1113. if(&SSLSetSessionOption && darwinver_maj >= 13) {
  1114. #else
  1115. if(&SSLSetSessionOption) {
  1116. #endif /* CURL_BUILD_MAC */
  1117. bool break_on_auth = !conn_config->verifypeer ||
  1118. ssl_cafile || ssl_cablob;
  1119. err = SSLSetSessionOption(backend->ssl_ctx,
  1120. kSSLSessionOptionBreakOnServerAuth,
  1121. break_on_auth);
  1122. if(err != noErr) {
  1123. failf(data, "SSL: SSLSetSessionOption() failed: OSStatus %d", err);
  1124. return CURLE_SSL_CONNECT_ERROR;
  1125. }
  1126. }
  1127. else {
  1128. #if CURL_SUPPORT_MAC_10_8
  1129. err = SSLSetEnableCertVerify(backend->ssl_ctx,
  1130. conn_config->verifypeer ? true : FALSE);
  1131. if(err != noErr) {
  1132. failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err);
  1133. return CURLE_SSL_CONNECT_ERROR;
  1134. }
  1135. #endif /* CURL_SUPPORT_MAC_10_8 */
  1136. }
  1137. #else
  1138. err = SSLSetEnableCertVerify(backend->ssl_ctx,
  1139. conn_config->verifypeer ? true : FALSE);
  1140. if(err != noErr) {
  1141. failf(data, "SSL: SSLSetEnableCertVerify() failed: OSStatus %d", err);
  1142. return CURLE_SSL_CONNECT_ERROR;
  1143. }
  1144. #endif /* CURL_BUILD_MAC_10_6 || CURL_BUILD_IOS */
  1145. if((ssl_cafile || ssl_cablob) && verifypeer) {
  1146. bool is_cert_data = ssl_cablob != NULL;
  1147. bool is_cert_file = (!is_cert_data) && is_file(ssl_cafile);
  1148. if(!(is_cert_file || is_cert_data)) {
  1149. failf(data, "SSL: cannot load CA certificate file %s",
  1150. ssl_cafile ? ssl_cafile : "(blob memory)");
  1151. return CURLE_SSL_CACERT_BADFILE;
  1152. }
  1153. }
  1154. /* Configure hostname check. SNI is used if available.
  1155. * Both hostname check and SNI require SSLSetPeerDomainName().
  1156. * Also: the verifyhost setting influences SNI usage */
  1157. if(conn_config->verifyhost) {
  1158. char *server = connssl->peer.sni ?
  1159. connssl->peer.sni : connssl->peer.hostname;
  1160. err = SSLSetPeerDomainName(backend->ssl_ctx, server, strlen(server));
  1161. if(err != noErr) {
  1162. failf(data, "SSL: SSLSetPeerDomainName() failed: OSStatus %d",
  1163. err);
  1164. return CURLE_SSL_CONNECT_ERROR;
  1165. }
  1166. if(connssl->peer.type != CURL_SSL_PEER_DNS) {
  1167. infof(data, "WARNING: using IP address, SNI is being disabled by "
  1168. "the OS.");
  1169. }
  1170. }
  1171. else {
  1172. infof(data, "WARNING: disabling hostname validation also disables SNI.");
  1173. }
  1174. ciphers = conn_config->cipher_list;
  1175. if(ciphers) {
  1176. result = sectransp_set_selected_ciphers(data, backend->ssl_ctx, ciphers);
  1177. }
  1178. else {
  1179. result = sectransp_set_default_ciphers(data, backend->ssl_ctx);
  1180. }
  1181. if(result != CURLE_OK) {
  1182. failf(data, "SSL: Unable to set ciphers for SSL/TLS handshake. "
  1183. "Error code: %d", (int)result);
  1184. return CURLE_SSL_CIPHER;
  1185. }
  1186. #if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7
  1187. /* We want to enable 1/n-1 when using a CBC cipher unless the user
  1188. specifically does not want us doing that: */
  1189. if(&SSLSetSessionOption) {
  1190. SSLSetSessionOption(backend->ssl_ctx, kSSLSessionOptionSendOneByteRecord,
  1191. !ssl_config->enable_beast);
  1192. SSLSetSessionOption(backend->ssl_ctx, kSSLSessionOptionFalseStart,
  1193. ssl_config->falsestart); /* false start support */
  1194. }
  1195. #endif /* CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7 */
  1196. /* Check if there is a cached ID we can/should use here! */
  1197. if(ssl_config->primary.cache_session) {
  1198. char *ssl_sessionid;
  1199. size_t ssl_sessionid_len;
  1200. Curl_ssl_sessionid_lock(data);
  1201. if(!Curl_ssl_getsessionid(cf, data, &connssl->peer,
  1202. (void **)&ssl_sessionid, &ssl_sessionid_len,
  1203. NULL)) {
  1204. /* we got a session id, use it! */
  1205. err = SSLSetPeerID(backend->ssl_ctx, ssl_sessionid, ssl_sessionid_len);
  1206. Curl_ssl_sessionid_unlock(data);
  1207. if(err != noErr) {
  1208. failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err);
  1209. return CURLE_SSL_CONNECT_ERROR;
  1210. }
  1211. /* Informational message */
  1212. infof(data, "SSL reusing session ID");
  1213. }
  1214. /* If there is not one, then let's make one up! This has to be done prior
  1215. to starting the handshake. */
  1216. else {
  1217. ssl_sessionid =
  1218. aprintf("%s:%d:%d:%s:%d",
  1219. ssl_cafile ? ssl_cafile : "(blob memory)",
  1220. verifypeer, conn_config->verifyhost, connssl->peer.hostname,
  1221. connssl->peer.port);
  1222. ssl_sessionid_len = strlen(ssl_sessionid);
  1223. err = SSLSetPeerID(backend->ssl_ctx, ssl_sessionid, ssl_sessionid_len);
  1224. if(err != noErr) {
  1225. Curl_ssl_sessionid_unlock(data);
  1226. failf(data, "SSL: SSLSetPeerID() failed: OSStatus %d", err);
  1227. return CURLE_SSL_CONNECT_ERROR;
  1228. }
  1229. result = Curl_ssl_set_sessionid(cf, data, &connssl->peer, NULL,
  1230. ssl_sessionid, ssl_sessionid_len,
  1231. sectransp_session_free);
  1232. Curl_ssl_sessionid_unlock(data);
  1233. if(result)
  1234. return result;
  1235. }
  1236. }
  1237. err = SSLSetIOFuncs(backend->ssl_ctx,
  1238. sectransp_bio_cf_in_read,
  1239. sectransp_bio_cf_out_write);
  1240. if(err != noErr) {
  1241. failf(data, "SSL: SSLSetIOFuncs() failed: OSStatus %d", err);
  1242. return CURLE_SSL_CONNECT_ERROR;
  1243. }
  1244. err = SSLSetConnection(backend->ssl_ctx, cf);
  1245. if(err != noErr) {
  1246. failf(data, "SSL: SSLSetConnection() failed: %d", err);
  1247. return CURLE_SSL_CONNECT_ERROR;
  1248. }
  1249. connssl->connecting_state = ssl_connect_2;
  1250. return CURLE_OK;
  1251. }
  1252. static long pem_to_der(const char *in, unsigned char **out, size_t *outlen)
  1253. {
  1254. char *sep_start, *sep_end, *cert_start, *cert_end;
  1255. size_t i, j, err;
  1256. size_t len;
  1257. char *b64;
  1258. /* Jump through the separators at the beginning of the certificate. */
  1259. sep_start = strstr(in, "-----");
  1260. if(!sep_start)
  1261. return 0;
  1262. cert_start = strstr(sep_start + 1, "-----");
  1263. if(!cert_start)
  1264. return -1;
  1265. cert_start += 5;
  1266. /* Find separator after the end of the certificate. */
  1267. cert_end = strstr(cert_start, "-----");
  1268. if(!cert_end)
  1269. return -1;
  1270. sep_end = strstr(cert_end + 1, "-----");
  1271. if(!sep_end)
  1272. return -1;
  1273. sep_end += 5;
  1274. len = cert_end - cert_start;
  1275. b64 = malloc(len + 1);
  1276. if(!b64)
  1277. return -1;
  1278. /* Create base64 string without linefeeds. */
  1279. for(i = 0, j = 0; i < len; i++) {
  1280. if(cert_start[i] != '\r' && cert_start[i] != '\n')
  1281. b64[j++] = cert_start[i];
  1282. }
  1283. b64[j] = '\0';
  1284. err = Curl_base64_decode((const char *)b64, out, outlen);
  1285. free(b64);
  1286. if(err) {
  1287. free(*out);
  1288. return -1;
  1289. }
  1290. return sep_end - in;
  1291. }
  1292. #define MAX_CERTS_SIZE (50*1024*1024) /* arbitrary - to catch mistakes */
  1293. static int read_cert(const char *file, unsigned char **out, size_t *outlen)
  1294. {
  1295. int fd;
  1296. ssize_t n;
  1297. unsigned char buf[512];
  1298. struct dynbuf certs;
  1299. Curl_dyn_init(&certs, MAX_CERTS_SIZE);
  1300. fd = open(file, 0);
  1301. if(fd < 0)
  1302. return -1;
  1303. for(;;) {
  1304. n = read(fd, buf, sizeof(buf));
  1305. if(!n)
  1306. break;
  1307. if(n < 0) {
  1308. close(fd);
  1309. Curl_dyn_free(&certs);
  1310. return -1;
  1311. }
  1312. if(Curl_dyn_addn(&certs, buf, n)) {
  1313. close(fd);
  1314. return -1;
  1315. }
  1316. }
  1317. close(fd);
  1318. *out = Curl_dyn_uptr(&certs);
  1319. *outlen = Curl_dyn_len(&certs);
  1320. return 0;
  1321. }
  1322. static CURLcode append_cert_to_array(struct Curl_easy *data,
  1323. const unsigned char *buf, size_t buflen,
  1324. CFMutableArrayRef array)
  1325. {
  1326. char *certp;
  1327. CURLcode result;
  1328. SecCertificateRef cacert;
  1329. CFDataRef certdata;
  1330. certdata = CFDataCreate(kCFAllocatorDefault, buf, (CFIndex)buflen);
  1331. if(!certdata) {
  1332. failf(data, "SSL: failed to allocate array for CA certificate");
  1333. return CURLE_OUT_OF_MEMORY;
  1334. }
  1335. cacert = SecCertificateCreateWithData(kCFAllocatorDefault, certdata);
  1336. CFRelease(certdata);
  1337. if(!cacert) {
  1338. failf(data, "SSL: failed to create SecCertificate from CA certificate");
  1339. return CURLE_SSL_CACERT_BADFILE;
  1340. }
  1341. /* Check if cacert is valid. */
  1342. result = CopyCertSubject(data, cacert, &certp);
  1343. switch(result) {
  1344. case CURLE_OK:
  1345. break;
  1346. case CURLE_PEER_FAILED_VERIFICATION:
  1347. return CURLE_SSL_CACERT_BADFILE;
  1348. case CURLE_OUT_OF_MEMORY:
  1349. default:
  1350. return result;
  1351. }
  1352. free(certp);
  1353. CFArrayAppendValue(array, cacert);
  1354. CFRelease(cacert);
  1355. return CURLE_OK;
  1356. }
  1357. static CURLcode verify_cert_buf(struct Curl_cfilter *cf,
  1358. struct Curl_easy *data,
  1359. const unsigned char *certbuf, size_t buflen,
  1360. SSLContextRef ctx)
  1361. {
  1362. int n = 0;
  1363. CURLcode rc;
  1364. long res;
  1365. unsigned char *der;
  1366. size_t derlen, offset = 0;
  1367. OSStatus ret;
  1368. SecTrustResultType trust_eval;
  1369. CFMutableArrayRef array = NULL;
  1370. SecTrustRef trust = NULL;
  1371. CURLcode result = CURLE_PEER_FAILED_VERIFICATION;
  1372. (void)cf;
  1373. /*
  1374. * Certbuf now contains the contents of the certificate file, which can be
  1375. * - a single DER certificate,
  1376. * - a single PEM certificate or
  1377. * - a bunch of PEM certificates (certificate bundle).
  1378. *
  1379. * Go through certbuf, and convert any PEM certificate in it into DER
  1380. * format.
  1381. */
  1382. array = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
  1383. if(!array) {
  1384. failf(data, "SSL: out of memory creating CA certificate array");
  1385. result = CURLE_OUT_OF_MEMORY;
  1386. goto out;
  1387. }
  1388. while(offset < buflen) {
  1389. n++;
  1390. /*
  1391. * Check if the certificate is in PEM format, and convert it to DER. If
  1392. * this fails, we assume the certificate is in DER format.
  1393. */
  1394. res = pem_to_der((const char *)certbuf + offset, &der, &derlen);
  1395. if(res < 0) {
  1396. failf(data, "SSL: invalid CA certificate #%d (offset %zu) in bundle",
  1397. n, offset);
  1398. result = CURLE_SSL_CACERT_BADFILE;
  1399. goto out;
  1400. }
  1401. offset += res;
  1402. if(res == 0 && offset == 0) {
  1403. /* This is not a PEM file, probably a certificate in DER format. */
  1404. rc = append_cert_to_array(data, certbuf, buflen, array);
  1405. if(rc != CURLE_OK) {
  1406. CURL_TRC_CF(data, cf, "append_cert for CA failed");
  1407. result = rc;
  1408. goto out;
  1409. }
  1410. break;
  1411. }
  1412. else if(res == 0) {
  1413. /* No more certificates in the bundle. */
  1414. break;
  1415. }
  1416. rc = append_cert_to_array(data, der, derlen, array);
  1417. free(der);
  1418. if(rc != CURLE_OK) {
  1419. CURL_TRC_CF(data, cf, "append_cert for CA failed");
  1420. result = rc;
  1421. goto out;
  1422. }
  1423. }
  1424. ret = SSLCopyPeerTrust(ctx, &trust);
  1425. if(!trust) {
  1426. failf(data, "SSL: error getting certificate chain");
  1427. goto out;
  1428. }
  1429. else if(ret != noErr) {
  1430. failf(data, "SSLCopyPeerTrust() returned error %d", ret);
  1431. goto out;
  1432. }
  1433. CURL_TRC_CF(data, cf, "setting %d trust anchors", n);
  1434. ret = SecTrustSetAnchorCertificates(trust, array);
  1435. if(ret != noErr) {
  1436. failf(data, "SecTrustSetAnchorCertificates() returned error %d", ret);
  1437. goto out;
  1438. }
  1439. ret = SecTrustSetAnchorCertificatesOnly(trust, TRUE);
  1440. if(ret != noErr) {
  1441. failf(data, "SecTrustSetAnchorCertificatesOnly() returned error %d", ret);
  1442. goto out;
  1443. }
  1444. trust_eval = 0;
  1445. ret = SecTrustEvaluate(trust, &trust_eval);
  1446. if(ret != noErr) {
  1447. failf(data, "SecTrustEvaluate() returned error %d", ret);
  1448. goto out;
  1449. }
  1450. switch(trust_eval) {
  1451. case kSecTrustResultUnspecified:
  1452. /* what does this really mean? */
  1453. CURL_TRC_CF(data, cf, "trust result: Unspecified");
  1454. result = CURLE_OK;
  1455. goto out;
  1456. case kSecTrustResultProceed:
  1457. CURL_TRC_CF(data, cf, "trust result: Proceed");
  1458. result = CURLE_OK;
  1459. goto out;
  1460. case kSecTrustResultRecoverableTrustFailure:
  1461. failf(data, "SSL: peer not verified: RecoverableTrustFailure");
  1462. goto out;
  1463. case kSecTrustResultDeny:
  1464. failf(data, "SSL: peer not verified: Deny");
  1465. goto out;
  1466. default:
  1467. failf(data, "SSL: perr not verified: result=%d", trust_eval);
  1468. goto out;
  1469. }
  1470. out:
  1471. if(trust)
  1472. CFRelease(trust);
  1473. if(array)
  1474. CFRelease(array);
  1475. return result;
  1476. }
  1477. static CURLcode verify_cert(struct Curl_cfilter *cf,
  1478. struct Curl_easy *data, const char *cafile,
  1479. const struct curl_blob *ca_info_blob,
  1480. SSLContextRef ctx)
  1481. {
  1482. CURLcode result;
  1483. unsigned char *certbuf;
  1484. size_t buflen;
  1485. bool free_certbuf = FALSE;
  1486. if(ca_info_blob) {
  1487. CURL_TRC_CF(data, cf, "verify_peer, CA from config blob");
  1488. certbuf = ca_info_blob->data;
  1489. buflen = ca_info_blob->len;
  1490. }
  1491. else if(cafile) {
  1492. CURL_TRC_CF(data, cf, "verify_peer, CA from file '%s'", cafile);
  1493. if(read_cert(cafile, &certbuf, &buflen) < 0) {
  1494. failf(data, "SSL: failed to read or invalid CA certificate");
  1495. return CURLE_SSL_CACERT_BADFILE;
  1496. }
  1497. free_certbuf = TRUE;
  1498. }
  1499. else
  1500. return CURLE_SSL_CACERT_BADFILE;
  1501. result = verify_cert_buf(cf, data, certbuf, buflen, ctx);
  1502. if(free_certbuf)
  1503. free(certbuf);
  1504. return result;
  1505. }
  1506. #ifdef SECTRANSP_PINNEDPUBKEY
  1507. static CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data,
  1508. SSLContextRef ctx,
  1509. const char *pinnedpubkey)
  1510. { /* Scratch */
  1511. size_t pubkeylen, realpubkeylen, spkiHeaderLength = 24;
  1512. unsigned char *pubkey = NULL, *realpubkey = NULL;
  1513. const unsigned char *spkiHeader = NULL;
  1514. CFDataRef publicKeyBits = NULL;
  1515. /* Result is returned to caller */
  1516. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  1517. /* if a path was not specified, do not pin */
  1518. if(!pinnedpubkey)
  1519. return CURLE_OK;
  1520. if(!ctx)
  1521. return result;
  1522. do {
  1523. SecTrustRef trust;
  1524. OSStatus ret;
  1525. SecKeyRef keyRef;
  1526. ret = SSLCopyPeerTrust(ctx, &trust);
  1527. if(ret != noErr || !trust)
  1528. break;
  1529. keyRef = SecTrustCopyPublicKey(trust);
  1530. CFRelease(trust);
  1531. if(!keyRef)
  1532. break;
  1533. #ifdef SECTRANSP_PINNEDPUBKEY_V1
  1534. publicKeyBits = SecKeyCopyExternalRepresentation(keyRef, NULL);
  1535. CFRelease(keyRef);
  1536. if(!publicKeyBits)
  1537. break;
  1538. #elif SECTRANSP_PINNEDPUBKEY_V2
  1539. {
  1540. OSStatus success;
  1541. success = SecItemExport(keyRef, kSecFormatOpenSSL, 0, NULL,
  1542. &publicKeyBits);
  1543. CFRelease(keyRef);
  1544. if(success != errSecSuccess || !publicKeyBits)
  1545. break;
  1546. }
  1547. #endif /* SECTRANSP_PINNEDPUBKEY_V2 */
  1548. pubkeylen = (size_t)CFDataGetLength(publicKeyBits);
  1549. pubkey = (unsigned char *)CFDataGetBytePtr(publicKeyBits);
  1550. switch(pubkeylen) {
  1551. case 526:
  1552. /* 4096 bit RSA pubkeylen == 526 */
  1553. spkiHeader = rsa4096SpkiHeader;
  1554. break;
  1555. case 270:
  1556. /* 2048 bit RSA pubkeylen == 270 */
  1557. spkiHeader = rsa2048SpkiHeader;
  1558. break;
  1559. #ifdef SECTRANSP_PINNEDPUBKEY_V1
  1560. case 65:
  1561. /* ecDSA secp256r1 pubkeylen == 65 */
  1562. spkiHeader = ecDsaSecp256r1SpkiHeader;
  1563. spkiHeaderLength = 26;
  1564. break;
  1565. case 97:
  1566. /* ecDSA secp384r1 pubkeylen == 97 */
  1567. spkiHeader = ecDsaSecp384r1SpkiHeader;
  1568. spkiHeaderLength = 23;
  1569. break;
  1570. default:
  1571. infof(data, "SSL: unhandled public key length: %zu", pubkeylen);
  1572. #elif SECTRANSP_PINNEDPUBKEY_V2
  1573. default:
  1574. /* ecDSA secp256r1 pubkeylen == 91 header already included?
  1575. * ecDSA secp384r1 header already included too
  1576. * we assume rest of algorithms do same, so do nothing
  1577. */
  1578. result = Curl_pin_peer_pubkey(data, pinnedpubkey, pubkey,
  1579. pubkeylen);
  1580. #endif /* SECTRANSP_PINNEDPUBKEY_V2 */
  1581. continue; /* break from loop */
  1582. }
  1583. realpubkeylen = pubkeylen + spkiHeaderLength;
  1584. realpubkey = malloc(realpubkeylen);
  1585. if(!realpubkey)
  1586. break;
  1587. memcpy(realpubkey, spkiHeader, spkiHeaderLength);
  1588. memcpy(realpubkey + spkiHeaderLength, pubkey, pubkeylen);
  1589. result = Curl_pin_peer_pubkey(data, pinnedpubkey, realpubkey,
  1590. realpubkeylen);
  1591. } while(0);
  1592. Curl_safefree(realpubkey);
  1593. if(publicKeyBits)
  1594. CFRelease(publicKeyBits);
  1595. return result;
  1596. }
  1597. #endif /* SECTRANSP_PINNEDPUBKEY */
  1598. static CURLcode sectransp_connect_step2(struct Curl_cfilter *cf,
  1599. struct Curl_easy *data)
  1600. {
  1601. struct ssl_connect_data *connssl = cf->ctx;
  1602. struct st_ssl_backend_data *backend =
  1603. (struct st_ssl_backend_data *)connssl->backend;
  1604. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  1605. OSStatus err;
  1606. SSLCipherSuite cipher;
  1607. SSLProtocol protocol = 0;
  1608. DEBUGASSERT(ssl_connect_2 == connssl->connecting_state);
  1609. DEBUGASSERT(backend);
  1610. CURL_TRC_CF(data, cf, "connect_step2");
  1611. /* Here goes nothing: */
  1612. check_handshake:
  1613. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  1614. err = SSLHandshake(backend->ssl_ctx);
  1615. if(err != noErr) {
  1616. switch(err) {
  1617. case errSSLWouldBlock: /* they are not done with us yet */
  1618. connssl->io_need = backend->ssl_direction ?
  1619. CURL_SSL_IO_NEED_SEND : CURL_SSL_IO_NEED_RECV;
  1620. return CURLE_OK;
  1621. /* The below is errSSLServerAuthCompleted; it is not defined in
  1622. Leopard's headers */
  1623. case -9841:
  1624. if((conn_config->CAfile || conn_config->ca_info_blob) &&
  1625. conn_config->verifypeer) {
  1626. CURLcode result = verify_cert(cf, data, conn_config->CAfile,
  1627. conn_config->ca_info_blob,
  1628. backend->ssl_ctx);
  1629. if(result)
  1630. return result;
  1631. }
  1632. /* the documentation says we need to call SSLHandshake() again */
  1633. goto check_handshake;
  1634. /* Problem with encrypt / decrypt */
  1635. case errSSLPeerDecodeError:
  1636. failf(data, "Decode failed");
  1637. break;
  1638. case errSSLDecryptionFail:
  1639. case errSSLPeerDecryptionFail:
  1640. failf(data, "Decryption failed");
  1641. break;
  1642. case errSSLPeerDecryptError:
  1643. failf(data, "A decryption error occurred");
  1644. break;
  1645. case errSSLBadCipherSuite:
  1646. failf(data, "A bad SSL cipher suite was encountered");
  1647. break;
  1648. case errSSLCrypto:
  1649. failf(data, "An underlying cryptographic error was encountered");
  1650. break;
  1651. #if CURL_BUILD_MAC_10_11 || CURL_BUILD_IOS_9
  1652. case errSSLWeakPeerEphemeralDHKey:
  1653. failf(data, "Indicates a weak ephemeral Diffie-Hellman key");
  1654. break;
  1655. #endif
  1656. /* Problem with the message record validation */
  1657. case errSSLBadRecordMac:
  1658. case errSSLPeerBadRecordMac:
  1659. failf(data, "A record with a bad message authentication code (MAC) "
  1660. "was encountered");
  1661. break;
  1662. case errSSLRecordOverflow:
  1663. case errSSLPeerRecordOverflow:
  1664. failf(data, "A record overflow occurred");
  1665. break;
  1666. /* Problem with zlib decompression */
  1667. case errSSLPeerDecompressFail:
  1668. failf(data, "Decompression failed");
  1669. break;
  1670. /* Problem with access */
  1671. case errSSLPeerAccessDenied:
  1672. failf(data, "Access was denied");
  1673. break;
  1674. case errSSLPeerInsufficientSecurity:
  1675. failf(data, "There is insufficient security for this operation");
  1676. break;
  1677. /* These are all certificate problems with the server: */
  1678. case errSSLXCertChainInvalid:
  1679. failf(data, "SSL certificate problem: Invalid certificate chain");
  1680. return CURLE_PEER_FAILED_VERIFICATION;
  1681. case errSSLUnknownRootCert:
  1682. failf(data, "SSL certificate problem: Untrusted root certificate");
  1683. return CURLE_PEER_FAILED_VERIFICATION;
  1684. case errSSLNoRootCert:
  1685. failf(data, "SSL certificate problem: No root certificate");
  1686. return CURLE_PEER_FAILED_VERIFICATION;
  1687. case errSSLCertNotYetValid:
  1688. failf(data, "SSL certificate problem: The certificate chain had a "
  1689. "certificate that is not yet valid");
  1690. return CURLE_PEER_FAILED_VERIFICATION;
  1691. case errSSLCertExpired:
  1692. case errSSLPeerCertExpired:
  1693. failf(data, "SSL certificate problem: Certificate chain had an "
  1694. "expired certificate");
  1695. return CURLE_PEER_FAILED_VERIFICATION;
  1696. case errSSLBadCert:
  1697. case errSSLPeerBadCert:
  1698. failf(data, "SSL certificate problem: Couldn't understand the server "
  1699. "certificate format");
  1700. return CURLE_PEER_FAILED_VERIFICATION;
  1701. case errSSLPeerUnsupportedCert:
  1702. failf(data, "SSL certificate problem: An unsupported certificate "
  1703. "format was encountered");
  1704. return CURLE_PEER_FAILED_VERIFICATION;
  1705. case errSSLPeerCertRevoked:
  1706. failf(data, "SSL certificate problem: The certificate was revoked");
  1707. return CURLE_PEER_FAILED_VERIFICATION;
  1708. case errSSLPeerCertUnknown:
  1709. failf(data, "SSL certificate problem: The certificate is unknown");
  1710. return CURLE_PEER_FAILED_VERIFICATION;
  1711. /* These are all certificate problems with the client: */
  1712. case errSecAuthFailed:
  1713. failf(data, "SSL authentication failed");
  1714. break;
  1715. case errSSLPeerHandshakeFail:
  1716. failf(data, "SSL peer handshake failed, the server most likely "
  1717. "requires a client certificate to connect");
  1718. break;
  1719. case errSSLPeerUnknownCA:
  1720. failf(data, "SSL server rejected the client certificate due to "
  1721. "the certificate being signed by an unknown certificate "
  1722. "authority");
  1723. break;
  1724. /* This error is raised if the server's cert did not match the server's
  1725. hostname: */
  1726. case errSSLHostNameMismatch:
  1727. failf(data, "SSL certificate peer verification failed, the "
  1728. "certificate did not match \"%s\"\n", connssl->peer.dispname);
  1729. return CURLE_PEER_FAILED_VERIFICATION;
  1730. /* Problem with SSL / TLS negotiation */
  1731. case errSSLNegotiation:
  1732. failf(data, "Could not negotiate an SSL cipher suite with the server");
  1733. break;
  1734. case errSSLBadConfiguration:
  1735. failf(data, "A configuration error occurred");
  1736. break;
  1737. case errSSLProtocol:
  1738. failf(data, "SSL protocol error");
  1739. break;
  1740. case errSSLPeerProtocolVersion:
  1741. failf(data, "A bad protocol version was encountered");
  1742. break;
  1743. case errSSLPeerNoRenegotiation:
  1744. failf(data, "No renegotiation is allowed");
  1745. break;
  1746. /* Generic handshake errors: */
  1747. case errSSLConnectionRefused:
  1748. failf(data, "Server dropped the connection during the SSL handshake");
  1749. break;
  1750. case errSSLClosedAbort:
  1751. failf(data, "Server aborted the SSL handshake");
  1752. break;
  1753. case errSSLClosedGraceful:
  1754. failf(data, "The connection closed gracefully");
  1755. break;
  1756. case errSSLClosedNoNotify:
  1757. failf(data, "The server closed the session with no notification");
  1758. break;
  1759. /* Sometimes paramErr happens with buggy ciphers: */
  1760. case paramErr:
  1761. case errSSLInternal:
  1762. case errSSLPeerInternalError:
  1763. failf(data, "Internal SSL engine error encountered during the "
  1764. "SSL handshake");
  1765. break;
  1766. case errSSLFatalAlert:
  1767. failf(data, "Fatal SSL engine error encountered during the SSL "
  1768. "handshake");
  1769. break;
  1770. /* Unclassified error */
  1771. case errSSLBufferOverflow:
  1772. failf(data, "An insufficient buffer was provided");
  1773. break;
  1774. case errSSLIllegalParam:
  1775. failf(data, "An illegal parameter was encountered");
  1776. break;
  1777. case errSSLModuleAttach:
  1778. failf(data, "Module attach failure");
  1779. break;
  1780. case errSSLSessionNotFound:
  1781. failf(data, "An attempt to restore an unknown session failed");
  1782. break;
  1783. case errSSLPeerExportRestriction:
  1784. failf(data, "An export restriction occurred");
  1785. break;
  1786. case errSSLPeerUserCancelled:
  1787. failf(data, "The user canceled the operation");
  1788. break;
  1789. case errSSLPeerUnexpectedMsg:
  1790. failf(data, "Peer rejected unexpected message");
  1791. break;
  1792. #if CURL_BUILD_MAC_10_11 || CURL_BUILD_IOS_9
  1793. /* Treating non-fatal error as fatal like before */
  1794. case errSSLClientHelloReceived:
  1795. failf(data, "A non-fatal result for providing a server name "
  1796. "indication");
  1797. break;
  1798. #endif
  1799. /* Error codes defined in the enum but should never be returned.
  1800. We list them here just in case. */
  1801. #if CURL_BUILD_MAC_10_6
  1802. /* Only returned when kSSLSessionOptionBreakOnCertRequested is set */
  1803. case errSSLClientCertRequested:
  1804. failf(data, "Server requested a client certificate during the "
  1805. "handshake");
  1806. return CURLE_SSL_CLIENTCERT;
  1807. #endif
  1808. #if CURL_BUILD_MAC_10_9
  1809. /* Alias for errSSLLast, end of error range */
  1810. case errSSLUnexpectedRecord:
  1811. failf(data, "Unexpected (skipped) record in DTLS");
  1812. break;
  1813. #endif
  1814. default:
  1815. /* May also return codes listed in Security Framework Result Codes */
  1816. failf(data, "Unknown SSL protocol error in connection to %s:%d",
  1817. connssl->peer.hostname, err);
  1818. break;
  1819. }
  1820. return CURLE_SSL_CONNECT_ERROR;
  1821. }
  1822. else {
  1823. char cipher_str[64];
  1824. /* we have been connected fine, we are not waiting for anything else. */
  1825. connssl->connecting_state = ssl_connect_3;
  1826. #ifdef SECTRANSP_PINNEDPUBKEY
  1827. if(data->set.str[STRING_SSL_PINNEDPUBLICKEY]) {
  1828. CURLcode result =
  1829. pkp_pin_peer_pubkey(data, backend->ssl_ctx,
  1830. data->set.str[STRING_SSL_PINNEDPUBLICKEY]);
  1831. if(result) {
  1832. failf(data, "SSL: public key does not match pinned public key");
  1833. return result;
  1834. }
  1835. }
  1836. #endif /* SECTRANSP_PINNEDPUBKEY */
  1837. /* Informational message */
  1838. (void)SSLGetNegotiatedCipher(backend->ssl_ctx, &cipher);
  1839. (void)SSLGetNegotiatedProtocolVersion(backend->ssl_ctx, &protocol);
  1840. sectransp_cipher_suite_get_str((uint16_t) cipher, cipher_str,
  1841. sizeof(cipher_str), TRUE);
  1842. switch(protocol) {
  1843. case kSSLProtocol2:
  1844. infof(data, "SSL 2.0 connection using %s", cipher_str);
  1845. break;
  1846. case kSSLProtocol3:
  1847. infof(data, "SSL 3.0 connection using %s", cipher_str);
  1848. break;
  1849. case kTLSProtocol1:
  1850. infof(data, "TLS 1.0 connection using %s", cipher_str);
  1851. break;
  1852. #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
  1853. case kTLSProtocol11:
  1854. infof(data, "TLS 1.1 connection using %s", cipher_str);
  1855. break;
  1856. case kTLSProtocol12:
  1857. infof(data, "TLS 1.2 connection using %s", cipher_str);
  1858. break;
  1859. #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */
  1860. #if CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11
  1861. case kTLSProtocol13:
  1862. infof(data, "TLS 1.3 connection using %s", cipher_str);
  1863. break;
  1864. #endif /* CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11 */
  1865. default:
  1866. infof(data, "Unknown protocol connection");
  1867. break;
  1868. }
  1869. #if (CURL_BUILD_MAC_10_13 || CURL_BUILD_IOS_11) && \
  1870. defined(HAVE_BUILTIN_AVAILABLE)
  1871. if(connssl->alpn) {
  1872. if(__builtin_available(macOS 10.13.4, iOS 11, tvOS 11, *)) {
  1873. CFArrayRef alpnArr = NULL;
  1874. CFStringRef chosenProtocol = NULL;
  1875. err = SSLCopyALPNProtocols(backend->ssl_ctx, &alpnArr);
  1876. if(err == noErr && alpnArr && CFArrayGetCount(alpnArr) >= 1)
  1877. chosenProtocol = CFArrayGetValueAtIndex(alpnArr, 0);
  1878. #ifdef USE_HTTP2
  1879. if(chosenProtocol &&
  1880. !CFStringCompare(chosenProtocol, CFSTR(ALPN_H2), 0)) {
  1881. cf->conn->alpn = CURL_HTTP_VERSION_2;
  1882. }
  1883. else
  1884. #endif
  1885. if(chosenProtocol &&
  1886. !CFStringCompare(chosenProtocol, CFSTR(ALPN_HTTP_1_1), 0)) {
  1887. cf->conn->alpn = CURL_HTTP_VERSION_1_1;
  1888. }
  1889. else
  1890. infof(data, VTLS_INFOF_NO_ALPN);
  1891. /* chosenProtocol is a reference to the string within alpnArr
  1892. and does not need to be freed separately */
  1893. if(alpnArr)
  1894. CFRelease(alpnArr);
  1895. }
  1896. }
  1897. #endif
  1898. return CURLE_OK;
  1899. }
  1900. }
  1901. static CURLcode
  1902. add_cert_to_certinfo(struct Curl_easy *data,
  1903. SecCertificateRef server_cert,
  1904. int idx)
  1905. {
  1906. CURLcode result = CURLE_OK;
  1907. const char *beg;
  1908. const char *end;
  1909. CFDataRef cert_data = SecCertificateCopyData(server_cert);
  1910. if(!cert_data)
  1911. return CURLE_PEER_FAILED_VERIFICATION;
  1912. beg = (const char *)CFDataGetBytePtr(cert_data);
  1913. end = beg + CFDataGetLength(cert_data);
  1914. result = Curl_extract_certinfo(data, idx, beg, end);
  1915. CFRelease(cert_data);
  1916. return result;
  1917. }
  1918. static CURLcode
  1919. collect_server_cert_single(struct Curl_cfilter *cf, struct Curl_easy *data,
  1920. SecCertificateRef server_cert,
  1921. CFIndex idx)
  1922. {
  1923. CURLcode result = CURLE_OK;
  1924. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  1925. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1926. if(data->set.verbose) {
  1927. char *certp;
  1928. result = CopyCertSubject(data, server_cert, &certp);
  1929. if(!result) {
  1930. infof(data, "Server certificate: %s", certp);
  1931. free(certp);
  1932. }
  1933. }
  1934. #endif
  1935. if(ssl_config->certinfo)
  1936. result = add_cert_to_certinfo(data, server_cert, (int)idx);
  1937. return result;
  1938. }
  1939. /* This should be called during step3 of the connection at the earliest */
  1940. static CURLcode collect_server_cert(struct Curl_cfilter *cf,
  1941. struct Curl_easy *data)
  1942. {
  1943. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  1944. const bool show_verbose_server_cert = data->set.verbose;
  1945. #else
  1946. const bool show_verbose_server_cert = FALSE;
  1947. #endif
  1948. struct ssl_config_data *ssl_config = Curl_ssl_cf_get_config(cf, data);
  1949. CURLcode result = ssl_config->certinfo ?
  1950. CURLE_PEER_FAILED_VERIFICATION : CURLE_OK;
  1951. struct ssl_connect_data *connssl = cf->ctx;
  1952. struct st_ssl_backend_data *backend =
  1953. (struct st_ssl_backend_data *)connssl->backend;
  1954. CFArrayRef server_certs = NULL;
  1955. SecCertificateRef server_cert;
  1956. OSStatus err;
  1957. CFIndex i, count;
  1958. SecTrustRef trust = NULL;
  1959. DEBUGASSERT(backend);
  1960. if(!show_verbose_server_cert && !ssl_config->certinfo)
  1961. return CURLE_OK;
  1962. if(!backend->ssl_ctx)
  1963. return result;
  1964. #if CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS
  1965. #if CURL_BUILD_IOS
  1966. #pragma unused(server_certs)
  1967. err = SSLCopyPeerTrust(backend->ssl_ctx, &trust);
  1968. /* For some reason, SSLCopyPeerTrust() can return noErr and yet return
  1969. a null trust, so be on guard for that: */
  1970. if(err == noErr && trust) {
  1971. count = SecTrustGetCertificateCount(trust);
  1972. if(ssl_config->certinfo)
  1973. result = Curl_ssl_init_certinfo(data, (int)count);
  1974. for(i = 0L ; !result && (i < count) ; i++) {
  1975. server_cert = SecTrustGetCertificateAtIndex(trust, i);
  1976. result = collect_server_cert_single(cf, data, server_cert, i);
  1977. }
  1978. CFRelease(trust);
  1979. }
  1980. #else
  1981. /* SSLCopyPeerCertificates() is deprecated as of Mountain Lion.
  1982. The function SecTrustGetCertificateAtIndex() is officially present
  1983. in Lion, but it is unfortunately also present in Snow Leopard as
  1984. private API and does not work as expected. So we have to look for
  1985. a different symbol to make sure this code is only executed under
  1986. Lion or later. */
  1987. if(&SecTrustCopyPublicKey) {
  1988. #pragma unused(server_certs)
  1989. err = SSLCopyPeerTrust(backend->ssl_ctx, &trust);
  1990. /* For some reason, SSLCopyPeerTrust() can return noErr and yet return
  1991. a null trust, so be on guard for that: */
  1992. if(err == noErr && trust) {
  1993. count = SecTrustGetCertificateCount(trust);
  1994. if(ssl_config->certinfo)
  1995. result = Curl_ssl_init_certinfo(data, (int)count);
  1996. for(i = 0L ; !result && (i < count) ; i++) {
  1997. server_cert = SecTrustGetCertificateAtIndex(trust, i);
  1998. result = collect_server_cert_single(cf, data, server_cert, i);
  1999. }
  2000. CFRelease(trust);
  2001. }
  2002. }
  2003. else {
  2004. #if CURL_SUPPORT_MAC_10_8
  2005. err = SSLCopyPeerCertificates(backend->ssl_ctx, &server_certs);
  2006. /* Just in case SSLCopyPeerCertificates() returns null too... */
  2007. if(err == noErr && server_certs) {
  2008. count = CFArrayGetCount(server_certs);
  2009. if(ssl_config->certinfo)
  2010. result = Curl_ssl_init_certinfo(data, (int)count);
  2011. for(i = 0L ; !result && (i < count) ; i++) {
  2012. server_cert = (SecCertificateRef)CFArrayGetValueAtIndex(server_certs,
  2013. i);
  2014. result = collect_server_cert_single(cf, data, server_cert, i);
  2015. }
  2016. CFRelease(server_certs);
  2017. }
  2018. #endif /* CURL_SUPPORT_MAC_10_8 */
  2019. }
  2020. #endif /* CURL_BUILD_IOS */
  2021. #else
  2022. #pragma unused(trust)
  2023. err = SSLCopyPeerCertificates(backend->ssl_ctx, &server_certs);
  2024. if(err == noErr) {
  2025. count = CFArrayGetCount(server_certs);
  2026. if(ssl_config->certinfo)
  2027. result = Curl_ssl_init_certinfo(data, (int)count);
  2028. for(i = 0L ; !result && (i < count) ; i++) {
  2029. server_cert = (SecCertificateRef)CFArrayGetValueAtIndex(server_certs, i);
  2030. result = collect_server_cert_single(cf, data, server_cert, i);
  2031. }
  2032. CFRelease(server_certs);
  2033. }
  2034. #endif /* CURL_BUILD_MAC_10_7 || CURL_BUILD_IOS */
  2035. return result;
  2036. }
  2037. static CURLcode sectransp_connect_step3(struct Curl_cfilter *cf,
  2038. struct Curl_easy *data)
  2039. {
  2040. struct ssl_connect_data *connssl = cf->ctx;
  2041. CURLcode result;
  2042. CURL_TRC_CF(data, cf, "connect_step3");
  2043. /* There is no step 3!
  2044. * Well, okay, let's collect server certificates, and if verbose mode is on,
  2045. * let's print the details of the server certificates. */
  2046. result = collect_server_cert(cf, data);
  2047. if(result)
  2048. return result;
  2049. connssl->connecting_state = ssl_connect_done;
  2050. return CURLE_OK;
  2051. }
  2052. static CURLcode
  2053. sectransp_connect_common(struct Curl_cfilter *cf, struct Curl_easy *data,
  2054. bool nonblocking,
  2055. bool *done)
  2056. {
  2057. CURLcode result;
  2058. struct ssl_connect_data *connssl = cf->ctx;
  2059. curl_socket_t sockfd = Curl_conn_cf_get_socket(cf, data);
  2060. int what;
  2061. /* check if the connection has already been established */
  2062. if(ssl_connection_complete == connssl->state) {
  2063. *done = TRUE;
  2064. return CURLE_OK;
  2065. }
  2066. if(ssl_connect_1 == connssl->connecting_state) {
  2067. /* Find out how much more time we are allowed */
  2068. const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  2069. if(timeout_ms < 0) {
  2070. /* no need to continue if time already is up */
  2071. failf(data, "SSL connection timeout");
  2072. return CURLE_OPERATION_TIMEDOUT;
  2073. }
  2074. result = sectransp_connect_step1(cf, data);
  2075. if(result)
  2076. return result;
  2077. }
  2078. while(ssl_connect_2 == connssl->connecting_state) {
  2079. /* check allowed time left */
  2080. const timediff_t timeout_ms = Curl_timeleft(data, NULL, TRUE);
  2081. if(timeout_ms < 0) {
  2082. /* no need to continue if time already is up */
  2083. failf(data, "SSL connection timeout");
  2084. return CURLE_OPERATION_TIMEDOUT;
  2085. }
  2086. /* if ssl is expecting something, check if it is available. */
  2087. if(connssl->io_need) {
  2088. curl_socket_t writefd = (connssl->io_need & CURL_SSL_IO_NEED_SEND) ?
  2089. sockfd : CURL_SOCKET_BAD;
  2090. curl_socket_t readfd = (connssl->io_need & CURL_SSL_IO_NEED_RECV) ?
  2091. sockfd : CURL_SOCKET_BAD;
  2092. what = Curl_socket_check(readfd, CURL_SOCKET_BAD, writefd,
  2093. nonblocking ? 0 : timeout_ms);
  2094. if(what < 0) {
  2095. /* fatal error */
  2096. failf(data, "select/poll on SSL socket, errno: %d", SOCKERRNO);
  2097. return CURLE_SSL_CONNECT_ERROR;
  2098. }
  2099. else if(0 == what) {
  2100. if(nonblocking) {
  2101. *done = FALSE;
  2102. return CURLE_OK;
  2103. }
  2104. else {
  2105. /* timeout */
  2106. failf(data, "SSL connection timeout");
  2107. return CURLE_OPERATION_TIMEDOUT;
  2108. }
  2109. }
  2110. /* socket is readable or writable */
  2111. }
  2112. /* Run transaction, and return to the caller if it failed or if this
  2113. * connection is done nonblocking and this loop would execute again. This
  2114. * permits the owner of a multi handle to abort a connection attempt
  2115. * before step2 has completed while ensuring that a client using select()
  2116. * or epoll() will always have a valid fdset to wait on.
  2117. */
  2118. result = sectransp_connect_step2(cf, data);
  2119. if(result || (nonblocking && (ssl_connect_2 == connssl->connecting_state)))
  2120. return result;
  2121. } /* repeat step2 until all transactions are done. */
  2122. if(ssl_connect_3 == connssl->connecting_state) {
  2123. result = sectransp_connect_step3(cf, data);
  2124. if(result)
  2125. return result;
  2126. }
  2127. if(ssl_connect_done == connssl->connecting_state) {
  2128. CURL_TRC_CF(data, cf, "connected");
  2129. connssl->state = ssl_connection_complete;
  2130. *done = TRUE;
  2131. }
  2132. else
  2133. *done = FALSE;
  2134. /* Reset our connect state machine */
  2135. connssl->connecting_state = ssl_connect_1;
  2136. return CURLE_OK;
  2137. }
  2138. static CURLcode sectransp_connect_nonblocking(struct Curl_cfilter *cf,
  2139. struct Curl_easy *data,
  2140. bool *done)
  2141. {
  2142. return sectransp_connect_common(cf, data, TRUE, done);
  2143. }
  2144. static CURLcode sectransp_connect(struct Curl_cfilter *cf,
  2145. struct Curl_easy *data)
  2146. {
  2147. CURLcode result;
  2148. bool done = FALSE;
  2149. result = sectransp_connect_common(cf, data, FALSE, &done);
  2150. if(result)
  2151. return result;
  2152. DEBUGASSERT(done);
  2153. return CURLE_OK;
  2154. }
  2155. static ssize_t sectransp_recv(struct Curl_cfilter *cf,
  2156. struct Curl_easy *data,
  2157. char *buf,
  2158. size_t buffersize,
  2159. CURLcode *curlcode);
  2160. static CURLcode sectransp_shutdown(struct Curl_cfilter *cf,
  2161. struct Curl_easy *data,
  2162. bool send_shutdown, bool *done)
  2163. {
  2164. struct ssl_connect_data *connssl = cf->ctx;
  2165. struct st_ssl_backend_data *backend =
  2166. (struct st_ssl_backend_data *)connssl->backend;
  2167. CURLcode result = CURLE_OK;
  2168. ssize_t nread;
  2169. char buf[1024];
  2170. size_t i;
  2171. DEBUGASSERT(backend);
  2172. if(!backend->ssl_ctx || cf->shutdown) {
  2173. *done = TRUE;
  2174. goto out;
  2175. }
  2176. connssl->io_need = CURL_SSL_IO_NEED_NONE;
  2177. *done = FALSE;
  2178. if(send_shutdown && !backend->sent_shutdown) {
  2179. OSStatus err;
  2180. CURL_TRC_CF(data, cf, "shutdown, send close notify");
  2181. err = SSLClose(backend->ssl_ctx);
  2182. switch(err) {
  2183. case noErr:
  2184. backend->sent_shutdown = TRUE;
  2185. break;
  2186. case errSSLWouldBlock:
  2187. connssl->io_need = CURL_SSL_IO_NEED_SEND;
  2188. result = CURLE_OK;
  2189. goto out;
  2190. default:
  2191. CURL_TRC_CF(data, cf, "shutdown, error: %d", (int)err);
  2192. result = CURLE_SEND_ERROR;
  2193. goto out;
  2194. }
  2195. }
  2196. for(i = 0; i < 10; ++i) {
  2197. if(!backend->sent_shutdown) {
  2198. nread = sectransp_recv(cf, data, buf, (int)sizeof(buf), &result);
  2199. }
  2200. else {
  2201. /* We would like to read the close notify from the server using
  2202. * Secure Transport, however SSLRead() no longer works after we
  2203. * sent the notify from our side. So, we just read from the
  2204. * underlying filter and hope it will end. */
  2205. nread = Curl_conn_cf_recv(cf->next, data, buf, sizeof(buf), &result);
  2206. }
  2207. CURL_TRC_CF(data, cf, "shutdown read -> %zd, %d", nread, result);
  2208. if(nread <= 0)
  2209. break;
  2210. }
  2211. if(nread > 0) {
  2212. /* still data coming in? */
  2213. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  2214. }
  2215. else if(nread == 0) {
  2216. /* We got the close notify alert and are done. */
  2217. CURL_TRC_CF(data, cf, "shutdown done");
  2218. *done = TRUE;
  2219. }
  2220. else if(result == CURLE_AGAIN) {
  2221. connssl->io_need = CURL_SSL_IO_NEED_RECV;
  2222. result = CURLE_OK;
  2223. }
  2224. else {
  2225. DEBUGASSERT(result);
  2226. CURL_TRC_CF(data, cf, "shutdown, error: %d", result);
  2227. }
  2228. out:
  2229. cf->shutdown = (result || *done);
  2230. return result;
  2231. }
  2232. static void sectransp_close(struct Curl_cfilter *cf, struct Curl_easy *data)
  2233. {
  2234. struct ssl_connect_data *connssl = cf->ctx;
  2235. struct st_ssl_backend_data *backend =
  2236. (struct st_ssl_backend_data *)connssl->backend;
  2237. (void) data;
  2238. DEBUGASSERT(backend);
  2239. if(backend->ssl_ctx) {
  2240. CURL_TRC_CF(data, cf, "close");
  2241. #if CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS
  2242. if(&SSLCreateContext)
  2243. CFRelease(backend->ssl_ctx);
  2244. #if CURL_SUPPORT_MAC_10_8
  2245. else
  2246. (void)SSLDisposeContext(backend->ssl_ctx);
  2247. #endif /* CURL_SUPPORT_MAC_10_8 */
  2248. #else
  2249. (void)SSLDisposeContext(backend->ssl_ctx);
  2250. #endif /* CURL_BUILD_MAC_10_8 || CURL_BUILD_IOS */
  2251. backend->ssl_ctx = NULL;
  2252. }
  2253. }
  2254. static size_t sectransp_version(char *buffer, size_t size)
  2255. {
  2256. return msnprintf(buffer, size, "SecureTransport");
  2257. }
  2258. static bool sectransp_data_pending(struct Curl_cfilter *cf,
  2259. const struct Curl_easy *data)
  2260. {
  2261. const struct ssl_connect_data *connssl = cf->ctx;
  2262. struct st_ssl_backend_data *backend =
  2263. (struct st_ssl_backend_data *)connssl->backend;
  2264. OSStatus err;
  2265. size_t buffer;
  2266. (void)data;
  2267. DEBUGASSERT(backend);
  2268. if(backend->ssl_ctx) { /* SSL is in use */
  2269. CURL_TRC_CF((struct Curl_easy *)data, cf, "data_pending");
  2270. err = SSLGetBufferedReadSize(backend->ssl_ctx, &buffer);
  2271. if(err == noErr)
  2272. return buffer > 0UL;
  2273. return FALSE;
  2274. }
  2275. else
  2276. return FALSE;
  2277. }
  2278. static CURLcode sectransp_random(struct Curl_easy *data UNUSED_PARAM,
  2279. unsigned char *entropy, size_t length)
  2280. {
  2281. /* arc4random_buf() is not available on cats older than Lion, so let's
  2282. do this manually for the benefit of the older cats. */
  2283. size_t i;
  2284. u_int32_t random_number = 0;
  2285. (void)data;
  2286. for(i = 0 ; i < length ; i++) {
  2287. if(i % sizeof(u_int32_t) == 0)
  2288. random_number = arc4random();
  2289. entropy[i] = random_number & 0xFF;
  2290. random_number >>= 8;
  2291. }
  2292. i = random_number = 0;
  2293. return CURLE_OK;
  2294. }
  2295. static CURLcode sectransp_sha256sum(const unsigned char *tmp, /* input */
  2296. size_t tmplen,
  2297. unsigned char *sha256sum, /* output */
  2298. size_t sha256len)
  2299. {
  2300. (void)sha256len;
  2301. assert(sha256len >= CURL_SHA256_DIGEST_LENGTH);
  2302. (void)CC_SHA256(tmp, (CC_LONG)tmplen, sha256sum);
  2303. return CURLE_OK;
  2304. }
  2305. static bool sectransp_false_start(void)
  2306. {
  2307. #if CURL_BUILD_MAC_10_9 || CURL_BUILD_IOS_7
  2308. if(&SSLSetSessionOption)
  2309. return TRUE;
  2310. #endif
  2311. return FALSE;
  2312. }
  2313. static ssize_t sectransp_send(struct Curl_cfilter *cf,
  2314. struct Curl_easy *data,
  2315. const void *mem,
  2316. size_t len,
  2317. CURLcode *curlcode)
  2318. {
  2319. struct ssl_connect_data *connssl = cf->ctx;
  2320. struct st_ssl_backend_data *backend =
  2321. (struct st_ssl_backend_data *)connssl->backend;
  2322. size_t processed = 0UL;
  2323. OSStatus err;
  2324. DEBUGASSERT(backend);
  2325. /* The SSLWrite() function works a little differently than expected. The
  2326. fourth argument (processed) is currently documented in Apple's
  2327. documentation as: "On return, the length, in bytes, of the data actually
  2328. written."
  2329. Now, one could interpret that as "written to the socket," but actually,
  2330. it returns the amount of data that was written to a buffer internal to
  2331. the SSLContextRef instead. So it is possible for SSLWrite() to return
  2332. errSSLWouldBlock and a number of bytes "written" because those bytes were
  2333. encrypted and written to a buffer, not to the socket.
  2334. So if this happens, then we need to keep calling SSLWrite() over and
  2335. over again with no new data until it quits returning errSSLWouldBlock. */
  2336. /* Do we have buffered data to write from the last time we were called? */
  2337. if(backend->ssl_write_buffered_length) {
  2338. /* Write the buffered data: */
  2339. err = SSLWrite(backend->ssl_ctx, NULL, 0UL, &processed);
  2340. switch(err) {
  2341. case noErr:
  2342. /* processed is always going to be 0 because we did not write to
  2343. the buffer, so return how much was written to the socket */
  2344. processed = backend->ssl_write_buffered_length;
  2345. backend->ssl_write_buffered_length = 0UL;
  2346. break;
  2347. case errSSLWouldBlock: /* argh, try again */
  2348. *curlcode = CURLE_AGAIN;
  2349. return -1L;
  2350. default:
  2351. failf(data, "SSLWrite() returned error %d", err);
  2352. *curlcode = CURLE_SEND_ERROR;
  2353. return -1L;
  2354. }
  2355. }
  2356. else {
  2357. /* We have got new data to write: */
  2358. err = SSLWrite(backend->ssl_ctx, mem, len, &processed);
  2359. if(err != noErr) {
  2360. switch(err) {
  2361. case errSSLWouldBlock:
  2362. /* Data was buffered but not sent, we have to tell the caller
  2363. to try sending again, and remember how much was buffered */
  2364. backend->ssl_write_buffered_length = len;
  2365. *curlcode = CURLE_AGAIN;
  2366. return -1L;
  2367. default:
  2368. failf(data, "SSLWrite() returned error %d", err);
  2369. *curlcode = CURLE_SEND_ERROR;
  2370. return -1L;
  2371. }
  2372. }
  2373. }
  2374. return (ssize_t)processed;
  2375. }
  2376. static ssize_t sectransp_recv(struct Curl_cfilter *cf,
  2377. struct Curl_easy *data,
  2378. char *buf,
  2379. size_t buffersize,
  2380. CURLcode *curlcode)
  2381. {
  2382. struct ssl_connect_data *connssl = cf->ctx;
  2383. struct st_ssl_backend_data *backend =
  2384. (struct st_ssl_backend_data *)connssl->backend;
  2385. struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);
  2386. size_t processed = 0UL;
  2387. OSStatus err;
  2388. DEBUGASSERT(backend);
  2389. again:
  2390. *curlcode = CURLE_OK;
  2391. err = SSLRead(backend->ssl_ctx, buf, buffersize, &processed);
  2392. if(err != noErr) {
  2393. switch(err) {
  2394. case errSSLWouldBlock: /* return how much we read (if anything) */
  2395. if(processed) {
  2396. return (ssize_t)processed;
  2397. }
  2398. *curlcode = CURLE_AGAIN;
  2399. return -1L;
  2400. /* errSSLClosedGraceful - server gracefully shut down the SSL session
  2401. errSSLClosedNoNotify - server hung up on us instead of sending a
  2402. closure alert notice, read() is returning 0
  2403. Either way, inform the caller that the server disconnected. */
  2404. case errSSLClosedGraceful:
  2405. case errSSLClosedNoNotify:
  2406. *curlcode = CURLE_OK;
  2407. return 0;
  2408. /* The below is errSSLPeerAuthCompleted; it is not defined in
  2409. Leopard's headers */
  2410. case -9841:
  2411. if((conn_config->CAfile || conn_config->ca_info_blob) &&
  2412. conn_config->verifypeer) {
  2413. CURLcode result = verify_cert(cf, data, conn_config->CAfile,
  2414. conn_config->ca_info_blob,
  2415. backend->ssl_ctx);
  2416. if(result) {
  2417. *curlcode = result;
  2418. return -1;
  2419. }
  2420. }
  2421. goto again;
  2422. default:
  2423. failf(data, "SSLRead() return error %d", err);
  2424. *curlcode = CURLE_RECV_ERROR;
  2425. return -1L;
  2426. }
  2427. }
  2428. return (ssize_t)processed;
  2429. }
  2430. static void *sectransp_get_internals(struct ssl_connect_data *connssl,
  2431. CURLINFO info UNUSED_PARAM)
  2432. {
  2433. struct st_ssl_backend_data *backend =
  2434. (struct st_ssl_backend_data *)connssl->backend;
  2435. (void)info;
  2436. DEBUGASSERT(backend);
  2437. return backend->ssl_ctx;
  2438. }
  2439. const struct Curl_ssl Curl_ssl_sectransp = {
  2440. { CURLSSLBACKEND_SECURETRANSPORT, "secure-transport" }, /* info */
  2441. SSLSUPP_CAINFO_BLOB |
  2442. SSLSUPP_CERTINFO |
  2443. #ifdef SECTRANSP_PINNEDPUBKEY
  2444. SSLSUPP_PINNEDPUBKEY |
  2445. #endif /* SECTRANSP_PINNEDPUBKEY */
  2446. SSLSUPP_HTTPS_PROXY |
  2447. SSLSUPP_CIPHER_LIST,
  2448. sizeof(struct st_ssl_backend_data),
  2449. Curl_none_init, /* init */
  2450. Curl_none_cleanup, /* cleanup */
  2451. sectransp_version, /* version */
  2452. Curl_none_check_cxn, /* check_cxn */
  2453. sectransp_shutdown, /* shutdown */
  2454. sectransp_data_pending, /* data_pending */
  2455. sectransp_random, /* random */
  2456. Curl_none_cert_status_request, /* cert_status_request */
  2457. sectransp_connect, /* connect */
  2458. sectransp_connect_nonblocking, /* connect_nonblocking */
  2459. Curl_ssl_adjust_pollset, /* adjust_pollset */
  2460. sectransp_get_internals, /* get_internals */
  2461. sectransp_close, /* close_one */
  2462. Curl_none_close_all, /* close_all */
  2463. Curl_none_set_engine, /* set_engine */
  2464. Curl_none_set_engine_default, /* set_engine_default */
  2465. Curl_none_engines_list, /* engines_list */
  2466. sectransp_false_start, /* false_start */
  2467. sectransp_sha256sum, /* sha256sum */
  2468. NULL, /* associate_connection */
  2469. NULL, /* disassociate_connection */
  2470. sectransp_recv, /* recv decrypted data */
  2471. sectransp_send, /* send data to encrypt */
  2472. NULL, /* get_channel_binding */
  2473. };
  2474. #ifdef __GNUC__
  2475. #pragma GCC diagnostic pop
  2476. #endif
  2477. #ifdef __clang__
  2478. #pragma clang diagnostic pop
  2479. #endif
  2480. #endif /* USE_SECTRANSP */