vtls.c 23 KB

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