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.

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