Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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