iPXE
tls.c
Go to the documentation of this file.
00001 /*
00002  * Copyright (C) 2007 Michael Brown <mbrown@fensystems.co.uk>.
00003  *
00004  * This program is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License as
00006  * published by the Free Software Foundation; either version 2 of the
00007  * License, or any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful, but
00010  * WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012  * General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software
00016  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
00017  * 02110-1301, USA.
00018  */
00019 
00020 FILE_LICENCE ( GPL2_OR_LATER );
00021 
00022 /**
00023  * @file
00024  *
00025  * Transport Layer Security Protocol
00026  */
00027 
00028 #include <stdint.h>
00029 #include <stdlib.h>
00030 #include <stdarg.h>
00031 #include <string.h>
00032 #include <time.h>
00033 #include <errno.h>
00034 #include <byteswap.h>
00035 #include <ipxe/pending.h>
00036 #include <ipxe/hmac.h>
00037 #include <ipxe/md5.h>
00038 #include <ipxe/sha1.h>
00039 #include <ipxe/sha256.h>
00040 #include <ipxe/aes.h>
00041 #include <ipxe/rsa.h>
00042 #include <ipxe/iobuf.h>
00043 #include <ipxe/xfer.h>
00044 #include <ipxe/open.h>
00045 #include <ipxe/x509.h>
00046 #include <ipxe/privkey.h>
00047 #include <ipxe/certstore.h>
00048 #include <ipxe/rbg.h>
00049 #include <ipxe/validator.h>
00050 #include <ipxe/job.h>
00051 #include <ipxe/tls.h>
00052 
00053 /* Disambiguate the various error causes */
00054 #define EINVAL_CHANGE_CIPHER __einfo_error ( EINFO_EINVAL_CHANGE_CIPHER )
00055 #define EINFO_EINVAL_CHANGE_CIPHER                                      \
00056         __einfo_uniqify ( EINFO_EINVAL, 0x01,                           \
00057                           "Invalid Change Cipher record" )
00058 #define EINVAL_ALERT __einfo_error ( EINFO_EINVAL_ALERT )
00059 #define EINFO_EINVAL_ALERT                                              \
00060         __einfo_uniqify ( EINFO_EINVAL, 0x02,                           \
00061                           "Invalid Alert record" )
00062 #define EINVAL_HELLO __einfo_error ( EINFO_EINVAL_HELLO )
00063 #define EINFO_EINVAL_HELLO                                              \
00064         __einfo_uniqify ( EINFO_EINVAL, 0x03,                           \
00065                           "Invalid Server Hello record" )
00066 #define EINVAL_CERTIFICATE __einfo_error ( EINFO_EINVAL_CERTIFICATE )
00067 #define EINFO_EINVAL_CERTIFICATE                                        \
00068         __einfo_uniqify ( EINFO_EINVAL, 0x04,                           \
00069                           "Invalid Certificate" )
00070 #define EINVAL_CERTIFICATES __einfo_error ( EINFO_EINVAL_CERTIFICATES )
00071 #define EINFO_EINVAL_CERTIFICATES                                       \
00072         __einfo_uniqify ( EINFO_EINVAL, 0x05,                           \
00073                           "Invalid Server Certificate record" )
00074 #define EINVAL_HELLO_DONE __einfo_error ( EINFO_EINVAL_HELLO_DONE )
00075 #define EINFO_EINVAL_HELLO_DONE                                         \
00076         __einfo_uniqify ( EINFO_EINVAL, 0x06,                           \
00077                           "Invalid Server Hello Done record" )
00078 #define EINVAL_FINISHED __einfo_error ( EINFO_EINVAL_FINISHED )
00079 #define EINFO_EINVAL_FINISHED                                           \
00080         __einfo_uniqify ( EINFO_EINVAL, 0x07,                           \
00081                           "Invalid Server Finished record" )
00082 #define EINVAL_HANDSHAKE __einfo_error ( EINFO_EINVAL_HANDSHAKE )
00083 #define EINFO_EINVAL_HANDSHAKE                                          \
00084         __einfo_uniqify ( EINFO_EINVAL, 0x08,                           \
00085                           "Invalid Handshake record" )
00086 #define EINVAL_STREAM __einfo_error ( EINFO_EINVAL_STREAM )
00087 #define EINFO_EINVAL_STREAM                                             \
00088         __einfo_uniqify ( EINFO_EINVAL, 0x09,                           \
00089                           "Invalid stream-ciphered record" )
00090 #define EINVAL_BLOCK __einfo_error ( EINFO_EINVAL_BLOCK )
00091 #define EINFO_EINVAL_BLOCK                                              \
00092         __einfo_uniqify ( EINFO_EINVAL, 0x0a,                           \
00093                           "Invalid block-ciphered record" )
00094 #define EINVAL_PADDING __einfo_error ( EINFO_EINVAL_PADDING )
00095 #define EINFO_EINVAL_PADDING                                            \
00096         __einfo_uniqify ( EINFO_EINVAL, 0x0b,                           \
00097                           "Invalid block padding" )
00098 #define EINVAL_RX_STATE __einfo_error ( EINFO_EINVAL_RX_STATE )
00099 #define EINFO_EINVAL_RX_STATE                                           \
00100         __einfo_uniqify ( EINFO_EINVAL, 0x0c,                           \
00101                           "Invalid receive state" )
00102 #define EINVAL_MAC __einfo_error ( EINFO_EINVAL_MAC )
00103 #define EINFO_EINVAL_MAC                                                \
00104         __einfo_uniqify ( EINFO_EINVAL, 0x0d,                           \
00105                           "Invalid MAC" )
00106 #define EINVAL_TICKET __einfo_error ( EINFO_EINVAL_TICKET )
00107 #define EINFO_EINVAL_TICKET                                             \
00108         __einfo_uniqify ( EINFO_EINVAL, 0x0e,                           \
00109                           "Invalid New Session Ticket record")
00110 #define EIO_ALERT __einfo_error ( EINFO_EIO_ALERT )
00111 #define EINFO_EIO_ALERT                                                 \
00112         __einfo_uniqify ( EINFO_EIO, 0x01,                              \
00113                           "Unknown alert level" )
00114 #define ENOMEM_CONTEXT __einfo_error ( EINFO_ENOMEM_CONTEXT )
00115 #define EINFO_ENOMEM_CONTEXT                                            \
00116         __einfo_uniqify ( EINFO_ENOMEM, 0x01,                           \
00117                           "Not enough space for crypto context" )
00118 #define ENOMEM_CERTIFICATE __einfo_error ( EINFO_ENOMEM_CERTIFICATE )
00119 #define EINFO_ENOMEM_CERTIFICATE                                        \
00120         __einfo_uniqify ( EINFO_ENOMEM, 0x02,                           \
00121                           "Not enough space for certificate" )
00122 #define ENOMEM_CHAIN __einfo_error ( EINFO_ENOMEM_CHAIN )
00123 #define EINFO_ENOMEM_CHAIN                                              \
00124         __einfo_uniqify ( EINFO_ENOMEM, 0x03,                           \
00125                           "Not enough space for certificate chain" )
00126 #define ENOMEM_TX_PLAINTEXT __einfo_error ( EINFO_ENOMEM_TX_PLAINTEXT )
00127 #define EINFO_ENOMEM_TX_PLAINTEXT                                       \
00128         __einfo_uniqify ( EINFO_ENOMEM, 0x04,                           \
00129                           "Not enough space for transmitted plaintext" )
00130 #define ENOMEM_TX_CIPHERTEXT __einfo_error ( EINFO_ENOMEM_TX_CIPHERTEXT )
00131 #define EINFO_ENOMEM_TX_CIPHERTEXT                                      \
00132         __einfo_uniqify ( EINFO_ENOMEM, 0x05,                           \
00133                           "Not enough space for transmitted ciphertext" )
00134 #define ENOMEM_RX_DATA __einfo_error ( EINFO_ENOMEM_RX_DATA )
00135 #define EINFO_ENOMEM_RX_DATA                                            \
00136         __einfo_uniqify ( EINFO_ENOMEM, 0x07,                           \
00137                           "Not enough space for received data" )
00138 #define ENOMEM_RX_CONCAT __einfo_error ( EINFO_ENOMEM_RX_CONCAT )
00139 #define EINFO_ENOMEM_RX_CONCAT                                          \
00140         __einfo_uniqify ( EINFO_ENOMEM, 0x08,                           \
00141                           "Not enough space to concatenate received data" )
00142 #define ENOTSUP_CIPHER __einfo_error ( EINFO_ENOTSUP_CIPHER )
00143 #define EINFO_ENOTSUP_CIPHER                                            \
00144         __einfo_uniqify ( EINFO_ENOTSUP, 0x01,                          \
00145                           "Unsupported cipher" )
00146 #define ENOTSUP_NULL __einfo_error ( EINFO_ENOTSUP_NULL )
00147 #define EINFO_ENOTSUP_NULL                                              \
00148         __einfo_uniqify ( EINFO_ENOTSUP, 0x02,                          \
00149                           "Refusing to use null cipher" )
00150 #define ENOTSUP_SIG_HASH __einfo_error ( EINFO_ENOTSUP_SIG_HASH )
00151 #define EINFO_ENOTSUP_SIG_HASH                                          \
00152         __einfo_uniqify ( EINFO_ENOTSUP, 0x03,                          \
00153                           "Unsupported signature and hash algorithm" )
00154 #define ENOTSUP_VERSION __einfo_error ( EINFO_ENOTSUP_VERSION )
00155 #define EINFO_ENOTSUP_VERSION                                           \
00156         __einfo_uniqify ( EINFO_ENOTSUP, 0x04,                          \
00157                           "Unsupported protocol version" )
00158 #define EPERM_ALERT __einfo_error ( EINFO_EPERM_ALERT )
00159 #define EINFO_EPERM_ALERT                                               \
00160         __einfo_uniqify ( EINFO_EPERM, 0x01,                            \
00161                           "Received fatal alert" )
00162 #define EPERM_VERIFY __einfo_error ( EINFO_EPERM_VERIFY )
00163 #define EINFO_EPERM_VERIFY                                              \
00164         __einfo_uniqify ( EINFO_EPERM, 0x02,                            \
00165                           "Handshake verification failed" )
00166 #define EPERM_CLIENT_CERT __einfo_error ( EINFO_EPERM_CLIENT_CERT )
00167 #define EINFO_EPERM_CLIENT_CERT                                         \
00168         __einfo_uniqify ( EINFO_EPERM, 0x03,                            \
00169                           "No suitable client certificate available" )
00170 #define EPERM_RENEG_INSECURE __einfo_error ( EINFO_EPERM_RENEG_INSECURE )
00171 #define EINFO_EPERM_RENEG_INSECURE                                      \
00172         __einfo_uniqify ( EINFO_EPERM, 0x04,                            \
00173                           "Secure renegotiation not supported" )
00174 #define EPERM_RENEG_VERIFY __einfo_error ( EINFO_EPERM_RENEG_VERIFY )
00175 #define EINFO_EPERM_RENEG_VERIFY                                        \
00176         __einfo_uniqify ( EINFO_EPERM, 0x05,                            \
00177                           "Secure renegotiation verification failed" )
00178 #define EPROTO_VERSION __einfo_error ( EINFO_EPROTO_VERSION )
00179 #define EINFO_EPROTO_VERSION                                            \
00180         __einfo_uniqify ( EINFO_EPROTO, 0x01,                           \
00181                           "Illegal protocol version upgrade" )
00182 
00183 /** List of TLS session */
00184 static LIST_HEAD ( tls_sessions );
00185 
00186 static void tls_tx_resume_all ( struct tls_session *session );
00187 static int tls_send_plaintext ( struct tls_connection *tls, unsigned int type,
00188                                 const void *data, size_t len );
00189 static void tls_clear_cipher ( struct tls_connection *tls,
00190                                struct tls_cipherspec *cipherspec );
00191 
00192 /******************************************************************************
00193  *
00194  * Utility functions
00195  *
00196  ******************************************************************************
00197  */
00198 
00199 /** A TLS 24-bit integer
00200  *
00201  * TLS uses 24-bit integers in several places, which are awkward to
00202  * parse in C.
00203  */
00204 typedef struct {
00205         /** High byte */
00206         uint8_t high;
00207         /** Low word */
00208         uint16_t low;
00209 } __attribute__ (( packed )) tls24_t;
00210 
00211 /**
00212  * Extract 24-bit field value
00213  *
00214  * @v field24           24-bit field
00215  * @ret value           Field value
00216  *
00217  */
00218 static inline __attribute__ (( always_inline )) unsigned long
00219 tls_uint24 ( const tls24_t *field24 ) {
00220 
00221         return ( ( field24->high << 16 ) | be16_to_cpu ( field24->low ) );
00222 }
00223 
00224 /**
00225  * Set 24-bit field value
00226  *
00227  * @v field24           24-bit field
00228  * @v value             Field value
00229  */
00230 static void tls_set_uint24 ( tls24_t *field24, unsigned long value ) {
00231 
00232         field24->high = ( value >> 16 );
00233         field24->low = cpu_to_be16 ( value );
00234 }
00235 
00236 /**
00237  * Determine if TLS connection is ready for application data
00238  *
00239  * @v tls               TLS connection
00240  * @ret is_ready        TLS connection is ready
00241  */
00242 static int tls_ready ( struct tls_connection *tls ) {
00243         return ( ( ! is_pending ( &tls->client_negotiation ) ) &&
00244                  ( ! is_pending ( &tls->server_negotiation ) ) );
00245 }
00246 
00247 /******************************************************************************
00248  *
00249  * Hybrid MD5+SHA1 hash as used by TLSv1.1 and earlier
00250  *
00251  ******************************************************************************
00252  */
00253 
00254 /**
00255  * Initialise MD5+SHA1 algorithm
00256  *
00257  * @v ctx               MD5+SHA1 context
00258  */
00259 static void md5_sha1_init ( void *ctx ) {
00260         struct md5_sha1_context *context = ctx;
00261 
00262         digest_init ( &md5_algorithm, context->md5 );
00263         digest_init ( &sha1_algorithm, context->sha1 );
00264 }
00265 
00266 /**
00267  * Accumulate data with MD5+SHA1 algorithm
00268  *
00269  * @v ctx               MD5+SHA1 context
00270  * @v data              Data
00271  * @v len               Length of data
00272  */
00273 static void md5_sha1_update ( void *ctx, const void *data, size_t len ) {
00274         struct md5_sha1_context *context = ctx;
00275 
00276         digest_update ( &md5_algorithm, context->md5, data, len );
00277         digest_update ( &sha1_algorithm, context->sha1, data, len );
00278 }
00279 
00280 /**
00281  * Generate MD5+SHA1 digest
00282  *
00283  * @v ctx               MD5+SHA1 context
00284  * @v out               Output buffer
00285  */
00286 static void md5_sha1_final ( void *ctx, void *out ) {
00287         struct md5_sha1_context *context = ctx;
00288         struct md5_sha1_digest *digest = out;
00289 
00290         digest_final ( &md5_algorithm, context->md5, digest->md5 );
00291         digest_final ( &sha1_algorithm, context->sha1, digest->sha1 );
00292 }
00293 
00294 /** Hybrid MD5+SHA1 digest algorithm */
00295 static struct digest_algorithm md5_sha1_algorithm = {
00296         .name           = "md5+sha1",
00297         .ctxsize        = sizeof ( struct md5_sha1_context ),
00298         .blocksize      = 0, /* Not applicable */
00299         .digestsize     = sizeof ( struct md5_sha1_digest ),
00300         .init           = md5_sha1_init,
00301         .update         = md5_sha1_update,
00302         .final          = md5_sha1_final,
00303 };
00304 
00305 /** RSA digestInfo prefix for MD5+SHA1 algorithm */
00306 struct rsa_digestinfo_prefix rsa_md5_sha1_prefix __rsa_digestinfo_prefix = {
00307         .digest = &md5_sha1_algorithm,
00308         .data = NULL, /* MD5+SHA1 signatures have no digestInfo */
00309         .len = 0,
00310 };
00311 
00312 /******************************************************************************
00313  *
00314  * Cleanup functions
00315  *
00316  ******************************************************************************
00317  */
00318 
00319 /**
00320  * Free TLS session
00321  *
00322  * @v refcnt            Reference counter
00323  */
00324 static void free_tls_session ( struct refcnt *refcnt ) {
00325         struct tls_session *session =
00326                 container_of ( refcnt, struct tls_session, refcnt );
00327 
00328         /* Sanity check */
00329         assert ( list_empty ( &session->conn ) );
00330 
00331         /* Remove from list of sessions */
00332         list_del ( &session->list );
00333 
00334         /* Free session ticket */
00335         free ( session->ticket );
00336 
00337         /* Free session */
00338         free ( session );
00339 }
00340 
00341 /**
00342  * Free TLS connection
00343  *
00344  * @v refcnt            Reference counter
00345  */
00346 static void free_tls ( struct refcnt *refcnt ) {
00347         struct tls_connection *tls =
00348                 container_of ( refcnt, struct tls_connection, refcnt );
00349         struct tls_session *session = tls->session;
00350         struct io_buffer *iobuf;
00351         struct io_buffer *tmp;
00352 
00353         /* Free dynamically-allocated resources */
00354         free ( tls->new_session_ticket );
00355         tls_clear_cipher ( tls, &tls->tx_cipherspec );
00356         tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
00357         tls_clear_cipher ( tls, &tls->rx_cipherspec );
00358         tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
00359         list_for_each_entry_safe ( iobuf, tmp, &tls->rx_data, list ) {
00360                 list_del ( &iobuf->list );
00361                 free_iob ( iobuf );
00362         }
00363         x509_put ( tls->cert );
00364         x509_chain_put ( tls->chain );
00365 
00366         /* Drop reference to session */
00367         assert ( list_empty ( &tls->list ) );
00368         ref_put ( &session->refcnt );
00369 
00370         /* Free TLS structure itself */
00371         free ( tls );
00372 }
00373 
00374 /**
00375  * Finish with TLS connection
00376  *
00377  * @v tls               TLS connection
00378  * @v rc                Status code
00379  */
00380 static void tls_close ( struct tls_connection *tls, int rc ) {
00381 
00382         /* Remove pending operations, if applicable */
00383         pending_put ( &tls->client_negotiation );
00384         pending_put ( &tls->server_negotiation );
00385         pending_put ( &tls->validation );
00386 
00387         /* Remove process */
00388         process_del ( &tls->process );
00389 
00390         /* Close all interfaces */
00391         intf_shutdown ( &tls->cipherstream, rc );
00392         intf_shutdown ( &tls->plainstream, rc );
00393         intf_shutdown ( &tls->validator, rc );
00394 
00395         /* Remove from session */
00396         list_del ( &tls->list );
00397         INIT_LIST_HEAD ( &tls->list );
00398 
00399         /* Resume all other connections, in case we were the lead connection */
00400         tls_tx_resume_all ( tls->session );
00401 }
00402 
00403 /******************************************************************************
00404  *
00405  * Random number generation
00406  *
00407  ******************************************************************************
00408  */
00409 
00410 /**
00411  * Generate random data
00412  *
00413  * @v tls               TLS connection
00414  * @v data              Buffer to fill
00415  * @v len               Length of buffer
00416  * @ret rc              Return status code
00417  */
00418 static int tls_generate_random ( struct tls_connection *tls,
00419                                  void *data, size_t len ) {
00420         int rc;
00421 
00422         /* Generate random bits with no additional input and without
00423          * prediction resistance
00424          */
00425         if ( ( rc = rbg_generate ( NULL, 0, 0, data, len ) ) != 0 ) {
00426                 DBGC ( tls, "TLS %p could not generate random data: %s\n",
00427                        tls, strerror ( rc ) );
00428                 return rc;
00429         }
00430 
00431         return 0;
00432 }
00433 
00434 /**
00435  * Update HMAC with a list of ( data, len ) pairs
00436  *
00437  * @v digest            Hash function to use
00438  * @v digest_ctx        Digest context
00439  * @v args              ( data, len ) pairs of data, terminated by NULL
00440  */
00441 static void tls_hmac_update_va ( struct digest_algorithm *digest,
00442                                  void *digest_ctx, va_list args ) {
00443         void *data;
00444         size_t len;
00445 
00446         while ( ( data = va_arg ( args, void * ) ) ) {
00447                 len = va_arg ( args, size_t );
00448                 hmac_update ( digest, digest_ctx, data, len );
00449         }
00450 }
00451 
00452 /**
00453  * Generate secure pseudo-random data using a single hash function
00454  *
00455  * @v tls               TLS connection
00456  * @v digest            Hash function to use
00457  * @v secret            Secret
00458  * @v secret_len        Length of secret
00459  * @v out               Output buffer
00460  * @v out_len           Length of output buffer
00461  * @v seeds             ( data, len ) pairs of seed data, terminated by NULL
00462  */
00463 static void tls_p_hash_va ( struct tls_connection *tls,
00464                             struct digest_algorithm *digest,
00465                             void *secret, size_t secret_len,
00466                             void *out, size_t out_len,
00467                             va_list seeds ) {
00468         uint8_t secret_copy[secret_len];
00469         uint8_t digest_ctx[digest->ctxsize];
00470         uint8_t digest_ctx_partial[digest->ctxsize];
00471         uint8_t a[digest->digestsize];
00472         uint8_t out_tmp[digest->digestsize];
00473         size_t frag_len = digest->digestsize;
00474         va_list tmp;
00475 
00476         /* Copy the secret, in case HMAC modifies it */
00477         memcpy ( secret_copy, secret, secret_len );
00478         secret = secret_copy;
00479         DBGC2 ( tls, "TLS %p %s secret:\n", tls, digest->name );
00480         DBGC2_HD ( tls, secret, secret_len );
00481 
00482         /* Calculate A(1) */
00483         hmac_init ( digest, digest_ctx, secret, &secret_len );
00484         va_copy ( tmp, seeds );
00485         tls_hmac_update_va ( digest, digest_ctx, tmp );
00486         va_end ( tmp );
00487         hmac_final ( digest, digest_ctx, secret, &secret_len, a );
00488         DBGC2 ( tls, "TLS %p %s A(1):\n", tls, digest->name );
00489         DBGC2_HD ( tls, &a, sizeof ( a ) );
00490 
00491         /* Generate as much data as required */
00492         while ( out_len ) {
00493                 /* Calculate output portion */
00494                 hmac_init ( digest, digest_ctx, secret, &secret_len );
00495                 hmac_update ( digest, digest_ctx, a, sizeof ( a ) );
00496                 memcpy ( digest_ctx_partial, digest_ctx, digest->ctxsize );
00497                 va_copy ( tmp, seeds );
00498                 tls_hmac_update_va ( digest, digest_ctx, tmp );
00499                 va_end ( tmp );
00500                 hmac_final ( digest, digest_ctx,
00501                              secret, &secret_len, out_tmp );
00502 
00503                 /* Copy output */
00504                 if ( frag_len > out_len )
00505                         frag_len = out_len;
00506                 memcpy ( out, out_tmp, frag_len );
00507                 DBGC2 ( tls, "TLS %p %s output:\n", tls, digest->name );
00508                 DBGC2_HD ( tls, out, frag_len );
00509 
00510                 /* Calculate A(i) */
00511                 hmac_final ( digest, digest_ctx_partial,
00512                              secret, &secret_len, a );
00513                 DBGC2 ( tls, "TLS %p %s A(n):\n", tls, digest->name );
00514                 DBGC2_HD ( tls, &a, sizeof ( a ) );
00515 
00516                 out += frag_len;
00517                 out_len -= frag_len;
00518         }
00519 }
00520 
00521 /**
00522  * Generate secure pseudo-random data
00523  *
00524  * @v tls               TLS connection
00525  * @v secret            Secret
00526  * @v secret_len        Length of secret
00527  * @v out               Output buffer
00528  * @v out_len           Length of output buffer
00529  * @v ...               ( data, len ) pairs of seed data, terminated by NULL
00530  */
00531 static void tls_prf ( struct tls_connection *tls, void *secret,
00532                       size_t secret_len, void *out, size_t out_len, ... ) {
00533         va_list seeds;
00534         va_list tmp;
00535         size_t subsecret_len;
00536         void *md5_secret;
00537         void *sha1_secret;
00538         uint8_t buf[out_len];
00539         unsigned int i;
00540 
00541         va_start ( seeds, out_len );
00542 
00543         if ( tls->version >= TLS_VERSION_TLS_1_2 ) {
00544                 /* Use P_SHA256 for TLSv1.2 and later */
00545                 tls_p_hash_va ( tls, &sha256_algorithm, secret, secret_len,
00546                                 out, out_len, seeds );
00547         } else {
00548                 /* Use combination of P_MD5 and P_SHA-1 for TLSv1.1
00549                  * and earlier
00550                  */
00551 
00552                 /* Split secret into two, with an overlap of up to one byte */
00553                 subsecret_len = ( ( secret_len + 1 ) / 2 );
00554                 md5_secret = secret;
00555                 sha1_secret = ( secret + secret_len - subsecret_len );
00556 
00557                 /* Calculate MD5 portion */
00558                 va_copy ( tmp, seeds );
00559                 tls_p_hash_va ( tls, &md5_algorithm, md5_secret,
00560                                 subsecret_len, out, out_len, seeds );
00561                 va_end ( tmp );
00562 
00563                 /* Calculate SHA1 portion */
00564                 va_copy ( tmp, seeds );
00565                 tls_p_hash_va ( tls, &sha1_algorithm, sha1_secret,
00566                                 subsecret_len, buf, out_len, seeds );
00567                 va_end ( tmp );
00568 
00569                 /* XOR the two portions together into the final output buffer */
00570                 for ( i = 0 ; i < out_len ; i++ )
00571                         *( ( uint8_t * ) out + i ) ^= buf[i];
00572         }
00573 
00574         va_end ( seeds );
00575 }
00576 
00577 /**
00578  * Generate secure pseudo-random data
00579  *
00580  * @v secret            Secret
00581  * @v secret_len        Length of secret
00582  * @v out               Output buffer
00583  * @v out_len           Length of output buffer
00584  * @v label             String literal label
00585  * @v ...               ( data, len ) pairs of seed data
00586  */
00587 #define tls_prf_label( tls, secret, secret_len, out, out_len, label, ... ) \
00588         tls_prf ( (tls), (secret), (secret_len), (out), (out_len),         \
00589                   label, ( sizeof ( label ) - 1 ), __VA_ARGS__, NULL )
00590 
00591 /******************************************************************************
00592  *
00593  * Secret management
00594  *
00595  ******************************************************************************
00596  */
00597 
00598 /**
00599  * Generate master secret
00600  *
00601  * @v tls               TLS connection
00602  *
00603  * The pre-master secret and the client and server random values must
00604  * already be known.
00605  */
00606 static void tls_generate_master_secret ( struct tls_connection *tls ) {
00607         DBGC ( tls, "TLS %p pre-master-secret:\n", tls );
00608         DBGC_HD ( tls, &tls->pre_master_secret,
00609                   sizeof ( tls->pre_master_secret ) );
00610         DBGC ( tls, "TLS %p client random bytes:\n", tls );
00611         DBGC_HD ( tls, &tls->client_random, sizeof ( tls->client_random ) );
00612         DBGC ( tls, "TLS %p server random bytes:\n", tls );
00613         DBGC_HD ( tls, &tls->server_random, sizeof ( tls->server_random ) );
00614 
00615         tls_prf_label ( tls, &tls->pre_master_secret,
00616                         sizeof ( tls->pre_master_secret ),
00617                         &tls->master_secret, sizeof ( tls->master_secret ),
00618                         "master secret",
00619                         &tls->client_random, sizeof ( tls->client_random ),
00620                         &tls->server_random, sizeof ( tls->server_random ) );
00621 
00622         DBGC ( tls, "TLS %p generated master secret:\n", tls );
00623         DBGC_HD ( tls, &tls->master_secret, sizeof ( tls->master_secret ) );
00624 }
00625 
00626 /**
00627  * Generate key material
00628  *
00629  * @v tls               TLS connection
00630  *
00631  * The master secret must already be known.
00632  */
00633 static int tls_generate_keys ( struct tls_connection *tls ) {
00634         struct tls_cipherspec *tx_cipherspec = &tls->tx_cipherspec_pending;
00635         struct tls_cipherspec *rx_cipherspec = &tls->rx_cipherspec_pending;
00636         size_t hash_size = tx_cipherspec->suite->digest->digestsize;
00637         size_t key_size = tx_cipherspec->suite->key_len;
00638         size_t iv_size = tx_cipherspec->suite->cipher->blocksize;
00639         size_t total = ( 2 * ( hash_size + key_size + iv_size ) );
00640         uint8_t key_block[total];
00641         uint8_t *key;
00642         int rc;
00643 
00644         /* Generate key block */
00645         tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
00646                         key_block, sizeof ( key_block ), "key expansion",
00647                         &tls->server_random, sizeof ( tls->server_random ),
00648                         &tls->client_random, sizeof ( tls->client_random ) );
00649 
00650         /* Split key block into portions */
00651         key = key_block;
00652 
00653         /* TX MAC secret */
00654         memcpy ( tx_cipherspec->mac_secret, key, hash_size );
00655         DBGC ( tls, "TLS %p TX MAC secret:\n", tls );
00656         DBGC_HD ( tls, key, hash_size );
00657         key += hash_size;
00658 
00659         /* RX MAC secret */
00660         memcpy ( rx_cipherspec->mac_secret, key, hash_size );
00661         DBGC ( tls, "TLS %p RX MAC secret:\n", tls );
00662         DBGC_HD ( tls, key, hash_size );
00663         key += hash_size;
00664 
00665         /* TX key */
00666         if ( ( rc = cipher_setkey ( tx_cipherspec->suite->cipher,
00667                                     tx_cipherspec->cipher_ctx,
00668                                     key, key_size ) ) != 0 ) {
00669                 DBGC ( tls, "TLS %p could not set TX key: %s\n",
00670                        tls, strerror ( rc ) );
00671                 return rc;
00672         }
00673         DBGC ( tls, "TLS %p TX key:\n", tls );
00674         DBGC_HD ( tls, key, key_size );
00675         key += key_size;
00676 
00677         /* RX key */
00678         if ( ( rc = cipher_setkey ( rx_cipherspec->suite->cipher,
00679                                     rx_cipherspec->cipher_ctx,
00680                                     key, key_size ) ) != 0 ) {
00681                 DBGC ( tls, "TLS %p could not set TX key: %s\n",
00682                        tls, strerror ( rc ) );
00683                 return rc;
00684         }
00685         DBGC ( tls, "TLS %p RX key:\n", tls );
00686         DBGC_HD ( tls, key, key_size );
00687         key += key_size;
00688 
00689         /* TX initialisation vector */
00690         cipher_setiv ( tx_cipherspec->suite->cipher,
00691                        tx_cipherspec->cipher_ctx, key );
00692         DBGC ( tls, "TLS %p TX IV:\n", tls );
00693         DBGC_HD ( tls, key, iv_size );
00694         key += iv_size;
00695 
00696         /* RX initialisation vector */
00697         cipher_setiv ( rx_cipherspec->suite->cipher,
00698                        rx_cipherspec->cipher_ctx, key );
00699         DBGC ( tls, "TLS %p RX IV:\n", tls );
00700         DBGC_HD ( tls, key, iv_size );
00701         key += iv_size;
00702 
00703         assert ( ( key_block + total ) == key );
00704 
00705         return 0;
00706 }
00707 
00708 /******************************************************************************
00709  *
00710  * Cipher suite management
00711  *
00712  ******************************************************************************
00713  */
00714 
00715 /** Null cipher suite */
00716 struct tls_cipher_suite tls_cipher_suite_null = {
00717         .pubkey = &pubkey_null,
00718         .cipher = &cipher_null,
00719         .digest = &digest_null,
00720 };
00721 
00722 /** Number of supported cipher suites */
00723 #define TLS_NUM_CIPHER_SUITES table_num_entries ( TLS_CIPHER_SUITES )
00724 
00725 /**
00726  * Identify cipher suite
00727  *
00728  * @v cipher_suite      Cipher suite specification
00729  * @ret suite           Cipher suite, or NULL
00730  */
00731 static struct tls_cipher_suite *
00732 tls_find_cipher_suite ( unsigned int cipher_suite ) {
00733         struct tls_cipher_suite *suite;
00734 
00735         /* Identify cipher suite */
00736         for_each_table_entry ( suite, TLS_CIPHER_SUITES ) {
00737                 if ( suite->code == cipher_suite )
00738                         return suite;
00739         }
00740 
00741         return NULL;
00742 }
00743 
00744 /**
00745  * Clear cipher suite
00746  *
00747  * @v cipherspec        TLS cipher specification
00748  */
00749 static void tls_clear_cipher ( struct tls_connection *tls __unused,
00750                                struct tls_cipherspec *cipherspec ) {
00751 
00752         if ( cipherspec->suite ) {
00753                 pubkey_final ( cipherspec->suite->pubkey,
00754                                cipherspec->pubkey_ctx );
00755         }
00756         free ( cipherspec->dynamic );
00757         memset ( cipherspec, 0, sizeof ( *cipherspec ) );
00758         cipherspec->suite = &tls_cipher_suite_null;
00759 }
00760 
00761 /**
00762  * Set cipher suite
00763  *
00764  * @v tls               TLS connection
00765  * @v cipherspec        TLS cipher specification
00766  * @v suite             Cipher suite
00767  * @ret rc              Return status code
00768  */
00769 static int tls_set_cipher ( struct tls_connection *tls,
00770                             struct tls_cipherspec *cipherspec,
00771                             struct tls_cipher_suite *suite ) {
00772         struct pubkey_algorithm *pubkey = suite->pubkey;
00773         struct cipher_algorithm *cipher = suite->cipher;
00774         struct digest_algorithm *digest = suite->digest;
00775         size_t total;
00776         void *dynamic;
00777 
00778         /* Clear out old cipher contents, if any */
00779         tls_clear_cipher ( tls, cipherspec );
00780         
00781         /* Allocate dynamic storage */
00782         total = ( pubkey->ctxsize + 2 * cipher->ctxsize + digest->digestsize );
00783         dynamic = zalloc ( total );
00784         if ( ! dynamic ) {
00785                 DBGC ( tls, "TLS %p could not allocate %zd bytes for crypto "
00786                        "context\n", tls, total );
00787                 return -ENOMEM_CONTEXT;
00788         }
00789 
00790         /* Assign storage */
00791         cipherspec->dynamic = dynamic;
00792         cipherspec->pubkey_ctx = dynamic;       dynamic += pubkey->ctxsize;
00793         cipherspec->cipher_ctx = dynamic;       dynamic += cipher->ctxsize;
00794         cipherspec->cipher_next_ctx = dynamic;  dynamic += cipher->ctxsize;
00795         cipherspec->mac_secret = dynamic;       dynamic += digest->digestsize;
00796         assert ( ( cipherspec->dynamic + total ) == dynamic );
00797 
00798         /* Store parameters */
00799         cipherspec->suite = suite;
00800 
00801         return 0;
00802 }
00803 
00804 /**
00805  * Select next cipher suite
00806  *
00807  * @v tls               TLS connection
00808  * @v cipher_suite      Cipher suite specification
00809  * @ret rc              Return status code
00810  */
00811 static int tls_select_cipher ( struct tls_connection *tls,
00812                                unsigned int cipher_suite ) {
00813         struct tls_cipher_suite *suite;
00814         int rc;
00815 
00816         /* Identify cipher suite */
00817         suite = tls_find_cipher_suite ( cipher_suite );
00818         if ( ! suite ) {
00819                 DBGC ( tls, "TLS %p does not support cipher %04x\n",
00820                        tls, ntohs ( cipher_suite ) );
00821                 return -ENOTSUP_CIPHER;
00822         }
00823 
00824         /* Set ciphers */
00825         if ( ( rc = tls_set_cipher ( tls, &tls->tx_cipherspec_pending,
00826                                      suite ) ) != 0 )
00827                 return rc;
00828         if ( ( rc = tls_set_cipher ( tls, &tls->rx_cipherspec_pending,
00829                                      suite ) ) != 0 )
00830                 return rc;
00831 
00832         DBGC ( tls, "TLS %p selected %s-%s-%d-%s\n", tls, suite->pubkey->name,
00833                suite->cipher->name, ( suite->key_len * 8 ),
00834                suite->digest->name );
00835 
00836         return 0;
00837 }
00838 
00839 /**
00840  * Activate next cipher suite
00841  *
00842  * @v tls               TLS connection
00843  * @v pending           Pending cipher specification
00844  * @v active            Active cipher specification to replace
00845  * @ret rc              Return status code
00846  */
00847 static int tls_change_cipher ( struct tls_connection *tls,
00848                                struct tls_cipherspec *pending,
00849                                struct tls_cipherspec *active ) {
00850 
00851         /* Sanity check */
00852         if ( pending->suite == &tls_cipher_suite_null ) {
00853                 DBGC ( tls, "TLS %p refusing to use null cipher\n", tls );
00854                 return -ENOTSUP_NULL;
00855         }
00856 
00857         tls_clear_cipher ( tls, active );
00858         memswap ( active, pending, sizeof ( *active ) );
00859         return 0;
00860 }
00861 
00862 /******************************************************************************
00863  *
00864  * Signature and hash algorithms
00865  *
00866  ******************************************************************************
00867  */
00868 
00869 /** Number of supported signature and hash algorithms */
00870 #define TLS_NUM_SIG_HASH_ALGORITHMS \
00871         table_num_entries ( TLS_SIG_HASH_ALGORITHMS )
00872 
00873 /**
00874  * Find TLS signature and hash algorithm
00875  *
00876  * @v pubkey            Public-key algorithm
00877  * @v digest            Digest algorithm
00878  * @ret sig_hash        Signature and hash algorithm, or NULL
00879  */
00880 static struct tls_signature_hash_algorithm *
00881 tls_signature_hash_algorithm ( struct pubkey_algorithm *pubkey,
00882                                struct digest_algorithm *digest ) {
00883         struct tls_signature_hash_algorithm *sig_hash;
00884 
00885         /* Identify signature and hash algorithm */
00886         for_each_table_entry ( sig_hash, TLS_SIG_HASH_ALGORITHMS ) {
00887                 if ( ( sig_hash->pubkey == pubkey ) &&
00888                      ( sig_hash->digest == digest ) ) {
00889                         return sig_hash;
00890                 }
00891         }
00892 
00893         return NULL;
00894 }
00895 
00896 /******************************************************************************
00897  *
00898  * Handshake verification
00899  *
00900  ******************************************************************************
00901  */
00902 
00903 /**
00904  * Add handshake record to verification hash
00905  *
00906  * @v tls               TLS connection
00907  * @v data              Handshake record
00908  * @v len               Length of handshake record
00909  */
00910 static void tls_add_handshake ( struct tls_connection *tls,
00911                                 const void *data, size_t len ) {
00912 
00913         digest_update ( &md5_sha1_algorithm, tls->handshake_md5_sha1_ctx,
00914                         data, len );
00915         digest_update ( &sha256_algorithm, tls->handshake_sha256_ctx,
00916                         data, len );
00917 }
00918 
00919 /**
00920  * Calculate handshake verification hash
00921  *
00922  * @v tls               TLS connection
00923  * @v out               Output buffer
00924  *
00925  * Calculates the MD5+SHA1 or SHA256 digest over all handshake
00926  * messages seen so far.
00927  */
00928 static void tls_verify_handshake ( struct tls_connection *tls, void *out ) {
00929         struct digest_algorithm *digest = tls->handshake_digest;
00930         uint8_t ctx[ digest->ctxsize ];
00931 
00932         memcpy ( ctx, tls->handshake_ctx, sizeof ( ctx ) );
00933         digest_final ( digest, ctx, out );
00934 }
00935 
00936 /******************************************************************************
00937  *
00938  * Record handling
00939  *
00940  ******************************************************************************
00941  */
00942 
00943 /**
00944  * Resume TX state machine
00945  *
00946  * @v tls               TLS connection
00947  */
00948 static void tls_tx_resume ( struct tls_connection *tls ) {
00949         process_add ( &tls->process );
00950 }
00951 
00952 /**
00953  * Resume TX state machine for all connections within a session
00954  *
00955  * @v session           TLS session
00956  */
00957 static void tls_tx_resume_all ( struct tls_session *session ) {
00958         struct tls_connection *tls;
00959 
00960         list_for_each_entry ( tls, &session->conn, list )
00961                 tls_tx_resume ( tls );
00962 }
00963 
00964 /**
00965  * Restart negotiation
00966  *
00967  * @v tls               TLS connection
00968  */
00969 static void tls_restart ( struct tls_connection *tls ) {
00970 
00971         /* Sanity check */
00972         assert ( ! tls->tx_pending );
00973         assert ( ! is_pending ( &tls->client_negotiation ) );
00974         assert ( ! is_pending ( &tls->server_negotiation ) );
00975         assert ( ! is_pending ( &tls->validation ) );
00976 
00977         /* (Re)initialise handshake context */
00978         digest_init ( &md5_sha1_algorithm, tls->handshake_md5_sha1_ctx );
00979         digest_init ( &sha256_algorithm, tls->handshake_sha256_ctx );
00980         tls->handshake_digest = &sha256_algorithm;
00981         tls->handshake_ctx = tls->handshake_sha256_ctx;
00982 
00983         /* (Re)start negotiation */
00984         tls->tx_pending = TLS_TX_CLIENT_HELLO;
00985         tls_tx_resume ( tls );
00986         pending_get ( &tls->client_negotiation );
00987         pending_get ( &tls->server_negotiation );
00988 }
00989 
00990 /**
00991  * Transmit Handshake record
00992  *
00993  * @v tls               TLS connection
00994  * @v data              Plaintext record
00995  * @v len               Length of plaintext record
00996  * @ret rc              Return status code
00997  */
00998 static int tls_send_handshake ( struct tls_connection *tls,
00999                                 void *data, size_t len ) {
01000 
01001         /* Add to handshake digest */
01002         tls_add_handshake ( tls, data, len );
01003 
01004         /* Send record */
01005         return tls_send_plaintext ( tls, TLS_TYPE_HANDSHAKE, data, len );
01006 }
01007 
01008 /**
01009  * Transmit Client Hello record
01010  *
01011  * @v tls               TLS connection
01012  * @ret rc              Return status code
01013  */
01014 static int tls_send_client_hello ( struct tls_connection *tls ) {
01015         struct tls_session *session = tls->session;
01016         size_t name_len = strlen ( session->name );
01017         struct {
01018                 uint32_t type_length;
01019                 uint16_t version;
01020                 uint8_t random[32];
01021                 uint8_t session_id_len;
01022                 uint8_t session_id[tls->session_id_len];
01023                 uint16_t cipher_suite_len;
01024                 uint16_t cipher_suites[TLS_NUM_CIPHER_SUITES];
01025                 uint8_t compression_methods_len;
01026                 uint8_t compression_methods[1];
01027                 uint16_t extensions_len;
01028                 struct {
01029                         uint16_t server_name_type;
01030                         uint16_t server_name_len;
01031                         struct {
01032                                 uint16_t len;
01033                                 struct {
01034                                         uint8_t type;
01035                                         uint16_t len;
01036                                         uint8_t name[name_len];
01037                                 } __attribute__ (( packed )) list[1];
01038                         } __attribute__ (( packed )) server_name;
01039                         uint16_t max_fragment_length_type;
01040                         uint16_t max_fragment_length_len;
01041                         struct {
01042                                 uint8_t max;
01043                         } __attribute__ (( packed )) max_fragment_length;
01044                         uint16_t signature_algorithms_type;
01045                         uint16_t signature_algorithms_len;
01046                         struct {
01047                                 uint16_t len;
01048                                 struct tls_signature_hash_id
01049                                         code[TLS_NUM_SIG_HASH_ALGORITHMS];
01050                         } __attribute__ (( packed )) signature_algorithms;
01051                         uint16_t renegotiation_info_type;
01052                         uint16_t renegotiation_info_len;
01053                         struct {
01054                                 uint8_t len;
01055                                 uint8_t data[ tls->secure_renegotiation ?
01056                                               sizeof ( tls->verify.client ) :0];
01057                         } __attribute__ (( packed )) renegotiation_info;
01058                         uint16_t session_ticket_type;
01059                         uint16_t session_ticket_len;
01060                         struct {
01061                                 uint8_t data[session->ticket_len];
01062                         } __attribute__ (( packed )) session_ticket;
01063                 } __attribute__ (( packed )) extensions;
01064         } __attribute__ (( packed )) hello;
01065         struct tls_cipher_suite *suite;
01066         struct tls_signature_hash_algorithm *sighash;
01067         unsigned int i;
01068 
01069         /* Construct record */
01070         memset ( &hello, 0, sizeof ( hello ) );
01071         hello.type_length = ( cpu_to_le32 ( TLS_CLIENT_HELLO ) |
01072                               htonl ( sizeof ( hello ) -
01073                                       sizeof ( hello.type_length ) ) );
01074         hello.version = htons ( tls->version );
01075         memcpy ( &hello.random, &tls->client_random, sizeof ( hello.random ) );
01076         hello.session_id_len = tls->session_id_len;
01077         memcpy ( hello.session_id, tls->session_id,
01078                  sizeof ( hello.session_id ) );
01079         hello.cipher_suite_len = htons ( sizeof ( hello.cipher_suites ) );
01080         i = 0 ; for_each_table_entry ( suite, TLS_CIPHER_SUITES )
01081                 hello.cipher_suites[i++] = suite->code;
01082         hello.compression_methods_len = sizeof ( hello.compression_methods );
01083         hello.extensions_len = htons ( sizeof ( hello.extensions ) );
01084         hello.extensions.server_name_type = htons ( TLS_SERVER_NAME );
01085         hello.extensions.server_name_len
01086                 = htons ( sizeof ( hello.extensions.server_name ) );
01087         hello.extensions.server_name.len
01088                 = htons ( sizeof ( hello.extensions.server_name.list ) );
01089         hello.extensions.server_name.list[0].type = TLS_SERVER_NAME_HOST_NAME;
01090         hello.extensions.server_name.list[0].len
01091                 = htons ( sizeof ( hello.extensions.server_name.list[0].name ));
01092         memcpy ( hello.extensions.server_name.list[0].name, session->name,
01093                  sizeof ( hello.extensions.server_name.list[0].name ) );
01094         hello.extensions.max_fragment_length_type
01095                 = htons ( TLS_MAX_FRAGMENT_LENGTH );
01096         hello.extensions.max_fragment_length_len
01097                 = htons ( sizeof ( hello.extensions.max_fragment_length ) );
01098         hello.extensions.max_fragment_length.max
01099                 = TLS_MAX_FRAGMENT_LENGTH_4096;
01100         hello.extensions.signature_algorithms_type
01101                 = htons ( TLS_SIGNATURE_ALGORITHMS );
01102         hello.extensions.signature_algorithms_len
01103                 = htons ( sizeof ( hello.extensions.signature_algorithms ) );
01104         hello.extensions.signature_algorithms.len
01105                 = htons ( sizeof ( hello.extensions.signature_algorithms.code));
01106         i = 0 ; for_each_table_entry ( sighash, TLS_SIG_HASH_ALGORITHMS )
01107                 hello.extensions.signature_algorithms.code[i++] = sighash->code;
01108         hello.extensions.renegotiation_info_type
01109                 = htons ( TLS_RENEGOTIATION_INFO );
01110         hello.extensions.renegotiation_info_len
01111                 = htons ( sizeof ( hello.extensions.renegotiation_info ) );
01112         hello.extensions.renegotiation_info.len
01113                 = sizeof ( hello.extensions.renegotiation_info.data );
01114         memcpy ( hello.extensions.renegotiation_info.data, tls->verify.client,
01115                  sizeof ( hello.extensions.renegotiation_info.data ) );
01116         hello.extensions.session_ticket_type = htons ( TLS_SESSION_TICKET );
01117         hello.extensions.session_ticket_len
01118                 = htons ( sizeof ( hello.extensions.session_ticket ) );
01119         memcpy ( hello.extensions.session_ticket.data, session->ticket,
01120                  sizeof ( hello.extensions.session_ticket.data ) );
01121 
01122         return tls_send_handshake ( tls, &hello, sizeof ( hello ) );
01123 }
01124 
01125 /**
01126  * Transmit Certificate record
01127  *
01128  * @v tls               TLS connection
01129  * @ret rc              Return status code
01130  */
01131 static int tls_send_certificate ( struct tls_connection *tls ) {
01132         struct {
01133                 uint32_t type_length;
01134                 tls24_t length;
01135                 struct {
01136                         tls24_t length;
01137                         uint8_t data[ tls->cert->raw.len ];
01138                 } __attribute__ (( packed )) certificates[1];
01139         } __attribute__ (( packed )) *certificate;
01140         int rc;
01141 
01142         /* Allocate storage for Certificate record (which may be too
01143          * large for the stack).
01144          */
01145         certificate = zalloc ( sizeof ( *certificate ) );
01146         if ( ! certificate )
01147                 return -ENOMEM_CERTIFICATE;
01148 
01149         /* Populate record */
01150         certificate->type_length =
01151                 ( cpu_to_le32 ( TLS_CERTIFICATE ) |
01152                   htonl ( sizeof ( *certificate ) -
01153                           sizeof ( certificate->type_length ) ) );
01154         tls_set_uint24 ( &certificate->length,
01155                          sizeof ( certificate->certificates ) );
01156         tls_set_uint24 ( &certificate->certificates[0].length,
01157                          sizeof ( certificate->certificates[0].data ) );
01158         memcpy ( certificate->certificates[0].data,
01159                  tls->cert->raw.data,
01160                  sizeof ( certificate->certificates[0].data ) );
01161 
01162         /* Transmit record */
01163         rc = tls_send_handshake ( tls, certificate, sizeof ( *certificate ) );
01164 
01165         /* Free record */
01166         free ( certificate );
01167 
01168         return rc;
01169 }
01170 
01171 /**
01172  * Transmit Client Key Exchange record
01173  *
01174  * @v tls               TLS connection
01175  * @ret rc              Return status code
01176  */
01177 static int tls_send_client_key_exchange ( struct tls_connection *tls ) {
01178         struct tls_cipherspec *cipherspec = &tls->tx_cipherspec_pending;
01179         struct pubkey_algorithm *pubkey = cipherspec->suite->pubkey;
01180         size_t max_len = pubkey_max_len ( pubkey, cipherspec->pubkey_ctx );
01181         struct {
01182                 uint32_t type_length;
01183                 uint16_t encrypted_pre_master_secret_len;
01184                 uint8_t encrypted_pre_master_secret[max_len];
01185         } __attribute__ (( packed )) key_xchg;
01186         size_t unused;
01187         int len;
01188         int rc;
01189 
01190         /* Encrypt pre-master secret using server's public key */
01191         memset ( &key_xchg, 0, sizeof ( key_xchg ) );
01192         len = pubkey_encrypt ( pubkey, cipherspec->pubkey_ctx,
01193                                &tls->pre_master_secret,
01194                                sizeof ( tls->pre_master_secret ),
01195                                key_xchg.encrypted_pre_master_secret );
01196         if ( len < 0 ) {
01197                 rc = len;
01198                 DBGC ( tls, "TLS %p could not encrypt pre-master secret: %s\n",
01199                        tls, strerror ( rc ) );
01200                 return rc;
01201         }
01202         unused = ( max_len - len );
01203         key_xchg.type_length =
01204                 ( cpu_to_le32 ( TLS_CLIENT_KEY_EXCHANGE ) |
01205                   htonl ( sizeof ( key_xchg ) -
01206                           sizeof ( key_xchg.type_length ) - unused ) );
01207         key_xchg.encrypted_pre_master_secret_len =
01208                 htons ( sizeof ( key_xchg.encrypted_pre_master_secret ) -
01209                         unused );
01210 
01211         return tls_send_handshake ( tls, &key_xchg,
01212                                     ( sizeof ( key_xchg ) - unused ) );
01213 }
01214 
01215 /**
01216  * Transmit Certificate Verify record
01217  *
01218  * @v tls               TLS connection
01219  * @ret rc              Return status code
01220  */
01221 static int tls_send_certificate_verify ( struct tls_connection *tls ) {
01222         struct digest_algorithm *digest = tls->handshake_digest;
01223         struct x509_certificate *cert = tls->cert;
01224         struct pubkey_algorithm *pubkey = cert->signature_algorithm->pubkey;
01225         uint8_t digest_out[ digest->digestsize ];
01226         uint8_t ctx[ pubkey->ctxsize ];
01227         struct tls_signature_hash_algorithm *sig_hash = NULL;
01228         int rc;
01229 
01230         /* Generate digest to be signed */
01231         tls_verify_handshake ( tls, digest_out );
01232 
01233         /* Initialise public-key algorithm */
01234         if ( ( rc = pubkey_init ( pubkey, ctx, private_key.data,
01235                                   private_key.len ) ) != 0 ) {
01236                 DBGC ( tls, "TLS %p could not initialise %s client private "
01237                        "key: %s\n", tls, pubkey->name, strerror ( rc ) );
01238                 goto err_pubkey_init;
01239         }
01240 
01241         /* TLSv1.2 and later use explicit algorithm identifiers */
01242         if ( tls->version >= TLS_VERSION_TLS_1_2 ) {
01243                 sig_hash = tls_signature_hash_algorithm ( pubkey, digest );
01244                 if ( ! sig_hash ) {
01245                         DBGC ( tls, "TLS %p could not identify (%s,%s) "
01246                                "signature and hash algorithm\n", tls,
01247                                pubkey->name, digest->name );
01248                         rc = -ENOTSUP_SIG_HASH;
01249                         goto err_sig_hash;
01250                 }
01251         }
01252 
01253         /* Generate and transmit record */
01254         {
01255                 size_t max_len = pubkey_max_len ( pubkey, ctx );
01256                 int use_sig_hash = ( ( sig_hash == NULL ) ? 0 : 1 );
01257                 struct {
01258                         uint32_t type_length;
01259                         struct tls_signature_hash_id sig_hash[use_sig_hash];
01260                         uint16_t signature_len;
01261                         uint8_t signature[max_len];
01262                 } __attribute__ (( packed )) certificate_verify;
01263                 size_t unused;
01264                 int len;
01265 
01266                 /* Sign digest */
01267                 len = pubkey_sign ( pubkey, ctx, digest, digest_out,
01268                                     certificate_verify.signature );
01269                 if ( len < 0 ) {
01270                         rc = len;
01271                         DBGC ( tls, "TLS %p could not sign %s digest using %s "
01272                                "client private key: %s\n", tls, digest->name,
01273                                pubkey->name, strerror ( rc ) );
01274                         goto err_pubkey_sign;
01275                 }
01276                 unused = ( max_len - len );
01277 
01278                 /* Construct Certificate Verify record */
01279                 certificate_verify.type_length =
01280                         ( cpu_to_le32 ( TLS_CERTIFICATE_VERIFY ) |
01281                           htonl ( sizeof ( certificate_verify ) -
01282                                   sizeof ( certificate_verify.type_length ) -
01283                                   unused ) );
01284                 if ( use_sig_hash ) {
01285                         memcpy ( &certificate_verify.sig_hash[0],
01286                                  &sig_hash->code,
01287                                  sizeof ( certificate_verify.sig_hash[0] ) );
01288                 }
01289                 certificate_verify.signature_len =
01290                         htons ( sizeof ( certificate_verify.signature ) -
01291                                 unused );
01292 
01293                 /* Transmit record */
01294                 rc = tls_send_handshake ( tls, &certificate_verify,
01295                                    ( sizeof ( certificate_verify ) - unused ) );
01296         }
01297 
01298  err_pubkey_sign:
01299  err_sig_hash:
01300         pubkey_final ( pubkey, ctx );
01301  err_pubkey_init:
01302         return rc;
01303 }
01304 
01305 /**
01306  * Transmit Change Cipher record
01307  *
01308  * @v tls               TLS connection
01309  * @ret rc              Return status code
01310  */
01311 static int tls_send_change_cipher ( struct tls_connection *tls ) {
01312         static const uint8_t change_cipher[1] = { 1 };
01313         return tls_send_plaintext ( tls, TLS_TYPE_CHANGE_CIPHER,
01314                                     change_cipher, sizeof ( change_cipher ) );
01315 }
01316 
01317 /**
01318  * Transmit Finished record
01319  *
01320  * @v tls               TLS connection
01321  * @ret rc              Return status code
01322  */
01323 static int tls_send_finished ( struct tls_connection *tls ) {
01324         struct digest_algorithm *digest = tls->handshake_digest;
01325         struct {
01326                 uint32_t type_length;
01327                 uint8_t verify_data[ sizeof ( tls->verify.client ) ];
01328         } __attribute__ (( packed )) finished;
01329         uint8_t digest_out[ digest->digestsize ];
01330         int rc;
01331 
01332         /* Construct client verification data */
01333         tls_verify_handshake ( tls, digest_out );
01334         tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
01335                         tls->verify.client, sizeof ( tls->verify.client ),
01336                         "client finished", digest_out, sizeof ( digest_out ) );
01337 
01338         /* Construct record */
01339         memset ( &finished, 0, sizeof ( finished ) );
01340         finished.type_length = ( cpu_to_le32 ( TLS_FINISHED ) |
01341                                  htonl ( sizeof ( finished ) -
01342                                          sizeof ( finished.type_length ) ) );
01343         memcpy ( finished.verify_data, tls->verify.client,
01344                  sizeof ( finished.verify_data ) );
01345 
01346         /* Transmit record */
01347         if ( ( rc = tls_send_handshake ( tls, &finished,
01348                                          sizeof ( finished ) ) ) != 0 )
01349                 return rc;
01350 
01351         /* Mark client as finished */
01352         pending_put ( &tls->client_negotiation );
01353 
01354         return 0;
01355 }
01356 
01357 /**
01358  * Receive new Change Cipher record
01359  *
01360  * @v tls               TLS connection
01361  * @v data              Plaintext record
01362  * @v len               Length of plaintext record
01363  * @ret rc              Return status code
01364  */
01365 static int tls_new_change_cipher ( struct tls_connection *tls,
01366                                    const void *data, size_t len ) {
01367         int rc;
01368 
01369         if ( ( len != 1 ) || ( *( ( uint8_t * ) data ) != 1 ) ) {
01370                 DBGC ( tls, "TLS %p received invalid Change Cipher\n", tls );
01371                 DBGC_HD ( tls, data, len );
01372                 return -EINVAL_CHANGE_CIPHER;
01373         }
01374 
01375         if ( ( rc = tls_change_cipher ( tls, &tls->rx_cipherspec_pending,
01376                                         &tls->rx_cipherspec ) ) != 0 ) {
01377                 DBGC ( tls, "TLS %p could not activate RX cipher: %s\n",
01378                        tls, strerror ( rc ) );
01379                 return rc;
01380         }
01381         tls->rx_seq = ~( ( uint64_t ) 0 );
01382 
01383         return 0;
01384 }
01385 
01386 /**
01387  * Receive new Alert record
01388  *
01389  * @v tls               TLS connection
01390  * @v data              Plaintext record
01391  * @v len               Length of plaintext record
01392  * @ret rc              Return status code
01393  */
01394 static int tls_new_alert ( struct tls_connection *tls, const void *data,
01395                            size_t len ) {
01396         const struct {
01397                 uint8_t level;
01398                 uint8_t description;
01399                 char next[0];
01400         } __attribute__ (( packed )) *alert = data;
01401 
01402         /* Sanity check */
01403         if ( sizeof ( *alert ) != len ) {
01404                 DBGC ( tls, "TLS %p received overlength Alert\n", tls );
01405                 DBGC_HD ( tls, data, len );
01406                 return -EINVAL_ALERT;
01407         }
01408 
01409         switch ( alert->level ) {
01410         case TLS_ALERT_WARNING:
01411                 DBGC ( tls, "TLS %p received warning alert %d\n",
01412                        tls, alert->description );
01413                 return 0;
01414         case TLS_ALERT_FATAL:
01415                 DBGC ( tls, "TLS %p received fatal alert %d\n",
01416                        tls, alert->description );
01417                 return -EPERM_ALERT;
01418         default:
01419                 DBGC ( tls, "TLS %p received unknown alert level %d"
01420                        "(alert %d)\n", tls, alert->level, alert->description );
01421                 return -EIO_ALERT;
01422         }
01423 }
01424 
01425 /**
01426  * Receive new Hello Request handshake record
01427  *
01428  * @v tls               TLS connection
01429  * @v data              Plaintext handshake record
01430  * @v len               Length of plaintext handshake record
01431  * @ret rc              Return status code
01432  */
01433 static int tls_new_hello_request ( struct tls_connection *tls,
01434                                    const void *data __unused,
01435                                    size_t len __unused ) {
01436 
01437         /* Ignore if a handshake is in progress */
01438         if ( ! tls_ready ( tls ) ) {
01439                 DBGC ( tls, "TLS %p ignoring Hello Request\n", tls );
01440                 return 0;
01441         }
01442 
01443         /* Fail unless server supports secure renegotiation */
01444         if ( ! tls->secure_renegotiation ) {
01445                 DBGC ( tls, "TLS %p refusing to renegotiate insecurely\n",
01446                        tls );
01447                 return -EPERM_RENEG_INSECURE;
01448         }
01449 
01450         /* Restart negotiation */
01451         tls_restart ( tls );
01452 
01453         return 0;
01454 }
01455 
01456 /**
01457  * Receive new Server Hello handshake record
01458  *
01459  * @v tls               TLS connection
01460  * @v data              Plaintext handshake record
01461  * @v len               Length of plaintext handshake record
01462  * @ret rc              Return status code
01463  */
01464 static int tls_new_server_hello ( struct tls_connection *tls,
01465                                   const void *data, size_t len ) {
01466         const struct {
01467                 uint16_t version;
01468                 uint8_t random[32];
01469                 uint8_t session_id_len;
01470                 uint8_t session_id[0];
01471         } __attribute__ (( packed )) *hello_a = data;
01472         const uint8_t *session_id;
01473         const struct {
01474                 uint16_t cipher_suite;
01475                 uint8_t compression_method;
01476                 char next[0];
01477         } __attribute__ (( packed )) *hello_b;
01478         const struct {
01479                 uint16_t len;
01480                 uint8_t data[0];
01481         } __attribute__ (( packed )) *exts;
01482         const struct {
01483                 uint16_t type;
01484                 uint16_t len;
01485                 uint8_t data[0];
01486         } __attribute__ (( packed )) *ext;
01487         const struct {
01488                 uint8_t len;
01489                 uint8_t data[0];
01490         } __attribute__ (( packed )) *reneg = NULL;
01491         uint16_t version;
01492         size_t exts_len;
01493         size_t ext_len;
01494         size_t remaining;
01495         int rc;
01496 
01497         /* Parse header */
01498         if ( ( sizeof ( *hello_a ) > len ) ||
01499              ( hello_a->session_id_len > ( len - sizeof ( *hello_a ) ) ) ||
01500              ( sizeof ( *hello_b ) > ( len - sizeof ( *hello_a ) -
01501                                        hello_a->session_id_len ) ) ) {
01502                 DBGC ( tls, "TLS %p received underlength Server Hello\n", tls );
01503                 DBGC_HD ( tls, data, len );
01504                 return -EINVAL_HELLO;
01505         }
01506         session_id = hello_a->session_id;
01507         hello_b = ( ( void * ) ( session_id + hello_a->session_id_len ) );
01508 
01509         /* Parse extensions, if present */
01510         remaining = ( len - sizeof ( *hello_a ) - hello_a->session_id_len -
01511                       sizeof ( *hello_b ) );
01512         if ( remaining ) {
01513 
01514                 /* Parse extensions length */
01515                 exts = ( ( void * ) hello_b->next );
01516                 if ( ( sizeof ( *exts ) > remaining ) ||
01517                      ( ( exts_len = ntohs ( exts->len ) ) >
01518                        ( remaining - sizeof ( *exts ) ) ) ) {
01519                         DBGC ( tls, "TLS %p received underlength extensions\n",
01520                                tls );
01521                         DBGC_HD ( tls, data, len );
01522                         return -EINVAL_HELLO;
01523                 }
01524 
01525                 /* Parse extensions */
01526                 for ( ext = ( ( void * ) exts->data ), remaining = exts_len ;
01527                       remaining ;
01528                       ext = ( ( ( void * ) ext ) + sizeof ( *ext ) + ext_len ),
01529                               remaining -= ( sizeof ( *ext ) + ext_len ) ) {
01530 
01531                         /* Parse extension length */
01532                         if ( ( sizeof ( *ext ) > remaining ) ||
01533                              ( ( ext_len = ntohs ( ext->len ) ) >
01534                                ( remaining - sizeof ( *ext ) ) ) ) {
01535                                 DBGC ( tls, "TLS %p received underlength "
01536                                        "extension\n", tls );
01537                                 DBGC_HD ( tls, data, len );
01538                                 return -EINVAL_HELLO;
01539                         }
01540 
01541                         /* Record known extensions */
01542                         switch ( ext->type ) {
01543                         case htons ( TLS_RENEGOTIATION_INFO ) :
01544                                 reneg = ( ( void * ) ext->data );
01545                                 if ( ( sizeof ( *reneg ) > ext_len ) ||
01546                                      ( reneg->len >
01547                                        ( ext_len - sizeof ( *reneg ) ) ) ) {
01548                                         DBGC ( tls, "TLS %p received "
01549                                                "underlength renegotiation "
01550                                                "info\n", tls );
01551                                         DBGC_HD ( tls, data, len );
01552                                         return -EINVAL_HELLO;
01553                                 }
01554                                 break;
01555                         }
01556                 }
01557         }
01558 
01559         /* Check and store protocol version */
01560         version = ntohs ( hello_a->version );
01561         if ( version < TLS_VERSION_TLS_1_0 ) {
01562                 DBGC ( tls, "TLS %p does not support protocol version %d.%d\n",
01563                        tls, ( version >> 8 ), ( version & 0xff ) );
01564                 return -ENOTSUP_VERSION;
01565         }
01566         if ( version > tls->version ) {
01567                 DBGC ( tls, "TLS %p server attempted to illegally upgrade to "
01568                        "protocol version %d.%d\n",
01569                        tls, ( version >> 8 ), ( version & 0xff ) );
01570                 return -EPROTO_VERSION;
01571         }
01572         tls->version = version;
01573         DBGC ( tls, "TLS %p using protocol version %d.%d\n",
01574                tls, ( version >> 8 ), ( version & 0xff ) );
01575 
01576         /* Use MD5+SHA1 digest algorithm for handshake verification
01577          * for versions earlier than TLSv1.2.
01578          */
01579         if ( tls->version < TLS_VERSION_TLS_1_2 ) {
01580                 tls->handshake_digest = &md5_sha1_algorithm;
01581                 tls->handshake_ctx = tls->handshake_md5_sha1_ctx;
01582         }
01583 
01584         /* Copy out server random bytes */
01585         memcpy ( &tls->server_random, &hello_a->random,
01586                  sizeof ( tls->server_random ) );
01587 
01588         /* Select cipher suite */
01589         if ( ( rc = tls_select_cipher ( tls, hello_b->cipher_suite ) ) != 0 )
01590                 return rc;
01591 
01592         /* Reuse or generate master secret */
01593         if ( hello_a->session_id_len &&
01594              ( hello_a->session_id_len == tls->session_id_len ) &&
01595              ( memcmp ( session_id, tls->session_id,
01596                         tls->session_id_len ) == 0 ) ) {
01597 
01598                 /* Session ID match: reuse master secret */
01599                 DBGC ( tls, "TLS %p resuming session ID:\n", tls );
01600                 DBGC_HDA ( tls, 0, tls->session_id, tls->session_id_len );
01601 
01602         } else {
01603 
01604                 /* Generate new master secret */
01605                 tls_generate_master_secret ( tls );
01606 
01607                 /* Record new session ID, if present */
01608                 if ( hello_a->session_id_len &&
01609                      ( hello_a->session_id_len <= sizeof ( tls->session_id ))){
01610                         tls->session_id_len = hello_a->session_id_len;
01611                         memcpy ( tls->session_id, session_id,
01612                                  tls->session_id_len );
01613                         DBGC ( tls, "TLS %p new session ID:\n", tls );
01614                         DBGC_HDA ( tls, 0, tls->session_id,
01615                                    tls->session_id_len );
01616                 }
01617         }
01618 
01619         /* Generate keys */
01620         if ( ( rc = tls_generate_keys ( tls ) ) != 0 )
01621                 return rc;
01622 
01623         /* Handle secure renegotiation */
01624         if ( tls->secure_renegotiation ) {
01625 
01626                 /* Secure renegotiation is expected; verify data */
01627                 if ( ( reneg == NULL ) ||
01628                      ( reneg->len != sizeof ( tls->verify ) ) ||
01629                      ( memcmp ( reneg->data, &tls->verify,
01630                                 sizeof ( tls->verify ) ) != 0 ) ) {
01631                         DBGC ( tls, "TLS %p server failed secure "
01632                                "renegotiation\n", tls );
01633                         return -EPERM_RENEG_VERIFY;
01634                 }
01635 
01636         } else if ( reneg != NULL ) {
01637 
01638                 /* Secure renegotiation is being enabled */
01639                 if ( reneg->len != 0 ) {
01640                         DBGC ( tls, "TLS %p server provided non-empty initial "
01641                                "renegotiation\n", tls );
01642                         return -EPERM_RENEG_VERIFY;
01643                 }
01644                 tls->secure_renegotiation = 1;
01645         }
01646 
01647         return 0;
01648 }
01649 
01650 /**
01651  * Receive New Session Ticket handshake record
01652  *
01653  * @v tls               TLS connection
01654  * @v data              Plaintext handshake record
01655  * @v len               Length of plaintext handshake record
01656  * @ret rc              Return status code
01657  */
01658 static int tls_new_session_ticket ( struct tls_connection *tls,
01659                                     const void *data, size_t len ) {
01660         const struct {
01661                 uint32_t lifetime;
01662                 uint16_t len;
01663                 uint8_t ticket[0];
01664         } __attribute__ (( packed )) *new_session_ticket = data;
01665         size_t ticket_len;
01666 
01667         /* Parse header */
01668         if ( sizeof ( *new_session_ticket ) > len ) {
01669                 DBGC ( tls, "TLS %p received underlength New Session Ticket\n",
01670                        tls );
01671                 DBGC_HD ( tls, data, len );
01672                 return -EINVAL_TICKET;
01673         }
01674         ticket_len = ntohs ( new_session_ticket->len );
01675         if ( ticket_len > ( len - sizeof ( *new_session_ticket ) ) ) {
01676                 DBGC ( tls, "TLS %p received overlength New Session Ticket\n",
01677                        tls );
01678                 DBGC_HD ( tls, data, len );
01679                 return -EINVAL_TICKET;
01680         }
01681 
01682         /* Free any unapplied new session ticket */
01683         free ( tls->new_session_ticket );
01684         tls->new_session_ticket = NULL;
01685         tls->new_session_ticket_len = 0;
01686 
01687         /* Record ticket */
01688         tls->new_session_ticket = malloc ( ticket_len );
01689         if ( ! tls->new_session_ticket )
01690                 return -ENOMEM;
01691         memcpy ( tls->new_session_ticket, new_session_ticket->ticket,
01692                  ticket_len );
01693         tls->new_session_ticket_len = ticket_len;
01694         DBGC ( tls, "TLS %p new session ticket:\n", tls );
01695         DBGC_HDA ( tls, 0, tls->new_session_ticket,
01696                    tls->new_session_ticket_len );
01697 
01698         return 0;
01699 }
01700 
01701 /**
01702  * Parse certificate chain
01703  *
01704  * @v tls               TLS connection
01705  * @v data              Certificate chain
01706  * @v len               Length of certificate chain
01707  * @ret rc              Return status code
01708  */
01709 static int tls_parse_chain ( struct tls_connection *tls,
01710                              const void *data, size_t len ) {
01711         size_t remaining = len;
01712         int rc;
01713 
01714         /* Free any existing certificate chain */
01715         x509_chain_put ( tls->chain );
01716         tls->chain = NULL;
01717 
01718         /* Create certificate chain */
01719         tls->chain = x509_alloc_chain();
01720         if ( ! tls->chain ) {
01721                 rc = -ENOMEM_CHAIN;
01722                 goto err_alloc_chain;
01723         }
01724 
01725         /* Add certificates to chain */
01726         while ( remaining ) {
01727                 const struct {
01728                         tls24_t length;
01729                         uint8_t data[0];
01730                 } __attribute__ (( packed )) *certificate = data;
01731                 size_t certificate_len;
01732                 size_t record_len;
01733                 struct x509_certificate *cert;
01734 
01735                 /* Parse header */
01736                 if ( sizeof ( *certificate ) > remaining ) {
01737                         DBGC ( tls, "TLS %p underlength certificate:\n", tls );
01738                         DBGC_HDA ( tls, 0, data, remaining );
01739                         rc = -EINVAL_CERTIFICATE;
01740                         goto err_underlength;
01741                 }
01742                 certificate_len = tls_uint24 ( &certificate->length );
01743                 if ( certificate_len > ( remaining - sizeof ( *certificate ) )){
01744                         DBGC ( tls, "TLS %p overlength certificate:\n", tls );
01745                         DBGC_HDA ( tls, 0, data, remaining );
01746                         rc = -EINVAL_CERTIFICATE;
01747                         goto err_overlength;
01748                 }
01749                 record_len = ( sizeof ( *certificate ) + certificate_len );
01750 
01751                 /* Add certificate to chain */
01752                 if ( ( rc = x509_append_raw ( tls->chain, certificate->data,
01753                                               certificate_len ) ) != 0 ) {
01754                         DBGC ( tls, "TLS %p could not append certificate: %s\n",
01755                                tls, strerror ( rc ) );
01756                         DBGC_HDA ( tls, 0, data, remaining );
01757                         goto err_parse;
01758                 }
01759                 cert = x509_last ( tls->chain );
01760                 DBGC ( tls, "TLS %p found certificate %s\n",
01761                        tls, x509_name ( cert ) );
01762 
01763                 /* Move to next certificate in list */
01764                 data += record_len;
01765                 remaining -= record_len;
01766         }
01767 
01768         return 0;
01769 
01770  err_parse:
01771  err_overlength:
01772  err_underlength:
01773         x509_chain_put ( tls->chain );
01774         tls->chain = NULL;
01775  err_alloc_chain:
01776         return rc;
01777 }
01778 
01779 /**
01780  * Receive new Certificate handshake record
01781  *
01782  * @v tls               TLS connection
01783  * @v data              Plaintext handshake record
01784  * @v len               Length of plaintext handshake record
01785  * @ret rc              Return status code
01786  */
01787 static int tls_new_certificate ( struct tls_connection *tls,
01788                                  const void *data, size_t len ) {
01789         const struct {
01790                 tls24_t length;
01791                 uint8_t certificates[0];
01792         } __attribute__ (( packed )) *certificate = data;
01793         size_t certificates_len;
01794         int rc;
01795 
01796         /* Parse header */
01797         if ( sizeof ( *certificate ) > len ) {
01798                 DBGC ( tls, "TLS %p received underlength Server Certificate\n",
01799                        tls );
01800                 DBGC_HD ( tls, data, len );
01801                 return -EINVAL_CERTIFICATES;
01802         }
01803         certificates_len = tls_uint24 ( &certificate->length );
01804         if ( certificates_len > ( len - sizeof ( *certificate ) ) ) {
01805                 DBGC ( tls, "TLS %p received overlength Server Certificate\n",
01806                        tls );
01807                 DBGC_HD ( tls, data, len );
01808                 return -EINVAL_CERTIFICATES;
01809         }
01810 
01811         /* Parse certificate chain */
01812         if ( ( rc = tls_parse_chain ( tls, certificate->certificates,
01813                                       certificates_len ) ) != 0 )
01814                 return rc;
01815 
01816         return 0;
01817 }
01818 
01819 /**
01820  * Receive new Certificate Request handshake record
01821  *
01822  * @v tls               TLS connection
01823  * @v data              Plaintext handshake record
01824  * @v len               Length of plaintext handshake record
01825  * @ret rc              Return status code
01826  */
01827 static int tls_new_certificate_request ( struct tls_connection *tls,
01828                                          const void *data __unused,
01829                                          size_t len __unused ) {
01830 
01831         /* We can only send a single certificate, so there is no point
01832          * in parsing the Certificate Request.
01833          */
01834 
01835         /* Free any existing client certificate */
01836         x509_put ( tls->cert );
01837 
01838         /* Determine client certificate to be sent */
01839         tls->cert = certstore_find_key ( &private_key );
01840         if ( ! tls->cert ) {
01841                 DBGC ( tls, "TLS %p could not find certificate corresponding "
01842                        "to private key\n", tls );
01843                 return -EPERM_CLIENT_CERT;
01844         }
01845         x509_get ( tls->cert );
01846         DBGC ( tls, "TLS %p sending client certificate %s\n",
01847                tls, x509_name ( tls->cert ) );
01848 
01849         return 0;
01850 }
01851 
01852 /**
01853  * Receive new Server Hello Done handshake record
01854  *
01855  * @v tls               TLS connection
01856  * @v data              Plaintext handshake record
01857  * @v len               Length of plaintext handshake record
01858  * @ret rc              Return status code
01859  */
01860 static int tls_new_server_hello_done ( struct tls_connection *tls,
01861                                        const void *data, size_t len ) {
01862         const struct {
01863                 char next[0];
01864         } __attribute__ (( packed )) *hello_done = data;
01865         int rc;
01866 
01867         /* Sanity check */
01868         if ( sizeof ( *hello_done ) != len ) {
01869                 DBGC ( tls, "TLS %p received overlength Server Hello Done\n",
01870                        tls );
01871                 DBGC_HD ( tls, data, len );
01872                 return -EINVAL_HELLO_DONE;
01873         }
01874 
01875         /* Begin certificate validation */
01876         if ( ( rc = create_validator ( &tls->validator, tls->chain ) ) != 0 ) {
01877                 DBGC ( tls, "TLS %p could not start certificate validation: "
01878                        "%s\n", tls, strerror ( rc ) );
01879                 return rc;
01880         }
01881         pending_get ( &tls->validation );
01882 
01883         return 0;
01884 }
01885 
01886 /**
01887  * Receive new Finished handshake record
01888  *
01889  * @v tls               TLS connection
01890  * @v data              Plaintext handshake record
01891  * @v len               Length of plaintext handshake record
01892  * @ret rc              Return status code
01893  */
01894 static int tls_new_finished ( struct tls_connection *tls,
01895                               const void *data, size_t len ) {
01896         struct tls_session *session = tls->session;
01897         struct digest_algorithm *digest = tls->handshake_digest;
01898         const struct {
01899                 uint8_t verify_data[ sizeof ( tls->verify.server ) ];
01900                 char next[0];
01901         } __attribute__ (( packed )) *finished = data;
01902         uint8_t digest_out[ digest->digestsize ];
01903 
01904         /* Sanity check */
01905         if ( sizeof ( *finished ) != len ) {
01906                 DBGC ( tls, "TLS %p received overlength Finished\n", tls );
01907                 DBGC_HD ( tls, data, len );
01908                 return -EINVAL_FINISHED;
01909         }
01910 
01911         /* Verify data */
01912         tls_verify_handshake ( tls, digest_out );
01913         tls_prf_label ( tls, &tls->master_secret, sizeof ( tls->master_secret ),
01914                         tls->verify.server, sizeof ( tls->verify.server ),
01915                         "server finished", digest_out, sizeof ( digest_out ) );
01916         if ( memcmp ( tls->verify.server, finished->verify_data,
01917                       sizeof ( tls->verify.server ) ) != 0 ) {
01918                 DBGC ( tls, "TLS %p verification failed\n", tls );
01919                 return -EPERM_VERIFY;
01920         }
01921 
01922         /* Mark server as finished */
01923         pending_put ( &tls->server_negotiation );
01924 
01925         /* If we are resuming a session (i.e. if the server Finished
01926          * arrives before the client Finished is sent), then schedule
01927          * transmission of Change Cipher and Finished.
01928          */
01929         if ( is_pending ( &tls->client_negotiation ) ) {
01930                 tls->tx_pending |= ( TLS_TX_CHANGE_CIPHER | TLS_TX_FINISHED );
01931                 tls_tx_resume ( tls );
01932         }
01933 
01934         /* Record session ID, ticket, and master secret, if applicable */
01935         if ( tls->session_id_len || tls->new_session_ticket_len ) {
01936                 memcpy ( session->master_secret, tls->master_secret,
01937                          sizeof ( session->master_secret ) );
01938         }
01939         if ( tls->session_id_len ) {
01940                 session->id_len = tls->session_id_len;
01941                 memcpy ( session->id, tls->session_id, sizeof ( session->id ) );
01942         }
01943         if ( tls->new_session_ticket_len ) {
01944                 free ( session->ticket );
01945                 session->ticket = tls->new_session_ticket;
01946                 session->ticket_len = tls->new_session_ticket_len;
01947                 tls->new_session_ticket = NULL;
01948                 tls->new_session_ticket_len = 0;
01949         }
01950 
01951         /* Move to end of session's connection list and allow other
01952          * connections to start making progress.
01953          */
01954         list_del ( &tls->list );
01955         list_add_tail ( &tls->list, &session->conn );
01956         tls_tx_resume_all ( session );
01957 
01958         /* Send notification of a window change */
01959         xfer_window_changed ( &tls->plainstream );
01960 
01961         return 0;
01962 }
01963 
01964 /**
01965  * Receive new Handshake record
01966  *
01967  * @v tls               TLS connection
01968  * @v data              Plaintext record
01969  * @v len               Length of plaintext record
01970  * @ret rc              Return status code
01971  */
01972 static int tls_new_handshake ( struct tls_connection *tls,
01973                                const void *data, size_t len ) {
01974         size_t remaining = len;
01975         int rc;
01976 
01977         while ( remaining ) {
01978                 const struct {
01979                         uint8_t type;
01980                         tls24_t length;
01981                         uint8_t payload[0];
01982                 } __attribute__ (( packed )) *handshake = data;
01983                 const void *payload;
01984                 size_t payload_len;
01985                 size_t record_len;
01986 
01987                 /* Parse header */
01988                 if ( sizeof ( *handshake ) > remaining ) {
01989                         DBGC ( tls, "TLS %p received underlength Handshake\n",
01990                                tls );
01991                         DBGC_HD ( tls, data, remaining );
01992                         return -EINVAL_HANDSHAKE;
01993                 }
01994                 payload_len = tls_uint24 ( &handshake->length );
01995                 if ( payload_len > ( remaining - sizeof ( *handshake ) ) ) {
01996                         DBGC ( tls, "TLS %p received overlength Handshake\n",
01997                                tls );
01998                         DBGC_HD ( tls, data, len );
01999                         return -EINVAL_HANDSHAKE;
02000                 }
02001                 payload = &handshake->payload;
02002                 record_len = ( sizeof ( *handshake ) + payload_len );
02003 
02004                 /* Handle payload */
02005                 switch ( handshake->type ) {
02006                 case TLS_HELLO_REQUEST:
02007                         rc = tls_new_hello_request ( tls, payload,
02008                                                      payload_len );
02009                         break;
02010                 case TLS_SERVER_HELLO:
02011                         rc = tls_new_server_hello ( tls, payload, payload_len );
02012                         break;
02013                 case TLS_NEW_SESSION_TICKET:
02014                         rc = tls_new_session_ticket ( tls, payload,
02015                                                       payload_len );
02016                         break;
02017                 case TLS_CERTIFICATE:
02018                         rc = tls_new_certificate ( tls, payload, payload_len );
02019                         break;
02020                 case TLS_CERTIFICATE_REQUEST:
02021                         rc = tls_new_certificate_request ( tls, payload,
02022                                                            payload_len );
02023                         break;
02024                 case TLS_SERVER_HELLO_DONE:
02025                         rc = tls_new_server_hello_done ( tls, payload,
02026                                                          payload_len );
02027                         break;
02028                 case TLS_FINISHED:
02029                         rc = tls_new_finished ( tls, payload, payload_len );
02030                         break;
02031                 default:
02032                         DBGC ( tls, "TLS %p ignoring handshake type %d\n",
02033                                tls, handshake->type );
02034                         rc = 0;
02035                         break;
02036                 }
02037 
02038                 /* Add to handshake digest (except for Hello Requests,
02039                  * which are explicitly excluded).
02040                  */
02041                 if ( handshake->type != TLS_HELLO_REQUEST )
02042                         tls_add_handshake ( tls, data, record_len );
02043 
02044                 /* Abort on failure */
02045                 if ( rc != 0 )
02046                         return rc;
02047 
02048                 /* Move to next handshake record */
02049                 data += record_len;
02050                 remaining -= record_len;
02051         }
02052 
02053         return 0;
02054 }
02055 
02056 /**
02057  * Receive new record
02058  *
02059  * @v tls               TLS connection
02060  * @v type              Record type
02061  * @v rx_data           List of received data buffers
02062  * @ret rc              Return status code
02063  */
02064 static int tls_new_record ( struct tls_connection *tls, unsigned int type,
02065                             struct list_head *rx_data ) {
02066         struct io_buffer *iobuf;
02067         int ( * handler ) ( struct tls_connection *tls, const void *data,
02068                             size_t len );
02069         int rc;
02070 
02071         /* Deliver data records to the plainstream interface */
02072         if ( type == TLS_TYPE_DATA ) {
02073 
02074                 /* Fail unless we are ready to receive data */
02075                 if ( ! tls_ready ( tls ) )
02076                         return -ENOTCONN;
02077 
02078                 /* Deliver each I/O buffer in turn */
02079                 while ( ( iobuf = list_first_entry ( rx_data, struct io_buffer,
02080                                                      list ) ) ) {
02081                         list_del ( &iobuf->list );
02082                         if ( ( rc = xfer_deliver_iob ( &tls->plainstream,
02083                                                        iobuf ) ) != 0 ) {
02084                                 DBGC ( tls, "TLS %p could not deliver data: "
02085                                        "%s\n", tls, strerror ( rc ) );
02086                                 return rc;
02087                         }
02088                 }
02089                 return 0;
02090         }
02091 
02092         /* For all other records, merge into a single I/O buffer */
02093         iobuf = iob_concatenate ( rx_data );
02094         if ( ! iobuf ) {
02095                 DBGC ( tls, "TLS %p could not concatenate non-data record "
02096                        "type %d\n", tls, type );
02097                 return -ENOMEM_RX_CONCAT;
02098         }
02099 
02100         /* Determine handler */
02101         switch ( type ) {
02102         case TLS_TYPE_CHANGE_CIPHER:
02103                 handler = tls_new_change_cipher;
02104                 break;
02105         case TLS_TYPE_ALERT:
02106                 handler = tls_new_alert;
02107                 break;
02108         case TLS_TYPE_HANDSHAKE:
02109                 handler = tls_new_handshake;
02110                 break;
02111         default:
02112                 /* RFC4346 says that we should just ignore unknown
02113                  * record types.
02114                  */
02115                 handler = NULL;
02116                 DBGC ( tls, "TLS %p ignoring record type %d\n", tls, type );
02117                 break;
02118         }
02119 
02120         /* Handle record and free I/O buffer */
02121         rc = ( handler ? handler ( tls, iobuf->data, iob_len ( iobuf ) ) : 0 );
02122         free_iob ( iobuf );
02123         return rc;
02124 }
02125 
02126 /******************************************************************************
02127  *
02128  * Record encryption/decryption
02129  *
02130  ******************************************************************************
02131  */
02132 
02133 /**
02134  * Initialise HMAC
02135  *
02136  * @v cipherspec        Cipher specification
02137  * @v ctx               Context
02138  * @v seq               Sequence number
02139  * @v tlshdr            TLS header
02140  */
02141 static void tls_hmac_init ( struct tls_cipherspec *cipherspec, void *ctx,
02142                             uint64_t seq, struct tls_header *tlshdr ) {
02143         struct digest_algorithm *digest = cipherspec->suite->digest;
02144 
02145         hmac_init ( digest, ctx, cipherspec->mac_secret, &digest->digestsize );
02146         seq = cpu_to_be64 ( seq );
02147         hmac_update ( digest, ctx, &seq, sizeof ( seq ) );
02148         hmac_update ( digest, ctx, tlshdr, sizeof ( *tlshdr ) );
02149 }
02150 
02151 /**
02152  * Update HMAC
02153  *
02154  * @v cipherspec        Cipher specification
02155  * @v ctx               Context
02156  * @v data              Data
02157  * @v len               Length of data
02158  */
02159 static void tls_hmac_update ( struct tls_cipherspec *cipherspec, void *ctx,
02160                               const void *data, size_t len ) {
02161         struct digest_algorithm *digest = cipherspec->suite->digest;
02162 
02163         hmac_update ( digest, ctx, data, len );
02164 }
02165 
02166 /**
02167  * Finalise HMAC
02168  *
02169  * @v cipherspec        Cipher specification
02170  * @v ctx               Context
02171  * @v mac               HMAC to fill in
02172  */
02173 static void tls_hmac_final ( struct tls_cipherspec *cipherspec, void *ctx,
02174                              void *hmac ) {
02175         struct digest_algorithm *digest = cipherspec->suite->digest;
02176 
02177         hmac_final ( digest, ctx, cipherspec->mac_secret,
02178                      &digest->digestsize, hmac );
02179 }
02180 
02181 /**
02182  * Calculate HMAC
02183  *
02184  * @v cipherspec        Cipher specification
02185  * @v seq               Sequence number
02186  * @v tlshdr            TLS header
02187  * @v data              Data
02188  * @v len               Length of data
02189  * @v mac               HMAC to fill in
02190  */
02191 static void tls_hmac ( struct tls_cipherspec *cipherspec,
02192                        uint64_t seq, struct tls_header *tlshdr,
02193                        const void *data, size_t len, void *hmac ) {
02194         struct digest_algorithm *digest = cipherspec->suite->digest;
02195         uint8_t ctx[digest->ctxsize];
02196 
02197         tls_hmac_init ( cipherspec, ctx, seq, tlshdr );
02198         tls_hmac_update ( cipherspec, ctx, data, len );
02199         tls_hmac_final ( cipherspec, ctx, hmac );
02200 }
02201 
02202 /**
02203  * Allocate and assemble stream-ciphered record from data and MAC portions
02204  *
02205  * @v tls               TLS connection
02206  * @ret data            Data
02207  * @ret len             Length of data
02208  * @ret digest          MAC digest
02209  * @ret plaintext_len   Length of plaintext record
02210  * @ret plaintext       Allocated plaintext record
02211  */
02212 static void * __malloc
02213 tls_assemble_stream ( struct tls_connection *tls, const void *data, size_t len,
02214                       void *digest, size_t *plaintext_len ) {
02215         size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
02216         void *plaintext;
02217         void *content;
02218         void *mac;
02219 
02220         /* Calculate stream-ciphered struct length */
02221         *plaintext_len = ( len + mac_len );
02222 
02223         /* Allocate stream-ciphered struct */
02224         plaintext = malloc ( *plaintext_len );
02225         if ( ! plaintext )
02226                 return NULL;
02227         content = plaintext;
02228         mac = ( content + len );
02229 
02230         /* Fill in stream-ciphered struct */
02231         memcpy ( content, data, len );
02232         memcpy ( mac, digest, mac_len );
02233 
02234         return plaintext;
02235 }
02236 
02237 /**
02238  * Allocate and assemble block-ciphered record from data and MAC portions
02239  *
02240  * @v tls               TLS connection
02241  * @ret data            Data
02242  * @ret len             Length of data
02243  * @ret digest          MAC digest
02244  * @ret plaintext_len   Length of plaintext record
02245  * @ret plaintext       Allocated plaintext record
02246  */
02247 static void * tls_assemble_block ( struct tls_connection *tls,
02248                                    const void *data, size_t len,
02249                                    void *digest, size_t *plaintext_len ) {
02250         size_t blocksize = tls->tx_cipherspec.suite->cipher->blocksize;
02251         size_t mac_len = tls->tx_cipherspec.suite->digest->digestsize;
02252         size_t iv_len;
02253         size_t padding_len;
02254         void *plaintext;
02255         void *iv;
02256         void *content;
02257         void *mac;
02258         void *padding;
02259 
02260         /* TLSv1.1 and later use an explicit IV */
02261         iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ? blocksize : 0 );
02262 
02263         /* Calculate block-ciphered struct length */
02264         padding_len = ( ( blocksize - 1 ) & -( iv_len + len + mac_len + 1 ) );
02265         *plaintext_len = ( iv_len + len + mac_len + padding_len + 1 );
02266 
02267         /* Allocate block-ciphered struct */
02268         plaintext = malloc ( *plaintext_len );
02269         if ( ! plaintext )
02270                 return NULL;
02271         iv = plaintext;
02272         content = ( iv + iv_len );
02273         mac = ( content + len );
02274         padding = ( mac + mac_len );
02275 
02276         /* Fill in block-ciphered struct */
02277         tls_generate_random ( tls, iv, iv_len );
02278         memcpy ( content, data, len );
02279         memcpy ( mac, digest, mac_len );
02280         memset ( padding, padding_len, ( padding_len + 1 ) );
02281 
02282         return plaintext;
02283 }
02284 
02285 /**
02286  * Send plaintext record
02287  *
02288  * @v tls               TLS connection
02289  * @v type              Record type
02290  * @v data              Plaintext record
02291  * @v len               Length of plaintext record
02292  * @ret rc              Return status code
02293  */
02294 static int tls_send_plaintext ( struct tls_connection *tls, unsigned int type,
02295                                 const void *data, size_t len ) {
02296         struct tls_header plaintext_tlshdr;
02297         struct tls_header *tlshdr;
02298         struct tls_cipherspec *cipherspec = &tls->tx_cipherspec;
02299         struct cipher_algorithm *cipher = cipherspec->suite->cipher;
02300         void *plaintext = NULL;
02301         size_t plaintext_len;
02302         struct io_buffer *ciphertext = NULL;
02303         size_t ciphertext_len;
02304         size_t mac_len = cipherspec->suite->digest->digestsize;
02305         uint8_t mac[mac_len];
02306         int rc;
02307 
02308         /* Construct header */
02309         plaintext_tlshdr.type = type;
02310         plaintext_tlshdr.version = htons ( tls->version );
02311         plaintext_tlshdr.length = htons ( len );
02312 
02313         /* Calculate MAC */
02314         tls_hmac ( cipherspec, tls->tx_seq, &plaintext_tlshdr, data, len, mac );
02315 
02316         /* Allocate and assemble plaintext struct */
02317         if ( is_stream_cipher ( cipher ) ) {
02318                 plaintext = tls_assemble_stream ( tls, data, len, mac,
02319                                                   &plaintext_len );
02320         } else {
02321                 plaintext = tls_assemble_block ( tls, data, len, mac,
02322                                                  &plaintext_len );
02323         }
02324         if ( ! plaintext ) {
02325                 DBGC ( tls, "TLS %p could not allocate %zd bytes for "
02326                        "plaintext\n", tls, plaintext_len );
02327                 rc = -ENOMEM_TX_PLAINTEXT;
02328                 goto done;
02329         }
02330 
02331         DBGC2 ( tls, "Sending plaintext data:\n" );
02332         DBGC2_HD ( tls, plaintext, plaintext_len );
02333 
02334         /* Allocate ciphertext */
02335         ciphertext_len = ( sizeof ( *tlshdr ) + plaintext_len );
02336         ciphertext = xfer_alloc_iob ( &tls->cipherstream, ciphertext_len );
02337         if ( ! ciphertext ) {
02338                 DBGC ( tls, "TLS %p could not allocate %zd bytes for "
02339                        "ciphertext\n", tls, ciphertext_len );
02340                 rc = -ENOMEM_TX_CIPHERTEXT;
02341                 goto done;
02342         }
02343 
02344         /* Assemble ciphertext */
02345         tlshdr = iob_put ( ciphertext, sizeof ( *tlshdr ) );
02346         tlshdr->type = type;
02347         tlshdr->version = htons ( tls->version );
02348         tlshdr->length = htons ( plaintext_len );
02349         memcpy ( cipherspec->cipher_next_ctx, cipherspec->cipher_ctx,
02350                  cipher->ctxsize );
02351         cipher_encrypt ( cipher, cipherspec->cipher_next_ctx, plaintext,
02352                          iob_put ( ciphertext, plaintext_len ), plaintext_len );
02353 
02354         /* Free plaintext as soon as possible to conserve memory */
02355         free ( plaintext );
02356         plaintext = NULL;
02357 
02358         /* Send ciphertext */
02359         if ( ( rc = xfer_deliver_iob ( &tls->cipherstream,
02360                                        iob_disown ( ciphertext ) ) ) != 0 ) {
02361                 DBGC ( tls, "TLS %p could not deliver ciphertext: %s\n",
02362                        tls, strerror ( rc ) );
02363                 goto done;
02364         }
02365 
02366         /* Update TX state machine to next record */
02367         tls->tx_seq += 1;
02368         memcpy ( tls->tx_cipherspec.cipher_ctx,
02369                  tls->tx_cipherspec.cipher_next_ctx, cipher->ctxsize );
02370 
02371  done:
02372         free ( plaintext );
02373         free_iob ( ciphertext );
02374         return rc;
02375 }
02376 
02377 /**
02378  * Split stream-ciphered record into data and MAC portions
02379  *
02380  * @v tls               TLS connection
02381  * @v rx_data           List of received data buffers
02382  * @v mac               MAC to fill in
02383  * @ret rc              Return status code
02384  */
02385 static int tls_split_stream ( struct tls_connection *tls,
02386                               struct list_head *rx_data, void **mac ) {
02387         size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
02388         struct io_buffer *iobuf;
02389 
02390         /* Extract MAC */
02391         iobuf = list_last_entry ( rx_data, struct io_buffer, list );
02392         assert ( iobuf != NULL );
02393         if ( iob_len ( iobuf ) < mac_len ) {
02394                 DBGC ( tls, "TLS %p received underlength MAC\n", tls );
02395                 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
02396                 return -EINVAL_STREAM;
02397         }
02398         iob_unput ( iobuf, mac_len );
02399         *mac = iobuf->tail;
02400 
02401         return 0;
02402 }
02403 
02404 /**
02405  * Split block-ciphered record into data and MAC portions
02406  *
02407  * @v tls               TLS connection
02408  * @v rx_data           List of received data buffers
02409  * @v mac               MAC to fill in
02410  * @ret rc              Return status code
02411  */
02412 static int tls_split_block ( struct tls_connection *tls,
02413                              struct list_head *rx_data, void **mac ) {
02414         size_t mac_len = tls->rx_cipherspec.suite->digest->digestsize;
02415         struct io_buffer *iobuf;
02416         size_t iv_len;
02417         uint8_t *padding_final;
02418         uint8_t *padding;
02419         size_t padding_len;
02420 
02421         /* TLSv1.1 and later use an explicit IV */
02422         iobuf = list_first_entry ( rx_data, struct io_buffer, list );
02423         iv_len = ( ( tls->version >= TLS_VERSION_TLS_1_1 ) ?
02424                    tls->rx_cipherspec.suite->cipher->blocksize : 0 );
02425         if ( iob_len ( iobuf ) < iv_len ) {
02426                 DBGC ( tls, "TLS %p received underlength IV\n", tls );
02427                 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
02428                 return -EINVAL_BLOCK;
02429         }
02430         iob_pull ( iobuf, iv_len );
02431 
02432         /* Extract and verify padding */
02433         iobuf = list_last_entry ( rx_data, struct io_buffer, list );
02434         padding_final = ( iobuf->tail - 1 );
02435         padding_len = *padding_final;
02436         if ( ( padding_len + 1 ) > iob_len ( iobuf ) ) {
02437                 DBGC ( tls, "TLS %p received underlength padding\n", tls );
02438                 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
02439                 return -EINVAL_BLOCK;
02440         }
02441         iob_unput ( iobuf, ( padding_len + 1 ) );
02442         for ( padding = iobuf->tail ; padding < padding_final ; padding++ ) {
02443                 if ( *padding != padding_len ) {
02444                         DBGC ( tls, "TLS %p received bad padding\n", tls );
02445                         DBGC_HD ( tls, padding, padding_len );
02446                         return -EINVAL_PADDING;
02447                 }
02448         }
02449 
02450         /* Extract MAC */
02451         if ( iob_len ( iobuf ) < mac_len ) {
02452                 DBGC ( tls, "TLS %p received underlength MAC\n", tls );
02453                 DBGC_HD ( tls, iobuf->data, iob_len ( iobuf ) );
02454                 return -EINVAL_BLOCK;
02455         }
02456         iob_unput ( iobuf, mac_len );
02457         *mac = iobuf->tail;
02458 
02459         return 0;
02460 }
02461 
02462 /**
02463  * Receive new ciphertext record
02464  *
02465  * @v tls               TLS connection
02466  * @v tlshdr            Record header
02467  * @v rx_data           List of received data buffers
02468  * @ret rc              Return status code
02469  */
02470 static int tls_new_ciphertext ( struct tls_connection *tls,
02471                                 struct tls_header *tlshdr,
02472                                 struct list_head *rx_data ) {
02473         struct tls_header plaintext_tlshdr;
02474         struct tls_cipherspec *cipherspec = &tls->rx_cipherspec;
02475         struct cipher_algorithm *cipher = cipherspec->suite->cipher;
02476         struct digest_algorithm *digest = cipherspec->suite->digest;
02477         uint8_t ctx[digest->ctxsize];
02478         uint8_t verify_mac[digest->digestsize];
02479         struct io_buffer *iobuf;
02480         void *mac;
02481         size_t len = 0;
02482         int rc;
02483 
02484         /* Decrypt the received data */
02485         list_for_each_entry ( iobuf, &tls->rx_data, list ) {
02486                 cipher_decrypt ( cipher, cipherspec->cipher_ctx,
02487                                  iobuf->data, iobuf->data, iob_len ( iobuf ) );
02488         }
02489 
02490         /* Split record into content and MAC */
02491         if ( is_stream_cipher ( cipher ) ) {
02492                 if ( ( rc = tls_split_stream ( tls, rx_data, &mac ) ) != 0 )
02493                         return rc;
02494         } else {
02495                 if ( ( rc = tls_split_block ( tls, rx_data, &mac ) ) != 0 )
02496                         return rc;
02497         }
02498 
02499         /* Calculate total length */
02500         DBGC2 ( tls, "Received plaintext data:\n" );
02501         list_for_each_entry ( iobuf, rx_data, list ) {
02502                 DBGC2_HD ( tls, iobuf->data, iob_len ( iobuf ) );
02503                 len += iob_len ( iobuf );
02504         }
02505 
02506         /* Verify MAC */
02507         plaintext_tlshdr.type = tlshdr->type;
02508         plaintext_tlshdr.version = tlshdr->version;
02509         plaintext_tlshdr.length = htons ( len );
02510         tls_hmac_init ( cipherspec, ctx, tls->rx_seq, &plaintext_tlshdr );
02511         list_for_each_entry ( iobuf, rx_data, list ) {
02512                 tls_hmac_update ( cipherspec, ctx, iobuf->data,
02513                                   iob_len ( iobuf ) );
02514         }
02515         tls_hmac_final ( cipherspec, ctx, verify_mac );
02516         if ( memcmp ( mac, verify_mac, sizeof ( verify_mac ) ) != 0 ) {
02517                 DBGC ( tls, "TLS %p failed MAC verification\n", tls );
02518                 return -EINVAL_MAC;
02519         }
02520 
02521         /* Process plaintext record */
02522         if ( ( rc = tls_new_record ( tls, tlshdr->type, rx_data ) ) != 0 )
02523                 return rc;
02524 
02525         return 0;
02526 }
02527 
02528 /******************************************************************************
02529  *
02530  * Plaintext stream operations
02531  *
02532  ******************************************************************************
02533  */
02534 
02535 /**
02536  * Check flow control window
02537  *
02538  * @v tls               TLS connection
02539  * @ret len             Length of window
02540  */
02541 static size_t tls_plainstream_window ( struct tls_connection *tls ) {
02542 
02543         /* Block window unless we are ready to accept data */
02544         if ( ! tls_ready ( tls ) )
02545                 return 0;
02546 
02547         return xfer_window ( &tls->cipherstream );
02548 }
02549 
02550 /**
02551  * Deliver datagram as raw data
02552  *
02553  * @v tls               TLS connection
02554  * @v iobuf             I/O buffer
02555  * @v meta              Data transfer metadata
02556  * @ret rc              Return status code
02557  */
02558 static int tls_plainstream_deliver ( struct tls_connection *tls,
02559                                      struct io_buffer *iobuf,
02560                                      struct xfer_metadata *meta __unused ) {
02561         int rc;
02562         
02563         /* Refuse unless we are ready to accept data */
02564         if ( ! tls_ready ( tls ) ) {
02565                 rc = -ENOTCONN;
02566                 goto done;
02567         }
02568 
02569         if ( ( rc = tls_send_plaintext ( tls, TLS_TYPE_DATA, iobuf->data,
02570                                          iob_len ( iobuf ) ) ) != 0 )
02571                 goto done;
02572 
02573  done:
02574         free_iob ( iobuf );
02575         return rc;
02576 }
02577 
02578 /**
02579  * Report job progress
02580  *
02581  * @v tls               TLS connection
02582  * @v progress          Progress report to fill in
02583  * @ret ongoing_rc      Ongoing job status code (if known)
02584  */
02585 static int tls_progress ( struct tls_connection *tls,
02586                           struct job_progress *progress ) {
02587 
02588         /* Return cipherstream or validator progress as applicable */
02589         if ( is_pending ( &tls->validation ) ) {
02590                 return job_progress ( &tls->validator, progress );
02591         } else {
02592                 return job_progress ( &tls->cipherstream, progress );
02593         }
02594 }
02595 
02596 /** TLS plaintext stream interface operations */
02597 static struct interface_operation tls_plainstream_ops[] = {
02598         INTF_OP ( xfer_deliver, struct tls_connection *,
02599                   tls_plainstream_deliver ),
02600         INTF_OP ( xfer_window, struct tls_connection *,
02601                   tls_plainstream_window ),
02602         INTF_OP ( job_progress, struct tls_connection *, tls_progress ),
02603         INTF_OP ( intf_close, struct tls_connection *, tls_close ),
02604 };
02605 
02606 /** TLS plaintext stream interface descriptor */
02607 static struct interface_descriptor tls_plainstream_desc =
02608         INTF_DESC_PASSTHRU ( struct tls_connection, plainstream,
02609                              tls_plainstream_ops, cipherstream );
02610 
02611 /******************************************************************************
02612  *
02613  * Ciphertext stream operations
02614  *
02615  ******************************************************************************
02616  */
02617 
02618 /**
02619  * Handle received TLS header
02620  *
02621  * @v tls               TLS connection
02622  * @ret rc              Returned status code
02623  */
02624 static int tls_newdata_process_header ( struct tls_connection *tls ) {
02625         size_t data_len = ntohs ( tls->rx_header.length );
02626         size_t remaining = data_len;
02627         size_t frag_len;
02628         struct io_buffer *iobuf;
02629         struct io_buffer *tmp;
02630         int rc;
02631 
02632         /* Allocate data buffers now that we know the length */
02633         assert ( list_empty ( &tls->rx_data ) );
02634         while ( remaining ) {
02635 
02636                 /* Calculate fragment length.  Ensure that no block is
02637                  * smaller than TLS_RX_MIN_BUFSIZE (by increasing the
02638                  * allocation length if necessary).
02639                  */
02640                 frag_len = remaining;
02641                 if ( frag_len > TLS_RX_BUFSIZE )
02642                         frag_len = TLS_RX_BUFSIZE;
02643                 remaining -= frag_len;
02644                 if ( remaining < TLS_RX_MIN_BUFSIZE ) {
02645                         frag_len += remaining;
02646                         remaining = 0;
02647                 }
02648 
02649                 /* Allocate buffer */
02650                 iobuf = alloc_iob_raw ( frag_len, TLS_RX_ALIGN, 0 );
02651                 if ( ! iobuf ) {
02652                         DBGC ( tls, "TLS %p could not allocate %zd of %zd "
02653                                "bytes for receive buffer\n", tls,
02654                                remaining, data_len );
02655                         rc = -ENOMEM_RX_DATA;
02656                         goto err;
02657                 }
02658 
02659                 /* Ensure tailroom is exactly what we asked for.  This
02660                  * will result in unaligned I/O buffers when the
02661                  * fragment length is unaligned, which can happen only
02662                  * before we switch to using a block cipher.
02663                  */
02664                 iob_reserve ( iobuf, ( iob_tailroom ( iobuf ) - frag_len ) );
02665 
02666                 /* Add I/O buffer to list */
02667                 list_add_tail ( &iobuf->list, &tls->rx_data );
02668         }
02669 
02670         /* Move to data state */
02671         tls->rx_state = TLS_RX_DATA;
02672 
02673         return 0;
02674 
02675  err:
02676         list_for_each_entry_safe ( iobuf, tmp, &tls->rx_data, list ) {
02677                 list_del ( &iobuf->list );
02678                 free_iob ( iobuf );
02679         }
02680         return rc;
02681 }
02682 
02683 /**
02684  * Handle received TLS data payload
02685  *
02686  * @v tls               TLS connection
02687  * @ret rc              Returned status code
02688  */
02689 static int tls_newdata_process_data ( struct tls_connection *tls ) {
02690         struct io_buffer *iobuf;
02691         int rc;
02692 
02693         /* Move current buffer to end of list */
02694         iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
02695         list_del ( &iobuf->list );
02696         list_add_tail ( &iobuf->list, &tls->rx_data );
02697 
02698         /* Continue receiving data if any space remains */
02699         iobuf = list_first_entry ( &tls->rx_data, struct io_buffer, list );
02700         if ( iob_tailroom ( iobuf ) )
02701                 return 0;
02702 
02703         /* Process record */
02704         if ( ( rc = tls_new_ciphertext ( tls, &tls->rx_header,
02705                                          &tls->rx_data ) ) != 0 )
02706                 return rc;
02707 
02708         /* Increment RX sequence number */
02709         tls->rx_seq += 1;
02710 
02711         /* Return to header state */
02712         assert ( list_empty ( &tls->rx_data ) );
02713         tls->rx_state = TLS_RX_HEADER;
02714         iob_unput ( &tls->rx_header_iobuf, sizeof ( tls->rx_header ) );
02715 
02716         return 0;
02717 }
02718 
02719 /**
02720  * Check flow control window
02721  *
02722  * @v tls               TLS connection
02723  * @ret len             Length of window
02724  */
02725 static size_t tls_cipherstream_window ( struct tls_connection *tls ) {
02726 
02727         /* Open window until we are ready to accept data */
02728         if ( ! tls_ready ( tls ) )
02729                 return -1UL;
02730 
02731         return xfer_window ( &tls->plainstream );
02732 }
02733 
02734 /**
02735  * Receive new ciphertext
02736  *
02737  * @v tls               TLS connection
02738  * @v iobuf             I/O buffer
02739  * @v meta              Data transfer metadat
02740  * @ret rc              Return status code
02741  */
02742 static int tls_cipherstream_deliver ( struct tls_connection *tls,
02743                                       struct io_buffer *iobuf,
02744                                       struct xfer_metadata *xfer __unused ) {
02745         size_t frag_len;
02746         int ( * process ) ( struct tls_connection *tls );
02747         struct io_buffer *dest;
02748         int rc;
02749 
02750         while ( iob_len ( iobuf ) ) {
02751 
02752                 /* Select buffer according to current state */
02753                 switch ( tls->rx_state ) {
02754                 case TLS_RX_HEADER:
02755                         dest = &tls->rx_header_iobuf;
02756                         process = tls_newdata_process_header;
02757                         break;
02758                 case TLS_RX_DATA:
02759                         dest = list_first_entry ( &tls->rx_data,
02760                                                   struct io_buffer, list );
02761                         assert ( dest != NULL );
02762                         process = tls_newdata_process_data;
02763                         break;
02764                 default:
02765                         assert ( 0 );
02766                         rc = -EINVAL_RX_STATE;
02767                         goto done;
02768                 }
02769 
02770                 /* Copy data portion to buffer */
02771                 frag_len = iob_len ( iobuf );
02772                 if ( frag_len > iob_tailroom ( dest ) )
02773                         frag_len = iob_tailroom ( dest );
02774                 memcpy ( iob_put ( dest, frag_len ), iobuf->data, frag_len );
02775                 iob_pull ( iobuf, frag_len );
02776 
02777                 /* Process data if buffer is now full */
02778                 if ( iob_tailroom ( dest ) == 0 ) {
02779                         if ( ( rc = process ( tls ) ) != 0 ) {
02780                                 tls_close ( tls, rc );
02781                                 goto done;
02782                         }
02783                 }
02784         }
02785         rc = 0;
02786 
02787  done:
02788         free_iob ( iobuf );
02789         return rc;
02790 }
02791 
02792 /** TLS ciphertext stream interface operations */
02793 static struct interface_operation tls_cipherstream_ops[] = {
02794         INTF_OP ( xfer_deliver, struct tls_connection *,
02795                   tls_cipherstream_deliver ),
02796         INTF_OP ( xfer_window, struct tls_connection *,
02797                   tls_cipherstream_window ),
02798         INTF_OP ( xfer_window_changed, struct tls_connection *,
02799                   tls_tx_resume ),
02800         INTF_OP ( intf_close, struct tls_connection *, tls_close ),
02801 };
02802 
02803 /** TLS ciphertext stream interface descriptor */
02804 static struct interface_descriptor tls_cipherstream_desc =
02805         INTF_DESC_PASSTHRU ( struct tls_connection, cipherstream,
02806                              tls_cipherstream_ops, plainstream );
02807 
02808 /******************************************************************************
02809  *
02810  * Certificate validator
02811  *
02812  ******************************************************************************
02813  */
02814 
02815 /**
02816  * Handle certificate validation completion
02817  *
02818  * @v tls               TLS connection
02819  * @v rc                Reason for completion
02820  */
02821 static void tls_validator_done ( struct tls_connection *tls, int rc ) {
02822         struct tls_session *session = tls->session;
02823         struct tls_cipherspec *cipherspec = &tls->tx_cipherspec_pending;
02824         struct pubkey_algorithm *pubkey = cipherspec->suite->pubkey;
02825         struct x509_certificate *cert;
02826 
02827         /* Mark validation as complete */
02828         pending_put ( &tls->validation );
02829 
02830         /* Close validator interface */
02831         intf_restart ( &tls->validator, rc );
02832 
02833         /* Check for validation failure */
02834         if ( rc != 0 ) {
02835                 DBGC ( tls, "TLS %p certificate validation failed: %s\n",
02836                        tls, strerror ( rc ) );
02837                 goto err;
02838         }
02839         DBGC ( tls, "TLS %p certificate validation succeeded\n", tls );
02840 
02841         /* Extract first certificate */
02842         cert = x509_first ( tls->chain );
02843         assert ( cert != NULL );
02844 
02845         /* Verify server name */
02846         if ( ( rc = x509_check_name ( cert, session->name ) ) != 0 ) {
02847                 DBGC ( tls, "TLS %p server certificate does not match %s: %s\n",
02848                        tls, session->name, strerror ( rc ) );
02849                 goto err;
02850         }
02851 
02852         /* Initialise public key algorithm */
02853         if ( ( rc = pubkey_init ( pubkey, cipherspec->pubkey_ctx,
02854                                   cert->subject.public_key.raw.data,
02855                                   cert->subject.public_key.raw.len ) ) != 0 ) {
02856                 DBGC ( tls, "TLS %p cannot initialise public key: %s\n",
02857                        tls, strerror ( rc ) );
02858                 goto err;
02859         }
02860 
02861         /* Schedule Client Key Exchange, Change Cipher, and Finished */
02862         tls->tx_pending |= ( TLS_TX_CLIENT_KEY_EXCHANGE |
02863                              TLS_TX_CHANGE_CIPHER |
02864                              TLS_TX_FINISHED );
02865         if ( tls->cert ) {
02866                 tls->tx_pending |= ( TLS_TX_CERTIFICATE |
02867                                      TLS_TX_CERTIFICATE_VERIFY );
02868         }
02869         tls_tx_resume ( tls );
02870 
02871         return;
02872 
02873  err:
02874         tls_close ( tls, rc );
02875         return;
02876 }
02877 
02878 /** TLS certificate validator interface operations */
02879 static struct interface_operation tls_validator_ops[] = {
02880         INTF_OP ( intf_close, struct tls_connection *, tls_validator_done ),
02881 };
02882 
02883 /** TLS certificate validator interface descriptor */
02884 static struct interface_descriptor tls_validator_desc =
02885         INTF_DESC ( struct tls_connection, validator, tls_validator_ops );
02886 
02887 /******************************************************************************
02888  *
02889  * Controlling process
02890  *
02891  ******************************************************************************
02892  */
02893 
02894 /**
02895  * TLS TX state machine
02896  *
02897  * @v tls               TLS connection
02898  */
02899 static void tls_tx_step ( struct tls_connection *tls ) {
02900         struct tls_session *session = tls->session;
02901         struct tls_connection *conn;
02902         int rc;
02903 
02904         /* Wait for cipherstream to become ready */
02905         if ( ! xfer_window ( &tls->cipherstream ) )
02906                 return;
02907 
02908         /* Send first pending transmission */
02909         if ( tls->tx_pending & TLS_TX_CLIENT_HELLO ) {
02910                 /* Serialise server negotiations within a session, to
02911                  * provide a consistent view of session IDs and
02912                  * session tickets.
02913                  */
02914                 list_for_each_entry ( conn, &session->conn, list ) {
02915                         if ( conn == tls )
02916                                 break;
02917                         if ( is_pending ( &conn->server_negotiation ) )
02918                                 return;
02919                 }
02920                 /* Record or generate session ID and associated master secret */
02921                 if ( session->id_len ) {
02922                         /* Attempt to resume an existing session */
02923                         memcpy ( tls->session_id, session->id,
02924                                  sizeof ( tls->session_id ) );
02925                         tls->session_id_len = session->id_len;
02926                         memcpy ( tls->master_secret, session->master_secret,
02927                                  sizeof ( tls->master_secret ) );
02928                 } else {
02929                         /* No existing session: use a random session ID */
02930                         assert ( sizeof ( tls->session_id ) ==
02931                                  sizeof ( tls->client_random ) );
02932                         memcpy ( tls->session_id, &tls->client_random,
02933                                  sizeof ( tls->session_id ) );
02934                         tls->session_id_len = sizeof ( tls->session_id );
02935                 }
02936                 /* Send Client Hello */
02937                 if ( ( rc = tls_send_client_hello ( tls ) ) != 0 ) {
02938                         DBGC ( tls, "TLS %p could not send Client Hello: %s\n",
02939                                tls, strerror ( rc ) );
02940                         goto err;
02941                 }
02942                 tls->tx_pending &= ~TLS_TX_CLIENT_HELLO;
02943         } else if ( tls->tx_pending & TLS_TX_CERTIFICATE ) {
02944                 /* Send Certificate */
02945                 if ( ( rc = tls_send_certificate ( tls ) ) != 0 ) {
02946                         DBGC ( tls, "TLS %p cold not send Certificate: %s\n",
02947                                tls, strerror ( rc ) );
02948                         goto err;
02949                 }
02950                 tls->tx_pending &= ~TLS_TX_CERTIFICATE;
02951         } else if ( tls->tx_pending & TLS_TX_CLIENT_KEY_EXCHANGE ) {
02952                 /* Send Client Key Exchange */
02953                 if ( ( rc = tls_send_client_key_exchange ( tls ) ) != 0 ) {
02954                         DBGC ( tls, "TLS %p could not send Client Key "
02955                                "Exchange: %s\n", tls, strerror ( rc ) );
02956                         goto err;
02957                 }
02958                 tls->tx_pending &= ~TLS_TX_CLIENT_KEY_EXCHANGE;
02959         } else if ( tls->tx_pending & TLS_TX_CERTIFICATE_VERIFY ) {
02960                 /* Send Certificate Verify */
02961                 if ( ( rc = tls_send_certificate_verify ( tls ) ) != 0 ) {
02962                         DBGC ( tls, "TLS %p could not send Certificate "
02963                                "Verify: %s\n", tls, strerror ( rc ) );
02964                         goto err;
02965                 }
02966                 tls->tx_pending &= ~TLS_TX_CERTIFICATE_VERIFY;
02967         } else if ( tls->tx_pending & TLS_TX_CHANGE_CIPHER ) {
02968                 /* Send Change Cipher, and then change the cipher in use */
02969                 if ( ( rc = tls_send_change_cipher ( tls ) ) != 0 ) {
02970                         DBGC ( tls, "TLS %p could not send Change Cipher: "
02971                                "%s\n", tls, strerror ( rc ) );
02972                         goto err;
02973                 }
02974                 if ( ( rc = tls_change_cipher ( tls,
02975                                                 &tls->tx_cipherspec_pending,
02976                                                 &tls->tx_cipherspec )) != 0 ){
02977                         DBGC ( tls, "TLS %p could not activate TX cipher: "
02978                                "%s\n", tls, strerror ( rc ) );
02979                         goto err;
02980                 }
02981                 tls->tx_seq = 0;
02982                 tls->tx_pending &= ~TLS_TX_CHANGE_CIPHER;
02983         } else if ( tls->tx_pending & TLS_TX_FINISHED ) {
02984                 /* Send Finished */
02985                 if ( ( rc = tls_send_finished ( tls ) ) != 0 ) {
02986                         DBGC ( tls, "TLS %p could not send Finished: %s\n",
02987                                tls, strerror ( rc ) );
02988                         goto err;
02989                 }
02990                 tls->tx_pending &= ~TLS_TX_FINISHED;
02991         }
02992 
02993         /* Reschedule process if pending transmissions remain,
02994          * otherwise send notification of a window change.
02995          */
02996         if ( tls->tx_pending ) {
02997                 tls_tx_resume ( tls );
02998         } else {
02999                 xfer_window_changed ( &tls->plainstream );
03000         }
03001 
03002         return;
03003 
03004  err:
03005         tls_close ( tls, rc );
03006 }
03007 
03008 /** TLS TX process descriptor */
03009 static struct process_descriptor tls_process_desc =
03010         PROC_DESC_ONCE ( struct tls_connection, process, tls_tx_step );
03011 
03012 /******************************************************************************
03013  *
03014  * Session management
03015  *
03016  ******************************************************************************
03017  */
03018 
03019 /**
03020  * Find or create session for TLS connection
03021  *
03022  * @v tls               TLS connection
03023  * @v name              Server name
03024  * @ret rc              Return status code
03025  */
03026 static int tls_session ( struct tls_connection *tls, const char *name ) {
03027         struct tls_session *session;
03028         char *name_copy;
03029         int rc;
03030 
03031         /* Find existing matching session, if any */
03032         list_for_each_entry ( session, &tls_sessions, list ) {
03033                 if ( strcmp ( name, session->name ) == 0 ) {
03034                         ref_get ( &session->refcnt );
03035                         tls->session = session;
03036                         DBGC ( tls, "TLS %p joining session %s\n", tls, name );
03037                         return 0;
03038                 }
03039         }
03040 
03041         /* Create new session */
03042         session = zalloc ( sizeof ( *session ) + strlen ( name )
03043                            + 1 /* NUL */ );
03044         if ( ! session ) {
03045                 rc = -ENOMEM;
03046                 goto err_alloc;
03047         }
03048         ref_init ( &session->refcnt, free_tls_session );
03049         name_copy = ( ( ( void * ) session ) + sizeof ( *session ) );
03050         strcpy ( name_copy, name );
03051         session->name = name_copy;
03052         INIT_LIST_HEAD ( &session->conn );
03053         list_add ( &session->list, &tls_sessions );
03054 
03055         /* Record session */
03056         tls->session = session;
03057 
03058         DBGC ( tls, "TLS %p created session %s\n", tls, name );
03059         return 0;
03060 
03061         ref_put ( &session->refcnt );
03062  err_alloc:
03063         return rc;
03064 }
03065 
03066 /******************************************************************************
03067  *
03068  * Instantiator
03069  *
03070  ******************************************************************************
03071  */
03072 
03073 int add_tls ( struct interface *xfer, const char *name,
03074               struct interface **next ) {
03075         struct tls_connection *tls;
03076         int rc;
03077 
03078         /* Allocate and initialise TLS structure */
03079         tls = malloc ( sizeof ( *tls ) );
03080         if ( ! tls ) {
03081                 rc = -ENOMEM;
03082                 goto err_alloc;
03083         }
03084         memset ( tls, 0, sizeof ( *tls ) );
03085         ref_init ( &tls->refcnt, free_tls );
03086         INIT_LIST_HEAD ( &tls->list );
03087         intf_init ( &tls->plainstream, &tls_plainstream_desc, &tls->refcnt );
03088         intf_init ( &tls->cipherstream, &tls_cipherstream_desc, &tls->refcnt );
03089         intf_init ( &tls->validator, &tls_validator_desc, &tls->refcnt );
03090         process_init_stopped ( &tls->process, &tls_process_desc,
03091                                &tls->refcnt );
03092         tls->version = TLS_VERSION_TLS_1_2;
03093         tls_clear_cipher ( tls, &tls->tx_cipherspec );
03094         tls_clear_cipher ( tls, &tls->tx_cipherspec_pending );
03095         tls_clear_cipher ( tls, &tls->rx_cipherspec );
03096         tls_clear_cipher ( tls, &tls->rx_cipherspec_pending );
03097         tls->client_random.gmt_unix_time = time ( NULL );
03098         iob_populate ( &tls->rx_header_iobuf, &tls->rx_header, 0,
03099                        sizeof ( tls->rx_header ) );
03100         INIT_LIST_HEAD ( &tls->rx_data );
03101         if ( ( rc = tls_generate_random ( tls, &tls->client_random.random,
03102                           ( sizeof ( tls->client_random.random ) ) ) ) != 0 ) {
03103                 goto err_random;
03104         }
03105         tls->pre_master_secret.version = htons ( tls->version );
03106         if ( ( rc = tls_generate_random ( tls, &tls->pre_master_secret.random,
03107                       ( sizeof ( tls->pre_master_secret.random ) ) ) ) != 0 ) {
03108                 goto err_random;
03109         }
03110         if ( ( rc = tls_session ( tls, name ) ) != 0 )
03111                 goto err_session;
03112         list_add_tail ( &tls->list, &tls->session->conn );
03113 
03114         /* Start negotiation */
03115         tls_restart ( tls );
03116 
03117         /* Attach to parent interface, mortalise self, and return */
03118         intf_plug_plug ( &tls->plainstream, xfer );
03119         *next = &tls->cipherstream;
03120         ref_put ( &tls->refcnt );
03121         return 0;
03122 
03123  err_session:
03124  err_random:
03125         ref_put ( &tls->refcnt );
03126  err_alloc:
03127         return rc;
03128 }
03129 
03130 /* Drag in objects via add_tls() */
03131 REQUIRING_SYMBOL ( add_tls );
03132 
03133 /* Drag in crypto configuration */
03134 REQUIRE_OBJECT ( config_crypto );