You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tls.c 47KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754
  1. /*
  2. * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License as
  6. * published by the Free Software Foundation; either version 2 of the
  7. * License, or any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write to the Free Software
  16. * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  17. */
  18. FILE_LICENCE ( GPL2_OR_LATER );
  19. /**
  20. * @file
  21. *
  22. * Transport Layer Security Protocol
  23. */
  24. #include <stdint.h>
  25. #include <stdlib.h>
  26. #include <stdarg.h>
  27. #include <string.h>
  28. #include <errno.h>
  29. #include <byteswap.h>
  30. #include <ipxe/hmac.h>
  31. #include <ipxe/md5.h>
  32. #include <ipxe/sha1.h>
  33. #include <ipxe/aes.h>
  34. #include <ipxe/rsa.h>
  35. #include <ipxe/iobuf.h>
  36. #include <ipxe/xfer.h>
  37. #include <ipxe/open.h>
  38. #include <ipxe/asn1.h>
  39. #include <ipxe/x509.h>
  40. #include <ipxe/tls.h>
  41. static int tls_send_plaintext ( struct tls_session *tls, unsigned int type,
  42. const void *data, size_t len );
  43. static void tls_clear_cipher ( struct tls_session *tls,
  44. struct tls_cipherspec *cipherspec );
  45. /******************************************************************************
  46. *
  47. * Utility functions
  48. *
  49. ******************************************************************************
  50. */
  51. /**
  52. * Extract 24-bit field value
  53. *
  54. * @v field24 24-bit field
  55. * @ret value Field value
  56. *
  57. * TLS uses 24-bit integers in several places, which are awkward to
  58. * parse in C.
  59. */
  60. static unsigned long tls_uint24 ( uint8_t field24[3] ) {
  61. return ( ( field24[0] << 16 ) + ( field24[1] << 8 ) + field24[2] );
  62. }
  63. /******************************************************************************
  64. *
  65. * Cleanup functions
  66. *
  67. ******************************************************************************
  68. */
  69. /**
  70. * Free TLS session
  71. *
  72. * @v refcnt Reference counter
  73. */
  74. static void free_tls ( struct refcnt *refcnt ) {
  75. struct tls_session *tls =
  76. container_of ( refcnt, struct tls_session, refcnt );
  77. /* Free dynamically-allocated resources */
  78. tls_clear_cipher ( tls, &tls->tx_cipherspec );
  79. tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
  80. tls_clear_cipher ( tls, &tls->rx_cipherspec );
  81. tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
  82. x509_free_rsa_public_key ( &tls->rsa );
  83. free ( tls->rx_data );
  84. /* Free TLS structure itself */
  85. free ( tls );
  86. }
  87. /**
  88. * Finish with TLS session
  89. *
  90. * @v tls TLS session
  91. * @v rc Status code
  92. */
  93. static void tls_close ( struct tls_session *tls, int rc ) {
  94. /* Remove process */
  95. process_del ( &tls->process );
  96. /* Close ciphertext and plaintext streams */
  97. intf_shutdown ( &tls->cipherstream, rc );
  98. intf_shutdown ( &tls->plainstream, rc );
  99. }
  100. /******************************************************************************
  101. *
  102. * Random number generation
  103. *
  104. ******************************************************************************
  105. */
  106. /**
  107. * Generate random data
  108. *
  109. * @v data Buffer to fill
  110. * @v len Length of buffer
  111. */
  112. static void tls_generate_random ( void *data, size_t len ) {
  113. /* FIXME: Some real random data source would be nice... */
  114. memset ( data, 0x01, len );
  115. }
  116. /**
  117. * Update HMAC with a list of ( data, len ) pairs
  118. *
  119. * @v digest Hash function to use
  120. * @v digest_ctx Digest context
  121. * @v args ( data, len ) pairs of data, terminated by NULL
  122. */
  123. static void tls_hmac_update_va ( struct digest_algorithm *digest,
  124. void *digest_ctx, va_list args ) {
  125. void *data;
  126. size_t len;
  127. while ( ( data = va_arg ( args, void * ) ) ) {
  128. len = va_arg ( args, size_t );
  129. hmac_update ( digest, digest_ctx, data, len );
  130. }
  131. }
  132. /**
  133. * Generate secure pseudo-random data using a single hash function
  134. *
  135. * @v tls TLS session
  136. * @v digest Hash function to use
  137. * @v secret Secret
  138. * @v secret_len Length of secret
  139. * @v out Output buffer
  140. * @v out_len Length of output buffer
  141. * @v seeds ( data, len ) pairs of seed data, terminated by NULL
  142. */
  143. static void tls_p_hash_va ( struct tls_session *tls,
  144. struct digest_algorithm *digest,
  145. void *secret, size_t secret_len,
  146. void *out, size_t out_len,
  147. va_list seeds ) {
  148. uint8_t secret_copy[secret_len];
  149. uint8_t digest_ctx[digest->ctxsize];
  150. uint8_t digest_ctx_partial[digest->ctxsize];
  151. uint8_t a[digest->digestsize];
  152. uint8_t out_tmp[digest->digestsize];
  153. size_t frag_len = digest->digestsize;
  154. va_list tmp;
  155. /* Copy the secret, in case HMAC modifies it */
  156. memcpy ( secret_copy, secret, secret_len );
  157. secret = secret_copy;
  158. DBGC2 ( tls, "TLS %p %s secret:\n", tls, digest->name );
  159. DBGC2_HD ( tls, secret, secret_len );
  160. /* Calculate A(1) */
  161. hmac_init ( digest, digest_ctx, secret, &secret_len );
  162. va_copy ( tmp, seeds );
  163. tls_hmac_update_va ( digest, digest_ctx, tmp );
  164. va_end ( tmp );
  165. hmac_final ( digest, digest_ctx, secret, &secret_len, a );
  166. DBGC2 ( tls, "TLS %p %s A(1):\n", tls, digest->name );
  167. DBGC2_HD ( tls, &a, sizeof ( a ) );
  168. /* Generate as much data as required */
  169. while ( out_len ) {
  170. /* Calculate output portion */
  171. hmac_init ( digest, digest_ctx, secret, &secret_len );
  172. hmac_update ( digest, digest_ctx, a, sizeof ( a ) );
  173. memcpy ( digest_ctx_partial, digest_ctx, digest->ctxsize );
  174. va_copy ( tmp, seeds );
  175. tls_hmac_update_va ( digest, digest_ctx, tmp );
  176. va_end ( tmp );
  177. hmac_final ( digest, digest_ctx,
  178. secret, &secret_len, out_tmp );
  179. /* Copy output */
  180. if ( frag_len > out_len )
  181. frag_len = out_len;
  182. memcpy ( out, out_tmp, frag_len );
  183. DBGC2 ( tls, "TLS %p %s output:\n", tls, digest->name );
  184. DBGC2_HD ( tls, out, frag_len );
  185. /* Calculate A(i) */
  186. hmac_final ( digest, digest_ctx_partial,
  187. secret, &secret_len, a );
  188. DBGC2 ( tls, "TLS %p %s A(n):\n", tls, digest->name );
  189. DBGC2_HD ( tls, &a, sizeof ( a ) );
  190. out += frag_len;
  191. out_len -= frag_len;
  192. }
  193. }
  194. /**
  195. * Generate secure pseudo-random data
  196. *
  197. * @v tls TLS session
  198. * @v secret Secret
  199. * @v secret_len Length of secret
  200. * @v out Output buffer
  201. * @v out_len Length of output buffer
  202. * @v ... ( data, len ) pairs of seed data, terminated by NULL
  203. */
  204. static void tls_prf ( struct tls_session *tls, void *secret, size_t secret_len,
  205. void *out, size_t out_len, ... ) {
  206. va_list seeds;
  207. va_list tmp;
  208. size_t subsecret_len;
  209. void *md5_secret;
  210. void *sha1_secret;
  211. uint8_t out_md5[out_len];
  212. uint8_t out_sha1[out_len];
  213. unsigned int i;
  214. va_start ( seeds, out_len );
  215. /* Split secret into two, with an overlap of up to one byte */
  216. subsecret_len = ( ( secret_len + 1 ) / 2 );
  217. md5_secret = secret;
  218. sha1_secret = ( secret + secret_len - subsecret_len );
  219. /* Calculate MD5 portion */
  220. va_copy ( tmp, seeds );
  221. tls_p_hash_va ( tls, &md5_algorithm, md5_secret, subsecret_len,
  222. out_md5, out_len, seeds );
  223. va_end ( tmp );
  224. /* Calculate SHA1 portion */
  225. va_copy ( tmp, seeds );
  226. tls_p_hash_va ( tls, &sha1_algorithm, sha1_secret, subsecret_len,
  227. out_sha1, out_len, seeds );
  228. va_end ( tmp );
  229. /* XOR the two portions together into the final output buffer */
  230. for ( i = 0 ; i < out_len ; i++ ) {
  231. *( ( uint8_t * ) out + i ) = ( out_md5[i] ^ out_sha1[i] );
  232. }
  233. va_end ( seeds );
  234. }
  235. /**
  236. * Generate secure pseudo-random data
  237. *
  238. * @v secret Secret
  239. * @v secret_len Length of secret
  240. * @v out Output buffer
  241. * @v out_len Length of output buffer
  242. * @v label String literal label
  243. * @v ... ( data, len ) pairs of seed data
  244. */
  245. #define tls_prf_label( tls, secret, secret_len, out, out_len, label, ... ) \
  246. tls_prf ( (tls), (secret), (secret_len), (out), (out_len), \
  247. label, ( sizeof ( label ) - 1 ), __VA_ARGS__, NULL )
  248. /******************************************************************************
  249. *
  250. * Secret management
  251. *
  252. ******************************************************************************
  253. */
  254. /**
  255. * Generate master secret
  256. *
  257. * @v tls TLS session
  258. *
  259. * The pre-master secret and the client and server random values must
  260. * already be known.
  261. */
  262. static void tls_generate_master_secret ( struct tls_session *tls ) {
  263. DBGC ( tls, "TLS %p pre-master-secret:\n", tls );
  264. DBGC_HD ( tls, &tls->pre_master_secret,
  265. sizeof ( tls->pre_master_secret ) );
  266. DBGC ( tls, "TLS %p client random bytes:\n", tls );
  267. DBGC_HD ( tls, &tls->client_random, sizeof ( tls->client_random ) );
  268. DBGC ( tls, "TLS %p server random bytes:\n", tls );
  269. DBGC_HD ( tls, &tls->server_random, sizeof ( tls->server_random ) );
  270. tls_prf_label ( tls, &tls->pre_master_secret,
  271. sizeof ( tls->pre_master_secret ),
  272. &tls->master_secret, sizeof ( tls->master_secret ),
  273. "master secret",
  274. &tls->client_random, sizeof ( tls->client_random ),
  275. &tls->server_random, sizeof ( tls->server_random ) );
  276. DBGC ( tls, "TLS %p generated master secret:\n", tls );
  277. DBGC_HD ( tls, &tls->master_secret, sizeof ( tls->master_secret ) );
  278. }
  279. /**
  280. * Generate key material
  281. *
  282. * @v tls TLS session
  283. *
  284. * The master secret must already be known.
  285. */
  286. static int tls_generate_keys ( struct tls_session *tls ) {
  287. struct tls_cipherspec *tx_cipherspec = &tls->tx_cipherspec_pending;
  288. struct tls_cipherspec *rx_cipherspec = &tls->rx_cipherspec_pending;
  289. size_t hash_size = tx_cipherspec->digest->digestsize;
  290. size_t key_size = tx_cipherspec->key_len;
  291. size_t iv_size = tx_cipherspec->cipher->blocksize;
  292. size_t total = ( 2 * ( hash_size + key_size + iv_size ) );
  293. uint8_t key_block[total];
  294. uint8_t *key;
  295. int rc;
  296. /* Generate key block */
  297. tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
  298. key_block, sizeof ( key_block ), "key expansion",
  299. &tls->server_random, sizeof ( tls->server_random ),
  300. &tls->client_random, sizeof ( tls->client_random ) );
  301. /* Split key block into portions */
  302. key = key_block;
  303. /* TX MAC secret */
  304. memcpy ( tx_cipherspec->mac_secret, key, hash_size );
  305. DBGC ( tls, "TLS %p TX MAC secret:\n", tls );
  306. DBGC_HD ( tls, key, hash_size );
  307. key += hash_size;
  308. /* RX MAC secret */
  309. memcpy ( rx_cipherspec->mac_secret, key, hash_size );
  310. DBGC ( tls, "TLS %p RX MAC secret:\n", tls );
  311. DBGC_HD ( tls, key, hash_size );
  312. key += hash_size;
  313. /* TX key */
  314. if ( ( rc = cipher_setkey ( tx_cipherspec->cipher,
  315. tx_cipherspec->cipher_ctx,
  316. key, key_size ) ) != 0 ) {
  317. DBGC ( tls, "TLS %p could not set TX key: %s\n",
  318. tls, strerror ( rc ) );
  319. return rc;
  320. }
  321. DBGC ( tls, "TLS %p TX key:\n", tls );
  322. DBGC_HD ( tls, key, key_size );
  323. key += key_size;
  324. /* RX key */
  325. if ( ( rc = cipher_setkey ( rx_cipherspec->cipher,
  326. rx_cipherspec->cipher_ctx,
  327. key, key_size ) ) != 0 ) {
  328. DBGC ( tls, "TLS %p could not set TX key: %s\n",
  329. tls, strerror ( rc ) );
  330. return rc;
  331. }
  332. DBGC ( tls, "TLS %p RX key:\n", tls );
  333. DBGC_HD ( tls, key, key_size );
  334. key += key_size;
  335. /* TX initialisation vector */
  336. cipher_setiv ( tx_cipherspec->cipher, tx_cipherspec->cipher_ctx, key );
  337. DBGC ( tls, "TLS %p TX IV:\n", tls );
  338. DBGC_HD ( tls, key, iv_size );
  339. key += iv_size;
  340. /* RX initialisation vector */
  341. cipher_setiv ( rx_cipherspec->cipher, rx_cipherspec->cipher_ctx, key );
  342. DBGC ( tls, "TLS %p RX IV:\n", tls );
  343. DBGC_HD ( tls, key, iv_size );
  344. key += iv_size;
  345. assert ( ( key_block + total ) == key );
  346. return 0;
  347. }
  348. /******************************************************************************
  349. *
  350. * Cipher suite management
  351. *
  352. ******************************************************************************
  353. */
  354. /**
  355. * Clear cipher suite
  356. *
  357. * @v cipherspec TLS cipher specification
  358. */
  359. static void tls_clear_cipher ( struct tls_session *tls __unused,
  360. struct tls_cipherspec *cipherspec ) {
  361. free ( cipherspec->dynamic );
  362. memset ( cipherspec, 0, sizeof ( cipherspec ) );
  363. cipherspec->pubkey = &pubkey_null;
  364. cipherspec->cipher = &cipher_null;
  365. cipherspec->digest = &digest_null;
  366. }
  367. /**
  368. * Set cipher suite
  369. *
  370. * @v tls TLS session
  371. * @v cipherspec TLS cipher specification
  372. * @v pubkey Public-key encryption elgorithm
  373. * @v cipher Bulk encryption cipher algorithm
  374. * @v digest MAC digest algorithm
  375. * @v key_len Key length
  376. * @ret rc Return status code
  377. */
  378. static int tls_set_cipher ( struct tls_session *tls,
  379. struct tls_cipherspec *cipherspec,
  380. struct pubkey_algorithm *pubkey,
  381. struct cipher_algorithm *cipher,
  382. struct digest_algorithm *digest,
  383. size_t key_len ) {
  384. size_t total;
  385. void *dynamic;
  386. /* Clear out old cipher contents, if any */
  387. tls_clear_cipher ( tls, cipherspec );
  388. /* Allocate dynamic storage */
  389. total = ( pubkey->ctxsize + 2 * cipher->ctxsize + digest->digestsize );
  390. dynamic = malloc ( total );
  391. if ( ! dynamic ) {
  392. DBGC ( tls, "TLS %p could not allocate %zd bytes for crypto "
  393. "context\n", tls, total );
  394. return -ENOMEM;
  395. }
  396. memset ( dynamic, 0, total );
  397. /* Assign storage */
  398. cipherspec->dynamic = dynamic;
  399. cipherspec->pubkey_ctx = dynamic; dynamic += pubkey->ctxsize;
  400. cipherspec->cipher_ctx = dynamic; dynamic += cipher->ctxsize;
  401. cipherspec->cipher_next_ctx = dynamic; dynamic += cipher->ctxsize;
  402. cipherspec->mac_secret = dynamic; dynamic += digest->digestsize;
  403. assert ( ( cipherspec->dynamic + total ) == dynamic );
  404. /* Store parameters */
  405. cipherspec->pubkey = pubkey;
  406. cipherspec->cipher = cipher;
  407. cipherspec->digest = digest;
  408. cipherspec->key_len = key_len;
  409. return 0;
  410. }
  411. /**
  412. * Select next cipher suite
  413. *
  414. * @v tls TLS session
  415. * @v cipher_suite Cipher suite specification
  416. * @ret rc Return status code
  417. */
  418. static int tls_select_cipher ( struct tls_session *tls,
  419. unsigned int cipher_suite ) {
  420. struct pubkey_algorithm *pubkey = &pubkey_null;
  421. struct cipher_algorithm *cipher = &cipher_null;
  422. struct digest_algorithm *digest = &digest_null;
  423. unsigned int key_len = 0;
  424. int rc;
  425. switch ( cipher_suite ) {
  426. case htons ( TLS_RSA_WITH_AES_128_CBC_SHA ):
  427. key_len = ( 128 / 8 );
  428. cipher = &aes_cbc_algorithm;
  429. digest = &sha1_algorithm;
  430. break;
  431. case htons ( TLS_RSA_WITH_AES_256_CBC_SHA ):
  432. key_len = ( 256 / 8 );
  433. cipher = &aes_cbc_algorithm;
  434. digest = &sha1_algorithm;
  435. break;
  436. default:
  437. DBGC ( tls, "TLS %p does not support cipher %04x\n",
  438. tls, ntohs ( cipher_suite ) );
  439. return -ENOTSUP;
  440. }
  441. /* Set ciphers */
  442. if ( ( rc = tls_set_cipher ( tls, &tls->tx_cipherspec_pending, pubkey,
  443. cipher, digest, key_len ) ) != 0 )
  444. return rc;
  445. if ( ( rc = tls_set_cipher ( tls, &tls->rx_cipherspec_pending, pubkey,
  446. cipher, digest, key_len ) ) != 0 )
  447. return rc;
  448. DBGC ( tls, "TLS %p selected %s-%s-%d-%s\n", tls,
  449. pubkey->name, cipher->name, ( key_len * 8 ), digest->name );
  450. return 0;
  451. }
  452. /**
  453. * Activate next cipher suite
  454. *
  455. * @v tls TLS session
  456. * @v pending Pending cipher specification
  457. * @v active Active cipher specification to replace
  458. * @ret rc Return status code
  459. */
  460. static int tls_change_cipher ( struct tls_session *tls,
  461. struct tls_cipherspec *pending,
  462. struct tls_cipherspec *active ) {
  463. /* Sanity check */
  464. if ( /* FIXME (when pubkey is not hard-coded to RSA):
  465. * ( pending->pubkey == &pubkey_null ) || */
  466. ( pending->cipher == &cipher_null ) ||
  467. ( pending->digest == &digest_null ) ) {
  468. DBGC ( tls, "TLS %p refusing to use null cipher\n", tls );
  469. return -ENOTSUP;
  470. }
  471. tls_clear_cipher ( tls, active );
  472. memswap ( active, pending, sizeof ( *active ) );
  473. return 0;
  474. }
  475. /******************************************************************************
  476. *
  477. * Handshake verification
  478. *
  479. ******************************************************************************
  480. */
  481. /**
  482. * Add handshake record to verification hash
  483. *
  484. * @v tls TLS session
  485. * @v data Handshake record
  486. * @v len Length of handshake record
  487. */
  488. static void tls_add_handshake ( struct tls_session *tls,
  489. const void *data, size_t len ) {
  490. digest_update ( &md5_algorithm, tls->handshake_md5_ctx, data, len );
  491. digest_update ( &sha1_algorithm, tls->handshake_sha1_ctx, data, len );
  492. }
  493. /**
  494. * Calculate handshake verification hash
  495. *
  496. * @v tls TLS session
  497. * @v out Output buffer
  498. *
  499. * Calculates the MD5+SHA1 digest over all handshake messages seen so
  500. * far.
  501. */
  502. static void tls_verify_handshake ( struct tls_session *tls, void *out ) {
  503. struct digest_algorithm *md5 = &md5_algorithm;
  504. struct digest_algorithm *sha1 = &sha1_algorithm;
  505. uint8_t md5_ctx[md5->ctxsize];
  506. uint8_t sha1_ctx[sha1->ctxsize];
  507. void *md5_digest = out;
  508. void *sha1_digest = ( out + md5->digestsize );
  509. memcpy ( md5_ctx, tls->handshake_md5_ctx, sizeof ( md5_ctx ) );
  510. memcpy ( sha1_ctx, tls->handshake_sha1_ctx, sizeof ( sha1_ctx ) );
  511. digest_final ( md5, md5_ctx, md5_digest );
  512. digest_final ( sha1, sha1_ctx, sha1_digest );
  513. }
  514. /******************************************************************************
  515. *
  516. * Record handling
  517. *
  518. ******************************************************************************
  519. */
  520. /**
  521. * Transmit Handshake record
  522. *
  523. * @v tls TLS session
  524. * @v data Plaintext record
  525. * @v len Length of plaintext record
  526. * @ret rc Return status code
  527. */
  528. static int tls_send_handshake ( struct tls_session *tls,
  529. void *data, size_t len ) {
  530. /* Add to handshake digest */
  531. tls_add_handshake ( tls, data, len );
  532. /* Send record */
  533. return tls_send_plaintext ( tls, TLS_TYPE_HANDSHAKE, data, len );
  534. }
  535. /**
  536. * Transmit Client Hello record
  537. *
  538. * @v tls TLS session
  539. * @ret rc Return status code
  540. */
  541. static int tls_send_client_hello ( struct tls_session *tls ) {
  542. struct {
  543. uint32_t type_length;
  544. uint16_t version;
  545. uint8_t random[32];
  546. uint8_t session_id_len;
  547. uint16_t cipher_suite_len;
  548. uint16_t cipher_suites[2];
  549. uint8_t compression_methods_len;
  550. uint8_t compression_methods[1];
  551. } __attribute__ (( packed )) hello;
  552. memset ( &hello, 0, sizeof ( hello ) );
  553. hello.type_length = ( cpu_to_le32 ( TLS_CLIENT_HELLO ) |
  554. htonl ( sizeof ( hello ) -
  555. sizeof ( hello.type_length ) ) );
  556. hello.version = htons ( TLS_VERSION_TLS_1_0 );
  557. memcpy ( &hello.random, &tls->client_random, sizeof ( hello.random ) );
  558. hello.cipher_suite_len = htons ( sizeof ( hello.cipher_suites ) );
  559. hello.cipher_suites[0] = htons ( TLS_RSA_WITH_AES_128_CBC_SHA );
  560. hello.cipher_suites[1] = htons ( TLS_RSA_WITH_AES_256_CBC_SHA );
  561. hello.compression_methods_len = sizeof ( hello.compression_methods );
  562. return tls_send_handshake ( tls, &hello, sizeof ( hello ) );
  563. }
  564. /**
  565. * Transmit Client Key Exchange record
  566. *
  567. * @v tls TLS session
  568. * @ret rc Return status code
  569. */
  570. static int tls_send_client_key_exchange ( struct tls_session *tls ) {
  571. /* FIXME: Hack alert */
  572. RSA_CTX *rsa_ctx;
  573. RSA_pub_key_new ( &rsa_ctx, tls->rsa.modulus, tls->rsa.modulus_len,
  574. tls->rsa.exponent, tls->rsa.exponent_len );
  575. struct {
  576. uint32_t type_length;
  577. uint16_t encrypted_pre_master_secret_len;
  578. uint8_t encrypted_pre_master_secret[rsa_ctx->num_octets];
  579. } __attribute__ (( packed )) key_xchg;
  580. memset ( &key_xchg, 0, sizeof ( key_xchg ) );
  581. key_xchg.type_length = ( cpu_to_le32 ( TLS_CLIENT_KEY_EXCHANGE ) |
  582. htonl ( sizeof ( key_xchg ) -
  583. sizeof ( key_xchg.type_length ) ) );
  584. key_xchg.encrypted_pre_master_secret_len
  585. = htons ( sizeof ( key_xchg.encrypted_pre_master_secret ) );
  586. /* FIXME: Hack alert */
  587. DBGC ( tls, "RSA encrypting plaintext, modulus, exponent:\n" );
  588. DBGC_HD ( tls, &tls->pre_master_secret,
  589. sizeof ( tls->pre_master_secret ) );
  590. DBGC_HD ( tls, tls->rsa.modulus, tls->rsa.modulus_len );
  591. DBGC_HD ( tls, tls->rsa.exponent, tls->rsa.exponent_len );
  592. RSA_encrypt ( rsa_ctx, ( const uint8_t * ) &tls->pre_master_secret,
  593. sizeof ( tls->pre_master_secret ),
  594. key_xchg.encrypted_pre_master_secret, 0 );
  595. DBGC ( tls, "RSA encrypt done. Ciphertext:\n" );
  596. DBGC_HD ( tls, &key_xchg.encrypted_pre_master_secret,
  597. sizeof ( key_xchg.encrypted_pre_master_secret ) );
  598. RSA_free ( rsa_ctx );
  599. return tls_send_handshake ( tls, &key_xchg, sizeof ( key_xchg ) );
  600. }
  601. /**
  602. * Transmit Change Cipher record
  603. *
  604. * @v tls TLS session
  605. * @ret rc Return status code
  606. */
  607. static int tls_send_change_cipher ( struct tls_session *tls ) {
  608. static const uint8_t change_cipher[1] = { 1 };
  609. return tls_send_plaintext ( tls, TLS_TYPE_CHANGE_CIPHER,
  610. change_cipher, sizeof ( change_cipher ) );
  611. }
  612. /**
  613. * Transmit Finished record
  614. *
  615. * @v tls TLS session
  616. * @ret rc Return status code
  617. */
  618. static int tls_send_finished ( struct tls_session *tls ) {
  619. struct {
  620. uint32_t type_length;
  621. uint8_t verify_data[12];
  622. } __attribute__ (( packed )) finished;
  623. uint8_t digest[MD5_DIGEST_SIZE + SHA1_DIGEST_SIZE];
  624. memset ( &finished, 0, sizeof ( finished ) );
  625. finished.type_length = ( cpu_to_le32 ( TLS_FINISHED ) |
  626. htonl ( sizeof ( finished ) -
  627. sizeof ( finished.type_length ) ) );
  628. tls_verify_handshake ( tls, digest );
  629. tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
  630. finished.verify_data, sizeof ( finished.verify_data ),
  631. "client finished", digest, sizeof ( digest ) );
  632. return tls_send_handshake ( tls, &finished, sizeof ( finished ) );
  633. }
  634. /**
  635. * Receive new Change Cipher record
  636. *
  637. * @v tls TLS session
  638. * @v data Plaintext record
  639. * @v len Length of plaintext record
  640. * @ret rc Return status code
  641. */
  642. static int tls_new_change_cipher ( struct tls_session *tls,
  643. void *data, size_t len ) {
  644. int rc;
  645. if ( ( len != 1 ) || ( *( ( uint8_t * ) data ) != 1 ) ) {
  646. DBGC ( tls, "TLS %p received invalid Change Cipher\n", tls );
  647. DBGC_HD ( tls, data, len );
  648. return -EINVAL;
  649. }
  650. if ( ( rc = tls_change_cipher ( tls, &tls->rx_cipherspec_pending,
  651. &tls->rx_cipherspec ) ) != 0 ) {
  652. DBGC ( tls, "TLS %p could not activate RX cipher: %s\n",
  653. tls, strerror ( rc ) );
  654. return rc;
  655. }
  656. tls->rx_seq = ~( ( uint64_t ) 0 );
  657. return 0;
  658. }
  659. /**
  660. * Receive new Alert record
  661. *
  662. * @v tls TLS session
  663. * @v data Plaintext record
  664. * @v len Length of plaintext record
  665. * @ret rc Return status code
  666. */
  667. static int tls_new_alert ( struct tls_session *tls, void *data, size_t len ) {
  668. struct {
  669. uint8_t level;
  670. uint8_t description;
  671. char next[0];
  672. } __attribute__ (( packed )) *alert = data;
  673. void *end = alert->next;
  674. /* Sanity check */
  675. if ( end != ( data + len ) ) {
  676. DBGC ( tls, "TLS %p received overlength Alert\n", tls );
  677. DBGC_HD ( tls, data, len );
  678. return -EINVAL;
  679. }
  680. switch ( alert->level ) {
  681. case TLS_ALERT_WARNING:
  682. DBGC ( tls, "TLS %p received warning alert %d\n",
  683. tls, alert->description );
  684. return 0;
  685. case TLS_ALERT_FATAL:
  686. DBGC ( tls, "TLS %p received fatal alert %d\n",
  687. tls, alert->description );
  688. return -EPERM;
  689. default:
  690. DBGC ( tls, "TLS %p received unknown alert level %d"
  691. "(alert %d)\n", tls, alert->level, alert->description );
  692. return -EIO;
  693. }
  694. }
  695. /**
  696. * Receive new Server Hello handshake record
  697. *
  698. * @v tls TLS session
  699. * @v data Plaintext handshake record
  700. * @v len Length of plaintext handshake record
  701. * @ret rc Return status code
  702. */
  703. static int tls_new_server_hello ( struct tls_session *tls,
  704. void *data, size_t len ) {
  705. struct {
  706. uint16_t version;
  707. uint8_t random[32];
  708. uint8_t session_id_len;
  709. char next[0];
  710. } __attribute__ (( packed )) *hello_a = data;
  711. struct {
  712. uint8_t session_id[hello_a->session_id_len];
  713. uint16_t cipher_suite;
  714. uint8_t compression_method;
  715. char next[0];
  716. } __attribute__ (( packed )) *hello_b = ( void * ) &hello_a->next;
  717. void *end = hello_b->next;
  718. int rc;
  719. /* Sanity check */
  720. if ( end != ( data + len ) ) {
  721. DBGC ( tls, "TLS %p received overlength Server Hello\n", tls );
  722. DBGC_HD ( tls, data, len );
  723. return -EINVAL;
  724. }
  725. /* Check protocol version */
  726. if ( ntohs ( hello_a->version ) < TLS_VERSION_TLS_1_0 ) {
  727. DBGC ( tls, "TLS %p does not support protocol version %d.%d\n",
  728. tls, ( ntohs ( hello_a->version ) >> 8 ),
  729. ( ntohs ( hello_a->version ) & 0xff ) );
  730. return -ENOTSUP;
  731. }
  732. /* Copy out server random bytes */
  733. memcpy ( &tls->server_random, &hello_a->random,
  734. sizeof ( tls->server_random ) );
  735. /* Select cipher suite */
  736. if ( ( rc = tls_select_cipher ( tls, hello_b->cipher_suite ) ) != 0 )
  737. return rc;
  738. /* Generate secrets */
  739. tls_generate_master_secret ( tls );
  740. if ( ( rc = tls_generate_keys ( tls ) ) != 0 )
  741. return rc;
  742. return 0;
  743. }
  744. /**
  745. * Receive new Certificate handshake record
  746. *
  747. * @v tls TLS session
  748. * @v data Plaintext handshake record
  749. * @v len Length of plaintext handshake record
  750. * @ret rc Return status code
  751. */
  752. static int tls_new_certificate ( struct tls_session *tls,
  753. void *data, size_t len ) {
  754. struct {
  755. uint8_t length[3];
  756. uint8_t certificates[0];
  757. } __attribute__ (( packed )) *certificate = data;
  758. struct {
  759. uint8_t length[3];
  760. uint8_t certificate[0];
  761. } __attribute__ (( packed )) *element =
  762. ( ( void * ) certificate->certificates );
  763. size_t elements_len = tls_uint24 ( certificate->length );
  764. void *end = ( certificate->certificates + elements_len );
  765. struct asn1_cursor cursor;
  766. int rc;
  767. /* Sanity check */
  768. if ( end != ( data + len ) ) {
  769. DBGC ( tls, "TLS %p received overlength Server Certificate\n",
  770. tls );
  771. DBGC_HD ( tls, data, len );
  772. return -EINVAL;
  773. }
  774. /* Traverse certificate chain */
  775. do {
  776. cursor.data = element->certificate;
  777. cursor.len = tls_uint24 ( element->length );
  778. if ( ( cursor.data + cursor.len ) > end ) {
  779. DBGC ( tls, "TLS %p received corrupt Server "
  780. "Certificate\n", tls );
  781. DBGC_HD ( tls, data, len );
  782. return -EINVAL;
  783. }
  784. // HACK
  785. if ( ( rc = x509_rsa_public_key ( &cursor,
  786. &tls->rsa ) ) != 0 ) {
  787. DBGC ( tls, "TLS %p cannot determine RSA public key: "
  788. "%s\n", tls, strerror ( rc ) );
  789. return rc;
  790. }
  791. return 0;
  792. element = ( cursor.data + cursor.len );
  793. } while ( element != end );
  794. return -EINVAL;
  795. }
  796. /**
  797. * Receive new Server Hello Done handshake record
  798. *
  799. * @v tls TLS session
  800. * @v data Plaintext handshake record
  801. * @v len Length of plaintext handshake record
  802. * @ret rc Return status code
  803. */
  804. static int tls_new_server_hello_done ( struct tls_session *tls,
  805. void *data, size_t len ) {
  806. struct {
  807. char next[0];
  808. } __attribute__ (( packed )) *hello_done = data;
  809. void *end = hello_done->next;
  810. /* Sanity check */
  811. if ( end != ( data + len ) ) {
  812. DBGC ( tls, "TLS %p received overlength Server Hello Done\n",
  813. tls );
  814. DBGC_HD ( tls, data, len );
  815. return -EINVAL;
  816. }
  817. /* Check that we are ready to send the Client Key Exchange */
  818. if ( tls->tx_state != TLS_TX_NONE ) {
  819. DBGC ( tls, "TLS %p received Server Hello Done while in "
  820. "TX state %d\n", tls, tls->tx_state );
  821. return -EIO;
  822. }
  823. /* Start sending the Client Key Exchange */
  824. tls->tx_state = TLS_TX_CLIENT_KEY_EXCHANGE;
  825. return 0;
  826. }
  827. /**
  828. * Receive new Finished handshake record
  829. *
  830. * @v tls TLS session
  831. * @v data Plaintext handshake record
  832. * @v len Length of plaintext handshake record
  833. * @ret rc Return status code
  834. */
  835. static int tls_new_finished ( struct tls_session *tls,
  836. void *data, size_t len ) {
  837. /* FIXME: Handle this properly */
  838. tls->tx_state = TLS_TX_DATA;
  839. ( void ) data;
  840. ( void ) len;
  841. return 0;
  842. }
  843. /**
  844. * Receive new Handshake record
  845. *
  846. * @v tls TLS session
  847. * @v data Plaintext record
  848. * @v len Length of plaintext record
  849. * @ret rc Return status code
  850. */
  851. static int tls_new_handshake ( struct tls_session *tls,
  852. void *data, size_t len ) {
  853. void *end = ( data + len );
  854. int rc;
  855. while ( data != end ) {
  856. struct {
  857. uint8_t type;
  858. uint8_t length[3];
  859. uint8_t payload[0];
  860. } __attribute__ (( packed )) *handshake = data;
  861. void *payload = &handshake->payload;
  862. size_t payload_len = tls_uint24 ( handshake->length );
  863. void *next = ( payload + payload_len );
  864. /* Sanity check */
  865. if ( next > end ) {
  866. DBGC ( tls, "TLS %p received overlength Handshake\n",
  867. tls );
  868. DBGC_HD ( tls, data, len );
  869. return -EINVAL;
  870. }
  871. switch ( handshake->type ) {
  872. case TLS_SERVER_HELLO:
  873. rc = tls_new_server_hello ( tls, payload, payload_len );
  874. break;
  875. case TLS_CERTIFICATE:
  876. rc = tls_new_certificate ( tls, payload, payload_len );
  877. break;
  878. case TLS_SERVER_HELLO_DONE:
  879. rc = tls_new_server_hello_done ( tls, payload,
  880. payload_len );
  881. break;
  882. case TLS_FINISHED:
  883. rc = tls_new_finished ( tls, payload, payload_len );
  884. break;
  885. default:
  886. DBGC ( tls, "TLS %p ignoring handshake type %d\n",
  887. tls, handshake->type );
  888. rc = 0;
  889. break;
  890. }
  891. /* Add to handshake digest (except for Hello Requests,
  892. * which are explicitly excluded).
  893. */
  894. if ( handshake->type != TLS_HELLO_REQUEST )
  895. tls_add_handshake ( tls, data,
  896. sizeof ( *handshake ) +
  897. payload_len );
  898. /* Abort on failure */
  899. if ( rc != 0 )
  900. return rc;
  901. /* Move to next handshake record */
  902. data = next;
  903. }
  904. return 0;
  905. }
  906. /**
  907. * Receive new record
  908. *
  909. * @v tls TLS session
  910. * @v type Record type
  911. * @v data Plaintext record
  912. * @v len Length of plaintext record
  913. * @ret rc Return status code
  914. */
  915. static int tls_new_record ( struct tls_session *tls,
  916. unsigned int type, void *data, size_t len ) {
  917. switch ( type ) {
  918. case TLS_TYPE_CHANGE_CIPHER:
  919. return tls_new_change_cipher ( tls, data, len );
  920. case TLS_TYPE_ALERT:
  921. return tls_new_alert ( tls, data, len );
  922. case TLS_TYPE_HANDSHAKE:
  923. return tls_new_handshake ( tls, data, len );
  924. case TLS_TYPE_DATA:
  925. return xfer_deliver_raw ( &tls->plainstream, data, len );
  926. default:
  927. /* RFC4346 says that we should just ignore unknown
  928. * record types.
  929. */
  930. DBGC ( tls, "TLS %p ignoring record type %d\n", tls, type );
  931. return 0;
  932. }
  933. }
  934. /******************************************************************************
  935. *
  936. * Record encryption/decryption
  937. *
  938. ******************************************************************************
  939. */
  940. /**
  941. * Calculate HMAC
  942. *
  943. * @v tls TLS session
  944. * @v cipherspec Cipher specification
  945. * @v seq Sequence number
  946. * @v tlshdr TLS header
  947. * @v data Data
  948. * @v len Length of data
  949. * @v mac HMAC to fill in
  950. */
  951. static void tls_hmac ( struct tls_session *tls __unused,
  952. struct tls_cipherspec *cipherspec,
  953. uint64_t seq, struct tls_header *tlshdr,
  954. const void *data, size_t len, void *hmac ) {
  955. struct digest_algorithm *digest = cipherspec->digest;
  956. uint8_t digest_ctx[digest->ctxsize];
  957. hmac_init ( digest, digest_ctx, cipherspec->mac_secret,
  958. &digest->digestsize );
  959. seq = cpu_to_be64 ( seq );
  960. hmac_update ( digest, digest_ctx, &seq, sizeof ( seq ) );
  961. hmac_update ( digest, digest_ctx, tlshdr, sizeof ( *tlshdr ) );
  962. hmac_update ( digest, digest_ctx, data, len );
  963. hmac_final ( digest, digest_ctx, cipherspec->mac_secret,
  964. &digest->digestsize, hmac );
  965. }
  966. /**
  967. * Allocate and assemble stream-ciphered record from data and MAC portions
  968. *
  969. * @v tls TLS session
  970. * @ret data Data
  971. * @ret len Length of data
  972. * @ret digest MAC digest
  973. * @ret plaintext_len Length of plaintext record
  974. * @ret plaintext Allocated plaintext record
  975. */
  976. static void * __malloc tls_assemble_stream ( struct tls_session *tls,
  977. const void *data, size_t len,
  978. void *digest, size_t *plaintext_len ) {
  979. size_t mac_len = tls->tx_cipherspec.digest->digestsize;
  980. void *plaintext;
  981. void *content;
  982. void *mac;
  983. /* Calculate stream-ciphered struct length */
  984. *plaintext_len = ( len + mac_len );
  985. /* Allocate stream-ciphered struct */
  986. plaintext = malloc ( *plaintext_len );
  987. if ( ! plaintext )
  988. return NULL;
  989. content = plaintext;
  990. mac = ( content + len );
  991. /* Fill in stream-ciphered struct */
  992. memcpy ( content, data, len );
  993. memcpy ( mac, digest, mac_len );
  994. return plaintext;
  995. }
  996. /**
  997. * Allocate and assemble block-ciphered record from data and MAC portions
  998. *
  999. * @v tls TLS session
  1000. * @ret data Data
  1001. * @ret len Length of data
  1002. * @ret digest MAC digest
  1003. * @ret plaintext_len Length of plaintext record
  1004. * @ret plaintext Allocated plaintext record
  1005. */
  1006. static void * tls_assemble_block ( struct tls_session *tls,
  1007. const void *data, size_t len,
  1008. void *digest, size_t *plaintext_len ) {
  1009. size_t blocksize = tls->tx_cipherspec.cipher->blocksize;
  1010. size_t iv_len = blocksize;
  1011. size_t mac_len = tls->tx_cipherspec.digest->digestsize;
  1012. size_t padding_len;
  1013. void *plaintext;
  1014. void *iv;
  1015. void *content;
  1016. void *mac;
  1017. void *padding;
  1018. /* FIXME: TLSv1.1 has an explicit IV */
  1019. iv_len = 0;
  1020. /* Calculate block-ciphered struct length */
  1021. padding_len = ( ( blocksize - 1 ) & -( iv_len + len + mac_len + 1 ) );
  1022. *plaintext_len = ( iv_len + len + mac_len + padding_len + 1 );
  1023. /* Allocate block-ciphered struct */
  1024. plaintext = malloc ( *plaintext_len );
  1025. if ( ! plaintext )
  1026. return NULL;
  1027. iv = plaintext;
  1028. content = ( iv + iv_len );
  1029. mac = ( content + len );
  1030. padding = ( mac + mac_len );
  1031. /* Fill in block-ciphered struct */
  1032. memset ( iv, 0, iv_len );
  1033. memcpy ( content, data, len );
  1034. memcpy ( mac, digest, mac_len );
  1035. memset ( padding, padding_len, ( padding_len + 1 ) );
  1036. return plaintext;
  1037. }
  1038. /**
  1039. * Send plaintext record
  1040. *
  1041. * @v tls TLS session
  1042. * @v type Record type
  1043. * @v data Plaintext record
  1044. * @v len Length of plaintext record
  1045. * @ret rc Return status code
  1046. */
  1047. static int tls_send_plaintext ( struct tls_session *tls, unsigned int type,
  1048. const void *data, size_t len ) {
  1049. struct tls_header plaintext_tlshdr;
  1050. struct tls_header *tlshdr;
  1051. struct tls_cipherspec *cipherspec = &tls->tx_cipherspec;
  1052. void *plaintext = NULL;
  1053. size_t plaintext_len;
  1054. struct io_buffer *ciphertext = NULL;
  1055. size_t ciphertext_len;
  1056. size_t mac_len = cipherspec->digest->digestsize;
  1057. uint8_t mac[mac_len];
  1058. int rc;
  1059. /* Construct header */
  1060. plaintext_tlshdr.type = type;
  1061. plaintext_tlshdr.version = htons ( TLS_VERSION_TLS_1_0 );
  1062. plaintext_tlshdr.length = htons ( len );
  1063. /* Calculate MAC */
  1064. tls_hmac ( tls, cipherspec, tls->tx_seq, &plaintext_tlshdr,
  1065. data, len, mac );
  1066. /* Allocate and assemble plaintext struct */
  1067. if ( is_stream_cipher ( cipherspec->cipher ) ) {
  1068. plaintext = tls_assemble_stream ( tls, data, len, mac,
  1069. &plaintext_len );
  1070. } else {
  1071. plaintext = tls_assemble_block ( tls, data, len, mac,
  1072. &plaintext_len );
  1073. }
  1074. if ( ! plaintext ) {
  1075. DBGC ( tls, "TLS %p could not allocate %zd bytes for "
  1076. "plaintext\n", tls, plaintext_len );
  1077. rc = -ENOMEM;
  1078. goto done;
  1079. }
  1080. DBGC2 ( tls, "Sending plaintext data:\n" );
  1081. DBGC2_HD ( tls, plaintext, plaintext_len );
  1082. /* Allocate ciphertext */
  1083. ciphertext_len = ( sizeof ( *tlshdr ) + plaintext_len );
  1084. ciphertext = xfer_alloc_iob ( &tls->cipherstream, ciphertext_len );
  1085. if ( ! ciphertext ) {
  1086. DBGC ( tls, "TLS %p could not allocate %zd bytes for "
  1087. "ciphertext\n", tls, ciphertext_len );
  1088. rc = -ENOMEM;
  1089. goto done;
  1090. }
  1091. /* Assemble ciphertext */
  1092. tlshdr = iob_put ( ciphertext, sizeof ( *tlshdr ) );
  1093. tlshdr->type = type;
  1094. tlshdr->version = htons ( TLS_VERSION_TLS_1_0 );
  1095. tlshdr->length = htons ( plaintext_len );
  1096. memcpy ( cipherspec->cipher_next_ctx, cipherspec->cipher_ctx,
  1097. cipherspec->cipher->ctxsize );
  1098. cipher_encrypt ( cipherspec->cipher, cipherspec->cipher_next_ctx,
  1099. plaintext, iob_put ( ciphertext, plaintext_len ),
  1100. plaintext_len );
  1101. /* Free plaintext as soon as possible to conserve memory */
  1102. free ( plaintext );
  1103. plaintext = NULL;
  1104. /* Send ciphertext */
  1105. if ( ( rc = xfer_deliver_iob ( &tls->cipherstream,
  1106. iob_disown ( ciphertext ) ) ) != 0 ) {
  1107. DBGC ( tls, "TLS %p could not deliver ciphertext: %s\n",
  1108. tls, strerror ( rc ) );
  1109. goto done;
  1110. }
  1111. /* Update TX state machine to next record */
  1112. tls->tx_seq += 1;
  1113. memcpy ( tls->tx_cipherspec.cipher_ctx,
  1114. tls->tx_cipherspec.cipher_next_ctx,
  1115. tls->tx_cipherspec.cipher->ctxsize );
  1116. done:
  1117. free ( plaintext );
  1118. free_iob ( ciphertext );
  1119. return rc;
  1120. }
  1121. /**
  1122. * Split stream-ciphered record into data and MAC portions
  1123. *
  1124. * @v tls TLS session
  1125. * @v plaintext Plaintext record
  1126. * @v plaintext_len Length of record
  1127. * @ret data Data
  1128. * @ret len Length of data
  1129. * @ret digest MAC digest
  1130. * @ret rc Return status code
  1131. */
  1132. static int tls_split_stream ( struct tls_session *tls,
  1133. void *plaintext, size_t plaintext_len,
  1134. void **data, size_t *len, void **digest ) {
  1135. void *content;
  1136. size_t content_len;
  1137. void *mac;
  1138. size_t mac_len;
  1139. /* Decompose stream-ciphered data */
  1140. mac_len = tls->rx_cipherspec.digest->digestsize;
  1141. if ( plaintext_len < mac_len ) {
  1142. DBGC ( tls, "TLS %p received underlength record\n", tls );
  1143. DBGC_HD ( tls, plaintext, plaintext_len );
  1144. return -EINVAL;
  1145. }
  1146. content_len = ( plaintext_len - mac_len );
  1147. content = plaintext;
  1148. mac = ( content + content_len );
  1149. /* Fill in return values */
  1150. *data = content;
  1151. *len = content_len;
  1152. *digest = mac;
  1153. return 0;
  1154. }
  1155. /**
  1156. * Split block-ciphered record into data and MAC portions
  1157. *
  1158. * @v tls TLS session
  1159. * @v plaintext Plaintext record
  1160. * @v plaintext_len Length of record
  1161. * @ret data Data
  1162. * @ret len Length of data
  1163. * @ret digest MAC digest
  1164. * @ret rc Return status code
  1165. */
  1166. static int tls_split_block ( struct tls_session *tls,
  1167. void *plaintext, size_t plaintext_len,
  1168. void **data, size_t *len,
  1169. void **digest ) {
  1170. void *iv;
  1171. size_t iv_len;
  1172. void *content;
  1173. size_t content_len;
  1174. void *mac;
  1175. size_t mac_len;
  1176. void *padding;
  1177. size_t padding_len;
  1178. unsigned int i;
  1179. /* Decompose block-ciphered data */
  1180. if ( plaintext_len < 1 ) {
  1181. DBGC ( tls, "TLS %p received underlength record\n", tls );
  1182. DBGC_HD ( tls, plaintext, plaintext_len );
  1183. return -EINVAL;
  1184. }
  1185. iv_len = tls->rx_cipherspec.cipher->blocksize;
  1186. /* FIXME: TLSv1.1 uses an explicit IV */
  1187. iv_len = 0;
  1188. mac_len = tls->rx_cipherspec.digest->digestsize;
  1189. padding_len = *( ( uint8_t * ) ( plaintext + plaintext_len - 1 ) );
  1190. if ( plaintext_len < ( iv_len + mac_len + padding_len + 1 ) ) {
  1191. DBGC ( tls, "TLS %p received underlength record\n", tls );
  1192. DBGC_HD ( tls, plaintext, plaintext_len );
  1193. return -EINVAL;
  1194. }
  1195. content_len = ( plaintext_len - iv_len - mac_len - padding_len - 1 );
  1196. iv = plaintext;
  1197. content = ( iv + iv_len );
  1198. mac = ( content + content_len );
  1199. padding = ( mac + mac_len );
  1200. /* Verify padding bytes */
  1201. for ( i = 0 ; i < padding_len ; i++ ) {
  1202. if ( *( ( uint8_t * ) ( padding + i ) ) != padding_len ) {
  1203. DBGC ( tls, "TLS %p received bad padding\n", tls );
  1204. DBGC_HD ( tls, plaintext, plaintext_len );
  1205. return -EINVAL;
  1206. }
  1207. }
  1208. /* Fill in return values */
  1209. *data = content;
  1210. *len = content_len;
  1211. *digest = mac;
  1212. return 0;
  1213. }
  1214. /**
  1215. * Receive new ciphertext record
  1216. *
  1217. * @v tls TLS session
  1218. * @v tlshdr Record header
  1219. * @v ciphertext Ciphertext record
  1220. * @ret rc Return status code
  1221. */
  1222. static int tls_new_ciphertext ( struct tls_session *tls,
  1223. struct tls_header *tlshdr, void *ciphertext ) {
  1224. struct tls_header plaintext_tlshdr;
  1225. struct tls_cipherspec *cipherspec = &tls->rx_cipherspec;
  1226. size_t record_len = ntohs ( tlshdr->length );
  1227. void *plaintext = NULL;
  1228. void *data;
  1229. size_t len;
  1230. void *mac;
  1231. size_t mac_len = cipherspec->digest->digestsize;
  1232. uint8_t verify_mac[mac_len];
  1233. int rc;
  1234. /* Allocate buffer for plaintext */
  1235. plaintext = malloc ( record_len );
  1236. if ( ! plaintext ) {
  1237. DBGC ( tls, "TLS %p could not allocate %zd bytes for "
  1238. "decryption buffer\n", tls, record_len );
  1239. rc = -ENOMEM;
  1240. goto done;
  1241. }
  1242. /* Decrypt the record */
  1243. cipher_decrypt ( cipherspec->cipher, cipherspec->cipher_ctx,
  1244. ciphertext, plaintext, record_len );
  1245. /* Split record into content and MAC */
  1246. if ( is_stream_cipher ( cipherspec->cipher ) ) {
  1247. if ( ( rc = tls_split_stream ( tls, plaintext, record_len,
  1248. &data, &len, &mac ) ) != 0 )
  1249. goto done;
  1250. } else {
  1251. if ( ( rc = tls_split_block ( tls, plaintext, record_len,
  1252. &data, &len, &mac ) ) != 0 )
  1253. goto done;
  1254. }
  1255. /* Verify MAC */
  1256. plaintext_tlshdr.type = tlshdr->type;
  1257. plaintext_tlshdr.version = tlshdr->version;
  1258. plaintext_tlshdr.length = htons ( len );
  1259. tls_hmac ( tls, cipherspec, tls->rx_seq, &plaintext_tlshdr,
  1260. data, len, verify_mac);
  1261. if ( memcmp ( mac, verify_mac, mac_len ) != 0 ) {
  1262. DBGC ( tls, "TLS %p failed MAC verification\n", tls );
  1263. DBGC_HD ( tls, plaintext, record_len );
  1264. goto done;
  1265. }
  1266. DBGC2 ( tls, "Received plaintext data:\n" );
  1267. DBGC2_HD ( tls, data, len );
  1268. /* Process plaintext record */
  1269. if ( ( rc = tls_new_record ( tls, tlshdr->type, data, len ) ) != 0 )
  1270. goto done;
  1271. rc = 0;
  1272. done:
  1273. free ( plaintext );
  1274. return rc;
  1275. }
  1276. /******************************************************************************
  1277. *
  1278. * Plaintext stream operations
  1279. *
  1280. ******************************************************************************
  1281. */
  1282. /**
  1283. * Check flow control window
  1284. *
  1285. * @v tls TLS session
  1286. * @ret len Length of window
  1287. */
  1288. static size_t tls_plainstream_window ( struct tls_session *tls ) {
  1289. /* Block window unless we are ready to accept data */
  1290. if ( tls->tx_state != TLS_TX_DATA )
  1291. return 0;
  1292. return xfer_window ( &tls->cipherstream );
  1293. }
  1294. /**
  1295. * Deliver datagram as raw data
  1296. *
  1297. * @v tls TLS session
  1298. * @v iobuf I/O buffer
  1299. * @v meta Data transfer metadata
  1300. * @ret rc Return status code
  1301. */
  1302. static int tls_plainstream_deliver ( struct tls_session *tls,
  1303. struct io_buffer *iobuf,
  1304. struct xfer_metadata *meta __unused ) {
  1305. int rc;
  1306. /* Refuse unless we are ready to accept data */
  1307. if ( tls->tx_state != TLS_TX_DATA ) {
  1308. rc = -ENOTCONN;
  1309. goto done;
  1310. }
  1311. if ( ( rc = tls_send_plaintext ( tls, TLS_TYPE_DATA, iobuf->data,
  1312. iob_len ( iobuf ) ) ) != 0 )
  1313. goto done;
  1314. done:
  1315. free_iob ( iobuf );
  1316. return rc;
  1317. }
  1318. /** TLS plaintext stream interface operations */
  1319. static struct interface_operation tls_plainstream_ops[] = {
  1320. INTF_OP ( xfer_deliver, struct tls_session *, tls_plainstream_deliver ),
  1321. INTF_OP ( xfer_window, struct tls_session *, tls_plainstream_window ),
  1322. INTF_OP ( intf_close, struct tls_session *, tls_close ),
  1323. };
  1324. /** TLS plaintext stream interface descriptor */
  1325. static struct interface_descriptor tls_plainstream_desc =
  1326. INTF_DESC_PASSTHRU ( struct tls_session, plainstream,
  1327. tls_plainstream_ops, cipherstream );
  1328. /******************************************************************************
  1329. *
  1330. * Ciphertext stream operations
  1331. *
  1332. ******************************************************************************
  1333. */
  1334. /**
  1335. * Handle received TLS header
  1336. *
  1337. * @v tls TLS session
  1338. * @ret rc Returned status code
  1339. */
  1340. static int tls_newdata_process_header ( struct tls_session *tls ) {
  1341. size_t data_len = ntohs ( tls->rx_header.length );
  1342. /* Allocate data buffer now that we know the length */
  1343. assert ( tls->rx_data == NULL );
  1344. tls->rx_data = malloc ( data_len );
  1345. if ( ! tls->rx_data ) {
  1346. DBGC ( tls, "TLS %p could not allocate %zd bytes "
  1347. "for receive buffer\n", tls, data_len );
  1348. return -ENOMEM;
  1349. }
  1350. /* Move to data state */
  1351. tls->rx_state = TLS_RX_DATA;
  1352. return 0;
  1353. }
  1354. /**
  1355. * Handle received TLS data payload
  1356. *
  1357. * @v tls TLS session
  1358. * @ret rc Returned status code
  1359. */
  1360. static int tls_newdata_process_data ( struct tls_session *tls ) {
  1361. int rc;
  1362. /* Process record */
  1363. if ( ( rc = tls_new_ciphertext ( tls, &tls->rx_header,
  1364. tls->rx_data ) ) != 0 )
  1365. return rc;
  1366. /* Increment RX sequence number */
  1367. tls->rx_seq += 1;
  1368. /* Free data buffer */
  1369. free ( tls->rx_data );
  1370. tls->rx_data = NULL;
  1371. /* Return to header state */
  1372. tls->rx_state = TLS_RX_HEADER;
  1373. return 0;
  1374. }
  1375. /**
  1376. * Receive new ciphertext
  1377. *
  1378. * @v tls TLS session
  1379. * @v iobuf I/O buffer
  1380. * @v meta Data transfer metadat
  1381. * @ret rc Return status code
  1382. */
  1383. static int tls_cipherstream_deliver ( struct tls_session *tls,
  1384. struct io_buffer *iobuf,
  1385. struct xfer_metadata *xfer __unused ) {
  1386. size_t frag_len;
  1387. void *buf;
  1388. size_t buf_len;
  1389. int ( * process ) ( struct tls_session *tls );
  1390. int rc;
  1391. while ( iob_len ( iobuf ) ) {
  1392. /* Select buffer according to current state */
  1393. switch ( tls->rx_state ) {
  1394. case TLS_RX_HEADER:
  1395. buf = &tls->rx_header;
  1396. buf_len = sizeof ( tls->rx_header );
  1397. process = tls_newdata_process_header;
  1398. break;
  1399. case TLS_RX_DATA:
  1400. buf = tls->rx_data;
  1401. buf_len = ntohs ( tls->rx_header.length );
  1402. process = tls_newdata_process_data;
  1403. break;
  1404. default:
  1405. assert ( 0 );
  1406. rc = -EINVAL;
  1407. goto done;
  1408. }
  1409. /* Copy data portion to buffer */
  1410. frag_len = ( buf_len - tls->rx_rcvd );
  1411. if ( frag_len > iob_len ( iobuf ) )
  1412. frag_len = iob_len ( iobuf );
  1413. memcpy ( ( buf + tls->rx_rcvd ), iobuf->data, frag_len );
  1414. tls->rx_rcvd += frag_len;
  1415. iob_pull ( iobuf, frag_len );
  1416. /* Process data if buffer is now full */
  1417. if ( tls->rx_rcvd == buf_len ) {
  1418. if ( ( rc = process ( tls ) ) != 0 ) {
  1419. tls_close ( tls, rc );
  1420. goto done;
  1421. }
  1422. tls->rx_rcvd = 0;
  1423. }
  1424. }
  1425. rc = 0;
  1426. done:
  1427. free_iob ( iobuf );
  1428. return rc;
  1429. }
  1430. /** TLS ciphertext stream interface operations */
  1431. static struct interface_operation tls_cipherstream_ops[] = {
  1432. INTF_OP ( xfer_deliver, struct tls_session *,
  1433. tls_cipherstream_deliver ),
  1434. INTF_OP ( intf_close, struct tls_session *, tls_close ),
  1435. };
  1436. /** TLS ciphertext stream interface descriptor */
  1437. static struct interface_descriptor tls_cipherstream_desc =
  1438. INTF_DESC_PASSTHRU ( struct tls_session, cipherstream,
  1439. tls_cipherstream_ops, plainstream );
  1440. /******************************************************************************
  1441. *
  1442. * Controlling process
  1443. *
  1444. ******************************************************************************
  1445. */
  1446. /**
  1447. * TLS TX state machine
  1448. *
  1449. * @v process TLS process
  1450. */
  1451. static void tls_step ( struct process *process ) {
  1452. struct tls_session *tls =
  1453. container_of ( process, struct tls_session, process );
  1454. int rc;
  1455. /* Wait for cipherstream to become ready */
  1456. if ( ! xfer_window ( &tls->cipherstream ) )
  1457. return;
  1458. switch ( tls->tx_state ) {
  1459. case TLS_TX_NONE:
  1460. /* Nothing to do */
  1461. break;
  1462. case TLS_TX_CLIENT_HELLO:
  1463. /* Send Client Hello */
  1464. if ( ( rc = tls_send_client_hello ( tls ) ) != 0 ) {
  1465. DBGC ( tls, "TLS %p could not send Client Hello: %s\n",
  1466. tls, strerror ( rc ) );
  1467. goto err;
  1468. }
  1469. tls->tx_state = TLS_TX_NONE;
  1470. break;
  1471. case TLS_TX_CLIENT_KEY_EXCHANGE:
  1472. /* Send Client Key Exchange */
  1473. if ( ( rc = tls_send_client_key_exchange ( tls ) ) != 0 ) {
  1474. DBGC ( tls, "TLS %p could send Client Key Exchange: "
  1475. "%s\n", tls, strerror ( rc ) );
  1476. goto err;
  1477. }
  1478. tls->tx_state = TLS_TX_CHANGE_CIPHER;
  1479. break;
  1480. case TLS_TX_CHANGE_CIPHER:
  1481. /* Send Change Cipher, and then change the cipher in use */
  1482. if ( ( rc = tls_send_change_cipher ( tls ) ) != 0 ) {
  1483. DBGC ( tls, "TLS %p could not send Change Cipher: "
  1484. "%s\n", tls, strerror ( rc ) );
  1485. goto err;
  1486. }
  1487. if ( ( rc = tls_change_cipher ( tls,
  1488. &tls->tx_cipherspec_pending,
  1489. &tls->tx_cipherspec )) != 0 ){
  1490. DBGC ( tls, "TLS %p could not activate TX cipher: "
  1491. "%s\n", tls, strerror ( rc ) );
  1492. goto err;
  1493. }
  1494. tls->tx_seq = 0;
  1495. tls->tx_state = TLS_TX_FINISHED;
  1496. break;
  1497. case TLS_TX_FINISHED:
  1498. /* Send Finished */
  1499. if ( ( rc = tls_send_finished ( tls ) ) != 0 ) {
  1500. DBGC ( tls, "TLS %p could not send Finished: %s\n",
  1501. tls, strerror ( rc ) );
  1502. goto err;
  1503. }
  1504. tls->tx_state = TLS_TX_NONE;
  1505. break;
  1506. case TLS_TX_DATA:
  1507. /* Nothing to do */
  1508. break;
  1509. default:
  1510. assert ( 0 );
  1511. }
  1512. return;
  1513. err:
  1514. tls_close ( tls, rc );
  1515. }
  1516. /******************************************************************************
  1517. *
  1518. * Instantiator
  1519. *
  1520. ******************************************************************************
  1521. */
  1522. int add_tls ( struct interface *xfer, struct interface **next ) {
  1523. struct tls_session *tls;
  1524. /* Allocate and initialise TLS structure */
  1525. tls = malloc ( sizeof ( *tls ) );
  1526. if ( ! tls )
  1527. return -ENOMEM;
  1528. memset ( tls, 0, sizeof ( *tls ) );
  1529. ref_init ( &tls->refcnt, free_tls );
  1530. intf_init ( &tls->plainstream, &tls_plainstream_desc, &tls->refcnt );
  1531. intf_init ( &tls->cipherstream, &tls_cipherstream_desc, &tls->refcnt );
  1532. tls_clear_cipher ( tls, &tls->tx_cipherspec );
  1533. tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
  1534. tls_clear_cipher ( tls, &tls->rx_cipherspec );
  1535. tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
  1536. tls->client_random.gmt_unix_time = 0;
  1537. tls_generate_random ( &tls->client_random.random,
  1538. ( sizeof ( tls->client_random.random ) ) );
  1539. tls->pre_master_secret.version = htons ( TLS_VERSION_TLS_1_0 );
  1540. tls_generate_random ( &tls->pre_master_secret.random,
  1541. ( sizeof ( tls->pre_master_secret.random ) ) );
  1542. digest_init ( &md5_algorithm, tls->handshake_md5_ctx );
  1543. digest_init ( &sha1_algorithm, tls->handshake_sha1_ctx );
  1544. tls->tx_state = TLS_TX_CLIENT_HELLO;
  1545. process_init ( &tls->process, tls_step, &tls->refcnt );
  1546. /* Attach to parent interface, mortalise self, and return */
  1547. intf_plug_plug ( &tls->plainstream, xfer );
  1548. *next = &tls->cipherstream;
  1549. ref_put ( &tls->refcnt );
  1550. return 0;
  1551. }