tls1.c 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324
  1. /*
  2. * Copyright (c) 2007, Cameron Rich
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * * Redistributions of source code must retain the above copyright notice,
  10. * this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. * * Neither the name of the axTLS project nor the names of its contributors
  15. * may be used to endorse or promote products derived from this software
  16. * without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  22. * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  23. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  24. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  25. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  26. * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  27. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  28. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. */
  30. /**
  31. * Common ssl/tlsv1 code to both the client and server implementations.
  32. */
  33. #include <string.h>
  34. #include <stdlib.h>
  35. #include <stdio.h>
  36. #include <stdarg.h>
  37. #include <errno.h>
  38. #include "lwip/sockets.h"
  39. #include "os_port.h"
  40. #include "ssl.h"
  41. #include "arch.h"
  42. /* The session expiry time */
  43. #define SSL_EXPIRY_TIME (CONFIG_SSL_EXPIRY_TIME*3600)
  44. static const uint8_t g_hello_request[] = { HS_HELLO_REQUEST, 0, 0, 0 };
  45. static const uint8_t g_chg_cipher_spec_pkt[] = { 1 };
  46. static const char * server_finished = "server finished";
  47. static const char * client_finished = "client finished";
  48. static int do_handshake(SSL *ssl, uint8_t *buf, int read_len);
  49. static int set_key_block(SSL *ssl, int is_write);
  50. static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len);
  51. static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt);
  52. static int send_raw_packet(SSL *ssl, uint8_t protocol);
  53. /**
  54. * The server will pick the cipher based on the order that the order that the
  55. * ciphers are listed. This order is defined at compile time.
  56. */
  57. #ifdef CONFIG_SSL_SKELETON_MODE
  58. const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] =
  59. { SSL_RC4_128_SHA };
  60. #else
  61. static void session_free(SSL_SESSION *ssl_sessions[], int sess_index);
  62. const uint8_t ssl_prot_prefs[NUM_PROTOCOLS] =
  63. #ifdef CONFIG_SSL_PROT_LOW /* low security, fast speed */
  64. { SSL_RC4_128_SHA, SSL_AES128_SHA, SSL_AES256_SHA, SSL_RC4_128_MD5 };
  65. #elif CONFIG_SSL_PROT_MEDIUM /* medium security, medium speed */
  66. { SSL_AES128_SHA, SSL_AES256_SHA, SSL_RC4_128_SHA, SSL_RC4_128_MD5 };
  67. #else /* CONFIG_SSL_PROT_HIGH */ /* high security, low speed */
  68. { SSL_AES256_SHA, SSL_AES128_SHA, SSL_RC4_128_SHA, SSL_RC4_128_MD5 };
  69. #endif
  70. #endif /* CONFIG_SSL_SKELETON_MODE */
  71. /**
  72. * The cipher map containing all the essentials for each cipher.
  73. */
  74. #ifdef CONFIG_SSL_SKELETON_MODE
  75. static const cipher_info_t cipher_info[NUM_PROTOCOLS] =
  76. {
  77. { /* RC4-SHA */
  78. SSL_RC4_128_SHA, /* RC4-SHA */
  79. 16, /* key size */
  80. 0, /* iv size */
  81. 2*(SHA1_SIZE+16), /* key block size */
  82. 0, /* no padding */
  83. SHA1_SIZE, /* digest size */
  84. hmac_sha1, /* hmac algorithm */
  85. (crypt_func)RC4_crypt, /* encrypt */
  86. (crypt_func)RC4_crypt /* decrypt */
  87. },
  88. };
  89. #else
  90. static const cipher_info_t cipher_info[NUM_PROTOCOLS] =
  91. {
  92. { /* AES128-SHA */
  93. SSL_AES128_SHA, /* AES128-SHA */
  94. 16, /* key size */
  95. 16, /* iv size */
  96. 2*(SHA1_SIZE+16+16), /* key block size */
  97. 16, /* block padding size */
  98. SHA1_SIZE, /* digest size */
  99. hmac_sha1, /* hmac algorithm */
  100. (crypt_func)AES_cbc_encrypt, /* encrypt */
  101. (crypt_func)AES_cbc_decrypt /* decrypt */
  102. },
  103. { /* AES256-SHA */
  104. SSL_AES256_SHA, /* AES256-SHA */
  105. 32, /* key size */
  106. 16, /* iv size */
  107. 2*(SHA1_SIZE+32+16), /* key block size */
  108. 16, /* block padding size */
  109. SHA1_SIZE, /* digest size */
  110. hmac_sha1, /* hmac algorithm */
  111. (crypt_func)AES_cbc_encrypt, /* encrypt */
  112. (crypt_func)AES_cbc_decrypt /* decrypt */
  113. },
  114. { /* RC4-SHA */
  115. SSL_RC4_128_SHA, /* RC4-SHA */
  116. 16, /* key size */
  117. 0, /* iv size */
  118. 2*(SHA1_SIZE+16), /* key block size */
  119. 0, /* no padding */
  120. SHA1_SIZE, /* digest size */
  121. hmac_sha1, /* hmac algorithm */
  122. (crypt_func)RC4_crypt, /* encrypt */
  123. (crypt_func)RC4_crypt /* decrypt */
  124. },
  125. /*
  126. * This protocol is from SSLv2 days and is unlikely to be used - but was
  127. * useful for testing different possible digest algorithms.
  128. */
  129. { /* RC4-MD5 */
  130. SSL_RC4_128_MD5, /* RC4-MD5 */
  131. 16, /* key size */
  132. 0, /* iv size */
  133. 2*(MD5_SIZE+16), /* key block size */
  134. 0, /* no padding */
  135. MD5_SIZE, /* digest size */
  136. hmac_md5, /* hmac algorithm */
  137. (crypt_func)RC4_crypt, /* encrypt */
  138. (crypt_func)RC4_crypt /* decrypt */
  139. },
  140. };
  141. #endif
  142. static void prf(const uint8_t *sec, int sec_len, uint8_t *seed, int seed_len,
  143. uint8_t *out, int olen);
  144. static const cipher_info_t *get_cipher_info(uint8_t cipher);
  145. static void increment_read_sequence(SSL *ssl);
  146. static void increment_write_sequence(SSL *ssl);
  147. static void add_hmac_digest(SSL *ssl, int snd, uint8_t *hmac_header,
  148. const uint8_t *buf, int buf_len, uint8_t *hmac_buf);
  149. /* win32 VC6.0 doesn't have variadic macros */
  150. #if defined(WIN32) && !defined(CONFIG_SSL_FULL_MODE)
  151. void DISPLAY_BYTES(SSL *ssl, const char *format,
  152. const uint8_t *data, int size, ...) {}
  153. #endif
  154. /**
  155. * Establish a new client/server context.
  156. */
  157. EXP_FUNC SSL_CTX *STDCALL ssl_ctx_new(SSL_CTX *ssl_ctx, uint32_t options, int num_sessions)
  158. {
  159. ssl_ctx->options = options;
  160. RNG_initialize();
  161. if (load_key_certs(ssl_ctx) < 0)
  162. {
  163. printf("error loading key certs\r\n");
  164. //free(ssl_ctx); /* can't load our key/certificate pair, so die */
  165. return NULL;
  166. }
  167. #ifndef CONFIG_SSL_SKELETON_MODE
  168. ssl_ctx->num_sessions = num_sessions;
  169. #endif
  170. SSL_CTX_MUTEX_INIT(ssl_ctx->mutex);
  171. #ifndef CONFIG_SSL_SKELETON_MODE
  172. if (num_sessions)
  173. {
  174. ssl_ctx->ssl_sessions = (SSL_SESSION **)
  175. calloc(1, num_sessions*sizeof(SSL_SESSION *));
  176. }
  177. #endif
  178. return ssl_ctx;
  179. }
  180. /*
  181. * Remove a client/server context.
  182. */
  183. EXP_FUNC void STDCALL ssl_ctx_free(SSL_CTX *ssl_ctx)
  184. {
  185. SSL *ssl;
  186. int i;
  187. if (ssl_ctx == NULL)
  188. return;
  189. ssl = ssl_ctx->head;
  190. /* clear out all the ssl entries */
  191. while (ssl)
  192. {
  193. SSL *next = ssl->next;
  194. ssl_free(ssl);
  195. ssl = next;
  196. }
  197. #ifndef CONFIG_SSL_SKELETON_MODE
  198. /* clear out all the sessions */
  199. for (i = 0; i < ssl_ctx->num_sessions; i++)
  200. session_free(ssl_ctx->ssl_sessions, i);
  201. free(ssl_ctx->ssl_sessions);
  202. #endif
  203. i = 0;
  204. //while (i < CONFIG_SSL_MAX_CERTS && ssl_ctx->certs[i].buf)
  205. {
  206. //free(ssl_ctx->certs[i].buf);
  207. //ssl_ctx->certs[i++].buf = NULL;
  208. }
  209. #ifdef CONFIG_SSL_CERT_VERIFICATION
  210. remove_ca_certs(ssl_ctx->ca_cert_ctx);
  211. #endif
  212. ssl_ctx->chain_length = 0;
  213. SSL_CTX_MUTEX_DESTROY(ssl_ctx->mutex);
  214. RSA_free(ssl_ctx->rsa_ctx);
  215. RNG_terminate();
  216. //free(ssl_ctx);
  217. }
  218. /*
  219. * Free any used resources used by this connection.
  220. */
  221. EXP_FUNC void STDCALL ssl_free(SSL *ssl)
  222. {
  223. SSL_CTX *ssl_ctx;
  224. if (ssl == NULL) /* just ignore null pointers */
  225. return;
  226. /* only notify if we weren't notified first */
  227. /* spec says we must notify when we are dying */
  228. if (!IS_SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY))
  229. send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY);
  230. ssl_ctx = ssl->ssl_ctx;
  231. SSL_CTX_LOCK(ssl_ctx->mutex);
  232. /* adjust the server SSL list */
  233. if (ssl->prev)
  234. ssl->prev->next = ssl->next;
  235. else
  236. ssl_ctx->head = ssl->next;
  237. if (ssl->next)
  238. ssl->next->prev = ssl->prev;
  239. else
  240. ssl_ctx->tail = ssl->prev;
  241. SSL_CTX_UNLOCK(ssl_ctx->mutex);
  242. /* may already be free - but be sure */
  243. free(ssl->encrypt_ctx);
  244. free(ssl->decrypt_ctx);
  245. disposable_free(ssl);
  246. #ifdef CONFIG_SSL_CERT_VERIFICATION
  247. x509_free(ssl->x509_ctx);
  248. #endif
  249. //free(ssl->ssl_ctx);
  250. //free(ssl);
  251. }
  252. /*
  253. * Write application data to the client
  254. */
  255. EXP_FUNC int STDCALL ssl_write(SSL *ssl, const uint8_t *out_data, int out_len)
  256. {
  257. int n = out_len, nw, i, tot = 0;
  258. /* maximum size of a TLS packet is around 16kB, so fragment */
  259. do
  260. {
  261. nw = n;
  262. if (nw > RT_MAX_PLAIN_LENGTH) /* fragment if necessary */
  263. nw = RT_MAX_PLAIN_LENGTH;
  264. if ((i = send_packet(ssl, PT_APP_PROTOCOL_DATA,
  265. &out_data[tot], nw)) <= 0)
  266. {
  267. out_len = i; /* an error */
  268. break;
  269. }
  270. tot += i;
  271. n -= i;
  272. } while (n > 0);
  273. return out_len;
  274. }
  275. /**
  276. * Add a certificate to the certificate chain.
  277. */
  278. int add_cert(SSL_CTX *ssl_ctx, const uint8_t *buf, int len)
  279. {
  280. int ret = SSL_ERROR_NO_CERT_DEFINED, i = 0;
  281. SSL_CERT *ssl_cert;
  282. X509_CTX *cert = NULL;
  283. int offset;
  284. while (ssl_ctx->certs[i].buf && i < CONFIG_SSL_MAX_CERTS)
  285. i++;
  286. if (i == CONFIG_SSL_MAX_CERTS) /* too many certs */
  287. {
  288. #ifdef CONFIG_SSL_FULL_MODE
  289. printf("Error: maximum number of certs added (%d) - change of "
  290. "compile-time configuration required\n",
  291. CONFIG_SSL_MAX_CERTS);
  292. #endif
  293. goto error;
  294. }
  295. if ((ret = x509_new(buf, &offset, &cert)))
  296. goto error;
  297. #if defined (CONFIG_SSL_FULL_MODE)
  298. if (ssl_ctx->options & SSL_DISPLAY_CERTS)
  299. x509_print(cert, NULL);
  300. #endif
  301. ssl_cert = &ssl_ctx->certs[i];
  302. ssl_cert->size = len;
  303. ssl_cert->buf = buf;
  304. ssl_ctx->chain_length++;
  305. len -= offset;
  306. ret = SSL_OK; /* ok so far */
  307. /* recurse? */
  308. if (len > 0)
  309. {
  310. ret = add_cert(ssl_ctx, &buf[offset], len);
  311. }
  312. error:
  313. x509_free(cert); /* don't need anymore */
  314. return ret;
  315. }
  316. #ifdef CONFIG_SSL_CERT_VERIFICATION
  317. /**
  318. * Add a certificate authority.
  319. */
  320. int add_cert_auth(SSL_CTX *ssl_ctx, const uint8_t *buf, int len)
  321. {
  322. int ret = SSL_OK; /* ignore errors for now */
  323. int i = 0;
  324. CA_CERT_CTX *ca_cert_ctx;
  325. if (ssl_ctx->ca_cert_ctx == NULL)
  326. ssl_ctx->ca_cert_ctx = (CA_CERT_CTX *)calloc(1, sizeof(CA_CERT_CTX));
  327. ca_cert_ctx = ssl_ctx->ca_cert_ctx;
  328. while (i < CONFIG_X509_MAX_CA_CERTS && ca_cert_ctx->cert[i])
  329. i++;
  330. while (len > 0)
  331. {
  332. int offset;
  333. if (i >= CONFIG_X509_MAX_CA_CERTS)
  334. {
  335. #ifdef CONFIG_SSL_FULL_MODE
  336. printf("Error: maximum number of CA certs added (%d) - change of "
  337. "compile-time configuration required\n",
  338. CONFIG_X509_MAX_CA_CERTS);
  339. #endif
  340. break;
  341. }
  342. /* ignore the return code */
  343. if (x509_new(buf, &offset, &ca_cert_ctx->cert[i]) == X509_OK)
  344. {
  345. #if defined (CONFIG_SSL_FULL_MODE)
  346. if (ssl_ctx->options & SSL_DISPLAY_CERTS)
  347. x509_print(ca_cert_ctx->cert[i], NULL);
  348. #endif
  349. }
  350. i++;
  351. len -= offset;
  352. }
  353. return ret;
  354. }
  355. /*
  356. * Retrieve an X.509 distinguished name component
  357. */
  358. EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component)
  359. {
  360. if (ssl->x509_ctx == NULL)
  361. return NULL;
  362. switch (component)
  363. {
  364. case SSL_X509_CERT_COMMON_NAME:
  365. return ssl->x509_ctx->cert_dn[X509_COMMON_NAME];
  366. case SSL_X509_CERT_ORGANIZATION:
  367. return ssl->x509_ctx->cert_dn[X509_ORGANIZATION];
  368. case SSL_X509_CERT_ORGANIZATIONAL_NAME:
  369. return ssl->x509_ctx->cert_dn[X509_ORGANIZATIONAL_UNIT];
  370. case SSL_X509_CA_CERT_COMMON_NAME:
  371. return ssl->x509_ctx->ca_cert_dn[X509_COMMON_NAME];
  372. case SSL_X509_CA_CERT_ORGANIZATION:
  373. return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATION];
  374. case SSL_X509_CA_CERT_ORGANIZATIONAL_NAME:
  375. return ssl->x509_ctx->ca_cert_dn[X509_ORGANIZATIONAL_UNIT];
  376. default:
  377. return NULL;
  378. }
  379. }
  380. /*
  381. * Retrieve a "Subject Alternative Name" from a v3 certificate
  382. */
  383. EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl,
  384. int dnsindex)
  385. {
  386. int i;
  387. if (ssl->x509_ctx == NULL || ssl->x509_ctx->subject_alt_dnsnames == NULL)
  388. return NULL;
  389. for (i = 0; i < dnsindex; ++i)
  390. {
  391. if (ssl->x509_ctx->subject_alt_dnsnames[i] == NULL)
  392. return NULL;
  393. }
  394. return ssl->x509_ctx->subject_alt_dnsnames[dnsindex];
  395. }
  396. #endif /* CONFIG_SSL_CERT_VERIFICATION */
  397. /*
  398. * Find an ssl object based on the client's file descriptor.
  399. */
  400. EXP_FUNC SSL * STDCALL ssl_find(SSL_CTX *ssl_ctx, int client_fd)
  401. {
  402. SSL *ssl;
  403. SSL_CTX_LOCK(ssl_ctx->mutex);
  404. ssl = ssl_ctx->head;
  405. /* search through all the ssl entries */
  406. while (ssl)
  407. {
  408. if (ssl->client_fd == client_fd)
  409. {
  410. SSL_CTX_UNLOCK(ssl_ctx->mutex);
  411. return ssl;
  412. }
  413. ssl = ssl->next;
  414. }
  415. SSL_CTX_UNLOCK(ssl_ctx->mutex);
  416. return NULL;
  417. }
  418. /*
  419. * Force the client to perform its handshake again.
  420. */
  421. EXP_FUNC int STDCALL ssl_renegotiate(SSL *ssl)
  422. {
  423. int ret = SSL_OK;
  424. disposable_new(ssl);
  425. #ifdef CONFIG_SSL_ENABLE_CLIENT
  426. if (IS_SET_SSL_FLAG(SSL_IS_CLIENT))
  427. {
  428. ret = do_client_connect(ssl);
  429. }
  430. else
  431. #endif
  432. {
  433. send_packet(ssl, PT_HANDSHAKE_PROTOCOL,
  434. g_hello_request, sizeof(g_hello_request));
  435. SET_SSL_FLAG(SSL_NEED_RECORD);
  436. }
  437. return ret;
  438. }
  439. /**
  440. * @brief Get what we need for key info.
  441. * @param cipher [in] The cipher information we are after
  442. * @param key_size [out] The key size for the cipher
  443. * @param iv_size [out] The iv size for the cipher
  444. * @return The amount of key information we need.
  445. */
  446. static const cipher_info_t *get_cipher_info(uint8_t cipher)
  447. {
  448. int i;
  449. for (i = 0; i < NUM_PROTOCOLS; i++)
  450. {
  451. if (cipher_info[i].cipher == cipher)
  452. {
  453. return &cipher_info[i];
  454. }
  455. }
  456. return NULL; /* error */
  457. }
  458. /*
  459. * Get a new ssl context for a new connection.
  460. */
  461. SSL *ssl_new(SSL *ssl, int client_fd)
  462. {
  463. SSL_CTX* ssl_ctx = ssl->ssl_ctx;
  464. ssl->need_bytes = SSL_RECORD_SIZE; /* need a record */
  465. ssl->client_fd = 0;
  466. ssl->flag = SSL_NEED_RECORD;
  467. ssl->bm_data = ssl->bm_all_data + BM_RECORD_OFFSET;
  468. ssl->bm_read_index = 0;
  469. ssl->hs_status = SSL_NOT_OK; /* not connected */
  470. #ifdef CONFIG_ENABLE_VERIFICATION
  471. ssl->ca_cert_ctx = ssl_ctx->ca_cert_ctx;
  472. #endif
  473. disposable_new(ssl);
  474. /* a bit hacky but saves a few bytes of memory */
  475. ssl->flag |= ssl_ctx->options;
  476. SSL_CTX_LOCK(ssl_ctx->mutex);
  477. if (ssl_ctx->head == NULL)
  478. {
  479. ssl_ctx->head = ssl;
  480. ssl_ctx->tail = ssl;
  481. }
  482. else
  483. {
  484. ssl->prev = ssl_ctx->tail;
  485. ssl_ctx->tail->next = ssl;
  486. ssl_ctx->tail = ssl;
  487. }
  488. ssl->encrypt_ctx = NULL;
  489. ssl->decrypt_ctx = NULL;
  490. SSL_CTX_UNLOCK(ssl_ctx->mutex);
  491. return ssl;
  492. }
  493. /*
  494. * Add a private key to a context.
  495. */
  496. int add_private_key(SSL_CTX *ssl_ctx, SSLObjLoader *ssl_obj)
  497. {
  498. int ret = SSL_OK;
  499. /* get the private key details */
  500. if (asn1_get_private_key(ssl_obj->buf, ssl_obj->len, &ssl_ctx->rsa_ctx))
  501. {
  502. ret = SSL_ERROR_INVALID_KEY;
  503. goto error;
  504. }
  505. error:
  506. return ret;
  507. }
  508. /**
  509. * Increment the read sequence number (as a 64 bit endian indepenent #)
  510. */
  511. static void increment_read_sequence(SSL *ssl)
  512. {
  513. int i;
  514. for (i = 7; i >= 0; i--)
  515. {
  516. if (++ssl->read_sequence[i])
  517. break;
  518. }
  519. }
  520. /**
  521. * Increment the read sequence number (as a 64 bit endian indepenent #)
  522. */
  523. static void increment_write_sequence(SSL *ssl)
  524. {
  525. int i;
  526. for (i = 7; i >= 0; i--)
  527. {
  528. if (++ssl->write_sequence[i])
  529. break;
  530. }
  531. }
  532. /**
  533. * Work out the HMAC digest in a packet.
  534. */
  535. static void add_hmac_digest(SSL *ssl, int mode, uint8_t *hmac_header,
  536. const uint8_t *buf, int buf_len, uint8_t *hmac_buf)
  537. {
  538. int hmac_len = buf_len + 8 + SSL_RECORD_SIZE;
  539. uint8_t *t_buf = (uint8_t *)alloca(hmac_len+10);
  540. memcpy(t_buf, (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE) ?
  541. ssl->write_sequence : ssl->read_sequence, 8);
  542. memcpy(&t_buf[8], hmac_header, SSL_RECORD_SIZE);
  543. memcpy(&t_buf[8+SSL_RECORD_SIZE], buf, buf_len);
  544. ssl->cipher_info->hmac(t_buf, hmac_len,
  545. (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ) ?
  546. ssl->server_mac : ssl->client_mac,
  547. ssl->cipher_info->digest_size, hmac_buf);
  548. #if 0
  549. print_blob("record", hmac_header, SSL_RECORD_SIZE);
  550. print_blob("buf", buf, buf_len);
  551. if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_WRITE)
  552. {
  553. print_blob("write seq", ssl->write_sequence, 8);
  554. }
  555. else
  556. {
  557. print_blob("read seq", ssl->read_sequence, 8);
  558. }
  559. if (mode == SSL_SERVER_WRITE || mode == SSL_CLIENT_READ)
  560. {
  561. print_blob("server mac",
  562. ssl->server_mac, ssl->cipher_info->digest_size);
  563. }
  564. else
  565. {
  566. print_blob("client mac",
  567. ssl->client_mac, ssl->cipher_info->digest_size);
  568. }
  569. print_blob("hmac", hmac_buf, SHA1_SIZE);
  570. #endif
  571. }
  572. /**
  573. * Verify that the digest of a packet is correct.
  574. */
  575. static int verify_digest(SSL *ssl, int mode, const uint8_t *buf, int read_len)
  576. {
  577. uint8_t hmac_buf[SHA1_SIZE];
  578. int hmac_offset;
  579. if (ssl->cipher_info->padding_size)
  580. {
  581. int last_blk_size = buf[read_len-1], i;
  582. hmac_offset = read_len-last_blk_size-ssl->cipher_info->digest_size-1;
  583. /* guard against a timing attack - make sure we do the digest */
  584. if (hmac_offset < 0)
  585. {
  586. hmac_offset = 0;
  587. }
  588. else
  589. {
  590. /* already looked at last byte */
  591. for (i = 1; i < last_blk_size; i++)
  592. {
  593. if (buf[read_len-i] != last_blk_size)
  594. {
  595. hmac_offset = 0;
  596. break;
  597. }
  598. }
  599. }
  600. }
  601. else /* stream cipher */
  602. {
  603. hmac_offset = read_len - ssl->cipher_info->digest_size;
  604. if (hmac_offset < 0)
  605. {
  606. hmac_offset = 0;
  607. }
  608. }
  609. /* sanity check the offset */
  610. ssl->hmac_header[3] = hmac_offset >> 8; /* insert size */
  611. ssl->hmac_header[4] = hmac_offset & 0xff;
  612. add_hmac_digest(ssl, mode, ssl->hmac_header, buf, hmac_offset, hmac_buf);
  613. if (memcmp(hmac_buf, &buf[hmac_offset], ssl->cipher_info->digest_size))
  614. {
  615. return SSL_ERROR_INVALID_HMAC;
  616. }
  617. return hmac_offset;
  618. }
  619. /**
  620. * Add a packet to the end of our sent and received packets, so that we may use
  621. * it to calculate the hash at the end.
  622. */
  623. void add_packet(SSL *ssl, const uint8_t *pkt, int len)
  624. {
  625. MD5_Update(&ssl->dc->md5_ctx, pkt, len);
  626. SHA1_Update(&ssl->dc->sha1_ctx, pkt, len);
  627. }
  628. /**
  629. * Work out the MD5 PRF.
  630. */
  631. static void p_hash_md5(const uint8_t *sec, int sec_len,
  632. uint8_t *seed, int seed_len, uint8_t *out, int olen)
  633. {
  634. uint8_t a1[128];
  635. /* A(1) */
  636. hmac_md5(seed, seed_len, sec, sec_len, a1);
  637. memcpy(&a1[MD5_SIZE], seed, seed_len);
  638. hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out);
  639. while (olen > MD5_SIZE)
  640. {
  641. uint8_t a2[MD5_SIZE];
  642. out += MD5_SIZE;
  643. olen -= MD5_SIZE;
  644. /* A(N) */
  645. hmac_md5(a1, MD5_SIZE, sec, sec_len, a2);
  646. memcpy(a1, a2, MD5_SIZE);
  647. /* work out the actual hash */
  648. hmac_md5(a1, MD5_SIZE+seed_len, sec, sec_len, out);
  649. }
  650. }
  651. /**
  652. * Work out the SHA1 PRF.
  653. */
  654. static void p_hash_sha1(const uint8_t *sec, int sec_len,
  655. uint8_t *seed, int seed_len, uint8_t *out, int olen)
  656. {
  657. uint8_t a1[128];
  658. /* A(1) */
  659. hmac_sha1(seed, seed_len, sec, sec_len, a1);
  660. memcpy(&a1[SHA1_SIZE], seed, seed_len);
  661. hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out);
  662. while (olen > SHA1_SIZE)
  663. {
  664. uint8_t a2[SHA1_SIZE];
  665. out += SHA1_SIZE;
  666. olen -= SHA1_SIZE;
  667. /* A(N) */
  668. hmac_sha1(a1, SHA1_SIZE, sec, sec_len, a2);
  669. memcpy(a1, a2, SHA1_SIZE);
  670. /* work out the actual hash */
  671. hmac_sha1(a1, SHA1_SIZE+seed_len, sec, sec_len, out);
  672. }
  673. }
  674. /**
  675. * Work out the PRF.
  676. */
  677. static void prf(const uint8_t *sec, int sec_len, uint8_t *seed, int seed_len,
  678. uint8_t *out, int olen)
  679. {
  680. int len, i;
  681. const uint8_t *S1, *S2;
  682. uint8_t xbuf[256]; /* needs to be > the amount of key data */
  683. uint8_t ybuf[256]; /* needs to be > the amount of key data */
  684. len = sec_len/2;
  685. S1 = sec;
  686. S2 = &sec[len];
  687. len += (sec_len & 1); /* add for odd, make longer */
  688. p_hash_md5(S1, len, seed, seed_len, xbuf, olen);
  689. p_hash_sha1(S2, len, seed, seed_len, ybuf, olen);
  690. for (i = 0; i < olen; i++)
  691. out[i] = xbuf[i] ^ ybuf[i];
  692. }
  693. /**
  694. * Generate a master secret based on the client/server random data and the
  695. * premaster secret.
  696. */
  697. void generate_master_secret(SSL *ssl, const uint8_t *premaster_secret)
  698. {
  699. uint8_t buf[128]; /* needs to be > 13+32+32 in size */
  700. strcpy((char *)buf, "master secret");
  701. memcpy(&buf[13], ssl->dc->client_random, SSL_RANDOM_SIZE);
  702. memcpy(&buf[45], ssl->dc->server_random, SSL_RANDOM_SIZE);
  703. prf(premaster_secret, SSL_SECRET_SIZE, buf, 77, ssl->dc->master_secret,
  704. SSL_SECRET_SIZE);
  705. }
  706. /**
  707. * Generate a 'random' blob of data used for the generation of keys.
  708. */
  709. static void generate_key_block(uint8_t *client_random, uint8_t *server_random,
  710. uint8_t *master_secret, uint8_t *key_block, int key_block_size)
  711. {
  712. uint8_t buf[128];
  713. strcpy((char *)buf, "key expansion");
  714. memcpy(&buf[13], server_random, SSL_RANDOM_SIZE);
  715. memcpy(&buf[45], client_random, SSL_RANDOM_SIZE);
  716. prf(master_secret, SSL_SECRET_SIZE, buf, 77, key_block, key_block_size);
  717. }
  718. /**
  719. * Calculate the digest used in the finished message. This function also
  720. * doubles up as a certificate verify function.
  721. */
  722. void finished_digest(SSL *ssl, const char *label, uint8_t *digest)
  723. {
  724. uint8_t mac_buf[128];
  725. uint8_t *q = mac_buf;
  726. MD5_CTX md5_ctx = ssl->dc->md5_ctx;
  727. SHA1_CTX sha1_ctx = ssl->dc->sha1_ctx;
  728. if (label)
  729. {
  730. strcpy((char *)q, label);
  731. q += strlen(label);
  732. }
  733. MD5_Final(q, &md5_ctx);
  734. q += MD5_SIZE;
  735. SHA1_Final(q, &sha1_ctx);
  736. q += SHA1_SIZE;
  737. if (label)
  738. {
  739. prf(ssl->dc->master_secret, SSL_SECRET_SIZE, mac_buf, (int)(q-mac_buf),
  740. digest, SSL_FINISHED_HASH_SIZE);
  741. }
  742. else /* for use in a certificate verify */
  743. {
  744. memcpy(digest, mac_buf, MD5_SIZE + SHA1_SIZE);
  745. }
  746. #if 0
  747. printf("label: %s\r\n", label);
  748. print_blob("master secret", ssl->dc->master_secret, 48);
  749. print_blob("mac_buf", mac_buf, q-mac_buf);
  750. print_blob("finished digest", digest, SSL_FINISHED_HASH_SIZE);
  751. #endif
  752. }
  753. /**
  754. * Retrieve (and initialise) the context of a cipher.
  755. */
  756. static void *crypt_new(SSL *ssl, uint8_t *key, uint8_t *iv, int is_decrypt)
  757. {
  758. switch (ssl->cipher)
  759. {
  760. #ifndef CONFIG_SSL_SKELETON_MODE
  761. case SSL_AES128_SHA:
  762. {
  763. AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX));
  764. AES_set_key(aes_ctx, key, iv, AES_MODE_128);
  765. if (is_decrypt)
  766. {
  767. AES_convert_key(aes_ctx);
  768. }
  769. return (void *)aes_ctx;
  770. }
  771. case SSL_AES256_SHA:
  772. {
  773. AES_CTX *aes_ctx = (AES_CTX *)malloc(sizeof(AES_CTX));
  774. AES_set_key(aes_ctx, key, iv, AES_MODE_256);
  775. if (is_decrypt)
  776. {
  777. AES_convert_key(aes_ctx);
  778. }
  779. return (void *)aes_ctx;
  780. }
  781. case SSL_RC4_128_MD5:
  782. #endif
  783. case SSL_RC4_128_SHA:
  784. {
  785. RC4_CTX *rc4_ctx = (RC4_CTX *)malloc(sizeof(RC4_CTX));
  786. RC4_setup(rc4_ctx, key, 16);
  787. return (void *)rc4_ctx;
  788. }
  789. }
  790. return NULL; /* its all gone wrong */
  791. }
  792. /**
  793. * Send a packet over the socket.
  794. */
  795. static int send_raw_packet(SSL *ssl, uint8_t protocol)
  796. {
  797. uint8_t *rec_buf = ssl->bm_all_data;
  798. int pkt_size = SSL_RECORD_SIZE+ssl->bm_index;
  799. int sent = 0;
  800. int ret = SSL_OK;
  801. rec_buf[0] = protocol;
  802. rec_buf[1] = 0x03; /* version = 3.1 or higher */
  803. rec_buf[2] = ssl->version & 0x0f;
  804. rec_buf[3] = ssl->bm_index >> 8;
  805. rec_buf[4] = ssl->bm_index & 0xff;
  806. DISPLAY_BYTES(ssl, "sending %d bytes", ssl->bm_all_data,
  807. pkt_size, pkt_size);
  808. while (sent < pkt_size)
  809. {
  810. ret = SOCKET_WRITE(ssl->client_fd,
  811. &ssl->bm_all_data[sent], pkt_size-sent);
  812. if (ret >= 0)
  813. sent += ret;
  814. else
  815. {
  816. #ifdef WIN32
  817. if (GetLastError() != WSAEWOULDBLOCK)
  818. #else
  819. if (errno != EAGAIN && errno != EWOULDBLOCK)
  820. #endif
  821. return SSL_ERROR_CONN_LOST;
  822. }
  823. /* keep going until the write buffer has some space */
  824. if (sent != pkt_size)
  825. {
  826. fd_set wfds;
  827. FD_ZERO(&wfds);
  828. FD_SET(ssl->client_fd, &wfds);
  829. /* block and wait for it */
  830. if (lwip_select(FD_SETSIZE, NULL, &wfds, NULL, NULL) < 0)
  831. return SSL_ERROR_CONN_LOST;
  832. }
  833. }
  834. fd_set wfds;
  835. FD_ZERO(&wfds);
  836. FD_SET(ssl->client_fd, &wfds);
  837. /* block and wait for it */
  838. if (lwip_select(FD_SETSIZE, NULL, &wfds, NULL, NULL) < 0)
  839. return SSL_ERROR_CONN_LOST;
  840. SET_SSL_FLAG(SSL_NEED_RECORD); /* reset for next time */
  841. ssl->bm_index = 0;
  842. if (protocol != PT_APP_PROTOCOL_DATA)
  843. {
  844. /* always return SSL_OK during handshake */
  845. ret = SSL_OK;
  846. }
  847. return ret;
  848. }
  849. /**
  850. * Send an encrypted packet with padding bytes if necessary.
  851. */
  852. int send_packet(SSL *ssl, uint8_t protocol, const uint8_t *in, int length)
  853. {
  854. int ret, msg_length = 0;
  855. /* if our state is bad, don't bother */
  856. if (ssl->hs_status == SSL_ERROR_DEAD)
  857. return SSL_ERROR_CONN_LOST;
  858. if (in) /* has the buffer already been initialised? */
  859. {
  860. memcpy(ssl->bm_data, in, length);
  861. }
  862. msg_length += length;
  863. if (IS_SET_SSL_FLAG(SSL_TX_ENCRYPTED))
  864. {
  865. int mode = IS_SET_SSL_FLAG(SSL_IS_CLIENT) ?
  866. SSL_CLIENT_WRITE : SSL_SERVER_WRITE;
  867. uint8_t hmac_header[SSL_RECORD_SIZE] =
  868. {
  869. protocol,
  870. 0x03, /* version = 3.1 or higher */
  871. ssl->version & 0x0f,
  872. msg_length >> 8,
  873. msg_length & 0xff
  874. };
  875. if (protocol == PT_HANDSHAKE_PROTOCOL)
  876. {
  877. DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0);
  878. if (ssl->bm_data[0] != HS_HELLO_REQUEST)
  879. {
  880. add_packet(ssl, ssl->bm_data, msg_length);
  881. }
  882. }
  883. /* add the packet digest */
  884. add_hmac_digest(ssl, mode, hmac_header, ssl->bm_data, msg_length,
  885. &ssl->bm_data[msg_length]);
  886. msg_length += ssl->cipher_info->digest_size;
  887. /* add padding? */
  888. if (ssl->cipher_info->padding_size)
  889. {
  890. int last_blk_size = msg_length%ssl->cipher_info->padding_size;
  891. int pad_bytes = ssl->cipher_info->padding_size - last_blk_size;
  892. /* ensure we always have at least 1 padding byte */
  893. if (pad_bytes == 0)
  894. pad_bytes += ssl->cipher_info->padding_size;
  895. memset(&ssl->bm_data[msg_length], pad_bytes-1, pad_bytes);
  896. msg_length += pad_bytes;
  897. }
  898. DISPLAY_BYTES(ssl, "unencrypted write", ssl->bm_data, msg_length);
  899. increment_write_sequence(ssl);
  900. /* add the explicit IV for TLS1.1 */
  901. if (ssl->version >= SSL_PROTOCOL_VERSION1_1 &&
  902. ssl->cipher_info->iv_size)
  903. {
  904. uint8_t iv_size = ssl->cipher_info->iv_size;
  905. uint8_t *t_buf = alloca(msg_length + iv_size);
  906. memcpy(t_buf + iv_size, ssl->bm_data, msg_length);
  907. get_random(iv_size, t_buf);
  908. msg_length += iv_size;
  909. memcpy(ssl->bm_data, t_buf, msg_length);
  910. }
  911. /* now encrypt the packet */
  912. ssl->cipher_info->encrypt(ssl->encrypt_ctx, ssl->bm_data,
  913. ssl->bm_data, msg_length);
  914. }
  915. else if (protocol == PT_HANDSHAKE_PROTOCOL)
  916. {
  917. DISPLAY_STATE(ssl, 1, ssl->bm_data[0], 0);
  918. if (ssl->bm_data[0] != HS_HELLO_REQUEST)
  919. {
  920. add_packet(ssl, ssl->bm_data, length);
  921. }
  922. }
  923. ssl->bm_index = msg_length;
  924. if ((ret = send_raw_packet(ssl, protocol)) <= 0)
  925. return ret;
  926. return length; /* just return what we wanted to send */
  927. }
  928. /**
  929. * Work out the cipher keys we are going to use for this session based on the
  930. * master secret.
  931. */
  932. static int set_key_block(SSL *ssl, int is_write)
  933. {
  934. const cipher_info_t *ciph_info = get_cipher_info(ssl->cipher);
  935. uint8_t *q;
  936. uint8_t client_key[32], server_key[32]; /* big enough for AES256 */
  937. uint8_t client_iv[16], server_iv[16]; /* big enough for AES128/256 */
  938. int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
  939. if (ciph_info == NULL)
  940. return -1;
  941. uint8_t key_tmp[MAX_KEYBLOCK_SIZE] = {0};
  942. /* only do once in a handshake */
  943. if (memcmp(ssl->dc->key_block, key_tmp, MAX_KEYBLOCK_SIZE) == 0)
  944. {
  945. #if 0
  946. print_blob("client", ssl->dc->client_random, 32);
  947. print_blob("server", ssl->dc->server_random, 32);
  948. print_blob("master", ssl->dc->master_secret, SSL_SECRET_SIZE);
  949. #endif
  950. generate_key_block(ssl->dc->client_random, ssl->dc->server_random,
  951. ssl->dc->master_secret, ssl->dc->key_block,
  952. ciph_info->key_block_size);
  953. #if 0
  954. print_blob("keyblock", ssl->dc->key_block, ciph_info->key_block_size);
  955. #endif
  956. }
  957. q = ssl->dc->key_block;
  958. if ((is_client && is_write) || (!is_client && !is_write))
  959. {
  960. memcpy(ssl->client_mac, q, ciph_info->digest_size);
  961. }
  962. q += ciph_info->digest_size;
  963. if ((!is_client && is_write) || (is_client && !is_write))
  964. {
  965. memcpy(ssl->server_mac, q, ciph_info->digest_size);
  966. }
  967. q += ciph_info->digest_size;
  968. memcpy(client_key, q, ciph_info->key_size);
  969. q += ciph_info->key_size;
  970. memcpy(server_key, q, ciph_info->key_size);
  971. q += ciph_info->key_size;
  972. #ifndef CONFIG_SSL_SKELETON_MODE
  973. if (ciph_info->iv_size) /* RC4 has no IV, AES does */
  974. {
  975. memcpy(client_iv, q, ciph_info->iv_size);
  976. q += ciph_info->iv_size;
  977. memcpy(server_iv, q, ciph_info->iv_size);
  978. q += ciph_info->iv_size;
  979. }
  980. #endif
  981. if( (is_write ? ssl->encrypt_ctx : ssl->decrypt_ctx) != NULL)
  982. free(is_write ? ssl->encrypt_ctx : ssl->decrypt_ctx);
  983. /* now initialise the ciphers */
  984. if (is_client)
  985. {
  986. finished_digest(ssl, server_finished, ssl->dc->final_finish_mac);
  987. if (is_write)
  988. ssl->encrypt_ctx = crypt_new(ssl, client_key, client_iv, 0);
  989. else
  990. ssl->decrypt_ctx = crypt_new(ssl, server_key, server_iv, 1);
  991. }
  992. else
  993. {
  994. finished_digest(ssl, client_finished, ssl->dc->final_finish_mac);
  995. if (is_write)
  996. ssl->encrypt_ctx = crypt_new(ssl, server_key, server_iv, 0);
  997. else
  998. ssl->decrypt_ctx = crypt_new(ssl, client_key, client_iv, 1);
  999. }
  1000. ssl->cipher_info = ciph_info;
  1001. return 0;
  1002. }
  1003. /**
  1004. * Blocking read
  1005. * data must be valid buffer of size length at least
  1006. * length
  1007. */
  1008. int basic_read2(SSL *ssl, uint8_t *data, uint32_t length)
  1009. {
  1010. // printf("basic_read2\n");
  1011. if(data == NULL)
  1012. return -1;
  1013. int ret = 0;
  1014. do
  1015. {
  1016. //printf("before_lwip_select\n");
  1017. fd_set rfds;
  1018. FD_ZERO(&rfds);
  1019. FD_SET(ssl->client_fd, &rfds);
  1020. /* block and wait for it */
  1021. if (lwip_select(FD_SETSIZE, &rfds, NULL, NULL, NULL) < 0)
  1022. return SSL_ERROR_CONN_LOST;
  1023. // printf("after_lwip_select\n");
  1024. int read_len = SOCKET_READ(ssl->client_fd, &data[ret], length-ret);
  1025. // printf("read_len = %d\n", read_len);
  1026. if (read_len < 0)
  1027. {
  1028. #ifdef WIN32
  1029. if (GetLastError() == WSAEWOULDBLOCK)
  1030. #else
  1031. if (errno == EAGAIN || errno == EWOULDBLOCK)
  1032. #endif
  1033. continue;
  1034. }
  1035. /* connection has gone, so die */
  1036. if (read_len <= 0)
  1037. {
  1038. printf("SSL_ERROR_CONN_LOST\n");
  1039. ssl->hs_status = SSL_ERROR_DEAD; /* make sure it stays dead */
  1040. return SSL_ERROR_CONN_LOST;
  1041. }
  1042. ret += read_len;
  1043. }while(ret < length);
  1044. DISPLAY_BYTES(ssl, "received %d bytes", data, ret, ret);
  1045. return ret;
  1046. }
  1047. int read_record(SSL *ssl)
  1048. {
  1049. if(!IS_SET_SSL_FLAG(SSL_NEED_RECORD))
  1050. return 0;
  1051. uint8_t record[SSL_RECORD_SIZE];
  1052. int ret = basic_read2(ssl, record, SSL_RECORD_SIZE);
  1053. if(ret != SSL_RECORD_SIZE)
  1054. return ret;
  1055. /* check for sslv2 "client hello" */
  1056. if (record[0] & 0x80 && record[2] == 1)
  1057. {
  1058. #ifdef CONFIG_SSL_ENABLE_V23_HANDSHAKE
  1059. uint8_t version = (record[3] << 4) + record[4];
  1060. DISPLAY_BYTES(ssl, "ssl2 record", record, 5);
  1061. /* should be v3.1 (TLSv1) or better */
  1062. ssl->version = ssl->client_version = version;
  1063. if (version > SSL_PROTOCOL_VERSION_MAX)
  1064. {
  1065. /* use client's version */
  1066. ssl->version = SSL_PROTOCOL_VERSION_MAX;
  1067. }
  1068. else if (version < SSL_PROTOCOL_MIN_VERSION)
  1069. {
  1070. ret = SSL_ERROR_INVALID_VERSION;
  1071. ssl_display_error(ret);
  1072. return ret;
  1073. }
  1074. add_packet(ssl, &record[2], 3);
  1075. ret = process_sslv23_client_hello(ssl);
  1076. #else
  1077. printf("Error: no SSLv23 handshaking allowed\n"); TTY_FLUSH();
  1078. ret = SSL_ERROR_NOT_SUPPORTED;
  1079. #endif
  1080. return ret;
  1081. }
  1082. ssl->need_bytes = (record[3] << 8) + record[4];
  1083. memcpy(ssl->hmac_header, record, 3); /* store for hmac */
  1084. ssl->record_type = record[0];
  1085. CLR_SSL_FLAG(SSL_NEED_RECORD);
  1086. return SSL_OK;
  1087. }
  1088. int basic_decrypt(SSL *ssl, uint8_t *buf, int len)
  1089. {
  1090. if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED))
  1091. {
  1092. ssl->cipher_info->decrypt(ssl->decrypt_ctx, buf, buf, len);
  1093. if (ssl->version >= SSL_PROTOCOL_VERSION1_1 &&
  1094. ssl->cipher_info->iv_size)
  1095. {
  1096. buf += ssl->cipher_info->iv_size;
  1097. ssl->need_bytes -= ssl->cipher_info->iv_size;
  1098. }
  1099. if(ssl->record_type != PT_APP_PROTOCOL_DATA)
  1100. len = verify_digest(ssl,
  1101. IS_SET_SSL_FLAG(SSL_IS_CLIENT) ? SSL_CLIENT_READ : SSL_SERVER_READ, buf, len);
  1102. /* does the hmac work? */
  1103. if (ssl->need_bytes < 0)
  1104. {
  1105. return ssl->need_bytes;
  1106. }
  1107. DISPLAY_BYTES(ssl, "decrypted", buf, len);
  1108. increment_read_sequence(ssl);
  1109. }
  1110. return len;
  1111. }
  1112. int ssl_read(SSL *ssl, uint8_t *in_data, int len)
  1113. {
  1114. if(len <= 0 || in_data == NULL)
  1115. return 0;
  1116. if(IS_SET_SSL_FLAG(SSL_NEED_RECORD))
  1117. {
  1118. read_record(ssl);
  1119. }
  1120. return process_data(ssl, in_data, len);
  1121. }
  1122. int process_data(SSL* ssl, uint8_t *in_data, int len)
  1123. {
  1124. /* The main part of the SSL packet */
  1125. switch (ssl->record_type)
  1126. {
  1127. case PT_HANDSHAKE_PROTOCOL:
  1128. if (ssl->dc != NULL)
  1129. {
  1130. ssl->dc->bm_proc_index = 0;
  1131. int ret = do_handshake(ssl, NULL, 0);
  1132. SET_SSL_FLAG(SSL_NEED_RECORD);
  1133. return ret;
  1134. }
  1135. else /* no client renegotiation allowed */
  1136. {
  1137. SET_SSL_FLAG(SSL_NEED_RECORD);
  1138. return SSL_ERROR_NO_CLIENT_RENOG;
  1139. }
  1140. case PT_CHANGE_CIPHER_SPEC:
  1141. if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes)
  1142. return -1;
  1143. ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes);
  1144. if(ssl->need_bytes < 0)
  1145. return -1;
  1146. if (ssl->next_state != HS_FINISHED)
  1147. {
  1148. return SSL_ERROR_INVALID_HANDSHAKE;
  1149. }
  1150. /* all encrypted from now on */
  1151. SET_SSL_FLAG(SSL_RX_ENCRYPTED);
  1152. if (set_key_block(ssl, 0) < 0)
  1153. {
  1154. return SSL_ERROR_INVALID_HANDSHAKE;
  1155. }
  1156. memset(ssl->read_sequence, 0, 8);
  1157. SET_SSL_FLAG(SSL_NEED_RECORD);
  1158. break;
  1159. case PT_APP_PROTOCOL_DATA:
  1160. if(len <= 0)
  1161. return 0;
  1162. if(ssl->need_bytes == 0)
  1163. return 0;
  1164. if (in_data)
  1165. {
  1166. uint16_t index = ssl->bm_index % 2048;
  1167. if(ssl->bm_read_index == 0)
  1168. {
  1169. int read_len = len;
  1170. if(read_len > 2048-index)
  1171. read_len = 2048-index;
  1172. if(read_len > ssl->need_bytes)
  1173. read_len = ssl->need_bytes;
  1174. read_len -= read_len % AES_BLOCKSIZE;
  1175. if(read_len <= 0)
  1176. read_len = AES_BLOCKSIZE;
  1177. if(ssl->need_bytes < AES_BLOCKSIZE)
  1178. read_len = AES_BLOCKSIZE;
  1179. int ret = basic_read2(ssl, ssl->bm_all_data + index, read_len);
  1180. if(ret != read_len)
  1181. return 0;
  1182. ssl->bm_read_index = basic_decrypt(ssl, ssl->bm_all_data + index, read_len);
  1183. ssl->need_bytes -= ssl->bm_read_index;
  1184. if(ssl->need_bytes == 0)
  1185. {
  1186. ssl->bm_read_index = 0;
  1187. SET_SSL_FLAG(SSL_NEED_RECORD);
  1188. return ssl_read(ssl, in_data, len);
  1189. }
  1190. }
  1191. if(len > ssl->bm_read_index)
  1192. len = ssl->bm_read_index;
  1193. memcpy(in_data, ssl->bm_all_data+index, len);
  1194. ssl->bm_index += len;
  1195. ssl->bm_read_index -= len;
  1196. if(ssl->need_bytes == 0)
  1197. SET_SSL_FLAG(SSL_NEED_RECORD);
  1198. if(ssl->bm_index >= 2048)
  1199. ssl->bm_index = 0;
  1200. return len;
  1201. }
  1202. return 0;
  1203. case PT_ALERT_PROTOCOL:
  1204. if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes)
  1205. return -1;
  1206. ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes);
  1207. if(ssl->need_bytes < 0)
  1208. return -1;
  1209. SET_SSL_FLAG(SSL_NEED_RECORD);
  1210. /* return the alert # with alert bit set */
  1211. if(ssl->bm_data[0] == SSL_ALERT_TYPE_WARNING &&
  1212. ssl->bm_data[1] == SSL_ALERT_CLOSE_NOTIFY)
  1213. {
  1214. send_alert(ssl, SSL_ALERT_CLOSE_NOTIFY);
  1215. SET_SSL_FLAG(SSL_SENT_CLOSE_NOTIFY);
  1216. return SSL_CLOSE_NOTIFY;
  1217. }
  1218. else
  1219. {
  1220. int ret = -ssl->bm_data[1];
  1221. DISPLAY_ALERT(ssl, -ret);
  1222. return ret;
  1223. }
  1224. default:
  1225. return SSL_ERROR_INVALID_PROT_MSG;
  1226. }
  1227. }
  1228. /**
  1229. * Do some basic checking of data and then perform the appropriate handshaking.
  1230. */
  1231. static int do_handshake(SSL *ssl, uint8_t *buf, int read_len)
  1232. {
  1233. uint8_t hs_hdr[SSL_HS_HDR_SIZE];
  1234. if (IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED))
  1235. {
  1236. if(basic_read2(ssl, ssl->bm_data, ssl->need_bytes) != ssl->need_bytes)
  1237. return -1;
  1238. ssl->need_bytes = basic_decrypt(ssl, ssl->bm_data, ssl->need_bytes);
  1239. if(ssl->need_bytes < 0)
  1240. return -1;
  1241. buf = ssl->bm_data;
  1242. }
  1243. else
  1244. {
  1245. if(basic_read2(ssl, hs_hdr, SSL_HS_HDR_SIZE) != SSL_HS_HDR_SIZE)
  1246. return -1;
  1247. buf = hs_hdr;
  1248. }
  1249. int hs_len = (buf[2]<<8) + buf[3];
  1250. uint8_t handshake_type = buf[0];
  1251. int ret = SSL_OK;
  1252. int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
  1253. /* some integrity checking on the handshake */
  1254. //PARANOIA_CHECK(read_len-SSL_HS_HDR_SIZE, hs_len);
  1255. if (handshake_type != ssl->next_state)
  1256. {
  1257. /* handle a special case on the client */
  1258. if (!is_client || handshake_type != HS_CERT_REQ ||
  1259. ssl->next_state != HS_SERVER_HELLO_DONE)
  1260. {
  1261. return SSL_ERROR_INVALID_HANDSHAKE;
  1262. }
  1263. }
  1264. //hs_len += SSL_HS_HDR_SIZE; /* adjust for when adding packets */
  1265. ssl->bm_index = hs_len+SSL_HS_HDR_SIZE; /* store the size and check later */
  1266. DISPLAY_STATE(ssl, 0, handshake_type, 0);
  1267. if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST)
  1268. {
  1269. add_packet(ssl, buf, SSL_HS_HDR_SIZE);
  1270. }
  1271. if(!IS_SET_SSL_FLAG(SSL_RX_ENCRYPTED))
  1272. {
  1273. if(hs_len != 0 && handshake_type != HS_CERTIFICATE)
  1274. {
  1275. if(basic_read2(ssl, ssl->bm_data, hs_len) != hs_len)
  1276. return -1;
  1277. hs_len = basic_decrypt(ssl, ssl->bm_data, hs_len);
  1278. if(hs_len < 0)
  1279. return -1;
  1280. buf = ssl->bm_data;
  1281. if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST)
  1282. add_packet(ssl, buf, hs_len);
  1283. }
  1284. }
  1285. else if (handshake_type != HS_CERT_VERIFY && handshake_type != HS_HELLO_REQUEST)
  1286. add_packet(ssl, ssl->bm_data+SSL_HS_HDR_SIZE, hs_len-SSL_HS_HDR_SIZE);
  1287. #if defined(CONFIG_SSL_ENABLE_CLIENT)
  1288. ret = is_client ?
  1289. do_clnt_handshake(ssl, handshake_type, buf, hs_len) :
  1290. do_svr_handshake(ssl, handshake_type, buf, hs_len);
  1291. #else
  1292. ret = do_svr_handshake(ssl, handshake_type, buf, hs_len);
  1293. #endif
  1294. /* just use recursion to get the rest */
  1295. //if (hs_len < read_len && ret == SSL_OK)
  1296. //ret = do_handshake(ssl, &buf[hs_len], read_len-hs_len);
  1297. return ret;
  1298. }
  1299. /**
  1300. * Sends the change cipher spec message. We have just read a finished message
  1301. * from the client.
  1302. */
  1303. int send_change_cipher_spec(SSL *ssl)
  1304. {
  1305. int ret = send_packet(ssl, PT_CHANGE_CIPHER_SPEC,
  1306. g_chg_cipher_spec_pkt, sizeof(g_chg_cipher_spec_pkt));
  1307. SET_SSL_FLAG(SSL_TX_ENCRYPTED);
  1308. if (ret >= 0 && set_key_block(ssl, 1) < 0)
  1309. ret = SSL_ERROR_INVALID_HANDSHAKE;
  1310. memset(ssl->write_sequence, 0, 8);
  1311. return ret;
  1312. }
  1313. /**
  1314. * Send a "finished" message
  1315. */
  1316. int send_finished(SSL *ssl)
  1317. {
  1318. uint8_t buf[SSL_FINISHED_HASH_SIZE+4] = {
  1319. HS_FINISHED, 0, 0, SSL_FINISHED_HASH_SIZE };
  1320. /* now add the finished digest mac (12 bytes) */
  1321. finished_digest(ssl,
  1322. IS_SET_SSL_FLAG(SSL_IS_CLIENT) ?
  1323. client_finished : server_finished, &buf[4]);
  1324. #ifndef CONFIG_SSL_SKELETON_MODE
  1325. /* store in the session cache */
  1326. if (!IS_SET_SSL_FLAG(SSL_SESSION_RESUME) && ssl->ssl_ctx->num_sessions)
  1327. {
  1328. memcpy(ssl->session->master_secret,
  1329. ssl->dc->master_secret, SSL_SECRET_SIZE);
  1330. }
  1331. #endif
  1332. return send_packet(ssl, PT_HANDSHAKE_PROTOCOL,
  1333. buf, SSL_FINISHED_HASH_SIZE+4);
  1334. }
  1335. /**
  1336. * Send an alert message.
  1337. * Return 1 if the alert was an "error".
  1338. */
  1339. int send_alert(SSL *ssl, int error_code)
  1340. {
  1341. int alert_num = 0;
  1342. int is_warning = 0;
  1343. uint8_t buf[2];
  1344. /* Don't bother we're already dead */
  1345. if (ssl->hs_status == SSL_ERROR_DEAD)
  1346. {
  1347. return SSL_ERROR_CONN_LOST;
  1348. }
  1349. #ifdef CONFIG_SSL_FULL_MODE
  1350. if (IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
  1351. ssl_display_error(error_code);
  1352. #endif
  1353. switch (error_code)
  1354. {
  1355. case SSL_ALERT_CLOSE_NOTIFY:
  1356. is_warning = 1;
  1357. alert_num = SSL_ALERT_CLOSE_NOTIFY;
  1358. break;
  1359. case SSL_ERROR_CONN_LOST: /* don't send alert just yet */
  1360. is_warning = 1;
  1361. break;
  1362. case SSL_ERROR_INVALID_HANDSHAKE:
  1363. case SSL_ERROR_INVALID_PROT_MSG:
  1364. alert_num = SSL_ALERT_HANDSHAKE_FAILURE;
  1365. break;
  1366. case SSL_ERROR_INVALID_HMAC:
  1367. case SSL_ERROR_FINISHED_INVALID:
  1368. alert_num = SSL_ALERT_BAD_RECORD_MAC;
  1369. break;
  1370. case SSL_ERROR_INVALID_VERSION:
  1371. alert_num = SSL_ALERT_INVALID_VERSION;
  1372. break;
  1373. case SSL_ERROR_INVALID_SESSION:
  1374. case SSL_ERROR_NO_CIPHER:
  1375. case SSL_ERROR_INVALID_KEY:
  1376. alert_num = SSL_ALERT_ILLEGAL_PARAMETER;
  1377. break;
  1378. case SSL_ERROR_BAD_CERTIFICATE:
  1379. alert_num = SSL_ALERT_BAD_CERTIFICATE;
  1380. break;
  1381. case SSL_ERROR_NO_CLIENT_RENOG:
  1382. alert_num = SSL_ALERT_NO_RENEGOTIATION;
  1383. break;
  1384. default:
  1385. /* a catch-all for any badly verified certificates */
  1386. alert_num = (error_code <= SSL_X509_OFFSET) ?
  1387. SSL_ALERT_BAD_CERTIFICATE : SSL_ALERT_UNEXPECTED_MESSAGE;
  1388. break;
  1389. }
  1390. buf[0] = is_warning ? 1 : 2;
  1391. buf[1] = alert_num;
  1392. send_packet(ssl, PT_ALERT_PROTOCOL, buf, sizeof(buf));
  1393. DISPLAY_ALERT(ssl, alert_num);
  1394. return is_warning ? 0 : 1;
  1395. }
  1396. /**
  1397. * Process a client finished message.
  1398. */
  1399. int process_finished(SSL *ssl, uint8_t *buf, int hs_len)
  1400. {
  1401. int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
  1402. int ret = SSL_OK;
  1403. int resume = IS_SET_SSL_FLAG(SSL_SESSION_RESUME);
  1404. PARANOIA_CHECK(ssl->bm_index, SSL_FINISHED_HASH_SIZE);
  1405. /* check that we all work before we continue */
  1406. if (memcmp(ssl->dc->final_finish_mac, &buf[4], SSL_FINISHED_HASH_SIZE))
  1407. {
  1408. return SSL_ERROR_FINISHED_INVALID;
  1409. }
  1410. if ((!is_client && !resume) || (is_client && resume))
  1411. {
  1412. if ((ret = send_change_cipher_spec(ssl)) == SSL_OK)
  1413. ret = send_finished(ssl);
  1414. }
  1415. /* if we ever renegotiate */
  1416. ssl->next_state = is_client ? HS_HELLO_REQUEST : HS_CLIENT_HELLO;
  1417. ssl->hs_status = ret; /* set the final handshake status */
  1418. error:
  1419. return ret;
  1420. }
  1421. /**
  1422. * Send a certificate.
  1423. */
  1424. int send_certificate(SSL *ssl)
  1425. {
  1426. int i = 0;
  1427. uint8_t *buf = ssl->bm_data;
  1428. int offset = 7;
  1429. int chain_length;
  1430. buf[0] = HS_CERTIFICATE;
  1431. buf[1] = 0;
  1432. buf[4] = 0;
  1433. while (i < ssl->ssl_ctx->chain_length)
  1434. {
  1435. SSL_CERT *cert = &ssl->ssl_ctx->certs[i];
  1436. buf[offset++] = 0;
  1437. buf[offset++] = cert->size >> 8; /* cert 1 length */
  1438. buf[offset++] = cert->size & 0xff;
  1439. memcpy(&buf[offset], cert->buf, cert->size);
  1440. offset += cert->size;
  1441. i++;
  1442. }
  1443. chain_length = offset - 7;
  1444. buf[5] = chain_length >> 8; /* cert chain length */
  1445. buf[6] = chain_length & 0xff;
  1446. chain_length += 3;
  1447. buf[2] = chain_length >> 8; /* handshake length */
  1448. buf[3] = chain_length & 0xff;
  1449. ssl->bm_index = offset;
  1450. return send_packet(ssl, PT_HANDSHAKE_PROTOCOL, NULL, offset);
  1451. }
  1452. /**
  1453. * Create a blob of memory that we'll get rid of once the handshake is
  1454. * complete.
  1455. */
  1456. void disposable_new(SSL *ssl)
  1457. {
  1458. if (ssl->dc == NULL)
  1459. {
  1460. ssl->dc = (DISPOSABLE_CTX *)calloc(1, sizeof(DISPOSABLE_CTX));
  1461. memset(ssl->dc->key_block, 0, MAX_KEYBLOCK_SIZE);
  1462. MD5_Init(&ssl->dc->md5_ctx);
  1463. SHA1_Init(&ssl->dc->sha1_ctx);
  1464. }
  1465. }
  1466. /**
  1467. * Remove the temporary blob of memory.
  1468. */
  1469. void disposable_free(SSL *ssl)
  1470. {
  1471. if (ssl->dc)
  1472. {
  1473. //free(ssl->dc->key_block);
  1474. memset(ssl->dc, 0, sizeof(DISPOSABLE_CTX));
  1475. free(ssl->dc);
  1476. ssl->dc = NULL;
  1477. }
  1478. }
  1479. #ifndef CONFIG_SSL_SKELETON_MODE /* no session resumption in this mode */
  1480. /**
  1481. * Find if an existing session has the same session id. If so, use the
  1482. * master secret from this session for session resumption.
  1483. */
  1484. SSL_SESSION *ssl_session_update(int max_sessions, SSL_SESSION *ssl_sessions[],
  1485. SSL *ssl, const uint8_t *session_id)
  1486. {
  1487. time_t tm = time(NULL);
  1488. time_t oldest_sess_time = tm;
  1489. SSL_SESSION *oldest_sess = NULL;
  1490. int i;
  1491. /* no sessions? Then bail */
  1492. if (max_sessions == 0)
  1493. return NULL;
  1494. SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
  1495. if (session_id)
  1496. {
  1497. for (i = 0; i < max_sessions; i++)
  1498. {
  1499. if (ssl_sessions[i])
  1500. {
  1501. /* kill off any expired sessions (including those in
  1502. the future) */
  1503. if ((tm > ssl_sessions[i]->conn_time + SSL_EXPIRY_TIME) ||
  1504. (tm < ssl_sessions[i]->conn_time))
  1505. {
  1506. session_free(ssl_sessions, i);
  1507. continue;
  1508. }
  1509. /* if the session id matches, it must still be less than
  1510. the expiry time */
  1511. if (memcmp(ssl_sessions[i]->session_id, session_id,
  1512. SSL_SESSION_ID_SIZE) == 0)
  1513. {
  1514. ssl->session_index = i;
  1515. memcpy(ssl->dc->master_secret,
  1516. ssl_sessions[i]->master_secret, SSL_SECRET_SIZE);
  1517. SET_SSL_FLAG(SSL_SESSION_RESUME);
  1518. SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
  1519. return ssl_sessions[i]; /* a session was found */
  1520. }
  1521. }
  1522. }
  1523. }
  1524. /* If we've got here, no matching session was found - so create one */
  1525. for (i = 0; i < max_sessions; i++)
  1526. {
  1527. if (ssl_sessions[i] == NULL)
  1528. {
  1529. /* perfect, this will do */
  1530. ssl_sessions[i] = (SSL_SESSION *)calloc(1, sizeof(SSL_SESSION));
  1531. ssl_sessions[i]->conn_time = tm;
  1532. ssl->session_index = i;
  1533. SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
  1534. return ssl_sessions[i]; /* return the session object */
  1535. }
  1536. else if (ssl_sessions[i]->conn_time <= oldest_sess_time)
  1537. {
  1538. /* find the oldest session */
  1539. oldest_sess_time = ssl_sessions[i]->conn_time;
  1540. oldest_sess = ssl_sessions[i];
  1541. ssl->session_index = i;
  1542. }
  1543. }
  1544. /* ok, we've used up all of our sessions. So blow the oldest session away */
  1545. oldest_sess->conn_time = tm;
  1546. memset(oldest_sess->session_id, 0, sizeof(SSL_SESSION_ID_SIZE));
  1547. memset(oldest_sess->master_secret, 0, sizeof(SSL_SECRET_SIZE));
  1548. SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
  1549. return oldest_sess;
  1550. }
  1551. /**
  1552. * Free an existing session.
  1553. */
  1554. static void session_free(SSL_SESSION *ssl_sessions[], int sess_index)
  1555. {
  1556. if (ssl_sessions[sess_index])
  1557. {
  1558. free(ssl_sessions[sess_index]);
  1559. ssl_sessions[sess_index] = NULL;
  1560. }
  1561. }
  1562. /**
  1563. * This ssl object doesn't want this session anymore.
  1564. */
  1565. void kill_ssl_session(SSL_SESSION **ssl_sessions, SSL *ssl)
  1566. {
  1567. SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
  1568. if (ssl->ssl_ctx->num_sessions)
  1569. {
  1570. session_free(ssl_sessions, ssl->session_index);
  1571. ssl->session = NULL;
  1572. }
  1573. SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
  1574. }
  1575. #endif /* CONFIG_SSL_SKELETON_MODE */
  1576. /*
  1577. * Get the session id for a handshake. This will be a 32 byte sequence.
  1578. */
  1579. EXP_FUNC const uint8_t * STDCALL ssl_get_session_id(const SSL *ssl)
  1580. {
  1581. return ssl->session_id;
  1582. }
  1583. /*
  1584. * Get the session id size for a handshake.
  1585. */
  1586. EXP_FUNC uint8_t STDCALL ssl_get_session_id_size(const SSL *ssl)
  1587. {
  1588. return ssl->sess_id_size;
  1589. }
  1590. /*
  1591. * Return the cipher id (in the SSL form).
  1592. */
  1593. EXP_FUNC uint8_t STDCALL ssl_get_cipher_id(const SSL *ssl)
  1594. {
  1595. return ssl->cipher;
  1596. }
  1597. /*
  1598. * Return the status of the handshake.
  1599. */
  1600. EXP_FUNC int STDCALL ssl_handshake_status(const SSL *ssl)
  1601. {
  1602. return ssl->hs_status;
  1603. }
  1604. /*
  1605. * Retrieve various parameters about the SSL engine.
  1606. */
  1607. EXP_FUNC int STDCALL ssl_get_config(int offset)
  1608. {
  1609. switch (offset)
  1610. {
  1611. /* return the appropriate build mode */
  1612. case SSL_BUILD_MODE:
  1613. #if defined(CONFIG_SSL_FULL_MODE)
  1614. return SSL_BUILD_FULL_MODE;
  1615. #elif defined(CONFIG_SSL_ENABLE_CLIENT)
  1616. return SSL_BUILD_ENABLE_CLIENT;
  1617. #elif defined(CONFIG_ENABLE_VERIFICATION)
  1618. return SSL_BUILD_ENABLE_VERIFICATION;
  1619. #elif defined(CONFIG_SSL_SERVER_ONLY )
  1620. return SSL_BUILD_SERVER_ONLY;
  1621. #else
  1622. return SSL_BUILD_SKELETON_MODE;
  1623. #endif
  1624. case SSL_MAX_CERT_CFG_OFFSET:
  1625. return CONFIG_SSL_MAX_CERTS;
  1626. #ifdef CONFIG_SSL_CERT_VERIFICATION
  1627. case SSL_MAX_CA_CERT_CFG_OFFSET:
  1628. return CONFIG_X509_MAX_CA_CERTS;
  1629. #endif
  1630. #ifdef CONFIG_SSL_HAS_PEM
  1631. case SSL_HAS_PEM:
  1632. return 1;
  1633. #endif
  1634. default:
  1635. return 0;
  1636. }
  1637. }
  1638. #ifdef CONFIG_SSL_CERT_VERIFICATION
  1639. /**
  1640. * Authenticate a received certificate.
  1641. */
  1642. EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl)
  1643. {
  1644. int ret;
  1645. SSL_CTX_LOCK(ssl->ssl_ctx->mutex);
  1646. ret = x509_verify(ssl->ssl_ctx->ca_cert_ctx, ssl->x509_ctx);
  1647. SSL_CTX_UNLOCK(ssl->ssl_ctx->mutex);
  1648. if (ret) /* modify into an SSL error type */
  1649. {
  1650. ret = SSL_X509_ERROR(ret);
  1651. }
  1652. return ret;
  1653. }
  1654. /**
  1655. * Process a certificate message.
  1656. */
  1657. int process_certificate(SSL *ssl, X509_CTX **x509_ctx)
  1658. {
  1659. int ret = SSL_OK;
  1660. uint8_t cert_hdr[3];
  1661. if(basic_read2(ssl, cert_hdr, 3) != 3)
  1662. {
  1663. ret = SSL_NOT_OK;
  1664. return ret;
  1665. }
  1666. add_packet(ssl, cert_hdr, 3);
  1667. int len = 5;
  1668. int pkt_size = ssl->bm_index;
  1669. int cert_size;
  1670. int total_cert_size = (cert_hdr[1]<<8) + cert_hdr[2];
  1671. int is_client = IS_SET_SSL_FLAG(SSL_IS_CLIENT);
  1672. X509_CTX **chain = x509_ctx;
  1673. len += 2;
  1674. PARANOIA_CHECK(total_cert_size, 3);
  1675. while (len < total_cert_size)
  1676. {
  1677. if(basic_read2(ssl, cert_hdr, 3) != 3)
  1678. {
  1679. ret = SSL_NOT_OK;
  1680. return ret;
  1681. }
  1682. add_packet(ssl, cert_hdr, 3);
  1683. cert_size = (cert_hdr[1]<<8) + cert_hdr[2];
  1684. if(cert_size > RT_MAX_PLAIN_LENGTH)
  1685. {
  1686. ret = SSL_NOT_OK;
  1687. return ret;
  1688. }
  1689. len += 3;
  1690. if(basic_read2(ssl, ssl->bm_data, cert_size) != cert_size)
  1691. {
  1692. return SSL_NOT_OK;
  1693. }
  1694. add_packet(ssl, ssl->bm_data, cert_size);
  1695. if (x509_new(ssl->bm_data, NULL, chain))
  1696. {
  1697. ret = SSL_ERROR_BAD_CERTIFICATE;
  1698. goto error;
  1699. }
  1700. chain = &((*chain)->next);
  1701. len += cert_size;
  1702. }
  1703. PARANOIA_CHECK(pkt_size, len);
  1704. /* if we are client we can do the verify now or later */
  1705. if (is_client && !IS_SET_SSL_FLAG(SSL_SERVER_VERIFY_LATER))
  1706. {
  1707. ret = ssl_verify_cert(ssl);
  1708. }
  1709. ssl->next_state = is_client ? HS_SERVER_HELLO_DONE : HS_CLIENT_KEY_XCHG;
  1710. ssl->dc->bm_proc_index += len;
  1711. error:
  1712. return ret;
  1713. }
  1714. #endif /* CONFIG_SSL_CERT_VERIFICATION */
  1715. /**
  1716. * Debugging routine to display SSL handshaking stuff.
  1717. */
  1718. #ifdef CONFIG_SSL_FULL_MODE
  1719. /**
  1720. * Debugging routine to display SSL states.
  1721. */
  1722. void DISPLAY_STATE(SSL *ssl, int is_send, uint8_t state, int not_ok)
  1723. {
  1724. const char *str;
  1725. if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
  1726. return;
  1727. printf(not_ok ? "Error - invalid State:\t" : "State:\t");
  1728. printf(is_send ? "sending " : "receiving ");
  1729. switch (state)
  1730. {
  1731. case HS_HELLO_REQUEST:
  1732. str = "Hello Request (0)";
  1733. break;
  1734. case HS_CLIENT_HELLO:
  1735. str = "Client Hello (1)";
  1736. break;
  1737. case HS_SERVER_HELLO:
  1738. str = "Server Hello (2)";
  1739. break;
  1740. case HS_CERTIFICATE:
  1741. str = "Certificate (11)";
  1742. break;
  1743. case HS_SERVER_KEY_XCHG:
  1744. str = "Certificate Request (12)";
  1745. break;
  1746. case HS_CERT_REQ:
  1747. str = "Certificate Request (13)";
  1748. break;
  1749. case HS_SERVER_HELLO_DONE:
  1750. str = "Server Hello Done (14)";
  1751. break;
  1752. case HS_CERT_VERIFY:
  1753. str = "Certificate Verify (15)";
  1754. break;
  1755. case HS_CLIENT_KEY_XCHG:
  1756. str = "Client Key Exchange (16)";
  1757. break;
  1758. case HS_FINISHED:
  1759. str = "Finished (16)";
  1760. break;
  1761. default:
  1762. str = "Error (Unknown)";
  1763. break;
  1764. }
  1765. printf("%s\r\n", str);
  1766. TTY_FLUSH();
  1767. }
  1768. /**
  1769. * Debugging routine to display RSA objects
  1770. */
  1771. void DISPLAY_RSA(SSL *ssl, const RSA_CTX *rsa_ctx)
  1772. {
  1773. if (!IS_SET_SSL_FLAG(SSL_DISPLAY_RSA))
  1774. return;
  1775. RSA_print(rsa_ctx);
  1776. TTY_FLUSH();
  1777. }
  1778. /**
  1779. * Debugging routine to display SSL handshaking bytes.
  1780. */
  1781. void DISPLAY_BYTES(SSL *ssl, const char *format,
  1782. const uint8_t *data, int size, ...)
  1783. {
  1784. va_list(ap);
  1785. if (!IS_SET_SSL_FLAG(SSL_DISPLAY_BYTES))
  1786. return;
  1787. va_start(ap, size);
  1788. print_blob(format, data, size, va_arg(ap, char *));
  1789. va_end(ap);
  1790. TTY_FLUSH();
  1791. }
  1792. /**
  1793. * Debugging routine to display SSL handshaking errors.
  1794. */
  1795. EXP_FUNC void STDCALL ssl_display_error(int error_code)
  1796. {
  1797. if (error_code == SSL_OK)
  1798. return;
  1799. printf("Error: ");
  1800. /* X509 error? */
  1801. if (error_code < SSL_X509_OFFSET)
  1802. {
  1803. printf("%s\r\n", x509_display_error(error_code - SSL_X509_OFFSET));
  1804. return;
  1805. }
  1806. /* SSL alert error code */
  1807. if (error_code > SSL_ERROR_CONN_LOST)
  1808. {
  1809. printf("SSL error %d\n", -error_code);
  1810. return;
  1811. }
  1812. switch (error_code)
  1813. {
  1814. case SSL_ERROR_DEAD:
  1815. printf("connection dead");
  1816. break;
  1817. case SSL_ERROR_INVALID_HANDSHAKE:
  1818. printf("invalid handshake");
  1819. break;
  1820. case SSL_ERROR_INVALID_PROT_MSG:
  1821. printf("invalid protocol message");
  1822. break;
  1823. case SSL_ERROR_INVALID_HMAC:
  1824. printf("invalid mac");
  1825. break;
  1826. case SSL_ERROR_INVALID_VERSION:
  1827. printf("invalid version");
  1828. break;
  1829. case SSL_ERROR_INVALID_SESSION:
  1830. printf("invalid session");
  1831. break;
  1832. case SSL_ERROR_NO_CIPHER:
  1833. printf("no cipher");
  1834. break;
  1835. case SSL_ERROR_CONN_LOST:
  1836. printf("connection lost");
  1837. break;
  1838. case SSL_ERROR_BAD_CERTIFICATE:
  1839. printf("bad certificate");
  1840. break;
  1841. case SSL_ERROR_INVALID_KEY:
  1842. printf("invalid key");
  1843. break;
  1844. case SSL_ERROR_FINISHED_INVALID:
  1845. printf("finished invalid");
  1846. break;
  1847. case SSL_ERROR_NO_CERT_DEFINED:
  1848. printf("no certificate defined");
  1849. break;
  1850. case SSL_ERROR_NO_CLIENT_RENOG:
  1851. printf("client renegotiation not supported");
  1852. break;
  1853. case SSL_ERROR_NOT_SUPPORTED:
  1854. printf("Option not supported");
  1855. break;
  1856. default:
  1857. printf("undefined as yet - %d", error_code);
  1858. break;
  1859. }
  1860. printf("\r\n");
  1861. TTY_FLUSH();
  1862. }
  1863. /**
  1864. * Debugging routine to display alerts.
  1865. */
  1866. void DISPLAY_ALERT(SSL *ssl, int alert)
  1867. {
  1868. if (!IS_SET_SSL_FLAG(SSL_DISPLAY_STATES))
  1869. return;
  1870. printf("Alert: ");
  1871. switch (alert)
  1872. {
  1873. case SSL_ALERT_CLOSE_NOTIFY:
  1874. printf("close notify");
  1875. break;
  1876. case SSL_ALERT_INVALID_VERSION:
  1877. printf("invalid version");
  1878. break;
  1879. case SSL_ALERT_BAD_CERTIFICATE:
  1880. printf("bad certificate");
  1881. break;
  1882. case SSL_ALERT_UNEXPECTED_MESSAGE:
  1883. printf("unexpected message");
  1884. break;
  1885. case SSL_ALERT_BAD_RECORD_MAC:
  1886. printf("bad record mac");
  1887. break;
  1888. case SSL_ALERT_HANDSHAKE_FAILURE:
  1889. printf("handshake failure");
  1890. break;
  1891. case SSL_ALERT_ILLEGAL_PARAMETER:
  1892. printf("illegal parameter");
  1893. break;
  1894. case SSL_ALERT_DECODE_ERROR:
  1895. printf("decode error");
  1896. break;
  1897. case SSL_ALERT_DECRYPT_ERROR:
  1898. printf("decrypt error");
  1899. break;
  1900. case SSL_ALERT_NO_RENEGOTIATION:
  1901. printf("no renegotiation");
  1902. break;
  1903. default:
  1904. printf("alert - (unknown %d)", alert);
  1905. break;
  1906. }
  1907. printf("\r\n");
  1908. TTY_FLUSH();
  1909. }
  1910. #endif /* CONFIG_SSL_FULL_MODE */
  1911. /**
  1912. * Return the version of this library.
  1913. */
  1914. EXP_FUNC const char * STDCALL ssl_version()
  1915. {
  1916. static const char * axtls_version = AXTLS_VERSION;
  1917. return axtls_version;
  1918. }
  1919. /**
  1920. * Enable the various language bindings to work regardless of the
  1921. * configuration - they just return an error statement and a bad return code.
  1922. */
  1923. #if !defined(CONFIG_SSL_FULL_MODE)
  1924. EXP_FUNC void STDCALL ssl_display_error(int error_code) {}
  1925. #endif
  1926. #ifdef CONFIG_BINDINGS
  1927. #if !defined(CONFIG_SSL_ENABLE_CLIENT)
  1928. EXP_FUNC SSL * STDCALL ssl_client_new(SSL_CTX *ssl_ctx, int client_fd, const
  1929. uint8_t *session_id, uint8_t sess_id_size)
  1930. {
  1931. printf(unsupported_str);
  1932. return NULL;
  1933. }
  1934. #endif
  1935. #if !defined(CONFIG_SSL_CERT_VERIFICATION)
  1936. EXP_FUNC int STDCALL ssl_verify_cert(const SSL *ssl)
  1937. {
  1938. printf(unsupported_str);
  1939. return -1;
  1940. }
  1941. EXP_FUNC const char * STDCALL ssl_get_cert_dn(const SSL *ssl, int component)
  1942. {
  1943. printf(unsupported_str);
  1944. return NULL;
  1945. }
  1946. EXP_FUNC const char * STDCALL ssl_get_cert_subject_alt_dnsname(const SSL *ssl, int index)
  1947. {
  1948. printf(unsupported_str);
  1949. return NULL;
  1950. }
  1951. #endif /* CONFIG_SSL_CERT_VERIFICATION */
  1952. #endif /* CONFIG_BINDINGS */