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.

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