sectransp.c 96 KB

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