vtls.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) 1998 - 2016, Daniel Stenberg, <[email protected]>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.haxx.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. ***************************************************************************/
  22. /* This file is for implementing all "generic" SSL functions that all libcurl
  23. internals should use. It is then responsible for calling the proper
  24. "backend" function.
  25. SSL-functions in libcurl should call functions in this source file, and not
  26. to any specific SSL-layer.
  27. Curl_ssl_ - prefix for generic ones
  28. Curl_ossl_ - prefix for OpenSSL ones
  29. Curl_gtls_ - prefix for GnuTLS ones
  30. Curl_nss_ - prefix for NSS ones
  31. Curl_gskit_ - prefix for GSKit ones
  32. Curl_polarssl_ - prefix for PolarSSL ones
  33. Curl_cyassl_ - prefix for CyaSSL ones
  34. Curl_schannel_ - prefix for Schannel SSPI ones
  35. Curl_darwinssl_ - prefix for SecureTransport (Darwin) ones
  36. Note that this source code uses curlssl_* functions, and they are all
  37. defines/macros #defined by the lib-specific header files.
  38. "SSL/TLS Strong Encryption: An Introduction"
  39. https://httpd.apache.org/docs/2.0/ssl/ssl_intro.html
  40. */
  41. #include "curl_setup.h"
  42. #ifdef HAVE_SYS_TYPES_H
  43. #include <sys/types.h>
  44. #endif
  45. #ifdef HAVE_SYS_STAT_H
  46. #include <sys/stat.h>
  47. #endif
  48. #ifdef HAVE_FCNTL_H
  49. #include <fcntl.h>
  50. #endif
  51. #include "urldata.h"
  52. #include "vtls.h" /* generic SSL protos etc */
  53. #include "slist.h"
  54. #include "sendf.h"
  55. #include "strcase.h"
  56. #include "url.h"
  57. #include "progress.h"
  58. #include "share.h"
  59. #include "multiif.h"
  60. #include "timeval.h"
  61. #include "curl_md5.h"
  62. #include "warnless.h"
  63. #include "curl_base64.h"
  64. #include "curl_printf.h"
  65. /* The last #include files should be: */
  66. #include "curl_memory.h"
  67. #include "memdebug.h"
  68. /* convenience macro to check if this handle is using a shared SSL session */
  69. #define SSLSESSION_SHARED(data) (data->share && \
  70. (data->share->specifier & \
  71. (1<<CURL_LOCK_DATA_SSL_SESSION)))
  72. #define CLONE_STRING(var) \
  73. if(source->var) { \
  74. dest->var = strdup(source->var); \
  75. if(!dest->var) \
  76. return FALSE; \
  77. } \
  78. else \
  79. dest->var = NULL;
  80. bool
  81. Curl_ssl_config_matches(struct ssl_primary_config* data,
  82. struct ssl_primary_config* needle)
  83. {
  84. if((data->version == needle->version) &&
  85. (data->verifypeer == needle->verifypeer) &&
  86. (data->verifyhost == needle->verifyhost) &&
  87. Curl_safe_strcasecompare(data->CApath, needle->CApath) &&
  88. Curl_safe_strcasecompare(data->CAfile, needle->CAfile) &&
  89. Curl_safe_strcasecompare(data->clientcert, needle->clientcert) &&
  90. Curl_safe_strcasecompare(data->cipher_list, needle->cipher_list))
  91. return TRUE;
  92. return FALSE;
  93. }
  94. bool
  95. Curl_clone_primary_ssl_config(struct ssl_primary_config *source,
  96. struct ssl_primary_config *dest)
  97. {
  98. dest->verifyhost = source->verifyhost;
  99. dest->verifypeer = source->verifypeer;
  100. dest->version = source->version;
  101. CLONE_STRING(CAfile);
  102. CLONE_STRING(CApath);
  103. CLONE_STRING(cipher_list);
  104. CLONE_STRING(egdsocket);
  105. CLONE_STRING(random_file);
  106. CLONE_STRING(clientcert);
  107. return TRUE;
  108. }
  109. void Curl_free_primary_ssl_config(struct ssl_primary_config* sslc)
  110. {
  111. Curl_safefree(sslc->CAfile);
  112. Curl_safefree(sslc->CApath);
  113. Curl_safefree(sslc->cipher_list);
  114. Curl_safefree(sslc->egdsocket);
  115. Curl_safefree(sslc->random_file);
  116. Curl_safefree(sslc->clientcert);
  117. }
  118. int Curl_ssl_backend(void)
  119. {
  120. return (int)CURL_SSL_BACKEND;
  121. }
  122. #ifdef USE_SSL
  123. /* "global" init done? */
  124. static bool init_ssl=FALSE;
  125. /**
  126. * Global SSL init
  127. *
  128. * @retval 0 error initializing SSL
  129. * @retval 1 SSL initialized successfully
  130. */
  131. int Curl_ssl_init(void)
  132. {
  133. /* make sure this is only done once */
  134. if(init_ssl)
  135. return 1;
  136. init_ssl = TRUE; /* never again */
  137. return curlssl_init();
  138. }
  139. /* Global cleanup */
  140. void Curl_ssl_cleanup(void)
  141. {
  142. if(init_ssl) {
  143. /* only cleanup if we did a previous init */
  144. curlssl_cleanup();
  145. init_ssl = FALSE;
  146. }
  147. }
  148. static bool ssl_prefs_check(struct Curl_easy *data)
  149. {
  150. /* check for CURLOPT_SSLVERSION invalid parameter value */
  151. if((data->set.ssl.primary.version < 0)
  152. || (data->set.ssl.primary.version >= CURL_SSLVERSION_LAST)) {
  153. failf(data, "Unrecognized parameter value passed via CURLOPT_SSLVERSION");
  154. return FALSE;
  155. }
  156. return TRUE;
  157. }
  158. static CURLcode
  159. ssl_connect_init_proxy(struct connectdata *conn, int sockindex)
  160. {
  161. DEBUGASSERT(conn->bits.proxy_ssl_connected[sockindex]);
  162. if(ssl_connection_complete == conn->ssl[sockindex].state &&
  163. !conn->proxy_ssl[sockindex].use) {
  164. #if defined(HTTPS_PROXY_SUPPORT)
  165. conn->proxy_ssl[sockindex] = conn->ssl[sockindex];
  166. memset(&conn->ssl[sockindex], 0, sizeof(conn->ssl[sockindex]));
  167. #else
  168. return CURLE_NOT_BUILT_IN;
  169. #endif
  170. }
  171. return CURLE_OK;
  172. }
  173. CURLcode
  174. Curl_ssl_connect(struct connectdata *conn, int sockindex)
  175. {
  176. CURLcode result;
  177. if(conn->bits.proxy_ssl_connected[sockindex]) {
  178. result = ssl_connect_init_proxy(conn, sockindex);
  179. if(result)
  180. return result;
  181. }
  182. if(!ssl_prefs_check(conn->data))
  183. return CURLE_SSL_CONNECT_ERROR;
  184. /* mark this is being ssl-enabled from here on. */
  185. conn->ssl[sockindex].use = TRUE;
  186. conn->ssl[sockindex].state = ssl_connection_negotiating;
  187. result = curlssl_connect(conn, sockindex);
  188. if(!result)
  189. Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
  190. return result;
  191. }
  192. CURLcode
  193. Curl_ssl_connect_nonblocking(struct connectdata *conn, int sockindex,
  194. bool *done)
  195. {
  196. CURLcode result;
  197. if(conn->bits.proxy_ssl_connected[sockindex]) {
  198. result = ssl_connect_init_proxy(conn, sockindex);
  199. if(result)
  200. return result;
  201. }
  202. if(!ssl_prefs_check(conn->data))
  203. return CURLE_SSL_CONNECT_ERROR;
  204. /* mark this is being ssl requested from here on. */
  205. conn->ssl[sockindex].use = TRUE;
  206. #ifdef curlssl_connect_nonblocking
  207. result = curlssl_connect_nonblocking(conn, sockindex, done);
  208. #else
  209. *done = TRUE; /* fallback to BLOCKING */
  210. result = curlssl_connect(conn, sockindex);
  211. #endif /* non-blocking connect support */
  212. if(!result && *done)
  213. Curl_pgrsTime(conn->data, TIMER_APPCONNECT); /* SSL is connected */
  214. return result;
  215. }
  216. /*
  217. * Lock shared SSL session data
  218. */
  219. void Curl_ssl_sessionid_lock(struct connectdata *conn)
  220. {
  221. if(SSLSESSION_SHARED(conn->data))
  222. Curl_share_lock(conn->data,
  223. CURL_LOCK_DATA_SSL_SESSION, CURL_LOCK_ACCESS_SINGLE);
  224. }
  225. /*
  226. * Unlock shared SSL session data
  227. */
  228. void Curl_ssl_sessionid_unlock(struct connectdata *conn)
  229. {
  230. if(SSLSESSION_SHARED(conn->data))
  231. Curl_share_unlock(conn->data, CURL_LOCK_DATA_SSL_SESSION);
  232. }
  233. /*
  234. * Check if there's a session ID for the given connection in the cache, and if
  235. * there's one suitable, it is provided. Returns TRUE when no entry matched.
  236. */
  237. bool Curl_ssl_getsessionid(struct connectdata *conn,
  238. void **ssl_sessionid,
  239. size_t *idsize, /* set 0 if unknown */
  240. int sockindex)
  241. {
  242. struct curl_ssl_session *check;
  243. struct Curl_easy *data = conn->data;
  244. size_t i;
  245. long *general_age;
  246. bool no_match = TRUE;
  247. const bool isProxy = CONNECT_PROXY_SSL();
  248. struct ssl_primary_config * const ssl_config = isProxy ?
  249. &conn->proxy_ssl_config :
  250. &conn->ssl_config;
  251. const char * const name = isProxy ? conn->http_proxy.host.name :
  252. conn->host.name;
  253. int port = isProxy ? (int)conn->port : conn->remote_port;
  254. *ssl_sessionid = NULL;
  255. DEBUGASSERT(data->set.general_ssl.sessionid);
  256. if(!data->set.general_ssl.sessionid)
  257. /* session ID re-use is disabled */
  258. return TRUE;
  259. /* Lock if shared */
  260. if(SSLSESSION_SHARED(data))
  261. general_age = &data->share->sessionage;
  262. else
  263. general_age = &data->state.sessionage;
  264. for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) {
  265. check = &data->state.session[i];
  266. if(!check->sessionid)
  267. /* not session ID means blank entry */
  268. continue;
  269. if(strcasecompare(name, check->name) &&
  270. ((!conn->bits.conn_to_host && !check->conn_to_host) ||
  271. (conn->bits.conn_to_host && check->conn_to_host &&
  272. strcasecompare(conn->conn_to_host.name, check->conn_to_host))) &&
  273. ((!conn->bits.conn_to_port && check->conn_to_port == -1) ||
  274. (conn->bits.conn_to_port && check->conn_to_port != -1 &&
  275. conn->conn_to_port == check->conn_to_port)) &&
  276. (port == check->remote_port) &&
  277. strcasecompare(conn->handler->scheme, check->scheme) &&
  278. Curl_ssl_config_matches(ssl_config, &check->ssl_config)) {
  279. /* yes, we have a session ID! */
  280. (*general_age)++; /* increase general age */
  281. check->age = *general_age; /* set this as used in this age */
  282. *ssl_sessionid = check->sessionid;
  283. if(idsize)
  284. *idsize = check->idsize;
  285. no_match = FALSE;
  286. break;
  287. }
  288. }
  289. return no_match;
  290. }
  291. /*
  292. * Kill a single session ID entry in the cache.
  293. */
  294. void Curl_ssl_kill_session(struct curl_ssl_session *session)
  295. {
  296. if(session->sessionid) {
  297. /* defensive check */
  298. /* free the ID the SSL-layer specific way */
  299. curlssl_session_free(session->sessionid);
  300. session->sessionid = NULL;
  301. session->age = 0; /* fresh */
  302. Curl_free_primary_ssl_config(&session->ssl_config);
  303. Curl_safefree(session->name);
  304. Curl_safefree(session->conn_to_host);
  305. }
  306. }
  307. /*
  308. * Delete the given session ID from the cache.
  309. */
  310. void Curl_ssl_delsessionid(struct connectdata *conn, void *ssl_sessionid)
  311. {
  312. size_t i;
  313. struct Curl_easy *data=conn->data;
  314. for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++) {
  315. struct curl_ssl_session *check = &data->state.session[i];
  316. if(check->sessionid == ssl_sessionid) {
  317. Curl_ssl_kill_session(check);
  318. break;
  319. }
  320. }
  321. }
  322. /*
  323. * Store session id in the session cache. The ID passed on to this function
  324. * must already have been extracted and allocated the proper way for the SSL
  325. * layer. Curl_XXXX_session_free() will be called to free/kill the session ID
  326. * later on.
  327. */
  328. CURLcode Curl_ssl_addsessionid(struct connectdata *conn,
  329. void *ssl_sessionid,
  330. size_t idsize,
  331. int sockindex)
  332. {
  333. size_t i;
  334. struct Curl_easy *data=conn->data; /* the mother of all structs */
  335. struct curl_ssl_session *store = &data->state.session[0];
  336. long oldest_age=data->state.session[0].age; /* zero if unused */
  337. char *clone_host;
  338. char *clone_conn_to_host;
  339. int conn_to_port;
  340. long *general_age;
  341. const bool isProxy = CONNECT_PROXY_SSL();
  342. struct ssl_primary_config * const ssl_config = isProxy ?
  343. &conn->proxy_ssl_config :
  344. &conn->ssl_config;
  345. DEBUGASSERT(data->set.general_ssl.sessionid);
  346. clone_host = strdup(isProxy ? conn->http_proxy.host.name : conn->host.name);
  347. if(!clone_host)
  348. return CURLE_OUT_OF_MEMORY; /* bail out */
  349. if(conn->bits.conn_to_host) {
  350. clone_conn_to_host = strdup(conn->conn_to_host.name);
  351. if(!clone_conn_to_host) {
  352. free(clone_host);
  353. return CURLE_OUT_OF_MEMORY; /* bail out */
  354. }
  355. }
  356. else
  357. clone_conn_to_host = NULL;
  358. if(conn->bits.conn_to_port)
  359. conn_to_port = conn->conn_to_port;
  360. else
  361. conn_to_port = -1;
  362. /* Now we should add the session ID and the host name to the cache, (remove
  363. the oldest if necessary) */
  364. /* If using shared SSL session, lock! */
  365. if(SSLSESSION_SHARED(data)) {
  366. general_age = &data->share->sessionage;
  367. }
  368. else {
  369. general_age = &data->state.sessionage;
  370. }
  371. /* find an empty slot for us, or find the oldest */
  372. for(i = 1; (i < data->set.general_ssl.max_ssl_sessions) &&
  373. data->state.session[i].sessionid; i++) {
  374. if(data->state.session[i].age < oldest_age) {
  375. oldest_age = data->state.session[i].age;
  376. store = &data->state.session[i];
  377. }
  378. }
  379. if(i == data->set.general_ssl.max_ssl_sessions)
  380. /* cache is full, we must "kill" the oldest entry! */
  381. Curl_ssl_kill_session(store);
  382. else
  383. store = &data->state.session[i]; /* use this slot */
  384. /* now init the session struct wisely */
  385. store->sessionid = ssl_sessionid;
  386. store->idsize = idsize;
  387. store->age = *general_age; /* set current age */
  388. /* free it if there's one already present */
  389. free(store->name);
  390. free(store->conn_to_host);
  391. store->name = clone_host; /* clone host name */
  392. store->conn_to_host = clone_conn_to_host; /* clone connect to host name */
  393. store->conn_to_port = conn_to_port; /* connect to port number */
  394. /* port number */
  395. store->remote_port = isProxy ? (int)conn->port : conn->remote_port;
  396. store->scheme = conn->handler->scheme;
  397. if(!Curl_clone_primary_ssl_config(ssl_config, &store->ssl_config)) {
  398. store->sessionid = NULL; /* let caller free sessionid */
  399. free(clone_host);
  400. free(clone_conn_to_host);
  401. return CURLE_OUT_OF_MEMORY;
  402. }
  403. return CURLE_OK;
  404. }
  405. void Curl_ssl_close_all(struct Curl_easy *data)
  406. {
  407. size_t i;
  408. /* kill the session ID cache if not shared */
  409. if(data->state.session && !SSLSESSION_SHARED(data)) {
  410. for(i = 0; i < data->set.general_ssl.max_ssl_sessions; i++)
  411. /* the single-killer function handles empty table slots */
  412. Curl_ssl_kill_session(&data->state.session[i]);
  413. /* free the cache data */
  414. Curl_safefree(data->state.session);
  415. }
  416. curlssl_close_all(data);
  417. }
  418. #if defined(USE_SSLEAY) || defined(USE_GNUTLS) || defined(USE_SCHANNEL) || \
  419. defined(USE_DARWINSSL) || defined(USE_NSS)
  420. /* This function is for OpenSSL, GnuTLS, darwinssl, and schannel only. */
  421. int Curl_ssl_getsock(struct connectdata *conn, curl_socket_t *socks,
  422. int numsocks)
  423. {
  424. struct ssl_connect_data *connssl = &conn->ssl[FIRSTSOCKET];
  425. if(!numsocks)
  426. return GETSOCK_BLANK;
  427. if(connssl->connecting_state == ssl_connect_2_writing) {
  428. /* write mode */
  429. socks[0] = conn->sock[FIRSTSOCKET];
  430. return GETSOCK_WRITESOCK(0);
  431. }
  432. else if(connssl->connecting_state == ssl_connect_2_reading) {
  433. /* read mode */
  434. socks[0] = conn->sock[FIRSTSOCKET];
  435. return GETSOCK_READSOCK(0);
  436. }
  437. return GETSOCK_BLANK;
  438. }
  439. #else
  440. int Curl_ssl_getsock(struct connectdata *conn,
  441. curl_socket_t *socks,
  442. int numsocks)
  443. {
  444. (void)conn;
  445. (void)socks;
  446. (void)numsocks;
  447. return GETSOCK_BLANK;
  448. }
  449. /* USE_SSLEAY || USE_GNUTLS || USE_SCHANNEL || USE_DARWINSSL || USE_NSS */
  450. #endif
  451. void Curl_ssl_close(struct connectdata *conn, int sockindex)
  452. {
  453. DEBUGASSERT((sockindex <= 1) && (sockindex >= -1));
  454. curlssl_close(conn, sockindex);
  455. }
  456. CURLcode Curl_ssl_shutdown(struct connectdata *conn, int sockindex)
  457. {
  458. if(curlssl_shutdown(conn, sockindex))
  459. return CURLE_SSL_SHUTDOWN_FAILED;
  460. conn->ssl[sockindex].use = FALSE; /* get back to ordinary socket usage */
  461. conn->ssl[sockindex].state = ssl_connection_none;
  462. conn->recv[sockindex] = Curl_recv_plain;
  463. conn->send[sockindex] = Curl_send_plain;
  464. return CURLE_OK;
  465. }
  466. /* Selects an SSL crypto engine
  467. */
  468. CURLcode Curl_ssl_set_engine(struct Curl_easy *data, const char *engine)
  469. {
  470. return curlssl_set_engine(data, engine);
  471. }
  472. /* Selects the default SSL crypto engine
  473. */
  474. CURLcode Curl_ssl_set_engine_default(struct Curl_easy *data)
  475. {
  476. return curlssl_set_engine_default(data);
  477. }
  478. /* Return list of OpenSSL crypto engine names. */
  479. struct curl_slist *Curl_ssl_engines_list(struct Curl_easy *data)
  480. {
  481. return curlssl_engines_list(data);
  482. }
  483. /*
  484. * This sets up a session ID cache to the specified size. Make sure this code
  485. * is agnostic to what underlying SSL technology we use.
  486. */
  487. CURLcode Curl_ssl_initsessions(struct Curl_easy *data, size_t amount)
  488. {
  489. struct curl_ssl_session *session;
  490. if(data->state.session)
  491. /* this is just a precaution to prevent multiple inits */
  492. return CURLE_OK;
  493. session = calloc(amount, sizeof(struct curl_ssl_session));
  494. if(!session)
  495. return CURLE_OUT_OF_MEMORY;
  496. /* store the info in the SSL section */
  497. data->set.general_ssl.max_ssl_sessions = amount;
  498. data->state.session = session;
  499. data->state.sessionage = 1; /* this is brand new */
  500. return CURLE_OK;
  501. }
  502. size_t Curl_ssl_version(char *buffer, size_t size)
  503. {
  504. return curlssl_version(buffer, size);
  505. }
  506. /*
  507. * This function tries to determine connection status.
  508. *
  509. * Return codes:
  510. * 1 means the connection is still in place
  511. * 0 means the connection has been closed
  512. * -1 means the connection status is unknown
  513. */
  514. int Curl_ssl_check_cxn(struct connectdata *conn)
  515. {
  516. return curlssl_check_cxn(conn);
  517. }
  518. bool Curl_ssl_data_pending(const struct connectdata *conn,
  519. int connindex)
  520. {
  521. return curlssl_data_pending(conn, connindex);
  522. }
  523. void Curl_ssl_free_certinfo(struct Curl_easy *data)
  524. {
  525. int i;
  526. struct curl_certinfo *ci = &data->info.certs;
  527. if(ci->num_of_certs) {
  528. /* free all individual lists used */
  529. for(i=0; i<ci->num_of_certs; i++) {
  530. curl_slist_free_all(ci->certinfo[i]);
  531. ci->certinfo[i] = NULL;
  532. }
  533. free(ci->certinfo); /* free the actual array too */
  534. ci->certinfo = NULL;
  535. ci->num_of_certs = 0;
  536. }
  537. }
  538. CURLcode Curl_ssl_init_certinfo(struct Curl_easy *data, int num)
  539. {
  540. struct curl_certinfo *ci = &data->info.certs;
  541. struct curl_slist **table;
  542. /* Free any previous certificate information structures */
  543. Curl_ssl_free_certinfo(data);
  544. /* Allocate the required certificate information structures */
  545. table = calloc((size_t) num, sizeof(struct curl_slist *));
  546. if(!table)
  547. return CURLE_OUT_OF_MEMORY;
  548. ci->num_of_certs = num;
  549. ci->certinfo = table;
  550. return CURLE_OK;
  551. }
  552. /*
  553. * 'value' is NOT a zero terminated string
  554. */
  555. CURLcode Curl_ssl_push_certinfo_len(struct Curl_easy *data,
  556. int certnum,
  557. const char *label,
  558. const char *value,
  559. size_t valuelen)
  560. {
  561. struct curl_certinfo *ci = &data->info.certs;
  562. char *output;
  563. struct curl_slist *nl;
  564. CURLcode result = CURLE_OK;
  565. size_t labellen = strlen(label);
  566. size_t outlen = labellen + 1 + valuelen + 1; /* label:value\0 */
  567. output = malloc(outlen);
  568. if(!output)
  569. return CURLE_OUT_OF_MEMORY;
  570. /* sprintf the label and colon */
  571. snprintf(output, outlen, "%s:", label);
  572. /* memcpy the value (it might not be zero terminated) */
  573. memcpy(&output[labellen+1], value, valuelen);
  574. /* zero terminate the output */
  575. output[labellen + 1 + valuelen] = 0;
  576. nl = Curl_slist_append_nodup(ci->certinfo[certnum], output);
  577. if(!nl) {
  578. free(output);
  579. curl_slist_free_all(ci->certinfo[certnum]);
  580. result = CURLE_OUT_OF_MEMORY;
  581. }
  582. ci->certinfo[certnum] = nl;
  583. return result;
  584. }
  585. /*
  586. * This is a convenience function for push_certinfo_len that takes a zero
  587. * terminated value.
  588. */
  589. CURLcode Curl_ssl_push_certinfo(struct Curl_easy *data,
  590. int certnum,
  591. const char *label,
  592. const char *value)
  593. {
  594. size_t valuelen = strlen(value);
  595. return Curl_ssl_push_certinfo_len(data, certnum, label, value, valuelen);
  596. }
  597. CURLcode Curl_ssl_random(struct Curl_easy *data,
  598. unsigned char *entropy,
  599. size_t length)
  600. {
  601. int rc = curlssl_random(data, entropy, length);
  602. if(rc) {
  603. failf(data, "PRNG seeding failed");
  604. return CURLE_FAILED_INIT; /* possibly weird return code */
  605. }
  606. return CURLE_OK;
  607. }
  608. /*
  609. * Public key pem to der conversion
  610. */
  611. static CURLcode pubkey_pem_to_der(const char *pem,
  612. unsigned char **der, size_t *der_len)
  613. {
  614. char *stripped_pem, *begin_pos, *end_pos;
  615. size_t pem_count, stripped_pem_count = 0, pem_len;
  616. CURLcode result;
  617. /* if no pem, exit. */
  618. if(!pem)
  619. return CURLE_BAD_CONTENT_ENCODING;
  620. begin_pos = strstr(pem, "-----BEGIN PUBLIC KEY-----");
  621. if(!begin_pos)
  622. return CURLE_BAD_CONTENT_ENCODING;
  623. pem_count = begin_pos - pem;
  624. /* Invalid if not at beginning AND not directly following \n */
  625. if(0 != pem_count && '\n' != pem[pem_count - 1])
  626. return CURLE_BAD_CONTENT_ENCODING;
  627. /* 26 is length of "-----BEGIN PUBLIC KEY-----" */
  628. pem_count += 26;
  629. /* Invalid if not directly following \n */
  630. end_pos = strstr(pem + pem_count, "\n-----END PUBLIC KEY-----");
  631. if(!end_pos)
  632. return CURLE_BAD_CONTENT_ENCODING;
  633. pem_len = end_pos - pem;
  634. stripped_pem = malloc(pem_len - pem_count + 1);
  635. if(!stripped_pem)
  636. return CURLE_OUT_OF_MEMORY;
  637. /*
  638. * Here we loop through the pem array one character at a time between the
  639. * correct indices, and place each character that is not '\n' or '\r'
  640. * into the stripped_pem array, which should represent the raw base64 string
  641. */
  642. while(pem_count < pem_len) {
  643. if('\n' != pem[pem_count] && '\r' != pem[pem_count])
  644. stripped_pem[stripped_pem_count++] = pem[pem_count];
  645. ++pem_count;
  646. }
  647. /* Place the null terminator in the correct place */
  648. stripped_pem[stripped_pem_count] = '\0';
  649. result = Curl_base64_decode(stripped_pem, der, der_len);
  650. Curl_safefree(stripped_pem);
  651. return result;
  652. }
  653. /*
  654. * Generic pinned public key check.
  655. */
  656. CURLcode Curl_pin_peer_pubkey(struct Curl_easy *data,
  657. const char *pinnedpubkey,
  658. const unsigned char *pubkey, size_t pubkeylen)
  659. {
  660. FILE *fp;
  661. unsigned char *buf = NULL, *pem_ptr = NULL;
  662. long filesize;
  663. size_t size, pem_len;
  664. CURLcode pem_read;
  665. CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;
  666. #ifdef curlssl_sha256sum
  667. CURLcode encode;
  668. size_t encodedlen, pinkeylen;
  669. char *encoded, *pinkeycopy, *begin_pos, *end_pos;
  670. unsigned char *sha256sumdigest = NULL;
  671. #endif
  672. /* if a path wasn't specified, don't pin */
  673. if(!pinnedpubkey)
  674. return CURLE_OK;
  675. if(!pubkey || !pubkeylen)
  676. return result;
  677. /* only do this if pinnedpubkey starts with "sha256//", length 8 */
  678. if(strncmp(pinnedpubkey, "sha256//", 8) == 0) {
  679. #ifdef curlssl_sha256sum
  680. /* compute sha256sum of public key */
  681. sha256sumdigest = malloc(SHA256_DIGEST_LENGTH);
  682. if(!sha256sumdigest)
  683. return CURLE_OUT_OF_MEMORY;
  684. curlssl_sha256sum(pubkey, pubkeylen,
  685. sha256sumdigest, SHA256_DIGEST_LENGTH);
  686. encode = Curl_base64_encode(data, (char *)sha256sumdigest,
  687. SHA256_DIGEST_LENGTH, &encoded, &encodedlen);
  688. Curl_safefree(sha256sumdigest);
  689. if(encode)
  690. return encode;
  691. infof(data, "\t public key hash: sha256//%s\n", encoded);
  692. /* it starts with sha256//, copy so we can modify it */
  693. pinkeylen = strlen(pinnedpubkey) + 1;
  694. pinkeycopy = malloc(pinkeylen);
  695. if(!pinkeycopy) {
  696. Curl_safefree(encoded);
  697. return CURLE_OUT_OF_MEMORY;
  698. }
  699. memcpy(pinkeycopy, pinnedpubkey, pinkeylen);
  700. /* point begin_pos to the copy, and start extracting keys */
  701. begin_pos = pinkeycopy;
  702. do {
  703. end_pos = strstr(begin_pos, ";sha256//");
  704. /*
  705. * if there is an end_pos, null terminate,
  706. * otherwise it'll go to the end of the original string
  707. */
  708. if(end_pos)
  709. end_pos[0] = '\0';
  710. /* compare base64 sha256 digests, 8 is the length of "sha256//" */
  711. if(encodedlen == strlen(begin_pos + 8) &&
  712. !memcmp(encoded, begin_pos + 8, encodedlen)) {
  713. result = CURLE_OK;
  714. break;
  715. }
  716. /*
  717. * change back the null-terminator we changed earlier,
  718. * and look for next begin
  719. */
  720. if(end_pos) {
  721. end_pos[0] = ';';
  722. begin_pos = strstr(end_pos, "sha256//");
  723. }
  724. } while(end_pos && begin_pos);
  725. Curl_safefree(encoded);
  726. Curl_safefree(pinkeycopy);
  727. #else
  728. /* without sha256 support, this cannot match */
  729. (void)data;
  730. #endif
  731. return result;
  732. }
  733. fp = fopen(pinnedpubkey, "rb");
  734. if(!fp)
  735. return result;
  736. do {
  737. /* Determine the file's size */
  738. if(fseek(fp, 0, SEEK_END))
  739. break;
  740. filesize = ftell(fp);
  741. if(fseek(fp, 0, SEEK_SET))
  742. break;
  743. if(filesize < 0 || filesize > MAX_PINNED_PUBKEY_SIZE)
  744. break;
  745. /*
  746. * if the size of our certificate is bigger than the file
  747. * size then it can't match
  748. */
  749. size = curlx_sotouz((curl_off_t) filesize);
  750. if(pubkeylen > size)
  751. break;
  752. /*
  753. * Allocate buffer for the pinned key
  754. * With 1 additional byte for null terminator in case of PEM key
  755. */
  756. buf = malloc(size + 1);
  757. if(!buf)
  758. break;
  759. /* Returns number of elements read, which should be 1 */
  760. if((int) fread(buf, size, 1, fp) != 1)
  761. break;
  762. /* If the sizes are the same, it can't be base64 encoded, must be der */
  763. if(pubkeylen == size) {
  764. if(!memcmp(pubkey, buf, pubkeylen))
  765. result = CURLE_OK;
  766. break;
  767. }
  768. /*
  769. * Otherwise we will assume it's PEM and try to decode it
  770. * after placing null terminator
  771. */
  772. buf[size] = '\0';
  773. pem_read = pubkey_pem_to_der((const char *)buf, &pem_ptr, &pem_len);
  774. /* if it wasn't read successfully, exit */
  775. if(pem_read)
  776. break;
  777. /*
  778. * if the size of our certificate doesn't match the size of
  779. * the decoded file, they can't be the same, otherwise compare
  780. */
  781. if(pubkeylen == pem_len && !memcmp(pubkey, pem_ptr, pubkeylen))
  782. result = CURLE_OK;
  783. } while(0);
  784. Curl_safefree(buf);
  785. Curl_safefree(pem_ptr);
  786. fclose(fp);
  787. return result;
  788. }
  789. #ifndef CURL_DISABLE_CRYPTO_AUTH
  790. CURLcode Curl_ssl_md5sum(unsigned char *tmp, /* input */
  791. size_t tmplen,
  792. unsigned char *md5sum, /* output */
  793. size_t md5len)
  794. {
  795. #ifdef curlssl_md5sum
  796. curlssl_md5sum(tmp, tmplen, md5sum, md5len);
  797. #else
  798. MD5_context *MD5pw;
  799. (void) md5len;
  800. MD5pw = Curl_MD5_init(Curl_DIGEST_MD5);
  801. if(!MD5pw)
  802. return CURLE_OUT_OF_MEMORY;
  803. Curl_MD5_update(MD5pw, tmp, curlx_uztoui(tmplen));
  804. Curl_MD5_final(MD5pw, md5sum);
  805. #endif
  806. return CURLE_OK;
  807. }
  808. #endif
  809. /*
  810. * Check whether the SSL backend supports the status_request extension.
  811. */
  812. bool Curl_ssl_cert_status_request(void)
  813. {
  814. #ifdef curlssl_cert_status_request
  815. return curlssl_cert_status_request();
  816. #else
  817. return FALSE;
  818. #endif
  819. }
  820. /*
  821. * Check whether the SSL backend supports false start.
  822. */
  823. bool Curl_ssl_false_start(void)
  824. {
  825. #ifdef curlssl_false_start
  826. return curlssl_false_start();
  827. #else
  828. return FALSE;
  829. #endif
  830. }
  831. #endif /* USE_SSL */