AppleTLSSession.cc 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2013 Nils Maier
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "AppleTLSSession.h"
  36. #include <vector>
  37. #include <CoreFoundation/CoreFoundation.h>
  38. #include "LogFactory.h"
  39. #include "a2functional.h"
  40. #include "fmt.h"
  41. #define ioErr -36
  42. #define paramErr -50
  43. #define errSSLServerAuthCompleted -9841
  44. namespace {
  45. #if !defined(__MAC_10_8)
  46. static const SSLProtocol kTLSProtocol11 = (SSLProtocol)(kSSLProtocolAll + 1);
  47. static const SSLProtocol kTLSProtocol12 = (SSLProtocol)(kSSLProtocolAll + 2);
  48. #endif
  49. #ifndef CIPHER_NO_DHPARAM
  50. // Diffie-Hellman params, to seed the engine instead of having it spend up
  51. // to 30 seconds on generating them. It should be save to share these. :p
  52. // This was generated using: openssl dhparam -outform DER 2048
  53. static const uint8_t dhparam[] =
  54. "\x30\x82\x01\x08\x02\x82\x01\x01\x00\x97\xea\xd0\x46\xf7\xae\xa7\x76\x80"
  55. "\x9c\x74\x56\x98\xd8\x56\x97\x2b\x20\x6c\x77\xe2\x82\xbb\xc8\x84\xbe\xe7"
  56. "\x63\xaf\xcc\x30\xd0\x67\x97\x7d\x1b\xab\x59\x30\xa9\x13\x67\x21\xd7\xd4"
  57. "\x0e\x46\xcf\xe5\x80\xdf\xc9\xb9\xba\x54\x9b\x46\x2f\x3b\x45\xfc\x2f\xaf"
  58. "\xad\xc0\x17\x56\xdd\x52\x42\x57\x45\x70\x14\xe5\xbe\x67\xaa\xde\x69\x75"
  59. "\x30\x0d\xf9\xa2\xc4\x63\x4d\x7a\x39\xef\x14\x62\x18\x33\x44\xa1\xf9\xc1"
  60. "\x52\xd1\xb6\x72\x21\x98\xf8\xab\x16\x1b\x7b\x37\x65\xe3\xc5\x11\x00\xf6"
  61. "\x36\x1f\xd8\x5f\xd8\x9f\x43\xa8\xce\x9d\xbf\x5e\xd6\x2d\xfa\x0a\xc2\x01"
  62. "\x54\xc2\xd9\x81\x54\x55\xb5\x26\xf8\x88\x37\xf5\xfe\xe0\xef\x4a\x34\x81"
  63. "\xdc\x5a\xb3\x71\x46\x27\xe3\xcd\x24\xf6\x1b\xf1\xe2\x0f\xc2\xa1\x39\x53"
  64. "\x5b\xc5\x38\x46\x8e\x67\x4c\xd9\xdd\xe4\x37\x06\x03\x16\xf1\x1d\x7a\xba"
  65. "\x2d\xc1\xe4\x03\x1a\x58\xe5\x29\x5a\x29\x06\x69\x61\x7a\xd8\xa9\x05\x9f"
  66. "\xc1\xa2\x45\x9c\x17\xad\x52\x69\x33\xdc\x18\x8d\x15\xa6\x5e\xcd\x94\xf4"
  67. "\x45\xbb\x9f\xc2\x7b\x85\x00\x61\xb0\x1a\xdc\x3c\x86\xaa\x9f\x5c\x04\xb3"
  68. "\x90\x0b\x35\x64\xff\xd9\xe3\xac\xf2\xf2\xeb\x3a\x63\x02\x01\x02";
  69. #endif // CIPHER_NO_DHPARAM
  70. static inline const char *protoToString(SSLProtocol proto) {
  71. switch (proto) {
  72. case kSSLProtocol2:
  73. return "SSLv2 (!)";
  74. case kSSLProtocol3:
  75. return "SSLv3";
  76. case kTLSProtocol1:
  77. return "TLSv1";
  78. case kTLSProtocol11:
  79. return "TLSv1.1";
  80. case kTLSProtocol12:
  81. return "TLSv1.2";
  82. default:
  83. return "Unknown";
  84. }
  85. }
  86. #define SUITE(s) { s, #s }
  87. static struct {
  88. SSLCipherSuite suite;
  89. const char *name;
  90. } kSuites[] = {
  91. SUITE(SSL_NULL_WITH_NULL_NULL),
  92. SUITE(SSL_RSA_WITH_NULL_MD5),
  93. SUITE(SSL_RSA_WITH_NULL_SHA),
  94. SUITE(SSL_RSA_EXPORT_WITH_RC4_40_MD5),
  95. SUITE(SSL_RSA_WITH_RC4_128_MD5),
  96. SUITE(SSL_RSA_WITH_RC4_128_SHA),
  97. SUITE(SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5),
  98. SUITE(SSL_RSA_WITH_IDEA_CBC_SHA),
  99. SUITE(SSL_RSA_EXPORT_WITH_DES40_CBC_SHA),
  100. SUITE(SSL_RSA_WITH_DES_CBC_SHA),
  101. SUITE(SSL_RSA_WITH_3DES_EDE_CBC_SHA),
  102. SUITE(SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA),
  103. SUITE(SSL_DH_DSS_WITH_DES_CBC_SHA),
  104. SUITE(SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA),
  105. SUITE(SSL_DH_RSA_EXPORT_WITH_DES40_CBC_SHA),
  106. SUITE(SSL_DH_RSA_WITH_DES_CBC_SHA),
  107. SUITE(SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA),
  108. SUITE(SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA),
  109. SUITE(SSL_DHE_DSS_WITH_DES_CBC_SHA),
  110. SUITE(SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA),
  111. SUITE(SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA),
  112. SUITE(SSL_DHE_RSA_WITH_DES_CBC_SHA),
  113. SUITE(SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA),
  114. SUITE(SSL_DH_anon_EXPORT_WITH_RC4_40_MD5),
  115. SUITE(SSL_DH_anon_WITH_RC4_128_MD5),
  116. SUITE(SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA),
  117. SUITE(SSL_DH_anon_WITH_DES_CBC_SHA),
  118. SUITE(SSL_DH_anon_WITH_3DES_EDE_CBC_SHA),
  119. SUITE(SSL_FORTEZZA_DMS_WITH_NULL_SHA),
  120. SUITE(SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA),
  121. SUITE(TLS_RSA_WITH_AES_128_CBC_SHA),
  122. SUITE(TLS_DH_DSS_WITH_AES_128_CBC_SHA),
  123. SUITE(TLS_DH_RSA_WITH_AES_128_CBC_SHA),
  124. SUITE(TLS_DHE_DSS_WITH_AES_128_CBC_SHA),
  125. SUITE(TLS_DHE_RSA_WITH_AES_128_CBC_SHA),
  126. SUITE(TLS_DH_anon_WITH_AES_128_CBC_SHA),
  127. SUITE(TLS_RSA_WITH_AES_256_CBC_SHA),
  128. SUITE(TLS_DH_DSS_WITH_AES_256_CBC_SHA),
  129. SUITE(TLS_DH_RSA_WITH_AES_256_CBC_SHA),
  130. SUITE(TLS_DHE_DSS_WITH_AES_256_CBC_SHA),
  131. SUITE(TLS_DHE_RSA_WITH_AES_256_CBC_SHA),
  132. SUITE(TLS_DH_anon_WITH_AES_256_CBC_SHA),
  133. SUITE(TLS_ECDH_ECDSA_WITH_NULL_SHA),
  134. SUITE(TLS_ECDH_ECDSA_WITH_RC4_128_SHA),
  135. SUITE(TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA),
  136. SUITE(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA),
  137. SUITE(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA),
  138. SUITE(TLS_ECDHE_ECDSA_WITH_NULL_SHA),
  139. SUITE(TLS_ECDHE_ECDSA_WITH_RC4_128_SHA),
  140. SUITE(TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA),
  141. SUITE(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA),
  142. SUITE(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA),
  143. SUITE(TLS_ECDH_RSA_WITH_NULL_SHA),
  144. SUITE(TLS_ECDH_RSA_WITH_RC4_128_SHA),
  145. SUITE(TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA),
  146. SUITE(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA),
  147. SUITE(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA),
  148. SUITE(TLS_ECDHE_RSA_WITH_NULL_SHA),
  149. SUITE(TLS_ECDHE_RSA_WITH_RC4_128_SHA),
  150. SUITE(TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA),
  151. SUITE(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA),
  152. SUITE(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA),
  153. SUITE(TLS_ECDH_anon_WITH_NULL_SHA),
  154. SUITE(TLS_ECDH_anon_WITH_RC4_128_SHA),
  155. SUITE(SSL_RSA_WITH_RC2_CBC_MD5),
  156. SUITE(SSL_RSA_WITH_IDEA_CBC_MD5),
  157. SUITE(SSL_RSA_WITH_DES_CBC_MD5),
  158. SUITE(SSL_RSA_WITH_3DES_EDE_CBC_MD5),
  159. #if defined(__MAC_10_8)
  160. SUITE(TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA),
  161. SUITE(TLS_DHE_DSS_WITH_AES_128_CBC_SHA256),
  162. SUITE(TLS_DHE_DSS_WITH_AES_128_GCM_SHA256),
  163. SUITE(TLS_DHE_DSS_WITH_AES_256_CBC_SHA256),
  164. SUITE(TLS_DHE_DSS_WITH_AES_256_GCM_SHA384),
  165. SUITE(TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA),
  166. SUITE(TLS_DHE_RSA_WITH_AES_128_CBC_SHA256),
  167. SUITE(TLS_DHE_RSA_WITH_AES_128_GCM_SHA256),
  168. SUITE(TLS_DHE_RSA_WITH_AES_256_CBC_SHA256),
  169. SUITE(TLS_DHE_RSA_WITH_AES_256_GCM_SHA384),
  170. SUITE(TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA),
  171. SUITE(TLS_DH_DSS_WITH_AES_128_CBC_SHA256),
  172. SUITE(TLS_DH_DSS_WITH_AES_128_GCM_SHA256),
  173. SUITE(TLS_DH_DSS_WITH_AES_256_CBC_SHA256),
  174. SUITE(TLS_DH_DSS_WITH_AES_256_GCM_SHA384),
  175. SUITE(TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA),
  176. SUITE(TLS_DH_RSA_WITH_AES_128_CBC_SHA256),
  177. SUITE(TLS_DH_RSA_WITH_AES_128_GCM_SHA256),
  178. SUITE(TLS_DH_RSA_WITH_AES_256_CBC_SHA256),
  179. SUITE(TLS_DH_RSA_WITH_AES_256_GCM_SHA384),
  180. SUITE(TLS_DH_anon_WITH_3DES_EDE_CBC_SHA),
  181. SUITE(TLS_DH_anon_WITH_AES_128_CBC_SHA256),
  182. SUITE(TLS_DH_anon_WITH_AES_128_GCM_SHA256),
  183. SUITE(TLS_DH_anon_WITH_AES_256_CBC_SHA256),
  184. SUITE(TLS_DH_anon_WITH_AES_256_GCM_SHA384),
  185. SUITE(TLS_DH_anon_WITH_RC4_128_MD5),
  186. SUITE(TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256),
  187. SUITE(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256),
  188. SUITE(TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384),
  189. SUITE(TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384),
  190. SUITE(TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256),
  191. SUITE(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256),
  192. SUITE(TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384),
  193. SUITE(TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384),
  194. SUITE(TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256),
  195. SUITE(TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256),
  196. SUITE(TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384),
  197. SUITE(TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384),
  198. SUITE(TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256),
  199. SUITE(TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256),
  200. SUITE(TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384),
  201. SUITE(TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384),
  202. SUITE(TLS_EMPTY_RENEGOTIATION_INFO_SCSV),
  203. SUITE(TLS_NULL_WITH_NULL_NULL),
  204. SUITE(TLS_RSA_WITH_3DES_EDE_CBC_SHA),
  205. SUITE(TLS_RSA_WITH_AES_128_CBC_SHA256),
  206. SUITE(TLS_RSA_WITH_AES_128_GCM_SHA256),
  207. SUITE(TLS_RSA_WITH_AES_256_CBC_SHA256),
  208. SUITE(TLS_RSA_WITH_AES_256_GCM_SHA384),
  209. SUITE(TLS_RSA_WITH_NULL_MD5),
  210. SUITE(TLS_RSA_WITH_NULL_SHA),
  211. SUITE(TLS_RSA_WITH_NULL_SHA256),
  212. SUITE(TLS_RSA_WITH_RC4_128_MD5),
  213. SUITE(TLS_RSA_WITH_RC4_128_SHA),
  214. #endif
  215. SUITE(SSL_NO_SUCH_CIPHERSUITE)
  216. };
  217. #undef SUITE
  218. static inline const char* suiteToString(const SSLCipherSuite suite)
  219. {
  220. for (auto & s : kSuites) {
  221. if (s.suite == suite) {
  222. return s.name;
  223. }
  224. }
  225. return "Unknown suite";
  226. }
  227. static const char* kBlocked[] = {
  228. "NULL", "anon", "MD5", "EXPORT", "DES", "IDEA", "NO_SUCH", "EMPTY"
  229. };
  230. static inline bool isBlockedSuite(SSLCipherSuite suite)
  231. {
  232. const char* name = suiteToString(suite);
  233. for (auto& blocked : kBlocked) {
  234. if (strstr(name, blocked)) {
  235. return true;
  236. }
  237. }
  238. return false;
  239. }
  240. typedef std::vector<SSLCipherSuite> SSLCipherSuiteList;
  241. static SSLCipherSuiteList constructEnabledSuites(SSLContextRef ctx)
  242. {
  243. #ifndef CIPHER_CONSTRUCT_ALWAYS
  244. static
  245. #endif
  246. SSLCipherSuiteList rv(0);
  247. #ifndef CIPHER_CONSTRUCT_ALWAYS
  248. if (!rv.empty()) {
  249. return rv;
  250. }
  251. #endif
  252. size_t supported = 0;
  253. OSStatus err = SSLGetNumberSupportedCiphers(ctx, &supported);
  254. if (err != noErr || !supported) {
  255. return rv;
  256. }
  257. rv.resize(supported, SSL_NO_SUCH_CIPHERSUITE);
  258. err = SSLGetSupportedCiphers(ctx, &rv[0], &supported);
  259. if (err != noErr || !supported) {
  260. rv.clear();
  261. return rv;
  262. }
  263. rv.erase(std::remove_if(rv.begin(), rv.end(), isBlockedSuite), rv.end());
  264. return rv;
  265. }
  266. }
  267. namespace aria2 {
  268. TLSSession* TLSSession::make(TLSContext* ctx)
  269. {
  270. return new AppleTLSSession(static_cast<AppleTLSContext*>(ctx));
  271. }
  272. AppleTLSSession::AppleTLSSession(AppleTLSContext* ctx)
  273. : sslCtx_(nullptr),
  274. sockfd_(0),
  275. state_(st_constructed),
  276. lastError_(noErr),
  277. writeBuffered_(0)
  278. {
  279. lastError_ = SSLNewContext(ctx->getSide() == TLS_SERVER, &sslCtx_) == noErr;
  280. if (lastError_ == noErr) {
  281. state_ = st_error;
  282. return;
  283. }
  284. #if defined(__MAC_10_8)
  285. (void)SSLSetProtocolVersionMin(sslCtx_, kSSLProtocol3);
  286. (void)SSLSetProtocolVersionMax(sslCtx_, kTLSProtocol12);
  287. #else
  288. (void)SSLSetProtocolVersionEnabled(sslCtx_, kSSLProtocolAll, false);
  289. (void)SSLSetProtocolVersionEnabled(sslCtx_, kSSLProtocol3, true);
  290. (void)SSLSetProtocolVersionEnabled(sslCtx_, kTLSProtocol1, true);
  291. (void)SSLSetProtocolVersionEnabled(sslCtx_, kTLSProtocol11, true);
  292. (void)SSLSetProtocolVersionEnabled(sslCtx_, kTLSProtocol12, true);
  293. #endif
  294. (void)SSLSetEnableCertVerify(sslCtx_, ctx->getVerifyPeer());
  295. #ifndef CIPHER_ENABLE_ALL
  296. SSLCipherSuiteList enabled = constructEnabledSuites(sslCtx_);
  297. if (enabled.empty()) {
  298. A2_LOG_ERROR("AppleTLS: Failed to construct enabled ciphers list");
  299. state_ = st_error;
  300. return;
  301. }
  302. for (const auto& suite: enabled) {
  303. A2_LOG_INFO(fmt("AppleTLS: Enabled suite %s", suiteToString(suite)));
  304. }
  305. if (SSLSetEnabledCiphers(sslCtx_, &enabled[0], enabled.size()) != noErr) {
  306. A2_LOG_ERROR("AppleTLS: Failed to set enabled ciphers list");
  307. state_ = st_error;
  308. return;
  309. }
  310. #endif
  311. SecIdentityRef creds = ctx->getCredentials();
  312. if (!creds) {
  313. if (ctx->getSide() != TLS_SERVER) {
  314. // Done with client-only initialization
  315. return;
  316. }
  317. A2_LOG_ERROR("AppleTLS: No credentials");
  318. state_ = st_error;
  319. return;
  320. }
  321. CFArrayRef certs = CFArrayCreate(nullptr, (const void**)&creds, 1, nullptr);
  322. if (!certs) {
  323. A2_LOG_ERROR("AppleTLS: Failed to setup credentials");
  324. state_ = st_error;
  325. return;
  326. }
  327. std::unique_ptr<void, decltype(&CFRelease)> del_certs((void*)certs, CFRelease);
  328. lastError_ = SSLSetCertificate(sslCtx_, certs);
  329. if (lastError_ != noErr) {
  330. A2_LOG_ERROR(fmt("AppleTLS: Failed to set credentials: %s", getLastErrorString().c_str()));
  331. state_ = st_error;
  332. return;
  333. }
  334. #ifndef CIPHER_NO_DHPARAM
  335. lastError_ = SSLSetDiffieHellmanParams(sslCtx_, dhparam, sizeof(dhparam));
  336. if (lastError_ != noErr) {
  337. A2_LOG_WARN(fmt("AppleTLS: Failed to set DHParams: %s", getLastErrorString().c_str()));
  338. // Engine will still generate some for us, so this is no problem, except
  339. // it will take longer.
  340. }
  341. #endif // CIPHER_NO_DHPARAM
  342. }
  343. AppleTLSSession::~AppleTLSSession()
  344. {
  345. closeConnection();
  346. if (sslCtx_) {
  347. SSLDisposeContext(sslCtx_);
  348. sslCtx_ = nullptr;
  349. }
  350. state_ = st_error;
  351. }
  352. int AppleTLSSession::init(sock_t sockfd)
  353. {
  354. if (state_ != st_constructed) {
  355. lastError_ = noErr;
  356. return TLS_ERR_ERROR;
  357. }
  358. lastError_ = SSLSetIOFuncs(sslCtx_, SocketRead, SocketWrite);
  359. if (lastError_ != noErr) {
  360. state_ = st_error;
  361. return TLS_ERR_ERROR;
  362. }
  363. lastError_ = SSLSetConnection(sslCtx_, this);
  364. if (lastError_ != noErr) {
  365. state_ = st_error;
  366. return TLS_ERR_ERROR;
  367. }
  368. sockfd_ = sockfd;
  369. state_ = st_initialized;
  370. return TLS_ERR_OK;
  371. }
  372. int AppleTLSSession::setSNIHostname(const std::string& hostname)
  373. {
  374. if (state_ != st_initialized) {
  375. lastError_ = noErr;
  376. return TLS_ERR_ERROR;
  377. }
  378. lastError_ = SSLSetPeerDomainName(sslCtx_, hostname.c_str(), hostname.length());
  379. return (lastError_ != noErr) ? TLS_ERR_ERROR : TLS_ERR_OK;
  380. }
  381. int AppleTLSSession::closeConnection()
  382. {
  383. if (state_ != st_connected) {
  384. lastError_ = noErr;
  385. return TLS_ERR_ERROR;
  386. }
  387. lastError_ = SSLClose(sslCtx_);
  388. state_ = st_closed;
  389. return lastError_ == noErr ? TLS_ERR_OK : TLS_ERR_ERROR;
  390. }
  391. int AppleTLSSession::checkDirection() {
  392. // See: https://github.com/tatsuhiro-t/aria2/pull/61#issuecomment-16051793
  393. if (state_ == st_connected) {
  394. // Need to check read first, as SocketCore kinda expects this
  395. size_t buffered;
  396. lastError_ = SSLGetBufferedReadSize(sslCtx_, &buffered);
  397. if (lastError_ == noErr && buffered) {
  398. return TLS_WANT_READ;
  399. }
  400. }
  401. if (writeBuffered_) {
  402. return TLS_WANT_WRITE;
  403. }
  404. // Default to WANT_READ, as SocketCore kinda expects this
  405. return TLS_WANT_READ;
  406. }
  407. ssize_t AppleTLSSession::writeData(const void* data, size_t len)
  408. {
  409. if (state_ != st_connected) {
  410. lastError_ = noErr;
  411. return TLS_ERR_ERROR;
  412. }
  413. size_t processed = 0;
  414. if (writeBuffered_) {
  415. lastError_ = SSLWrite(sslCtx_, nullptr, 0, &processed);
  416. switch (lastError_) {
  417. case noErr:
  418. processed = writeBuffered_;
  419. writeBuffered_ = 0;
  420. return processed;
  421. case errSSLWouldBlock:
  422. return TLS_ERR_WOULDBLOCK;
  423. case errSSLClosedGraceful:
  424. case errSSLClosedNoNotify:
  425. closeConnection();
  426. return TLS_ERR_ERROR;
  427. default:
  428. closeConnection();
  429. state_ = st_error;
  430. return TLS_ERR_ERROR;
  431. }
  432. }
  433. lastError_ = SSLWrite(sslCtx_, data, len, &processed);
  434. switch (lastError_) {
  435. case noErr:
  436. return processed;
  437. case errSSLWouldBlock:
  438. writeBuffered_ = len;
  439. return TLS_ERR_WOULDBLOCK;
  440. case errSSLClosedGraceful:
  441. case errSSLClosedNoNotify:
  442. closeConnection();
  443. return TLS_ERR_ERROR;
  444. default:
  445. closeConnection();
  446. state_ = st_error;
  447. return TLS_ERR_ERROR;
  448. }
  449. }
  450. OSStatus AppleTLSSession::sockWrite(const void* data, size_t* len)
  451. {
  452. size_t remain = *len;
  453. const uint8_t *buffer = static_cast<const uint8_t*>(data);
  454. *len = 0;
  455. while (remain) {
  456. ssize_t w = write(sockfd_, buffer, remain);
  457. if (w <= 0) {
  458. switch (errno) {
  459. case EAGAIN:
  460. return errSSLWouldBlock;
  461. default:
  462. return errSSLClosedAbort;
  463. }
  464. }
  465. remain -= w;
  466. buffer += w;
  467. *len += w;
  468. }
  469. return noErr;
  470. }
  471. ssize_t AppleTLSSession::readData(void* data, size_t len)
  472. {
  473. if (state_ != st_connected) {
  474. lastError_ = noErr;
  475. return TLS_ERR_ERROR;
  476. }
  477. size_t processed = 0;
  478. lastError_ = SSLRead(sslCtx_, data, len, &processed);
  479. switch (lastError_) {
  480. case noErr:
  481. return processed;
  482. case errSSLWouldBlock:
  483. if (processed) {
  484. return processed;
  485. }
  486. return TLS_ERR_WOULDBLOCK;
  487. case errSSLClosedGraceful:
  488. case errSSLClosedNoNotify:
  489. closeConnection();
  490. return TLS_ERR_ERROR;
  491. default:
  492. closeConnection();
  493. state_ = st_error;
  494. return TLS_ERR_ERROR;
  495. }
  496. }
  497. OSStatus AppleTLSSession::sockRead(void* data, size_t* len)
  498. {
  499. size_t remain = *len;
  500. uint8_t *buffer = static_cast<uint8_t*>(data);
  501. *len = 0;
  502. while (remain) {
  503. ssize_t r = read(sockfd_, buffer, remain);
  504. if (r == 0) {
  505. return errSSLClosedGraceful;
  506. }
  507. if (r < 0) {
  508. switch (errno) {
  509. case ENOENT:
  510. return errSSLClosedGraceful;
  511. case ECONNRESET:
  512. return errSSLClosedAbort;
  513. case EAGAIN:
  514. return errSSLWouldBlock;
  515. default:
  516. return errSSLClosedAbort;
  517. }
  518. }
  519. remain -= r;
  520. buffer += r;
  521. *len += r;
  522. }
  523. return noErr;
  524. }
  525. int AppleTLSSession::tlsConnect(const std::string& hostname, std::string& handshakeErr)
  526. {
  527. if (state_ != st_initialized) {
  528. return TLS_ERR_ERROR;
  529. }
  530. if (!hostname.empty()) {
  531. setSNIHostname(hostname);
  532. }
  533. lastError_ = SSLHandshake(sslCtx_);
  534. switch (lastError_) {
  535. case noErr:
  536. break;
  537. case errSSLWouldBlock:
  538. return TLS_ERR_WOULDBLOCK;
  539. case errSSLServerAuthCompleted:
  540. return tlsConnect(hostname, handshakeErr);
  541. default:
  542. handshakeErr = getLastErrorString();
  543. return TLS_ERR_ERROR;
  544. }
  545. state_ = st_connected;
  546. SSLProtocol proto = kSSLProtocolUnknown;
  547. (void)SSLGetNegotiatedProtocolVersion(sslCtx_, &proto);
  548. SSLCipherSuite suite = SSL_NO_SUCH_CIPHERSUITE;
  549. (void)SSLGetNegotiatedCipher(sslCtx_, &suite);
  550. A2_LOG_INFO(fmt("AppleTLS: Connected to %s with %s (%s)",
  551. hostname.c_str(),
  552. protoToString(proto),
  553. suiteToString(suite)));
  554. return TLS_ERR_OK;
  555. }
  556. int AppleTLSSession::tlsAccept()
  557. {
  558. std::string hostname, err;
  559. return tlsConnect(hostname, err);
  560. }
  561. std::string AppleTLSSession::getLastErrorString()
  562. {
  563. switch (lastError_) {
  564. case errSSLProtocol:
  565. return "Protocol error";
  566. case errSSLNegotiation:
  567. return "No common cipher suites";
  568. case errSSLFatalAlert:
  569. return "Received fatal alert";
  570. case errSSLSessionNotFound:
  571. return "Unknown session";
  572. case errSSLClosedGraceful:
  573. return "Closed gracefully";
  574. case errSSLClosedAbort:
  575. return "Connection aborted";
  576. case errSSLXCertChainInvalid:
  577. return "Invalid certificate chain";
  578. case errSSLBadCert:
  579. return "Invalid certificate format";
  580. case errSSLCrypto:
  581. return "Cryptographic error";
  582. case paramErr:
  583. case errSSLInternal:
  584. return "Internal SSL error";
  585. case errSSLUnknownRootCert:
  586. return "Self-signed certificate";
  587. case errSSLNoRootCert:
  588. return "No root certificate";
  589. case errSSLCertExpired:
  590. return "Certificate expired";
  591. case errSSLCertNotYetValid:
  592. return "Certificate not yet valid";
  593. case errSSLClosedNoNotify:
  594. return "Closed without notification";
  595. case errSSLBufferOverflow:
  596. return "Buffer not large enough";
  597. case errSSLBadCipherSuite:
  598. return "Bad cipher suite";
  599. case errSSLPeerUnexpectedMsg:
  600. return "Unexpected peer message";
  601. case errSSLPeerBadRecordMac:
  602. return "Bad MAC";
  603. case errSSLPeerDecryptionFail:
  604. return "Decryption failure";
  605. case errSSLHostNameMismatch:
  606. return "Invalid hostname";
  607. case errSSLConnectionRefused:
  608. return "Connection refused";
  609. default:
  610. return fmt("Unspecified error %d", lastError_);
  611. }
  612. }
  613. }