vtls.c 26 KB

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