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