RFC 2246

The TLS Protocol Version 1.0

๐Ÿ“… published January 1999, from ietf

The TLS Protocol Version 1.0 ๐ŸŽ€

(part 1 of 16)

Okay bestie, this is RFC 2246, and it's titled "The TLS Protocol Version 1.0" ๐Ÿ’–. It was written by T. Dierks and C. Allen, both from Certicom ๐Ÿ‘‘. The category is Standards Track, and it's dated January 1999. The header doesn't list anything it obsoletes or updates, so there's no backstory there ๐Ÿงš.

Status of this Memo โœจ

This document specifies an Internet standards track protocol for the whole Internet community, and it literally begs for discussion and suggestions for improvements ๐Ÿฅบ. For the current standardization state and status of this protocol, check the current edition of the "Internet Official Protocol Standards" (STD 1). Distribution of this memo is unlimited ๐Ÿ’Œ.

Copyright (C) The Internet Society (1999). All Rights Reserved.

Abstract ๐Ÿฆ‹

This document specifies Version 1.0 of the Transport Layer Security (TLS) protocol ๐Ÿ’œ. TLS gives communications privacy over the Internet. It lets client/server apps talk in a way that's designed to prevent eavesdropping, tampering, or message forgery ๐Ÿ”’.

Table of Contents ๐Ÿ“–

   1.       Introduction                                              3
   2.       Goals                                                     4
   3.       Goals of this document                                    5
   4.       Presentation language                                     5
   4.1.     Basic block size                                          6
   4.2.     Miscellaneous                                             6
   4.3.     Vectors                                                   6
   4.4.     Numbers                                                   7
   4.5.     Enumerateds                                               7
   4.6.     Constructed types                                         8
   4.6.1.   Variants                                                  9
   4.7.     Cryptographic attributes                                 10
   4.8.     Constants                                                11
   5.       HMAC and the pseudorandom function                       11
   6.       The TLS Record Protocol                                  13
   6.1.     Connection states                                        14
   6.2.     Record layer                                             16
   6.2.1.   Fragmentation                                            16
   6.2.2.   Record compression and decompression                     17
   6.2.3.   Record payload protection                                18
   6.2.3.1. Null or standard stream cipher                           19
   6.2.3.2. CBC block cipher                                         19
   6.3.     Key calculation                                          21
   6.3.1.   Export key generation example                            22
   7.       The TLS Handshake Protocol                               23
   7.1.     Change cipher spec protocol                              24
   7.2.     Alert protocol                                           24
   7.2.1.   Closure alerts                                           25
   7.2.2.   Error alerts                                             26
   7.3.     Handshake Protocol overview                              29
   7.4.     Handshake protocol                                       32
   7.4.1.   Hello messages                                           33
   7.4.1.1. Hello request                                            33
   7.4.1.2. Client hello                                             34
   7.4.1.3. Server hello                                             36
   7.4.2.   Server certificate                                       37
   7.4.3.   Server key exchange message                              39
   7.4.4.   Certificate request                                      41
   7.4.5.   Server hello done                                        42
   7.4.6.   Client certificate                                       43
   7.4.7.   Client key exchange message                              43
   7.4.7.1. RSA encrypted premaster secret message                   44
   7.4.7.2. Client Diffie-Hellman public value                       45
   7.4.8.   Certificate verify                                       45
   7.4.9.   Finished                                                 46
   8.       Cryptographic computations                               47
   8.1.     Computing the master secret                              47
   8.1.1.   RSA                                                      48
   8.1.2.   Diffie-Hellman                                           48
   9.       Mandatory Cipher Suites                                  48
   10.      Application data protocol                                48
   A.       Protocol constant values                                 49
   A.1.     Record layer                                             49
   A.2.     Change cipher specs message                              50
   A.3.     Alert messages                                           50
   A.4.     Handshake protocol                                       51
   A.4.1.   Hello messages                                           51
   A.4.2.   Server authentication and key exchange messages          52
   A.4.3.   Client authentication and key exchange messages          53
   A.4.4.   Handshake finalization message                           54
   A.5.     The CipherSuite                                          54
   A.6.     The Security Parameters                                  56
   B.       Glossary                                                 57
   C.       CipherSuite definitions                                  61
   D.       Implementation Notes                                     64
   D.1.     Temporary RSA keys                                       64
   D.2.     Random Number Generation and Seeding                     64
   D.3.     Certificates and authentication                          65
   D.4.     CipherSuites                                             65
   E.       Backward Compatibility With SSL                          66
   E.1.     Version 2 client hello                                   67
   E.2.     Avoiding man-in-the-middle version rollback              68
   F.       Security analysis                                        69
   F.1.     Handshake protocol                                       69
   F.1.1.   Authentication and key exchange                          69
   F.1.1.1. Anonymous key exchange                                   69
   F.1.1.2. RSA key exchange and authentication                      70
   F.1.1.3. Diffie-Hellman key exchange with authentication          71
   F.1.2.   Version rollback attacks                                 71
   F.1.3.   Detecting attacks against the handshake protocol         72
   F.1.4.   Resuming sessions                                        72
   F.1.5.   MD5 and SHA                                              72
   F.2.     Protecting application data                              72
   F.3.     Final notes                                              73
   G.       Patent Statement                                         74
            Security Considerations                                  75
            References                                               75
            Credits                                                  77
            Comments                                                 78
            Full Copyright Statement                                 80

1. Introduction โœจ

Okay so the big goal of TLS is to give two communicating apps privacy and data integrity ๐Ÿ”. It's built in two layers. At the bottom, sitting on top of some reliable transport protocol (like TCP[TCP]) ๐Ÿงฑ, is the TLS Record Protocol ๐Ÿ’…. The Record Protocol gives the connection two basic properties:

  • The connection is private. ๐Ÿคซ Symmetric cryptography handles the data encryption (like DES [DES], RC4 [RC4], etc.). The keys for that encryption are generated uniquely for each connection, and they're based on a secret negotiated by another protocol (like the TLS Handshake Protocol). The Record Protocol can also be used without encryption.
  • The connection is reliable. ๐Ÿ›ก๏ธ Message transport includes an integrity check using a keyed MAC. Secure hash functions (e.g., SHA, MD5, etc.) do the MAC computations. The Record Protocol can run without a MAC, but it's usually only used that way while another protocol is using it as a transport to negotiate security parameters.

The TLS Record Protocol is used to wrap up various higher-level protocols ๐ŸŽ. One of those, the TLS Handshake Protocol, lets the server and client authenticate each other and agree on an encryption algorithm and cryptographic keys. All of that happens before the application protocol sends or receives its very first byte of data ๐Ÿซถ. The TLS Handshake Protocol gives the connection three basic properties:

  • The peer's identity can be authenticated using asymmetric, or public key, cryptography (e.g., RSA [RSA], DSS [DSS], etc.). This authentication can be made optional, but it's generally required for at least one of the peers.
  • The negotiation of a shared secret is secure: the negotiated secret is unavailable to eavesdroppers, and for any authenticated connection the secret cannot be obtained, even by an attacker who can place themselves in the middle of the connection ๐Ÿ˜ฑ.
  • The negotiation is reliable: no attacker can modify the negotiation communication without being detected by the parties to the communication ๐Ÿšจ.

One advantage of TLS is that it's application protocol independent ๐Ÿฆ‹. Higher-level protocols can layer on top of the TLS Protocol transparently. The TLS standard, however, doesn't say how protocols add security with TLS. Deciding how to start TLS handshaking and how to interpret the authentication certificates exchanged is left up to the judgment of the designers and implementors of protocols that run on top of TLS ๐Ÿง .

2. Goals ๐ŸŒธ

The goals of the TLS Protocol, in order of their priority, are:

  1. Cryptographic security ๐Ÿ”: TLS should be used to establish a secure connection between two parties.
  2. Interoperability ๐Ÿค: Independent programmers should be able to develop applications using TLS that can successfully exchange cryptographic parameters without knowing one another's code. Iconic, no notes.
  3. Extensibility ๐Ÿงฉ: TLS seeks to provide a framework into which new public key and bulk encryption methods can be incorporated as necessary. This also accomplishes two sub-goals: preventing the need to create a whole new protocol (which would risk introducing new weaknesses), and avoiding the need to implement an entire new security library.
  4. Relative efficiency โšก: Cryptographic operations tend to be super CPU intensive, especially public key operations. For this reason, the TLS protocol has an optional session caching scheme, so fewer connections need to be established from scratch. Care has also been taken to reduce network activity ๐Ÿ’œ.

3. Goals of this document โœจ

okay bestie, so this doc and TLS itself are built on the SSL 3.0 Protocol Specification from Netscape ๐Ÿซถ the differences from SSL 3.0 are not dramatic, but they're big enough that TLS 1.0 and SSL 3.0 do NOT interoperate ๐Ÿ’€ (though TLS 1.0 does have a way to back down to SSL 3.0, which is kinda iconic of it). this doc is mainly for people who are going to implement the protocol and for people doing cryptographic analysis of it ๐Ÿ”ฅ so it's written with those two groups in mind, and that's why a lot of the algorithm-dependent data structures and rules live in the body of the text instead of an appendix. easier access, no cap ๐Ÿ’…

this document is not trying to give any details of service definition or interface definition ๐Ÿ™ˆ it does cover select areas of policy, though, when they're needed to keep things solidly secure ๐Ÿ”

4. Presentation language ๐ŸŽ€

this doc is all about how data gets formatted in an external representation ๐Ÿฆ‹ we're using a very basic, somewhat casually defined presentation syntax. it pulls from a few sources. it kinda looks like the programming language "C" and it's also got vibes from XDR [XDR] in both its syntax and intent, but it would be risky to draw too many parallels, ngl ๐Ÿ™ˆ the whole point of this presentation language is to document TLS only, not to be a general tool for everything else.

4.1. Basic block size ๐Ÿง

every data item is explicitly specified ๐Ÿ’– the basic data block size is one byte (i.e. 8 bits). multi-byte data items are concatenations of bytes, from left to right, from top to bottom ๐ŸŒˆ a multi-byte item (a numeric in the example) gets formed from the bytestream, using C notation, like this:

    value = (byte[0] << 8*(n-1)) | (byte[1] << 8*(n-2)) |
            ... | byte[n-1];

this byte ordering for multi-byte values is the commonplace network byte order, aka big endian format ๐Ÿซถ

4.2. Miscellaneous ๐Ÿ“

comments begin with /* and end with */ ๐Ÿ’œ

optional components are denoted by enclosing them in [[ ]] double brackets โœจ

single byte entities that contain uninterpreted data are of type opaque ๐Ÿฆ‹

4.3. Vectors ๐ŸŒธ

a vector (a single dimensioned array) is a stream of homogeneous data elements ๐Ÿ’… the size of the vector can be specified at documentation time, or it can be left unspecified until runtime. either way, the length declares the number of bytes, not the number of elements, in the vector ๐Ÿ‘‘ the syntax for a new type T' that's a fixed length vector of type T is:

    T T'[n];

T' takes up n bytes in the data stream, where n is a multiple of the size of T ๐Ÿ’– the length of the vector is not included in the encoded stream.

here's the example: Datum is defined as three consecutive bytes that the protocol doesn't interpret, and Data is three consecutive Datum, which eats up a total of nine bytes ๐Ÿ˜ญ

    opaque Datum[3];      /* three uninterpreted bytes */
    Datum Data[9];        /* 3 consecutive 3 byte vectors */

variable length vectors are defined by specifying a subrange of legal lengths, inclusively, using the notation <floor..ceiling> ๐ŸŽ€ when encoded, the actual length comes before the vector's contents in the byte stream. the length is written as a number that uses as many bytes as needed to hold the vector's specified maximum (ceiling) length ๐Ÿงš a variable length vector with an actual length field of zero is called an empty vector.

    T T'<floor..ceiling>;

in this example, mandatory is a vector that has to contain between 300 and 400 bytes of type opaque ๐Ÿ”ฅ it can never be empty. the actual length field uses two bytes, a uint16, which is enough to represent the value 400 (see Section 4.4). longer, on the other hand, can represent up to 800 bytes of data, or 400 uint16 elements, and it may be empty ๐ŸŒˆ its encoding includes a two byte actual length field prepended to the vector. the length of an encoded vector must be an even multiple of the length of a single element (for example, a 17 byte vector of uint16 would be illegal) ๐Ÿ™ˆ

    opaque mandatory<300..400>;
          /* length field is 2 bytes, cannot be empty */
    uint16 longer<0..800>;
          /* zero to 400 16-bit unsigned integers */

4.4. Numbers ๐Ÿ”ข

the basic numeric data type is an unsigned byte (uint8) โœจ all larger numeric data types are formed from fixed length series of bytes concatenated as described in Section 4.1, and they're also unsigned. the following numeric types are predefined:

    uint8 uint16[2];
    uint8 uint24[3];
    uint8 uint32[4];
    uint8 uint64[8];

all values, here and elsewhere in the specification, are stored in "network" or "big-endian" order ๐Ÿซถ so the uint32 represented by the hex bytes 01 02 03 04 is equivalent to the decimal value 16909060 ๐Ÿงฎ bestie, that's the math being slay.

4.5. Enumerateds ๐Ÿฆ‹

there's an additional sparse data type called enum ๐Ÿ’– a field of type enum can only assume the values declared in its definition. each definition is a different type, and only enumerateds of the same type may be assigned or compared ๐Ÿ’… every element of an enumerated must be assigned a value, as shown in the next example. since the elements of the enumerated aren't ordered, they can be assigned any unique value, in any order ๐ŸŒธ

    enum { e1(v1), e2(v2), ... , en(vn) [[, (n)]] } Te;

enumerateds take up as much space in the byte stream as their maximal defined ordinal value would ๐Ÿ”ฅ the following definition would cause one byte to be used to carry fields of type Color.

    enum { red(3), blue(5), white(7) } Color;

you can optionally specify a value without its associated tag to force the width definition without defining a superfluous element ๐Ÿงš in the following example, Taste will consume two bytes in the data stream, but it can only assume the values 1, 2 or 4 ๐Ÿ’œ

    enum { sweet(1), sour(2), bitter(4), (32000) } Taste;

the names of the elements of an enumeration are scoped within the defined type ๐ŸŽ€ in the first example, a fully qualified reference to the second element of the enumeration would be Color.blue. that qualification isn't required if the target of the assignment is well specified โœจ

    Color color = Color.blue;     /* overspecified, legal */
    Color color = blue;           /* correct, type implicit */

for enumerateds that are never converted to external representation, the numerical information can be left out ๐Ÿ™ˆ

    enum { low, medium, high } Amount;

4.6. Constructed types ๐Ÿงฉ

structure types can be built from primitive types for convenience ๐ŸŒˆ each specification declares a new, unique type, and the syntax for the definition is pretty much like C ๐Ÿ’…

    struct {
      T1 f1;
      T2 f2;
      ...
      Tn fn;
    } [[T]];

the fields inside a structure can be qualified using the type's name, kinda like with enumerateds ๐Ÿ’– for example, T.f2 refers to the second field of the previous declaration. structure definitions can also be embedded ๐Ÿซถ

4.6.1. Variants ๐Ÿฆ‹

defined structures can have variants, based on some knowledge that's available within the environment ๐Ÿ”ฎ the selector must be an enumerated type that defines the possible variants the structure defines. there must be a case arm for every element of the enumeration declared in the select. the body of the variant structure can be given a label for reference ๐ŸŽ€ the mechanism by which the variant is selected at runtime is not prescribed by the presentation language.

    struct {
        T1 f1;
        T2 f2;
        ....
        Tn fn;
        select (E) {
            case e1: Te1;
            case e2: Te2;
            ....
            case en: Ten;
        } [[fv]];
    } [[Tv]];

for example:

    enum { apple, orange } VariantTag;
    struct {
        uint16 number;
        opaque string<0..10>; /* variable length */
    } V1;
    struct {
        uint32 number;
        opaque string[10];    /* fixed length */
    } V2;
    struct {
        select (VariantTag) { /* value of selector is implicit */
            case apple: V1;   /* VariantBody, tag = apple */
            case orange: V2;  /* VariantBody, tag = orange */
        } variant_body;       /* optional label on variant */
    } VariantRecord;

variant structures can be qualified (narrowed) by specifying a value for the selector before the type ๐Ÿ“ for example:

    orange VariantRecord

is a narrowed type of a VariantRecord containing a variant_body of type V2 ๐Ÿ’…

4.7. Cryptographic attributes ๐Ÿ”

the four cryptographic operations (digital signing, stream cipher encryption, block cipher encryption, and public key encryption) are designated digitally-signed, stream-ciphered, block-ciphered, and public-key-encrypted, respectively โœจ a field's cryptographic processing is specified by putting an appropriate keyword designation before the field's type specification. cryptographic keys are implied by the current session state (see Section 6.1) ๐ŸŒธ

in digital signing, one-way hash functions are used as input for a signing algorithm ๐Ÿซถ a digitally-signed element is encoded as an opaque vector <0..2^16-1>, where the length is specified by the signing algorithm and key ๐Ÿ’–

in RSA signing, a 36-byte structure of two hashes (one SHA and one MD5) is signed (encrypted with the private key) ๐Ÿ”ฅ it's encoded with PKCS #1 block type 0 or type 1 as described in [PKCS1].

in DSS, the 20 bytes of the SHA hash are run directly through the Digital Signing Algorithm with no additional hashing ๐Ÿงฎ this produces two values, r and s. the DSS signature is an opaque vector, as above, and its contents are the DER encoding of:

    Dss-Sig-Value  ::=  SEQUENCE  {
         r       INTEGER,
         s       INTEGER
    }

in stream cipher encryption, the plaintext is exclusive-ORed with an identical amount of output generated from a cryptographically-secure keyed pseudorandom number generator ๐ŸŒˆ

in block cipher encryption, every block of plaintext encrypts to a block of ciphertext ๐ŸŽ€ all block cipher encryption is done in CBC (Cipher Block Chaining) mode, and all items which are block-ciphered will be an exact multiple of the cipher block length ๐Ÿ’œ

in public key encryption, a public key algorithm is used to encrypt data in such a way that it can only be decrypted with the matching private key ๐Ÿฆ‹ a public-key-encrypted element is encoded as an opaque vector <0..2^16-1>, where the length is specified by the signing algorithm and key ๐Ÿ™ˆ

an RSA encrypted value is encoded with PKCS #1 block type 2 as described in [PKCS1] ๐Ÿ”

in the following example:

    stream-ciphered struct {
        uint8 field1;
        uint8 field2;
        digitally-signed opaque hash[20];
    } UserType;

the contents of hash are used as input for the signing algorithm, and then the entire structure is encrypted with a stream cipher ๐Ÿ˜ญ the length of this structure, in bytes, would be equal to 2 bytes for field1 and field2, plus two bytes for the length of the signature, plus the length of the output of the signing algorithm ๐Ÿง this is known because the algorithm and key used for the signing are known before encoding or decoding this structure ๐Ÿ‘‘

4.8. Constants โœจ

okay so typed constants are literally just a way to name a value in the spec, bestie ๐Ÿ’… you declare a symbol with the type you want and assign it a value. BUT (and this is a big one) under-specified types like opaque, variable-length vectors, and structs that contain opaque stuff CANNOT be assigned values. ๐Ÿ™ˆ And no fields of a multi-element struct or vector may be elided, so you have to spell out every single one ๐Ÿ’€

here's the example:

struct {
    uint8 f1;
    uint8 f2;
} Example1;

Example1 ex1 = {1, 4};  /* assigns f1 = 1, f2 = 4 */

5. HMAC and the pseudorandom function ๐Ÿฆ‹

okay this is giving crypto main character energy ๐Ÿ”ฅ a bunch of stuff in the TLS record and handshake layers needs a keyed MAC, which is basically a secure digest of some data that's protected by a secret. Forging the MAC is infeasible without knowing the MAC secret, so it's locked tight ๐Ÿ”’ the construction is called HMAC, and it's described in [HMAC].

HMAC can work with a bunch of different hash algorithms. TLS uses two of them in the handshake: MD5 and SHA-1, which we write as HMAC_MD5(secret, data) and HMAC_SHA(secret, data). Cipher suites can define extra hash algorithms to protect record data, but MD5 and SHA-1 are hard-coded into the handshake description for this version of the protocol ๐Ÿ’œ

we also need a way to stretch secrets into blocks of data for key generation or validation. That's the pseudo-random function (PRF) ๐Ÿงš it takes a secret, a seed, and an identifying label, and spits out output of any length you want. The cool part is it uses two hash algorithms, so the whole thing should stay secure as long as either one of them is still secure โœจ

first up, the data expansion function P_hash(secret, data) uses one hash function to stretch a secret and seed into however much output you need:

P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
                       HMAC_hash(secret, A(2) + seed) +
                       HMAC_hash(secret, A(3) + seed) + ...

where + means concatenation ๐ŸŽ€

and A() is defined like this:

A(0) = seed
A(i) = HMAC_hash(secret, A(i-1))

P_hash can be repeated as many times as needed to get the amount of data you want. For example, if you're using P_SHA-1 to make 64 bytes, you'd have to run it 4 times (all the way through A(4)), which makes 80 bytes of output. Then you throw away the last 16 bytes of that final run and keep the 64 bytes you actually need ๐Ÿ“

okay here's the glow-up: TLS's PRF splits the secret into two halves. One half generates data with P_MD5, the other half generates data with P_SHA-1, and then the two outputs get XOR'd together ๐Ÿ’–

S1 and S2 are the two halves, and they're the same length. S1 comes from the first half of the secret, and S2 comes from the second half. Their length is the overall secret length divided by two, rounded up. So if the secret has an odd number of bytes, the last byte of S1 is the same as the first byte of S2 ๐Ÿ‘€

L_S = length in bytes of secret;
L_S1 = L_S2 = ceil(L_S / 2);

the secret gets split into two halves (possibly sharing one byte, as I just said), where S1 takes the first L_S1 bytes and S2 takes the last L_S2 bytes ๐Ÿฆ‹

then the PRF is just the two pseudorandom streams mixed together with XOR:

PRF(secret, label, seed) = P_MD5(S1, label + seed) XOR
                           P_SHA-1(S2, label + seed);

the label is an ASCII string. It should go in exactly the form it's given, without a length byte or a trailing null character. For example, the label "slithy toves" gets hashed as these bytes:

73 6C 69 74 68 79 20 74 6F 76 65 73

ngl this is the kind of detail that trips people up ๐Ÿ˜ญ P_MD5 gives 16-byte outputs and P_SHA-1 gives 20-byte outputs, so their internal iterations don't line up. To make an 80-byte output, P_MD5 runs through A(5) while P_SHA-1 only goes through A(4) ๐ŸŒˆ

6. The TLS Record Protocol ๐ŸŽ€

okay the TLS Record Protocol is a layered protocol, so at every layer, messages can have fields for length, description, and content. It takes the messages you want to send, chops the data into manageable blocks, optionally compresses it, slaps a MAC on, encrypts, and then transmits ๐Ÿš€ on the receiving end, the data gets decrypted, verified, decompressed, and put back together before it's handed up to higher-level clients โœจ

four record protocol clients are described in this document: the handshake protocol, the alert protocol, the change cipher spec protocol, and the application data protocol ๐Ÿ’… if you want to extend TLS, you can add more record types. New record types SHOULD allocate type values right after the ContentType values for the four record types above (see Appendix A.2) ๐Ÿ“ and if a TLS implementation gets a record type it doesn't understand, it SHOULD just ignore it. Any protocol designed to run over TLS MUST be carefully designed to handle every possible attack against it ๐Ÿ’€ also, the type and length of a record aren't protected by encryption, so care SHOULD be taken to minimize how much traffic analysis can learn from those values ๐Ÿ™ˆ

6.1. Connection states ๐Ÿ”

okay a TLS connection state is basically the operating environment of the TLS Record Protocol. It specifies a compression algorithm, an encryption algorithm, and a MAC algorithm. The parameters for those algorithms are also known: the MAC secret, plus the bulk encryption keys and IVs for the connection in both the read and write directions. Logically there are always four connection states hanging around: the current read and write states, and the pending read and write states ๐Ÿซถ all records are processed under the current read and write states. The TLS Handshake Protocol can set the security parameters for the pending states, and it can pick either pending state to become current. When that happens, the old current state gets thrown out and replaced, and the pending state is reset to empty ๐Ÿ”„ it's illegal to make a state that hasn't been initialized with security parameters into a current state. And the starting current state always says no encryption, compression, or MAC is used ๐ŸŒธ

the security parameters for a TLS Connection's read and write state get set by providing these values:

  • connection end: whether this entity is the "client" or the "server" in this connection.
  • bulk encryption algorithm: the algorithm used for bulk encryption. This spec covers its key size, how much of that key is secret, whether it's a block or stream cipher, the block size (if that applies), and whether it counts as an "export" cipher ๐ŸŽ€
  • MAC algorithm: the algorithm used for message authentication. This spec covers the size of the hash that the MAC algorithm returns ๐Ÿ’œ
  • compression algorithm: the algorithm used for compressing data. This spec MUST include all the info the algorithm needs to do its compression job ๐Ÿงš
  • master secret: a 48-byte secret shared between the two peers in the connection ๐Ÿ”‘
  • client random: a 32-byte value provided by the client ๐ŸŽฒ
  • server random: a 32-byte value provided by the server ๐ŸŽฒ

these parameters are defined in the presentation language like so:

enum { server, client } ConnectionEnd;

enum { null, rc4, rc2, des, 3des, des40 } BulkCipherAlgorithm;

enum { stream, block } CipherType;

enum { true, false } IsExportable;

enum { null, md5, sha } MACAlgorithm;

enum { null(0), (255) } CompressionMethod;

/* The algorithms specified in CompressionMethod,
   BulkCipherAlgorithm, and MACAlgorithm MAY be added to. */

struct {
    ConnectionEnd          entity;
    BulkCipherAlgorithm    bulk_cipher_algorithm;
    CipherType             cipher_type;
    uint8                  key_size;
    uint8                  key_material_length;
    IsExportable           is_exportable;
    MACAlgorithm           mac_algorithm;
    uint8                  hash_size;
    CompressionMethod      compression_algorithm;
    opaque                 master_secret[48];
    opaque                 client_random[32];
    opaque                 server_random[32];
} SecurityParameters;

the record layer uses those security parameters to generate these six items ๐Ÿช„

client write MAC secret
server write MAC secret
client write key
server write key
client write IV (for block ciphers only)
server write IV (for block ciphers only)

the client write parameters are used by the server when it's receiving and processing records, and vice versa ๐Ÿ” the algorithm for turning the security parameters into these items is described in section 6.3 ๐Ÿ“–

once the security parameters are set and the keys are generated, you can instantiate the connection states by making them the current states. These current states MUST be updated for each record processed ๐Ÿ“ each connection state includes these elements:

  • compression state: the current state of the compression algorithm ๐Ÿ—œ๏ธ
  • cipher state: the current state of the encryption algorithm. This is the scheduled key for that connection. For block ciphers in CBC mode (the only mode specified for TLS), it starts out holding the IV for that connection state and then gets updated to hold the ciphertext of the last block encrypted or decrypted as records get processed. For stream ciphers, it holds whatever state info the stream needs to keep encrypting or decrypting ๐Ÿ”
  • MAC secret: the MAC secret for this connection, as generated above ๐Ÿคซ
  • sequence number: each connection state has a sequence number, and the read and write states keep their own separate ones. The sequence number MUST be set to zero whenever a connection state becomes the active state. Sequence numbers are of type uint64 and may not exceed 2^64-1. The number goes up by one after each record: specifically, the first record transmitted under a particular connection state SHOULD use sequence number 0 ๐Ÿ”ข

6.2. Record layer ๐Ÿ“ฆ

okay so the TLS Record Layer takes uninterpreted data from higher layers, in non-empty blocks of any size you want ๐Ÿ’…

6.2.1. Fragmentation โœจ

okay so the record layer chops up info blocks into TLSPlaintext records, and each chunk carries data of 2^14 bytes or less ๐Ÿ“ฆ. client message boundaries are NOT preserved here, bestie ๐Ÿ’€. multiple client messages with the same ContentType might get squished into one TLSPlaintext record, or one message might get split across a bunch of records. it's giving chaos, but it's organized chaos ๐Ÿ’…

   struct {
       uint8 major, minor;
   } ProtocolVersion;
   enum {
       change_cipher_spec(20), alert(21), handshake(22),
       application_data(23), (255)
   } ContentType;

   struct {
       ContentType type;
       ProtocolVersion version;
       uint16 length;
       opaque fragment[TLSPlaintext.length];
   } TLSPlaintext;
  • type: the higher level protocol that's used to process the enclosed fragment ๐ŸŽ€
  • version: the protocol version being used. this doc describes TLS Version 1.0, which uses the version { 3, 1 } ๐Ÿฆ‹. the value 3.1 is kinda historical, because TLS 1.0 is a minor tweak of the SSL 3.0 protocol, which has the version value 3.0 (see Appendix A.1) ๐ŸŒธ
  • length: the length in bytes of the following TLSPlaintext.fragment. it should not exceed 2^14 โœจ
  • fragment: the application data ๐Ÿซถ. it's transparent, so it's treated as an independent block that the higher level protocol named in the type field deals with
Note: data of different TLS Record layer content types can be interleaved ๐Ÿ”€. application data is generally lower priority for transmission than the other content types, so it's the one that waits its turn ๐Ÿฅน

6.2.2. Record compression and decompression ๐Ÿ—œ๏ธ

all records get compressed using the compression algorithm from the current session state. there's always an active compression algorithm, but at the start it's set to CompressionMethod.null ๐Ÿ™ˆ. the compression algorithm turns a TLSPlaintext structure into a TLSCompressed structure. compression functions get initialized with default state info whenever a connection state becomes active โญ

compression must be lossless, and it may not increase the content length by more than 1024 bytes ๐Ÿ’–. if the decompression function runs into a TLSCompressed.fragment that would decompress to more than 2^14 bytes, it should report a fatal decompression failure error ๐Ÿ˜ญ

   struct {
       ContentType type;       /* same as TLSPlaintext.type */
       ProtocolVersion version;/* same as TLSPlaintext.version */
       uint16 length;
       opaque fragment[TLSCompressed.length];
   } TLSCompressed;
  • length: the length in bytes of the following TLSCompressed.fragment. it should not exceed 2^14 + 1024 ๐Ÿ“
  • fragment: the compressed form of TLSPlaintext.fragment ๐Ÿงš
Note: a CompressionMethod.null operation is an identity operation, so no fields get altered ๐Ÿค
Implementation note: decompression functions are responsible for making sure that messages can't cause internal buffer overflows. this one's a big deal, bestie ๐Ÿšจ

6.2.3. Record payload protection ๐Ÿ”

the encryption and MAC functions turn a TLSCompressed structure into a TLSCiphertext, and the decryption functions reverse the whole process ๐Ÿ”„. the MAC of the record also includes a sequence number, so missing, extra or repeated messages can be detected ๐Ÿ•ต๏ธโ€โ™€๏ธ

   struct {
       ContentType type;
       ProtocolVersion version;
       uint16 length;
       select (CipherSpec.cipher_type) {
           case stream: GenericStreamCipher;
           case block: GenericBlockCipher;
       } fragment;
   } TLSCiphertext;
  • type: identical to TLSCompressed.type ๐ŸŽ€
  • version: identical to TLSCompressed.version ๐ŸŽ€
  • length: the length in bytes of the following TLSCiphertext.fragment. it may not exceed 2^14 + 2048 ๐Ÿ’œ
  • fragment: the encrypted form of TLSCompressed.fragment, with the MAC ๐Ÿ”’

6.2.3.1. Null or standard stream cipher ๐ŸŒŠ

stream ciphers (including BulkCipherAlgorithm.null, see Appendix A.6) convert TLSCompressed.fragment structures to and from stream TLSCiphertext.fragment structures ๐ŸŒˆ

   stream-ciphered struct {
       opaque content[TLSCompressed.length];
       opaque MAC[CipherSpec.hash_size];
   } GenericStreamCipher;

the MAC is generated as:

       HMAC_hash(MAC_write_secret, seq_num + TLSCompressed.type +
                     TLSCompressed.version + TLSCompressed.length +
                     TLSCompressed.fragment));

where "+" denotes concatenation ๐Ÿงฉ

  • seq_num: the sequence number for this record ๐Ÿ”ข
  • hash: the hashing algorithm specified by SecurityParameters.mac_algorithm ๐Ÿช„

the MAC is computed before encryption. the stream cipher encrypts the entire block, MAC included ๐Ÿ™Œ. for stream ciphers that don't use a synchronization vector (like RC4), the stream cipher state from the end of one record just carries over to the next packet ๐Ÿƒโ€โ™€๏ธ. if the CipherSuite is TLS_NULL_WITH_NULL_NULL, encryption is the identity operation, meaning the data isn't encrypted and the MAC size is zero, so no MAC is used ๐Ÿซฅ. TLSCiphertext.length is TLSCompressed.length plus CipherSpec.hash_size โœจ

6.2.3.2. CBC block cipher ๐Ÿง

for block ciphers (like RC2 or DES), the encryption and MAC functions convert TLSCompressed.fragment structures to and from block TLSCiphertext.fragment structures ๐Ÿฐ

   block-ciphered struct {
       opaque content[TLSCompressed.length];
       opaque MAC[CipherSpec.hash_size];
       uint8 padding[GenericBlockCipher.padding_length];
       uint8 padding_length;
   } GenericBlockCipher;

the MAC is generated as described in Section 6.2.3.1 ๐Ÿ”

  • padding: padding added to force the length of the plaintext to be a whole multiple of the block cipher's block length ๐Ÿงฑ. the padding can be any length up to 255 bytes, as long as TLSCiphertext.length ends up being a whole multiple of the block length. longer-than-necessary padding might be wanted to frustrate attacks that analyze the lengths of exchanged messages ๐Ÿ•ต๏ธ. each uint8 in the padding data vector must be filled with the padding length value ๐Ÿซก
  • padding_length: the padding length should be such that the total size of the GenericBlockCipher structure is a multiple of the cipher's block length. legal values range from zero to 255, inclusive ๐Ÿ’…. this length specifies the length of the padding field, not counting the padding_length field itself

the encrypted data length (TLSCiphertext.length) is one more than the sum of TLSCompressed.length, CipherSpec.hash_size, and padding_length ๐Ÿงฎ

Example: say the block length is 8 bytes, the content length (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes. the length before padding is 82 bytes ๐Ÿง . so the padding length modulo 8 must be equal to 6 to make the total length a whole multiple of 8 bytes (the block length) ๐ŸŽฏ. the padding length can be 6, 14, 22, and so on, all the way through 254 ๐ŸŒธ. if the padding length were the minimum necessary, 6, the padding would be 6 bytes, each containing the value 6. so the last 8 octets of the GenericBlockCipher before block encryption would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC ๐Ÿ“

Note: with block ciphers in CBC mode (Cipher Block Chaining), the initialization vector (IV) for the first record is generated with the other keys and secrets when the security parameters are set. the IV for each subsequent record is the last ciphertext block from the previous record ๐Ÿ”—

6.3. Key calculation ๐Ÿ”‘

the Record Protocol needs an algorithm to generate keys, IVs, and MAC secrets from the security parameters that the handshake protocol hands over ๐Ÿค

the master secret gets hashed into a sequence of secure bytes, and those bytes get assigned to the MAC secrets, keys, and non-export IVs that the current connection state needs (see Appendix A.6) ๐Ÿ’Ž. CipherSpecs need a client write MAC secret, a server write MAC secret, a client write key, a server write key, a client write IV, and a server write IV. they're generated from the master secret in that exact order. unused values are empty ๐Ÿซง

when generating keys and MAC secrets, the master secret is used as an entropy source, and the random values provide unencrypted salt material and IVs for exportable ciphers ๐Ÿง‚

to generate the key material, compute:

   key_block = PRF(SecurityParameters.master_secret,
                      "key expansion",
                      SecurityParameters.server_random +
                      SecurityParameters.client_random);

keep going until enough output has been generated. then the key_block gets partitioned like this ๐Ÿงฉ:

   client_write_MAC_secret[SecurityParameters.hash_size]
   server_write_MAC_secret[SecurityParameters.hash_size]
   client_write_key[SecurityParameters.key_material_length]
   server_write_key[SecurityParameters.key_material_length]
   client_write_IV[SecurityParameters.IV_size]
   server_write_IV[SecurityParameters.IV_size]

the client_write_IV and server_write_IV are only generated for non-export block ciphers. for exportable block ciphers, the initialization vectors get generated later, as described below. any extra key_block material gets discarded ๐Ÿ—‘๏ธ

Implementation note: the cipher spec defined in this document that needs the most material is 3DES_EDE_CBC_SHA. it requires 2 x 24 byte keys, 2 x 20 byte MAC secrets, and 2 x 8 byte IVs, for a total of 104 bytes of key material ๐Ÿคฏ

exportable encryption algorithms (the ones where CipherSpec.is_exportable is true) need some extra processing to derive their final write keys ๐Ÿ”“:

   final_client_write_key =
   PRF(SecurityParameters.client_write_key,
                              "client write key",
                              SecurityParameters.client_random +
                              SecurityParameters.server_random);
   final_server_write_key =
   PRF(SecurityParameters.server_write_key,
                              "server write key",
                              SecurityParameters.client_random +
                              SecurityParameters.server_random);

exportable encryption algorithms derive their IVs solely from the random values in the hello messages ๐ŸŽฒ:

   iv_block = PRF("", "IV block", SecurityParameters.client_random +
                  SecurityParameters.server_random);

the iv_block gets partitioned into two initialization vectors, just like the key_block was above:

   client_write_IV[SecurityParameters.IV_size]
   server_write_IV[SecurityParameters.IV_size]

note that the PRF is used without a secret in this case. that just means the secret has a length of zero bytes and contributes nothing to the hashing in the PRF ๐Ÿซถโœจ

6.3.1. Export key generation example โœจ

okay so bestie, TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 needs five random bytes for each of the two encryption keys and 16 bytes for each of the MAC keys, which adds up to 42 bytes of key material ๐ŸŽ€. The PRF output gets stored in the key_block, the key_block gets partitioned, and the write keys get salted because this is an exportable encryption algorithm ๐Ÿ” (it's giving very "we had to be careful" energy).

key_block               = PRF(master_secret,
                              "key expansion",
                              server_random +
                              client_random)[0..41]
client_write_MAC_secret = key_block[0..15]
server_write_MAC_secret = key_block[16..31]
client_write_key        = key_block[32..36]
server_write_key        = key_block[37..41]
final_client_write_key  = PRF(client_write_key,
                              "client write key",
                              client_random +
                              server_random)[0..15]
final_server_write_key  = PRF(server_write_key,
                              "server write key",
                              client_random +
                              server_random)[0..15]

iv_block                = PRF("", "IV block", client_random +
                              server_random)[0..15]
client_write_IV = iv_block[0..7]
server_write_IV = iv_block[8..15]

7. The TLS Handshake Protocol ๐Ÿค

okay the TLS Handshake Protocol is a whole squad of three sub-protocols ๐Ÿ‘ฏโ€โ™€๏ธ, and together they let the peers agree on security parameters for the record layer, authenticate themselves, set up those negotiated parameters, and tell each other when something has gone wrong. main character energy, honestly ๐Ÿ‘‘.

The Handshake Protocol is in charge of negotiating a session, and a session is made up of these items:

  • session identifier: an arbitrary byte sequence chosen by the server to identify an active or resumable session state ๐Ÿชช.
  • peer certificate: X509v3 [X509] certificate of the peer. This element of the state may be null ๐Ÿซฅ.
  • compression method: the algorithm used to compress data prior to encryption ๐Ÿ—œ๏ธ.
  • cipher spec: specifies the bulk data encryption algorithm (such as null, DES, etc.) and a MAC algorithm (such as MD5 or SHA). It also defines cryptographic attributes such as the hash_size. (See Appendix A.6 for formal definition) ๐Ÿ”‘.
  • master secret: 48-byte secret shared between the client and server ๐Ÿคซ.
  • is resumable: a flag indicating whether the session can be used to initiate new connections ๐Ÿ”.

These items are then used to create security parameters for the Record Layer when it's protecting application data ๐Ÿ›ก๏ธ. And many connections can be spun up from the same session through the resumption feature of the TLS Handshake Protocol, which is so efficient it's lowkey iconic โœจ.

7.1. Change cipher spec protocol ๐Ÿ”„

The change cipher spec protocol exists to signal transitions in ciphering strategies ๐Ÿฆ‹. It's a single message, and it's encrypted and compressed under the current (not the pending) connection state. The message is one single byte with a value of 1.

struct {
    enum { change_cipher_spec(1), (255) } type;
} ChangeCipherSpec;

Both the client and the server send the change cipher spec message to tell the receiving party that subsequent records will be protected under the newly negotiated CipherSpec and keys ๐Ÿ’Œ. When the receiver gets it, it instructs the Record Layer to immediately copy the read pending state into the read current state. Right after the sender sends this message, the sender SHOULD instruct the record layer to make the write pending state the write active state. (See section 6.1.) The change cipher spec message goes out during the handshake after the security parameters have been agreed upon, but before the verifying finished message is sent (see section 7.4.9) ๐Ÿค™.

7.2. Alert protocol ๐Ÿšจ

The TLS Record layer supports an alert type as one of its content types ๐Ÿ“ฃ. Alert messages convey how severe something is and describe what the alert is about. Alert messages with a level of fatal result in the immediate termination of the connection ๐Ÿ’€. In that case, other connections corresponding to the session MAY continue, but the session identifier MUST be invalidated, which stops the failed session from being used to set up new connections. Like other messages, alert messages are encrypted and compressed, as specified by the current connection state ๐Ÿ”’.

enum { warning(1), fatal(2), (255) } AlertLevel;

enum {
    close_notify(0),
    unexpected_message(10),
    bad_record_mac(20),
    decryption_failed(21),
    record_overflow(22),
    decompression_failure(30),
    handshake_failure(40),
    bad_certificate(42),
    unsupported_certificate(43),
    certificate_revoked(44),
    certificate_expired(45),
    certificate_unknown(46),
    illegal_parameter(47),
    unknown_ca(48),
    access_denied(49),
    decode_error(50),
    decrypt_error(51),
    export_restriction(60),
    protocol_version(70),
    insufficient_security(71),
    internal_error(80),
    user_canceled(90),
    no_renegotiation(100),
    (255)
} AlertDescription;

struct {
    AlertLevel level;
    AlertDescription description;
} Alert;

7.2.1. Closure alerts ๐Ÿ‘‹

okay this part is so important bestie: the client and the server MUST share knowledge that the connection is ending, so nobody can pull off a truncation attack ๐Ÿ™…โ€โ™€๏ธ. Either party MAY initiate the exchange of closing messages.

  • close_notify: this message tells the recipient that the sender won't send any more messages on this connection ๐Ÿ“ญ. The session becomes unresumable if any connection is terminated without proper close_notify messages with level equal to warning ๐Ÿซ .

Either party MAY initiate a close by sending a close_notify alert. Any data received after a closure alert gets ignored ๐Ÿ—‘๏ธ.

Each party is REQUIRED to send a close_notify alert before closing the write side of the connection. It is REQUIRED that the other party respond with a close_notify alert of its own and close down the connection immediately, discarding any pending writes ๐Ÿงน. It is not REQUIRED for the initiator of the close to wait for the responding close_notify alert before closing the read side of the connection ๐Ÿ’….

If the application protocol using TLS provides that any data MAY be carried over the underlying transport after the TLS connection is closed, the TLS implementation MUST receive the responding close_notify alert before indicating to the application layer that the TLS connection has ended ๐Ÿง. If the application protocol won't transfer any additional data and will only close the underlying transport connection, then the implementation MAY choose to close the transport without waiting for the responding close_notify. No part of this standard SHOULD be taken to dictate the manner in which a usage profile for TLS manages its data transport, including when connections are opened or closed ๐ŸŒธ.

NB: It is assumed that closing a connection reliably delivers pending data before destroying the transport. ๐Ÿซถ

7.2.2. Error alerts โœจ

okay so error handling in the TLS Handshake protocol is honestly giving simplicity ๐Ÿ’…. when something goes wrong, the party who detects it sends a message to the other side ๐Ÿšจ. the second a fatal alert gets sent or received, both parties immediately close the connection ๐Ÿ’€ no drama, just bye. servers and clients are required to forget any session identifiers, keys, and secrets tied to a failed connection ๐Ÿงน (don't keep the evidence, bestie).

here's the lineup of error alerts ๐ŸŽ€:

  • unexpected_message: an inappropriate message was received. this one is always fatal, and proper implementations should never actually see it in communication with each other ๐Ÿ™ˆ
  • bad_record_mac: a record came in with an incorrect MAC. always fatal ๐Ÿ’€
  • decryption_failed: a TLSCiphertext got decrypted in an invalid way. either it wasn't an even multiple of the block length, or its padding values were wrong when checked. always fatal ๐Ÿ˜ญ
  • record_overflow: a TLSCiphertext record came in longer than 2^14+2048 bytes, or a record decrypted into a TLSCompressed record with more than 2^14+1024 bytes. always fatal ๐Ÿ“
  • decompression_failure: the decompression function got improper input, like data that would expand to an excessive length. always fatal ๐ŸŒ€
  • handshake_failure: the sender couldn't negotiate an acceptable set of security parameters from the options available. this is a fatal error ๐Ÿ˜ฉ
  • bad_certificate: a certificate was corrupt, contained signatures that didn't verify correctly, etc. ๐Ÿ“œ
  • unsupported_certificate: a certificate was of an unsupported type ๐Ÿ™…โ€โ™€๏ธ
  • certificate_revoked: a certificate was revoked by its signer ๐Ÿšซ
  • certificate_expired: a certificate has expired or isn't currently valid โฐ
  • certificate_unknown: some other (unspecified) issue came up while processing the certificate, making it unacceptable ๐Ÿคทโ€โ™€๏ธ
  • illegal_parameter: a field in the handshake was out of range or inconsistent with other fields. always fatal ๐Ÿšซ
  • unknown_ca: a valid certificate chain or partial chain was received, but it wasn't accepted because the CA certificate couldn't be located or matched with a known, trusted CA. always fatal ๐Ÿ”
  • access_denied: a valid certificate was received, but once access control was applied, the sender decided not to keep negotiating. always fatal ๐Ÿ›‘
  • decode_error: a message couldn't be decoded because some field was out of the specified range, or the length of the message was incorrect. always fatal ๐Ÿงฉ
  • decrypt_error: a handshake cryptographic operation failed. this includes being unable to correctly verify a signature, decrypt a key exchange, or validate a finished message ๐Ÿ”‘
  • export_restriction: a negotiation that didn't comply with export restrictions was detected. for example, trying to transfer a 1024 bit ephemeral RSA key for the RSA_EXPORT handshake method. always fatal ๐ŸŒ
  • protocol_version: the protocol version the client tried to negotiate is recognized, but not supported. (old protocol versions might be avoided for security reasons, bestie ๐Ÿ™ƒ) always fatal ๐Ÿ•ฐ๏ธ
  • insufficient_security: returned instead of handshake_failure when a negotiation failed specifically because the server requires ciphers more secure than the client supports. always fatal ๐Ÿ”’
  • internal_error: an internal error unrelated to the peer or the correctness of the protocol makes it impossible to continue, like a memory allocation failure. always fatal ๐Ÿ› ๏ธ
  • user_canceled: the handshake is being canceled for some reason unrelated to a protocol failure. if the user cancels an operation after the handshake is complete, just closing the connection by sending a close_notify is more appropriate. this alert should be followed by a close_notify. generally a warning โš ๏ธ
  • no_renegotiation: sent by the client in response to a hello request, or by the server in response to a client hello after initial handshaking. these would normally lead to renegotiation. when that isn't appropriate, the recipient should respond with this alert, and then the original requester can decide whether to proceed with the connection. one case where this makes sense: a server spawned a process to satisfy a request, and that process might receive security parameters (key length, authentication, etc.) at startup, and it might be hard to communicate changes to those parameters after that point. always a warning ๐Ÿ”

for all errors where an alert level isn't explicitly specified, the sending party may decide, at its discretion, whether it's fatal or not. if an alert with a level of warning is received, the receiving party may decide, at its discretion, whether to treat it as a fatal error or not. however, all messages transmitted with a level of fatal must be treated as fatal messages. ๐Ÿซถ

7.3. Handshake Protocol overview โœจ

Okay so the crypto settings for a session? They get cooked up by the TLS Handshake Protocol, which runs right on top of the TLS Record Layer ๐Ÿ’…. When a TLS client and server first meet, they agree on a protocol version, pick their algorithms, optionally authenticate each other, and use public-key encryption to whip up shared secrets ๐Ÿ”โœจ.

The TLS Handshake Protocol goes through these steps:

  • Exchange hello messages to agree on algorithms, exchange random values, and check for session resumption.
  • Exchange the necessary cryptographic parameters so the client and server can agree on a premaster secret.
  • Exchange certificates and cryptographic information so the client and server can authenticate themselves.
  • Generate a master secret from the premaster secret and the exchanged random values.
  • Provide security parameters to the record layer.
  • Let the client and server verify that their peer calculated the same security parameters and that the handshake wasn't tampered with by an attacker ๐Ÿ•ต๏ธโ€โ™€๏ธ.

Bestie, listen to this part ๐Ÿซถ. Higher layers SHOULD NOT be overly reliant on TLS always negotiating the strongest possible connection between two peers. A man in the middle attacker has a bunch of ways to try to make two entities drop down to the least secure method they support ๐Ÿ˜ค. The protocol was designed to minimize that risk, but attacks are still possible. For example, an attacker could block access to the port a secure service runs on, or try to get the peers to negotiate an unauthenticated connection. The fundamental rule is that higher levels MUST be cognizant of their security requirements and never transmit information over a channel less secure than what they require ๐Ÿšจ. TLS is secure in the sense that any cipher suite offers its promised level of security. If you negotiate 3DES with a 1024 bit RSA key exchange with a host whose certificate you have verified, you can expect to be that secure ๐Ÿ’–.

You SHOULD never send data over a link encrypted with 40 bit security unless you feel that data is worth no more than the effort required to break that encryption. ๐Ÿ’€

Now the handshake itself ๐Ÿฆ‹. The client sends a client hello message, and the server MUST respond with a server hello message. If it doesn't, a fatal error occurs and the connection fails ๐Ÿ˜ญ. The client hello and server hello are used to establish security enhancement capabilities between client and server. They set up the following attributes: Protocol Version, Session ID, Cipher Suite, and Compression Method. On top of that, two random values get generated and exchanged: ClientHello.random and ServerHello.random ๐ŸŽฒ.

The actual key exchange uses up to four messages: the server certificate, the server key exchange, the client certificate, and the client key exchange. New key exchange methods can be made by specifying a format for these messages and defining how they're used so the client and server agree on a shared secret. That secret SHOULD be quite long. Right now, the defined key exchange methods exchange secrets between 48 and 128 bytes in length ๐Ÿ”ฅ.

After the hello messages, the server sends its certificate if it's going to be authenticated. A server key exchange message MAY also be sent if it's REQUIRED. For example, that happens if the server has no certificate, or if its certificate is for signing only. If the server is authenticated, it MAY request a certificate from the client, as long as that makes sense for the cipher suite selected. Then the server sends the server hello done message to say the hello-message phase is finished. After that it waits for the client to respond. If the server sent a certificate request message, the client MUST send the certificate message. Next comes the client key exchange message, and what's inside depends on the public key algorithm picked between the client hello and the server hello ๐Ÿง. If the client sent a certificate with signing ability, a digitally-signed certificate verify message gets sent to explicitly verify the certificate.

Now the client sends a change cipher spec message and copies the pending Cipher Spec into the current Cipher Spec. Right after, it sends the finished message under the new algorithms, keys, and secrets ๐ŸŒธ. The server replies with its own change cipher spec message, moves the pending Cipher Spec to current, and sends its finished message under the new Cipher Spec. At this point the handshake is complete, and the client and server MAY begin exchanging application layer data ๐ŸŽ‰. (See the flow chart below.)

   Client                                               Server

   ClientHello                  -------->
                                                   ServerHello
                                                  Certificate*
                                            ServerKeyExchange*
                                           CertificateRequest*
                                <--------      ServerHelloDone
   Certificate*
   ClientKeyExchange
   CertificateVerify*
   [ChangeCipherSpec]
   Finished                     -------->
                                            [ChangeCipherSpec]
                                <--------             Finished
   Application Data             <------->     Application Data

          Fig. 1 - Message flow for a full handshake

* Indicates optional or situation-dependent messages that are not always sent. ๐Ÿ™ˆ

Note: To help avoid pipeline stalls, ChangeCipherSpec is an independent TLS Protocol content type, and is not actually a TLS handshake message. ๐Ÿงš

Sometimes the client and server want to resume a previous session or duplicate an existing one, instead of negotiating new security parameters. The flow goes like this ๐Ÿฆ‹. The client sends a ClientHello using the Session ID of the session it wants to resume. The server checks its session cache for a match. If it finds one and is willing to re-establish the connection under that session state, it sends a ServerHello with the same Session ID value. At this point, both client and server MUST send change cipher spec messages and go straight to finished messages. Once re-establishment is complete, the client and server MAY begin exchanging application layer data. (See the flow chart below.) If no Session ID match is found, the server generates a new session ID and the TLS client and server do a full handshake instead ๐Ÿ”.

   Client                                                Server

   ClientHello                   -------->
                                                    ServerHello
                                             [ChangeCipherSpec]
                                 <--------             Finished
   [ChangeCipherSpec]
   Finished                      -------->
   Application Data              <------->     Application Data

       Fig. 2 - Message flow for an abbreviated handshake

The contents and meaning of each message get the full breakdown in the sections that follow ๐Ÿ“–๐Ÿ’œ.


7.4. Handshake protocol ๐ŸŽ€

The TLS Handshake Protocol is one of the defined higher level clients of the TLS Record Protocol ๐Ÿ‘‘. It's what negotiates the secure attributes of a session. Handshake messages go to the TLS Record Layer, where they get wrapped up in one or more TLSPlaintext structures. Those get processed and transmitted as the current active session state specifies ๐Ÿ“ฆ.

    enum {
        hello_request(0), client_hello(1), server_hello(2),
        certificate(11), server_key_exchange (12),
        certificate_request(13), server_hello_done(14),
        certificate_verify(15), client_key_exchange(16),
        finished(20), (255)
    } HandshakeType;

    struct {
        HandshakeType msg_type;    /* handshake type */
        uint24 length;             /* bytes in message */
        select (HandshakeType) {
            case hello_request:       HelloRequest;
            case client_hello:        ClientHello;
            case server_hello:        ServerHello;
            case certificate:         Certificate;
            case server_key_exchange: ServerKeyExchange;
            case certificate_request: CertificateRequest;
            case server_hello_done:   ServerHelloDone;
            case certificate_verify:  CertificateVerify;
            case client_key_exchange: ClientKeyExchange;
            case finished:            Finished;
        } body;
    } Handshake;

The handshake protocol messages are listed below in the order they MUST be sent, and sending them in an unexpected order results in a fatal error ๐Ÿšซ. Unneeded handshake messages can be left out, though ๐Ÿ™Œ. There's one exception to the ordering: the Certificate message is used twice in the handshake (server to client, then client to server), but it's only described in its first position ๐Ÿค“. The one message not bound by these ordering rules is the Hello Request message. It can be sent at any time, but it SHOULD be ignored by the client if it shows up in the middle of a handshake ๐Ÿ™ˆ.

7.4.1. Hello messages ๐ŸŒˆ

The hello phase messages exchange security enhancement capabilities between the client and server ๐Ÿ’ฌ. When a new session begins, the Record Layer's connection state encryption, hash, and compression algorithms are initialized to null. The current connection state is used for renegotiation messages ๐Ÿ”„.

7.4.1.1. Hello request ๐Ÿ””

When this message will be sent: The hello request message MAY be sent by the server at any time.

Meaning of this message: Hello request is a simple notification that the client should start the negotiation process over by sending a client hello message whenever it's convenient ๐Ÿ’Œ. The client IGNORES... (correction: this message will be ignored by the client if it's already negotiating a session ๐Ÿ˜…). This message MAY be ignored by the client if it doesn't want to renegotiate a session. Or the client MAY, if it wishes, respond with a no_renegotiation alert. Handshake messages are meant to take transmission precedence over application data, so the negotiation is expected to begin before more than a few records arrive from the client โšก. If the server sends a hello request but doesn't get a client hello back, it MAY close the connection with a fatal alert ๐Ÿ˜ฌ.

After sending a hello request, servers SHOULD NOT repeat the request until the subsequent handshake negotiation is complete ๐Ÿ›‘.

Structure of this message:

struct { } HelloRequest;
Note: This message SHOULD never be included in the message hashes which are maintained throughout the handshake and used in the finished messages and the certificate verify message. ๐Ÿ’…

7.4.1.2. Client hello โœจ

When this message will be sent: okay so when a client first connects to a server, it is REQUIRED to send the client hello as its very first message ๐Ÿ’… The client can also send one in response to a hello request, or on its own initiative, to renegotiate the security parameters of an existing connection ๐Ÿฆ‹

Structure of this message: the client hello includes a random structure, which gets used later in the protocol ๐ŸŒธ

struct {
   uint32 gmt_unix_time;
   opaque random_bytes[28];
} Random;

gmt_unix_time: this is the current time and date in standard UNIX 32-bit format (seconds since the midnight starting Jan 1, 1970, GMT), according to the sender's internal clock โฐ Clocks are not REQUIRED to be set correctly by the basic TLS Protocol, but higher level or application protocols MAY define additional requirements.

random_bytes: 28 bytes generated by a secure random number generator ๐Ÿ”

The client hello includes a variable length session identifier โœจ If it isn't empty, the value identifies a session between the same client and server whose security parameters the client wants to reuse. The session identifier MAY come from an earlier connection, this connection, or another currently active connection. The second option is useful if the client only wants to update the random structures and derived values of a connection ๐ŸŽ€ The third option lets you set up several independent secure connections without repeating the full handshake protocol ๐Ÿงš These independent connections can happen one after another or at the same time. A SessionID becomes valid when the handshake negotiating it finishes with the exchange of Finished messages, and it sticks around until it's removed due to aging, or because a fatal error was hit on a connection tied to the session. The server decides what the actual contents of the SessionID look like ๐Ÿ‘‘

opaque SessionID<0..32>;
Warning: the SessionID gets sent without encryption or immediate MAC protection, so servers MUST NOT place confidential information in session identifiers, and they MUST NOT let the contents of fake session identifiers cause any breach of security ๐Ÿ™ˆ (The content of the handshake as a whole, SessionID included, is protected by the Finished messages exchanged at the end of the handshake.)

The CipherSuite list, sent from the client to the server in the client hello, is all the combinations of cryptographic algorithms the client supports, listed in order of its preference (favorite first) ๐Ÿ’– Each CipherSuite defines a key exchange algorithm, a bulk encryption algorithm (including the secret key length), and a MAC algorithm. The server will pick a cipher suite or, if there are no acceptable choices, it will return a handshake failure alert and close the connection ๐Ÿ’€

uint8 CipherSuite[2];    /* Cryptographic suite selector */

The client hello also includes a list of compression algorithms the client supports, ordered by its preference ๐Ÿ“

enum { null(0), (255) } CompressionMethod;

struct {
    ProtocolVersion client_version;
    Random random;
    SessionID session_id;
    CipherSuite cipher_suites<2..2^16-1>;
    CompressionMethod compression_methods<1..2^8-1>;
} ClientHello;

client_version: the version of the TLS protocol the client wants to talk over during this session. It SHOULD be the latest (highest valued) version the client supports ๐ŸŒˆ For this version of the specification, the version will be 3.1 (see Appendix E for details about backward compatibility).

random: a client-generated random structure ๐Ÿฆ‹

session_id: the ID of a session the client wants to use for this connection. This field SHOULD be empty if no session_id is available, or if the client wants to generate new security parameters ๐Ÿซถ

cipher_suites: a list of the cryptographic options the client supports, with the client's first preference first. If the session_id field is not empty (which implies a session resumption request), this vector MUST include at least the cipher_suite from that session. Values are defined in Appendix A.5 โœจ

compression_methods: a list of the compression methods the client supports, sorted by client preference. If the session_id field is not empty (which implies a session resumption request), it MUST include the compression_method from that session. This vector MUST contain, and all implementations MUST support, CompressionMethod.null. That way, a client and server will always be able to agree on a compression method ๐ŸŒธ

After sending the client hello, the client waits for a server hello message ๐Ÿ‘€ Any other handshake message the server returns, except for a hello request, is treated as a fatal error ๐Ÿ˜ญ

Forward compatibility note: for the sake of forward compatibility, a client hello is allowed to include extra data after the compression methods ๐Ÿ”ฎ That data MUST be included in the handshake hashes, but MUST otherwise be ignored. This is the only handshake message where this is legal. For all other messages, the amount of data in the message MUST match the description of the message precisely ๐Ÿ’…


7.4.1.3. Server hello ๐Ÿ’œ

When this message will be sent: the server sends this message in response to a client hello when it has found an acceptable set of algorithms ๐ŸŽ€ If it can't find a match, it responds with a handshake failure alert ๐Ÿ’€

Structure of this message:

struct {
    ProtocolVersion server_version;
    Random random;
    SessionID session_id;
    CipherSuite cipher_suite;
    CompressionMethod compression_method;
} ServerHello;

server_version: this field contains the lower of the version suggested by the client in the client hello and the highest version the server supports ๐Ÿงš For this version of the specification, the version is 3.1 (see Appendix E for details about backward compatibility).

random: this structure is generated by the server and MUST be different from (and independent of) ClientHello.random ๐Ÿ”

session_id: this is the identity of the session that corresponds to this connection. If ClientHello.session_id was non-empty, the server looks in its session cache for a match. If a match is found and the server is willing to establish the new connection using the specified session state, the server responds with the same value the client supplied. That means a resumed session, and it dictates that the parties MUST proceed directly to the finished messages ๐Ÿฆ‹ Otherwise, this field contains a different value identifying the new session. The server MAY return an empty session_id to indicate that the session will not be cached, and therefore cannot be resumed ๐Ÿ™ˆ If a session is resumed, it MUST be resumed using the same cipher suite it was originally negotiated with ๐Ÿซถ

cipher_suite: the single cipher suite the server selected from the list in ClientHello.cipher_suites. For resumed sessions, this field is the value from the state of the session being resumed ๐ŸŒˆ

compression_method: the single compression algorithm the server selected from the list in ClientHello.compression_methods. For resumed sessions, this field is the value from the resumed session state ๐Ÿ“


7.4.2. Server certificate ๐Ÿฐ

When this message will be sent: the server MUST send a certificate whenever the agreed-upon key exchange method is not an anonymous one ๐Ÿ” This message always immediately follows the server hello ๐ŸŽ€

Meaning of this message: the certificate type MUST be appropriate for the selected cipher suite's key exchange algorithm, and it's generally an X.509v3 certificate ๐Ÿ“œ It MUST contain a key that matches the key exchange method, as follows. Unless otherwise specified, the signing algorithm for the certificate MUST be the same as the algorithm for the certificate key. Unless otherwise specified, the public key MAY be of any length ๐ŸŒธ

Key Exchange Algorithm  Certificate Key Type

RSA                     RSA public key; the certificate MUST
                        allow the key to be used for encryption.

RSA_EXPORT              RSA public key of length greater than
                        512 bits which can be used for signing,
                        or a key of 512 bits or shorter which
                        can be used for either encryption or
                        signing.

DHE_DSS                 DSS public key.

DHE_DSS_EXPORT          DSS public key.

DHE_RSA                 RSA public key which can be used for
                        signing.

DHE_RSA_EXPORT          RSA public key which can be used for
                        signing.

DH_DSS                  Diffie-Hellman key. The algorithm used
                        to sign the certificate SHOULD be DSS.

DH_RSA                  Diffie-Hellman key. The algorithm used
                        to sign the certificate SHOULD be RSA.

All certificate profiles, key and cryptographic formats are defined by the IETF PKIX working group [PKIX] ๐Ÿ“š When a key usage extension is present, the digitalSignature bit MUST be set for the key to be eligible for signing, as described above, and the keyEncipherment bit MUST be present to allow encryption, as described above. The keyAgreement bit MUST be set on Diffie-Hellman certificates ๐Ÿ”‘

As CipherSuites which specify new key exchange methods get defined for the TLS Protocol, they'll imply the certificate format and the required encoded keying information ๐Ÿงš

Structure of this message:

opaque ASN.1Cert<1..2^24-1>;

struct {
    ASN.1Cert certificate_list<0..2^24-1>;
} Certificate;

certificate_list: this is a sequence (chain) of X.509v3 certificates ๐Ÿ”— The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it. Because certificate validation requires that root keys be distributed independently, the self-signed certificate that specifies the root certificate authority MAY optionally be omitted from the chain, under the assumption that the remote end MUST already possess it in order to validate it in any case ๐Ÿ‘‘

The same message type and structure get used for the client's response to a certificate request message ๐Ÿซถ Note that a client MAY send no certificates if it doesn't have an appropriate certificate to send in response to the server's authentication request ๐Ÿฅบ

Note: PKCS #7 [PKCS7] is not used as the format for the certificate vector, because PKCS #6 [PKCS6] extended certificates are not used. Also, PKCS #7 defines a SET rather than a SEQUENCE, which makes parsing the list more difficult ๐Ÿ’…

7.4.3. Server key exchange message โœจ

okay so when does this message even get sent? ๐Ÿงš It goes out right after the server certificate message, or right after the server hello if this is an anonymous negotiation, bestie.

The server key exchange message only shows up when the server certificate message (if one was sent) doesn't have enough info for the client to exchange a premaster secret. These key exchange methods need it:

  • RSA_EXPORT (if the public key in the server certificate is longer than 512 bits)
  • DHE_DSS
  • DHE_DSS_EXPORT
  • DHE_RSA
  • DHE_RSA_EXPORT
  • DH_anon

And it is NOT legal to send it for these ones, so don't even ๐Ÿ™ˆ:

  • RSA
  • RSA_EXPORT (when the public key in the server certificate is less than or equal to 512 bits in length)
  • DH_DSS
  • DH_RSA

So what does this message actually do? ๐Ÿ’… It hands the client the crypto info it needs to get the premaster secret. Either that's an RSA public key to encrypt the premaster secret with, or a Diffie-Hellman public key so the client can finish a key exchange and end up with the premaster secret.

Future vibes: as more CipherSuites get defined for TLS with new key exchange algorithms, the server key exchange message will be sent if and only if the certificate type tied to that key exchange algorithm doesn't give the client enough info to exchange a premaster secret. ๐Ÿฆ‹

Note: According to current US export law, RSA moduli larger than 512 bits may not be used for key exchange in software exported from the US. With this message, the larger RSA keys encoded in certificates may be used to sign temporary shorter RSA keys for the RSA_EXPORT key exchange method. ๐Ÿ”ฅ

Here's the structure, bestie. Copy it exactly ๐ŸŽ€:

enum { rsa, diffie_hellman } KeyExchangeAlgorithm;

struct {
    opaque rsa_modulus<1..2^16-1>;
    opaque rsa_exponent<1..2^16-1>;
} ServerRSAParams;

rsa_modulus
    The modulus of the server's temporary RSA key.

rsa_exponent
    The public exponent of the server's temporary RSA key.

struct {
    opaque dh_p<1..2^16-1>;
    opaque dh_g<1..2^16-1>;
    opaque dh_Ys<1..2^16-1>;
} ServerDHParams;     /* Ephemeral DH parameters */

dh_p
    The prime modulus used for the Diffie-Hellman operation.

dh_g
    The generator used for the Diffie-Hellman operation.

dh_Ys
    The server's Diffie-Hellman public value (g^X mod p).

struct {
    select (KeyExchangeAlgorithm) {
        case diffie_hellman:
            ServerDHParams params;
            Signature signed_params;
        case rsa:
            ServerRSAParams params;
            Signature signed_params;
    };
} ServerKeyExchange;

params
    The server's key exchange parameters.

signed_params
    For non-anonymous key exchanges, a hash of the corresponding
    params value, with the signature appropriate to that hash
    applied.

md5_hash
    MD5(ClientHello.random + ServerHello.random + ServerParams);

sha_hash
    SHA(ClientHello.random + ServerHello.random + ServerParams);

enum { anonymous, rsa, dsa } SignatureAlgorithm;

select (SignatureAlgorithm)
{   case anonymous: struct { };
    case rsa:
        digitally-signed struct {
            opaque md5_hash[16];
            opaque sha_hash[20];
        };
    case dsa:
        digitally-signed struct {
            opaque sha_hash[20];
        };
} Signature;

7.4.4. Certificate request ๐ŸŒธ

when this gets sent: a non-anonymous server can optionally ask the client for a certificate, but only if it fits the selected cipher suite. ๐Ÿซถ If it's sent, it comes right after the Server Key Exchange message (if that one's sent), or else right after the Server Certificate message.

Structure time ๐Ÿ’–:

enum {
    rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),
    (255)
} ClientCertificateType;

opaque DistinguishedName<1..2^16-1>;

struct {
    ClientCertificateType certificate_types<1..2^8-1>;
    DistinguishedName certificate_authorities<3..2^16-1>;
} CertificateRequest;

certificate_types This field is a list of the types of certificates requested, sorted in order of the server's preference.

certificate_authorities A list of the distinguished names of acceptable certificate authorities. These distinguished names may specify a desired distinguished name for a root CA or for a subordinate CA; thus, this message can be used both to describe known roots and a desired authorization space.

Note: DistinguishedName is derived from [X509].

Note: It is a fatal handshake_failure alert for an anonymous server to request client identification. ๐Ÿ’€

7.4.5. Server hello done ๐Ÿ“

when this gets sent: the server hello done message is how the server says "that's a wrap" on the server hello and its buddies. After sending it, the server just waits for the client to respond. ๐Ÿงš

what it means: the server is finished sending the messages it needs for the key exchange, so the client can go ahead with its part. โœจ

Upon receiving server hello done, the client should verify that the server provided a valid certificate if one is required, and check that the server hello parameters are acceptable. ๐Ÿ‘‘

Structure: literally nothing, just this:

struct { } ServerHelloDone;

7.4.6. Client certificate ๐Ÿฆ‹

when this gets sent: this is the first thing the client can send after getting server hello done. It only gets sent if the server asked for a certificate. If the client doesn't have a suitable one, it should send a certificate message with no certificates in it. ๐Ÿ™ˆ If the server requires client authentication for the handshake to keep going, the client may respond with a fatal handshake failure alert. Client certificates go out using the Certificate structure from Section 7.4.2. ๐Ÿ’…

Note: When using a static Diffie-Hellman based key exchange method (DH_DSS or DH_RSA), if client authentication is requested, the Diffie-Hellman group and generator encoded in the client's certificate must match the server specified Diffie-Hellman parameters if the client's parameters are to be used for the key exchange. ๐Ÿ”ฅ

7.4.7. Client key exchange message ๐Ÿ’œ

when this gets sent: this one is ALWAYS sent by the client. It comes right after the client certificate message, if that was sent. Otherwise it's the very first thing the client sends after server hello done. ๐Ÿ˜ญ

what it means: this is where the premaster secret gets set. Either the client sends the RSA-encrypted secret directly, or it sends Diffie-Hellman parameters so both sides can agree on the same premaster secret. ๐Ÿซถ Now the sneaky bit: when the key exchange method is DH_RSA or DH_DSS, client certification was requested, and the client responded with a certificate holding a Diffie-Hellman public key whose parameters (group and generator) matched the ones the server gave in its certificate, this message won't contain any data. โญ

Structure: the message depends on which key exchange method got picked. Check Section 7.4.3 for the KeyExchangeAlgorithm definition. ๐ŸŽ€

struct {
    select (KeyExchangeAlgorithm) {
        case rsa: EncryptedPreMasterSecret;
        case diffie_hellman: ClientDiffieHellmanPublic;

    } exchange_keys;
} ClientKeyExchange;

7.4.7.1. RSA encrypted premaster secret message ๐ŸŒˆ

what it means: if RSA is being used for key agreement and authentication, the client makes a 48-byte premaster secret, encrypts it with the public key from the server's certificate (or the temporary RSA key from a server key exchange message), and sends the result in an encrypted premaster secret message. This structure is a variant of the client key exchange message, not a message on its own. ๐Ÿงš

Structure of this message:

struct {
    ProtocolVersion client_version;
    opaque random[46];
} PreMasterSecret;

client_version
    The latest (newest) version supported by the client. This is
    used to detect version roll-back attacks. Upon receiving the
    premaster secret, the server should check that this value
    matches the value transmitted by the client in the client
    hello message.

random
    46 securely-generated random bytes.

struct {
    public-key-encrypted PreMasterSecret pre_master_secret;
} EncryptedPreMasterSecret;
Note: An attack discovered by Daniel Bleichenbacher [BLEI] can be used to attack a TLS server which is using PKCS#1 encoded RSA. The attack takes advantage of the fact that by failing in different ways, a TLS server can be coerced into revealing whether a particular message, when decrypted, is properly PKCS#1 formatted or not. ๐Ÿ˜ฑ

The best way to avoid vulnerability to this attack is to treat incorrectly formatted messages in a manner indistinguishable from correctly formatted RSA blocks. Thus, when it receives an incorrectly formatted RSA block, a server should generate a random 48-byte value and proceed using it as the premaster secret. Thus, the server will act identically whether the received RSA block is correctly encoded or not. ๐Ÿ›ก๏ธ

pre_master_secret This random value is generated by the client and is used to generate the master secret, as specified in Section 8.1. ๐Ÿ’–

7.4.7.2. Client Diffie-Hellman public value ๐ŸŒท

what it means: this structure carries the client's Diffie-Hellman public value (Yc) if it wasn't already in the client's certificate. The encoding for Yc is set by the enumerated PublicValueEncoding. This structure is a variant of the client key exchange message, not a message on its own. โœจ

Structure of this message:

enum { implicit, explicit } PublicValueEncoding;

implicit
    If the client certificate already contains a suitable
    Diffie-Hellman key, then Yc is implicit and does not need to
    be sent again. In this case, the Client Key Exchange message
    will be sent, but will be empty.

explicit
    Yc needs to be sent.

struct {
    select (PublicValueEncoding) {
        case implicit: struct { };
        case explicit: opaque dh_Yc<1..2^16-1>;
    } dh_public;
} ClientDiffieHellmanPublic;

dh_Yc
    The client's Diffie-Hellman public value (Yc).

7.4.8. Certificate verify ๐ŸŽ€

When this message will be sent: okay so this message is how the client explicitly proves it owns its client certificate ๐Ÿ”. It only gets sent after a client certificate that can sign things, so basically every certificate except the ones holding fixed Diffie-Hellman parameters. And it has to come right after the client key exchange message, no detours ๐Ÿ’….

Structure of this message: here's the shape of it โœจ

struct {
     Signature signature;
} CertificateVerify;

The Signature type is defined in 7.4.3, so go check that if you forgot ๐Ÿงš

CertificateVerify.signature.md5_hash
    MD5(handshake_messages);

Certificate.signature.sha_hash
    SHA(handshake_messages);

Here, handshake_messages means every handshake message sent or received starting at client hello, up to but not including this message. That includes the type and length fields of each handshake message ๐Ÿฆ‹. It's basically all the Handshake structures from 7.4 that have been exchanged so far, stitched together in one big concatenation. Lowkey a lot, but it's the point ๐Ÿ’œ.

7.4.9. Finished ๐ŸŒธ

When this message will be sent: a finished message always goes out right after a change cipher spec message, and its whole job is to confirm that the key exchange and authentication actually worked ๐Ÿ”ฅ. It's essential that a change cipher spec message shows up between the other handshake messages and the Finished message, no skipping ๐Ÿ™ˆ.

Meaning of this message: the finished message is the very first thing protected with the algorithms, keys and secrets we just agreed on โœจ. Anyone receiving a finished message has to check that the contents are correct ๐Ÿซถ. Once a side has sent its own Finished message AND has received and validated its peer's Finished message, it can finally start sending and receiving application data over the connection ๐ŸŽ‰.

struct {
    opaque verify_data[12];
} Finished;

verify_data
    PRF(master_secret, finished_label, MD5(handshake_messages) +
    SHA-1(handshake_messages)) [0..11];

finished_label
    For Finished messages sent by the client, the string "client
    finished". For Finished messages sent by the server, the
    string "server finished".

handshake_messages
    All of the data from all handshake messages up to but not
    including this message. This is only data visible at the
    handshake layer and does not include record layer headers.

    This is the concatenation of all the Handshake structures as
    defined in 7.4 exchanged thus far.

It is a fatal error if a finished message is not preceded by a change cipher spec message at the appropriate point in the handshake ๐Ÿ’€. Not a vibe, very serious.

The hash in a server's finished message bakes in Sender.server, and the one in a client's finished message bakes in Sender.client ๐ŸŒˆ. The handshake_messages value covers every handshake message from client hello up to, but not including, this finished message. That can be different from the handshake_messages in Section 7.4.8, because it would include the certificate verify message (if one was sent) ๐Ÿ“. Also, the client's finished message and the server's finished message will have different handshake_messages, because whichever one goes out second includes the first one ๐Ÿ‘‘.

Note: Change cipher spec messages, alerts and any other record types are not handshake messages and are not included in the hash computations. Also, Hello Request messages are omitted from handshake hashes. ๐Ÿ™ˆ

8. Cryptographic computations ๐Ÿ”ฎ

So to start protecting the connection, the TLS Record Protocol needs a suite of algorithms, a master secret, and the client and server random values ๐Ÿ’–. The authentication, encryption and MAC algorithms all come from the cipher_suite the server picks and reveals in the server hello message ๐ŸŽ€. The compression algorithm gets negotiated in the hello messages, and so do the random values. The only thing left to do is calculate the master secret ๐Ÿงš.

8.1. Computing the master secret โœจ

For every key exchange method, the same algorithm turns the pre_master_secret into the master_secret ๐Ÿ’…. The pre_master_secret should be deleted from memory once the master_secret has been computed ๐Ÿซถ.

master_secret = PRF(pre_master_secret, "master secret",
                    ClientHello.random + ServerHello.random)
[0..47];

The master secret is always exactly 48 bytes long ๐Ÿฆ‹. The premaster secret's length does change depending on the key exchange method, though, so keep that in mind ๐ŸŒธ.

8.1.1. RSA ๐Ÿ”

When RSA is used for server authentication and key exchange, the client generates a 48-byte pre_master_secret, encrypts it under the server's public key, and sends it to the server ๐Ÿ’œ. The server uses its private key to decrypt the pre_master_secret ๐Ÿ”‘. Then both parties turn the pre_master_secret into the master_secret, exactly as specified above โœจ.

RSA digital signatures use PKCS #1 [PKCS1] block type 1. RSA public key encryption uses PKCS #1 block type 2 ๐ŸŽ€.

8.1.2. Diffie-Hellman ๐ŸŒˆ

A conventional Diffie-Hellman computation happens here. The negotiated key (Z) gets used as the pre_master_secret, and then it's converted into the master_secret, as specified above ๐Ÿ”ฅ.

Note: Diffie-Hellman parameters are specified by the server, and may be either ephemeral or contained within the server's certificate. ๐Ÿ‘‘

9. Mandatory Cipher Suites ๐Ÿ’…

Unless an application profile standard says otherwise, a TLS compliant application MUST implement the cipher suite TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA โœจ. That one is non-negotiable, bestie ๐Ÿซถ.


10. Application data protocol ๐Ÿฆ‹

Application data messages ride along on the Record Layer. They get fragmented, compressed and encrypted based on the current connection state ๐ŸŒธ. To the record layer, they're just transparent data, no judgment ๐Ÿ’œ.


A. Protocol constant values ๐Ÿ”ฎ

This section covers the protocol types and constants ๐Ÿ’–.

A.1. Record layer ๐ŸŽ€

struct {
    uint8 major, minor;
} ProtocolVersion;

ProtocolVersion version = { 3, 1 };     /* TLS v1.0 */

enum {
    change_cipher_spec(20), alert(21), handshake(22),
    application_data(23), (255)
} ContentType;

struct {
    ContentType type;
    ProtocolVersion version;
    uint16 length;
    opaque fragment[TLSPlaintext.length];
} TLSPlaintext;

struct {
    ContentType type;
    ProtocolVersion version;
    uint16 length;
    opaque fragment[TLSCompressed.length];
} TLSCompressed;

struct {
    ContentType type;
    ProtocolVersion version;
    uint16 length;
    select (CipherSpec.cipher_type) {
        case stream: GenericStreamCipher;
        case block:  GenericBlockCipher;
    } fragment;
} TLSCiphertext;

stream-ciphered struct {
    opaque content[TLSCompressed.length];
    opaque MAC[CipherSpec.hash_size];
} GenericStreamCipher;

block-ciphered struct {
    opaque content[TLSCompressed.length];
    opaque MAC[CipherSpec.hash_size];
    uint8 padding[GenericBlockCipher.padding_length];
    uint8 padding_length;
} GenericBlockCipher;

A.2. Change cipher specs message ๐ŸŒˆ

struct {
    enum { change_cipher_spec(1), (255) } type;
} ChangeCipherSpec;

A.3. Alert messages ๐Ÿšจ

enum { warning(1), fatal(2), (255) } AlertLevel;

    enum {
        close_notify(0),
        unexpected_message(10),
        bad_record_mac(20),
        decryption_failed(21),
        record_overflow(22),
        decompression_failure(30),
        handshake_failure(40),
        bad_certificate(42),
        unsupported_certificate(43),
        certificate_revoked(44),
        certificate_expired(45),
        certificate_unknown(46),
        illegal_parameter(47),
        unknown_ca(48),
        access_denied(49),
        decode_error(50),
        decrypt_error(51),
        export_restriction(60),
        protocol_version(70),
        insufficient_security(71),
        internal_error(80),
        user_canceled(90),
        no_renegotiation(100),
        (255)
    } AlertDescription;

struct {
    AlertLevel level;
    AlertDescription description;
} Alert;

A.4. Handshake protocol ๐Ÿค

enum {
    hello_request(0), client_hello(1), server_hello(2),
    certificate(11), server_key_exchange (12),
    certificate_request(13), server_hello_done(14),
    certificate_verify(15), client_key_exchange(16),
    finished(20), (255)
} HandshakeType;

struct {
    HandshakeType msg_type;
    uint24 length;
    select (HandshakeType) {
        case hello_request:       HelloRequest;
        case client_hello:        ClientHello;
        case server_hello:        ServerHello;
        case certificate:         Certificate;
        case server_key_exchange: ServerKeyExchange;
        case certificate_request: CertificateRequest;
        case server_hello_done:   ServerHelloDone;
        case certificate_verify:  CertificateVerify;
        case client_key_exchange: ClientKeyExchange;
        case finished:            Finished;
    } body;
} Handshake;

A.4.1. Hello messages ๐Ÿ‘‹

struct { } HelloRequest;

struct {
    uint32 gmt_unix_time;
    opaque random_bytes[28];
} Random;

opaque SessionID<0..32>;

uint8 CipherSuite[2];

enum { null(0), (255) } CompressionMethod;

struct {
    ProtocolVersion client_version;
    Random random;
    SessionID session_id;
    CipherSuite cipher_suites<2..2^16-1>;
    CompressionMethod compression_methods<1..2^8-1>;

} ClientHello;

struct {
    ProtocolVersion server_version;
    Random random;
    SessionID session_id;
    CipherSuite cipher_suite;
    CompressionMethod compression_method;
} ServerHello;

A.4.2. Server authentication and key exchange messages ๐Ÿ”

opaque ASN.1Cert<2^24-1>;

struct {
    ASN.1Cert certificate_list<1..2^24-1>;
} Certificate;

enum { rsa, diffie_hellman } KeyExchangeAlgorithm;

struct {
    opaque RSA_modulus<1..2^16-1>;
    opaque RSA_exponent<1..2^16-1>;
} ServerRSAParams;

struct {
    opaque DH_p<1..2^16-1>;
    opaque DH_g<1..2^16-1>;
    opaque DH_Ys<1..2^16-1>;
} ServerDHParams;

struct {
    select (KeyExchangeAlgorithm) {
        case diffie_hellman:
            ServerDHParams params;
            Signature signed_params;
        case rsa:
            ServerRSAParams params;
            Signature signed_params;
    };
} ServerKeyExchange;

enum { anonymous, rsa, dsa } SignatureAlgorithm;

select (SignatureAlgorithm)
{   case anonymous: struct { };
    case rsa:
        digitally-signed struct {

            opaque md5_hash[16];
            opaque sha_hash[20];
        };
    case dsa:
        digitally-signed struct {
            opaque sha_hash[20];
        };
} Signature;

enum {
    rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4),
    (255)
} ClientCertificateType;

opaque DistinguishedName<1..2^16-1>;

struct {
    ClientCertificateType certificate_types<1..2^8-1>;
    DistinguishedName certificate_authorities<3..2^16-1>;
} CertificateRequest;

struct { } ServerHelloDone;

A.4.3. Client authentication and key exchange messages โœจ

okay bestie, the client's turn to talk ๐Ÿ’… its ClientKeyExchange message is a select thing: the body depends on which KeyExchangeAlgorithm got picked. rsa sends an EncryptedPreMasterSecret, and diffie_hellman sends a DiffieHellmanClientPublicValue ๐Ÿ”

struct {
    select (KeyExchangeAlgorithm) {
        case rsa: EncryptedPreMasterSecret;
        case diffie_hellman: DiffieHellmanClientPublicValue;
    } exchange_keys;
} ClientKeyExchange;

struct {
    ProtocolVersion client_version;
    opaque random[46];

} PreMasterSecret;

struct {
    public-key-encrypted PreMasterSecret pre_master_secret;
} EncryptedPreMasterSecret;

enum { implicit, explicit } PublicValueEncoding;

struct {
    select (PublicValueEncoding) {
        case implicit: struct {};
        case explicit: opaque DH_Yc<1..2^16-1>;

    } dh_public;
} ClientDiffieHellmanPublic;

struct {
    Signature signature;
} CertificateVerify;

so the PreMasterSecret is the main character here ๐Ÿ‘‘ it's a ProtocolVersion client_version plus 46 random bytes (random[46]), and then it gets wrapped up as EncryptedPreMasterSecret for the RSA route. the PublicValueEncoding enum decides whether the Diffie-Hellman public value is implicit (empty struct, nothing sent ๐Ÿ™ˆ) or explicit (a DH_Yc value with a 1 to 2^16-1 length). and CertificateVerify is just a Signature wrapped in a struct, super minimal but iconic ๐Ÿซถ

A.4.4. Handshake finalization message ๐ŸŽ€

the Finished message is giving closure ๐Ÿ˜ญ it's one struct holding opaque verify_data[12], which is exactly 12 bytes. that's the last handshake vibe check before everything gets real ๐Ÿงš

A.5. The CipherSuite ๐Ÿ’œ

okay this part is the cipher suite codes, the values that show up in the client hello and server hello messages ๐ŸŒธ a CipherSuite is a cipher specification supported in TLS Version 1.0. bestie, read this next bit carefully because it's important ๐Ÿšจ

TLS_NULL_WITH_NULL_NULL is the initial state of a TLS connection during the first handshake on that channel, but it must not be negotiated, because it gives you no more protection than an unsecured connection ๐Ÿ’€ literally just vibes, no security.

the null suite is the starting state, never the thing you actually pick. no protection, no slay.

the next group of suites needs the server to have an RSA certificate that can be used for key exchange ๐Ÿ”‘ the server may ask for either an RSA or a DSS signature-capable certificate in the certificate request message. and yes, these are the RSA ones ๐Ÿ“

CipherSuite TLS_NULL_WITH_NULL_NULL                = { 0x00,0x00 };

CipherSuite TLS_RSA_WITH_NULL_MD5                  = { 0x00,0x01 };
CipherSuite TLS_RSA_WITH_NULL_SHA                  = { 0x00,0x02 };
CipherSuite TLS_RSA_EXPORT_WITH_RC4_40_MD5         = { 0x00,0x03 };
CipherSuite TLS_RSA_WITH_RC4_128_MD5               = { 0x00,0x04 };
CipherSuite TLS_RSA_WITH_RC4_128_SHA               = { 0x00,0x05 };
CipherSuite TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5     = { 0x00,0x06 };
CipherSuite TLS_RSA_WITH_IDEA_CBC_SHA              = { 0x00,0x07 };
CipherSuite TLS_RSA_EXPORT_WITH_DES40_CBC_SHA      = { 0x00,0x08 };
CipherSuite TLS_RSA_WITH_DES_CBC_SHA               = { 0x00,0x09 };
CipherSuite TLS_RSA_WITH_3DES_EDE_CBC_SHA          = { 0x00,0x0A };

next up are the server-authenticated Diffie-Hellman suites, where the client can also be authenticated, optionally ๐Ÿฆ‹ DH means the server's certificate holds the Diffie-Hellman parameters, signed by the certificate authority (CA). DHE means ephemeral Diffie-Hellman, where the parameters are signed by a DSS or RSA certificate, and that certificate has been signed by the CA โœจ the signing algorithm gets named right after the DH or DHE part. the server can request an RSA or DSS signature-capable certificate from the client for client authentication, or it may request a Diffie-Hellman certificate instead ๐ŸŒˆ and any Diffie-Hellman certificate the client sends must use the parameters (group and generator) the server described. main character energy for sure ๐Ÿ‘‘

CipherSuite TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA   = { 0x00,0x0B };
CipherSuite TLS_DH_DSS_WITH_DES_CBC_SHA            = { 0x00,0x0C };
CipherSuite TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA       = { 0x00,0x0D };
CipherSuite TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA   = { 0x00,0x0E };
CipherSuite TLS_DH_RSA_WITH_DES_CBC_SHA            = { 0x00,0x0F };
CipherSuite TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA       = { 0x00,0x10 };
CipherSuite TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA  = { 0x00,0x11 };
CipherSuite TLS_DHE_DSS_WITH_DES_CBC_SHA           = { 0x00,0x12 };
CipherSuite TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA      = { 0x00,0x13 };
CipherSuite TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA  = { 0x00,0x14 };
CipherSuite TLS_DHE_RSA_WITH_DES_CBC_SHA           = { 0x00,0x15 };
CipherSuite TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA      = { 0x00,0x16 };

then there are the completely anonymous Diffie-Hellman suites, where neither party gets authenticated ๐Ÿ™ƒ ngl this one is a red flag. it's vulnerable to man-in-the-middle attacks, so it's deprecated ๐Ÿ’€

anon means nobody checks who's who. a man-in-the-middle can absolutely walk right in. deprecated, not it ๐Ÿšซ
CipherSuite TLS_DH_anon_EXPORT_WITH_RC4_40_MD5     = { 0x00,0x17 };
CipherSuite TLS_DH_anon_WITH_RC4_128_MD5           = { 0x00,0x18 };
CipherSuite TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA  = { 0x00,0x19 };
CipherSuite TLS_DH_anon_WITH_DES_CBC_SHA           = { 0x00,0x1A };
CipherSuite TLS_DH_anon_WITH_3DES_EDE_CBC_SHA      = { 0x00,0x1B };

a few notes to finish the suite list ๐Ÿ“

Note: All cipher suites whose first byte is 0xFF are considered private and can be used for defining local/experimental algorithms. Interoperability of such types is a local matter. ๐Ÿงช

Note: Additional cipher suites can be registered by publishing an RFC which specifies the cipher suites, including the necessary TLS protocol information, including message encoding, premaster secret derivation, symmetric encryption and MAC calculation and appropriate reference information for the algorithms involved. The RFC editor's office may, at its discretion, choose to publish specifications for cipher suites which are not completely described (e.g., for classified algorithms) if it finds the specification to be of technical interest and completely specified. ๐ŸŒŸ

Note: The cipher suite values { 0x00, 0x1C } and { 0x00, 0x1D } are reserved to avoid collision with Fortezza-based cipher suites in SSL 3. ๐Ÿ”’

A.6. The Security Parameters ๐Ÿ”

these security parameters are what the TLS Handshake Protocol figures out, and then it hands them to the TLS Record Layer to set up a connection state ๐Ÿฆ‹ the SecurityParameters struct includes all of these enums and fields. the algorithm lists can grow over time, so the comment below is important ๐Ÿ‘€

enum { null(0), (255) } CompressionMethod;

enum { server, client } ConnectionEnd;

enum { null, rc4, rc2, des, 3des, des40, idea }
BulkCipherAlgorithm;

enum { stream, block } CipherType;

enum { true, false } IsExportable;

enum { null, md5, sha } MACAlgorithm;

/* The algorithms specified in CompressionMethod,
BulkCipherAlgorithm, and MACAlgorithm may be added to. */

    struct {
        ConnectionEnd entity;
        BulkCipherAlgorithm bulk_cipher_algorithm;
        CipherType cipher_type;
        uint8 key_size;
        uint8 key_material_length;
        IsExportable is_exportable;
        MACAlgorithm mac_algorithm;
        uint8 hash_size;
        CompressionMethod compression_algorithm;
        opaque master_secret[48];
        opaque client_random[32];
        opaque server_random[32];
    } SecurityParameters;

B. Glossary โœจ

Okay bestie, this is the glossary, aka the cheat sheet for all the terms. Let's get into it ๐Ÿ’…

application protocol ๐ŸŒธ Okay so an application protocol is one that normally sits right on top of the transport layer (e.g., TCP/IP). Examples are HTTP, TELNET, FTP, and SMTP. Iconic lineup, no notes ๐Ÿ™ˆ

asymmetric cipher ๐Ÿฆ‹ Just see public key cryptography. Same energy, different name.

authentication ๐Ÿ” Authentication is when one entity can figure out who another entity is. Identity check, but make it protocol-y โœจ

block cipher ๐Ÿ“ A block cipher is an algorithm that works on plaintext in chunks of bits called blocks. 64 bits is a common block size, so that's the one you'll see a lot ๐Ÿ’œ

bulk cipher ๐Ÿซถ A symmetric encryption algorithm that's used to encrypt big piles of data. Heavy lifting girl ๐Ÿ’ช

cipher block chaining (CBC) ๐Ÿงš CBC is a mode where every plaintext block gets encrypted with a block cipher, but first it gets exclusive-ORed with the previous ciphertext block. For the very first block, it gets XORed with the initialization vector instead. For decryption, every block is decrypted first, then exclusive-ORed with the previous ciphertext block (or IV). It's giving chain reaction, and I'm obsessed ๐Ÿ˜ญ

certificate ๐Ÿ“œ As part of the X.509 protocol (a.k.a. ISO Authentication framework), certificates get assigned by a trusted Certificate Authority. They make a strong binding between a party's identity, or some other attributes, and its public key. Trusted vibes only ๐Ÿ‘‘

client ๐Ÿ’– The application entity that starts a TLS connection to a server. This may or may not mean the client also started the underlying transport connection. The main operational difference between the server and the client is that the server is generally authenticated, while the client is only optionally authenticated. Server gets the verified badge, client gets the choice ๐ŸŽ€

client write key ๐Ÿ”‘ The key used to encrypt data that the client writes.

client write MAC secret ๐Ÿคซ The secret data used to authenticate data that the client writes.

connection ๐ŸŒˆ A connection is a transport (in the OSI layering model definition) that provides a suitable type of service. For TLS, these connections are peer to peer relationships. Connections are transient, and every connection is associated with one session. Here today, gone tomorrow, but make it secure โœจ

Data Encryption Standard ๐Ÿ’… DES is a very widely used symmetric encryption algorithm. It's a block cipher with a 56 bit key and an 8 byte block size. Okay, real talk: in TLS, for key generation purposes, DES is treated as having an 8 byte key length (64 bits), but it still only provides 56 bits of protection. (The low bit of each key byte is presumed to be set to produce odd parity in that key byte.) DES can also run in a mode where three independent keys and three encryptions are used for each block of data. That uses 168 bits of key (24 bytes in the TLS key generation method) and gives you the equivalent of 112 bits of security. [DES], [3DES] ๐Ÿ™ˆ

Digital Signature Standard (DSS) ๐Ÿ–Š๏ธ A standard for digital signing, including the Digital Signing Algorithm. It was approved by the National Institute of Standards and Technology and defined in NIST FIPS PUB 186, "Digital Signature Standard," published May, 1994 by the U.S. Dept. of Commerce. [DSS] ๐Ÿ›๏ธ

digital signatures โœ๏ธ Digital signatures use public key cryptography and one-way hash functions to make a signature of the data that can be authenticated. They're hard to forge or repudiate, so no sneaky backing out ๐Ÿ˜ค

handshake ๐Ÿค An initial negotiation between the client and the server that sets the parameters for their transactions. Opening conversation, very important ๐ŸŽ€

Initialization Vector (IV) ๐ŸŒธ When a block cipher is used in CBC mode, the initialization vector gets exclusive-ORed with the first plaintext block before encryption. It's the glow-up starter pack โœจ

IDEA ๐Ÿง  A 64-bit block cipher designed by Xuejia Lai and James Massey. [IDEA] ๐Ÿ‡จ๐Ÿ‡ญ

Message Authentication Code (MAC) ๐Ÿ” A Message Authentication Code is a one-way hash computed from a message and some secret data. It's difficult to forge without knowing the secret data. Its purpose is to detect if the message has been altered. Did somebody touch my message?! ๐Ÿ‘€

master secret ๐Ÿ—๏ธ Secure secret data used for generating encryption keys, MAC secrets, and IVs. The main character of the whole key situation ๐Ÿ‘‘

MD5 ๐Ÿฌ MD5 is a secure hashing function that turns an arbitrarily long data stream into a digest of fixed size (16 bytes). [MD5] ๐Ÿ’œ

public key cryptography ๐Ÿฆ‹ A class of cryptographic techniques that uses two-key ciphers. Messages encrypted with the public key can only be decrypted with the associated private key. Flip it around, and messages signed with the private key can be verified with the public key. Two keys, one vibe ๐ŸŽ€

one-way hash function ๐ŸŒ€ A one-way transformation that turns an arbitrary amount of data into a fixed-length hash. It's computationally hard to reverse the transformation or to find collisions. MD5 and SHA are examples of one-way hash functions. Literally a one-way street ๐Ÿšซ

RC2 ๐Ÿง A block cipher developed by Ron Rivest at RSA Data Security, Inc. [RSADSI], described in [RC2]. Vintage queen ๐ŸŽž๏ธ

RC4 ๐ŸŒŠ A stream cipher licensed by RSA Data Security [RSADSI]. A compatible cipher is described in [RC4]. Flowy, streamy, iconic ๐ŸŒŠ

RSA ๐Ÿš A very widely used public-key algorithm that can be used for either encryption or digital signing. [RSA] Everyone's favourite, no cap ๐Ÿซถ

salt ๐Ÿง‚ Non-secret random data used to make export encryption keys resist precomputation attacks. Sprinkle of randomness, extra spicy ๐ŸŒถ๏ธ

server ๐Ÿ–ฅ๏ธ The server is the application entity that responds to requests for connections from clients. See also under client. Ready to answer the door, always ๐Ÿšช

session ๐ŸŽฌ A TLS session is an association between a client and a server. Sessions are created by the handshake protocol. They define a set of cryptographic security parameters, which can be shared among multiple connections. Sessions exist so you don't have to renegotiate new security parameters for every single connection. Efficiency is the realest slay ๐Ÿ’…

session identifier ๐Ÿชช A session identifier is a value generated by a server that identifies a particular session. It's the name tag for the session ๐Ÿท๏ธ

server write key ๐Ÿ”‘ The key used to encrypt data that the server writes.

server write MAC secret ๐Ÿคซ The secret data used to authenticate data that the server writes.

SHA ๐ŸŒฟ The Secure Hash Algorithm is defined in FIPS PUB 180-1. It produces a 20-byte output. Note that all references to SHA actually use the modified SHA-1 algorithm. [SHA] ๐ŸŒฟ

SSL ๐Ÿ’ Netscape's Secure Socket Layer protocol [SSL3]. TLS is based on SSL Version 3.0. Big sibling energy ๐Ÿ‘‘

stream cipher ๐Ÿ’ง An encryption algorithm that converts a key into a cryptographically-strong keystream, which is then exclusive-ORed with the plaintext. Keystream goes brrr ๐ŸŒŠ

symmetric cipher ๐Ÿ” See bulk cipher. Same vibe, different outfit.

Transport Layer Security (TLS) ๐ŸŽ€ This protocol. It's also the Transport Layer Security working group of the Internet Engineering Task Force (IETF). See "Comments" at the end of this document. The name, the protocol, and the whole squad, all in one โœจ

C. CipherSuite definitions ๐Ÿ’…

okay so this is the cipher suite cheat sheet, bestie ๐ŸŽ€ Each row is one full combo of key exchange + cipher + hash. The little * means it's exportable, aka the weak-sauce ones ๐Ÿ’€

CipherSuite                      Is       Key          Cipher      Hash
                             Exportable Exchange

TLS_NULL_WITH_NULL_NULL               * NULL           NULL        NULL
TLS_RSA_WITH_NULL_MD5                 * RSA            NULL         MD5
TLS_RSA_WITH_NULL_SHA                 * RSA            NULL         SHA
TLS_RSA_EXPORT_WITH_RC4_40_MD5        * RSA_EXPORT     RC4_40       MD5
TLS_RSA_WITH_RC4_128_MD5                RSA            RC4_128      MD5
TLS_RSA_WITH_RC4_128_SHA                RSA            RC4_128      SHA
TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5    * RSA_EXPORT     RC2_CBC_40   MD5
TLS_RSA_WITH_IDEA_CBC_SHA               RSA            IDEA_CBC     SHA
TLS_RSA_EXPORT_WITH_DES40_CBC_SHA     * RSA_EXPORT     DES40_CBC    SHA
TLS_RSA_WITH_DES_CBC_SHA                RSA            DES_CBC      SHA
TLS_RSA_WITH_3DES_EDE_CBC_SHA           RSA            3DES_EDE_CBC SHA
TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA  * DH_DSS_EXPORT  DES40_CBC    SHA
TLS_DH_DSS_WITH_DES_CBC_SHA             DH_DSS         DES_CBC      SHA
TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA        DH_DSS         3DES_EDE_CBC SHA
TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA  * DH_RSA_EXPORT  DES40_CBC    SHA
TLS_DH_RSA_WITH_DES_CBC_SHA             DH_RSA         DES_CBC      SHA
TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA        DH_RSA         3DES_EDE_CBC SHA
TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA * DHE_DSS_EXPORT DES40_CBC    SHA
TLS_DHE_DSS_WITH_DES_CBC_SHA            DHE_DSS        DES_CBC      SHA
TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA       DHE_DSS        3DES_EDE_CBC SHA
TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA * DHE_RSA_EXPORT DES40_CBC    SHA
TLS_DHE_RSA_WITH_DES_CBC_SHA            DHE_RSA        DES_CBC      SHA
TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA       DHE_RSA        3DES_EDE_CBC SHA
TLS_DH_anon_EXPORT_WITH_RC4_40_MD5    * DH_anon_EXPORT RC4_40       MD5
TLS_DH_anon_WITH_RC4_128_MD5            DH_anon        RC4_128      MD5
TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA   DH_anon        DES40_CBC    SHA
TLS_DH_anon_WITH_DES_CBC_SHA            DH_anon        DES_CBC      SHA
TLS_DH_anon_WITH_3DES_EDE_CBC_SHA       DH_anon        3DES_EDE_CBC SHA

* Indicates IsExportable is True

Now the key exchange flavours, the vibes for each one โœจ

   Key
   Exchange
   Algorithm       Description                        Key size limit

   DHE_DSS         Ephemeral DH with DSS signatures   None
   DHE_DSS_EXPORT  Ephemeral DH with DSS signatures   DH = 512 bits
   DHE_RSA         Ephemeral DH with RSA signatures   None
   DHE_RSA_EXPORT  Ephemeral DH with RSA signatures   DH = 512 bits,
                                                      RSA = none
   DH_anon         Anonymous DH, no signatures        None
   DH_anon_EXPORT  Anonymous DH, no signatures        DH = 512 bits
   DH_DSS          DH with DSS-based certificates     None
   DH_DSS_EXPORT   DH with DSS-based certificates     DH = 512 bits
   DH_RSA          DH with RSA-based certificates     None
   DH_RSA_EXPORT   DH with RSA-based certificates     DH = 512 bits,
                                                      RSA = none
   NULL            No key exchange                    N/A
   RSA             RSA key exchange                   None
   RSA_EXPORT      RSA key exchange                   RSA = 512 bits

Key size limit ๐Ÿ“ gives the size of the largest public key that can be legally used for encryption in cipher suites that are exportable.

Next up, the ciphers and their stats ๐Ÿ“

                     Key      Expanded   Effective   IV    Block
 Cipher       Type  Material Key Material  Key Bits  Size   Size

 NULL       * Stream   0          0           0        0     N/A
 IDEA_CBC     Block   16         16         128        8      8
 RC2_CBC_40 * Block    5         16          40        8      8
 RC4_40     * Stream   5         16          40        0     N/A
 RC4_128      Stream  16         16         128        0     N/A
 DES40_CBC  * Block    5          8          40        8      8
 DES_CBC      Block    8          8          56        8      8
 3DES_EDE_CBC Block   24         24         168        8      8

* Indicates IsExportable is true.

  • Type ๐Ÿง: says whether it's a stream cipher or a block cipher running in CBC mode.
  • Key Material ๐Ÿ”‘: the number of bytes from the key_block that get used for generating the write keys.
  • Expanded Key Material ๐Ÿช„: the number of bytes actually fed into the encryption algorithm.
  • Effective Key Bits ๐Ÿง : how much entropy material is in the key material being fed into the encryption routines.
  • IV Size ๐ŸŽฒ: how much data needs to be generated for the initialization vector. It's zero for stream ciphers, and equal to the block size for block ciphers.
  • Block Size ๐Ÿงฑ: the amount of data a block cipher enciphers in one chunk. A block cipher running in CBC mode can only encrypt an even multiple of its block size.

And finally, the hash functions, plus their sizes and padding ๐ŸŒธ

  Hash      Hash      Padding
function    Size       Size
  NULL       0          0
  MD5        16         48
  SHA        20         40

D. Implementation Notes ๐Ÿ› ๏ธ

okay real talk, the TLS protocol literally cannot stop a lot of the common security mistakes ๐Ÿ˜ญ so this section is full of tips to help implementors not mess up. Read it, bestie ๐Ÿซถ

D.1. Temporary RSA keys ๐Ÿ”

US Export restrictions limit RSA keys used for encryption to 512 bits, but they don't put any limit on the lengths of RSA keys used for signing operations. Certificates often need to be larger than 512 bits, since 512-bit RSA keys are not secure enough for high-value transactions or for applications that need long-term security. Some certificates are also designated signing-only, which means they cannot be used for key exchange.

When the public key in the certificate cannot be used for encryption, the server signs a temporary RSA key, and that key is then exchanged. In exportable applications, the temporary RSA key should be the maximum allowable length (i.e., 512 bits). Because 512-bit RSA keys are relatively insecure, they should be changed often. For typical electronic commerce applications, it is suggested that keys be changed daily or every 500 transactions, and more often if possible. Note that while it is acceptable to use the same temporary key for multiple transactions, it must be signed each time it is used.

RSA key generation is a time-consuming process, so in many cases a low-priority process can be assigned the task of key generation ๐Ÿข

Whenever a new key is completed, the existing temporary key can be replaced with the new one โœจ

D.2. Random Number Generation and Seeding ๐ŸŽฐ

TLS requires a cryptographically-secure pseudorandom number generator (PRNG). Care must be taken in designing and seeding PRNGs. PRNGs based on secure hash operations, most notably MD5 and/or SHA, are acceptable, but they cannot provide more security than the size of the random number generator state. (For example, MD5-based PRNGs usually provide 128 bits of state.)

To estimate the amount of seed material being produced, add up the number of bits of unpredictable information in each seed byte. For example, keystroke timing values taken from a PC compatible's 18.2 Hz timer provide 1 or 2 secure bits each, even though the total size of the counter value is 16 bits or more. To seed a 128-bit PRNG, one would thus require approximately 100 such timer values.

Warning: The seeding functions in RSAREF and versions of BSAFE prior to 3.0 are order-independent. For example, if 1000 seed bits are supplied, one at a time, in 1000 separate calls to the seed function, the PRNG will end up in a state which depends only on the number of 0 or 1 seed bits in the seed data (i.e., there are 1001 possible final states). Applications using BSAFE or RSAREF must take extra care to ensure proper seeding. This may be accomplished by accumulating seed bits into a buffer and processing them all at once, or by processing an incrementing counter with every seed bit; either method will reintroduce order dependence into the seeding process. ๐Ÿšจ

D.3. Certificates and authentication ๐Ÿชช

Implementations are responsible for verifying the integrity of certificates, and they should generally support certificate revocation messages. Certificates should always be verified to ensure proper signing by a trusted Certificate Authority (CA). The selection and addition of trusted CAs should be done very carefully. Users should be able to view information about the certificate and the root CA ๐Ÿ‘€

D.4. CipherSuites ๐Ÿง

TLS supports a range of key sizes and security levels, including some which provide no or minimal security. A proper implementation will probably not support many cipher suites. For example, 40-bit encryption is easily broken, so implementations requiring strong security should not allow 40-bit keys. Similarly, anonymous Diffie-Hellman is strongly discouraged because it cannot prevent man-in-the-middle attacks. Applications should also enforce minimum and maximum key sizes. For example, certificate chains containing 512-bit RSA keys or signatures are not appropriate for high-security applications ๐Ÿ”ฅ

E. Backward Compatibility With SSL ๐ŸŽ€

okay bestie, for historical reasons (and so we don't burn through reserved port numbers like they're free ๐Ÿ’…), application protocols secured by TLS 1.0, SSL 3.0, and SSL 2.0 all frequently share the same connection port. Like, https (HTTP secured by SSL or TLS) uses port 443 no matter which security protocol it's actually running ๐Ÿ™ˆ So some mechanism must be determined to tell the protocols apart and negotiate between them. Main character problem, honestly ๐Ÿ˜ญ

TLS version 1.0 and SSL 3.0 are super similar, so supporting both is easy ๐Ÿซถ TLS clients who want to negotiate with SSL 3.0 servers should send client hello messages using the SSL 3.0 record format and client hello structure, and put {3, 1} in the version field to note that they support TLS 1.0. If the server only supports SSL 3.0, it will respond with an SSL 3.0 server hello. If it supports TLS, it responds with a TLS server hello. The negotiation then carries on however is appropriate for the protocol that got picked โœจ

It's the same energy the other way around. A TLS server that wants to play nice with SSL 3.0 clients should accept SSL 3.0 client hello messages and respond with an SSL 3.0 server hello if it gets an SSL 3.0 client hello with a version field of {3, 0}, which basically means "hey, this client doesn't do TLS" ๐Ÿ’€

Whenever a client already knows the highest protocol a server supports (like when it's resuming a session), it should start the connection in that native protocol ๐Ÿฆ‹

TLS 1.0 clients that want to support SSL Version 2.0 servers must send SSL Version 2.0 client hello messages [SSL2]. TLS servers should accept either client hello format if they want to support SSL 2.0 clients on the same connection port. The only deviations from the Version 2.0 specification are being able to specify a version with a value of three, and supporting more ciphering types in the CipherSpec ๐ŸŒˆ

Warning: The ability to send Version 2.0 client hello messages will be phased out with all due haste. Implementors should make every effort to move forward as quickly as possible. Version 3.0 provides better mechanisms for moving to newer versions. ๐Ÿšจ

The following cipher specifications are carryovers from SSL Version 2.0. These are assumed to use RSA for key exchange and authentication ๐Ÿ“

    V2CipherSpec TLS_RC4_128_WITH_MD5          = { 0x01,0x00,0x80 };
    V2CipherSpec TLS_RC4_128_EXPORT40_WITH_MD5 = { 0x02,0x00,0x80 };
    V2CipherSpec TLS_RC2_CBC_128_CBC_WITH_MD5  = { 0x03,0x00,0x80 };
    V2CipherSpec TLS_RC2_CBC_128_CBC_EXPORT40_WITH_MD5
                                               = { 0x04,0x00,0x80 };
    V2CipherSpec TLS_IDEA_128_CBC_WITH_MD5     = { 0x05,0x00,0x80 };
    V2CipherSpec TLS_DES_64_CBC_WITH_MD5       = { 0x06,0x00,0x40 };
    V2CipherSpec TLS_DES_192_EDE3_CBC_WITH_MD5 = { 0x07,0x00,0xC0 };

Cipher specifications native to TLS can be included in Version 2.0 client hello messages using the syntax below. Any V2CipherSpec element with its first byte equal to zero will be ignored by Version 2.0 servers. Clients sending any of the above V2CipherSpecs should also include the TLS equivalent (see Appendix A.5) ๐Ÿงš

    V2CipherSpec (see TLS name) = { 0x00, CipherSuite };

E.1. Version 2 client hello

The Version 2.0 client hello message is shown below using this document's presentation model. The true definition is still assumed to be the SSL Version 2.0 specification ๐Ÿ“œ

    uint8 V2CipherSpec[3];

    struct {
        uint8 msg_type;
        Version version;
        uint16 cipher_spec_length;
        uint16 session_id_length;
        uint16 challenge_length;
        V2CipherSpec cipher_specs[V2ClientHello.cipher_spec_length];
        opaque session_id[V2ClientHello.session_id_length];
        Random challenge;
    } V2ClientHello;

msg_type This field, together with the version field, identifies a version 2 client hello message. The value should be one (1) ๐Ÿ”ฅ

version The highest version of the protocol the client supports (equals ProtocolVersion.version, see Appendix A.1) ๐Ÿ’–

cipher_spec_length This field is the total length of the field cipher_specs. It cannot be zero and must be a multiple of the V2CipherSpec length (3) โœจ

session_id_length This field must have a value of either zero or 16. If it's zero, the client is creating a new session. If it's 16, the session_id field will contain the 16 bytes of session identification ๐ŸŒธ

challenge_length The length in bytes of the client's challenge to the server, used so the server can authenticate itself. This value must be 32 ๐Ÿฆ‹

cipher_specs This is a list of all CipherSpecs the client is willing and able to use. There must be at least one CipherSpec acceptable to the server ๐Ÿ‘‘

session_id If this field's length is not zero, it will contain the identification for a session the client wants to resume ๐Ÿซถ

challenge The client challenge to the server (so the server can identify itself) is a (nearly) arbitrary length random. The TLS server will right justify the challenge data to become the ClientHello.random data (padded with leading zeroes, if necessary), as specified in this protocol specification. If the length of the challenge is greater than 32 bytes, only the last 32 bytes are used. It is legitimate (but not necessary) for a V3 server to reject a V2 ClientHello that has fewer than 16 bytes of challenge data ๐ŸŒˆ

Note: Requests to resume a TLS session should use a TLS client hello ๐Ÿ’…

E.2. Avoiding man-in-the-middle version rollback

When TLS clients fall back to Version 2.0 compatibility mode, they should use special PKCS #1 block formatting. This is done so that TLS servers will reject Version 2.0 sessions with TLS-capable clients. This part is lowkey so important ๐Ÿ˜ญ๐Ÿ”’

When TLS clients are in Version 2.0 compatibility mode, they set the right-hand (least-significant) 8 random bytes of the PKCS padding (not including the terminal null of the padding) for the RSA encryption of the ENCRYPTED-KEY-DATA field of the CLIENT-MASTER-KEY to 0x03 (the other padding bytes are random). After decrypting the ENCRYPTED-KEY-DATA field, servers that support TLS should issue an error if these eight padding bytes are 0x03. Version 2.0 servers receiving blocks padded in this manner will proceed normally ๐Ÿ™ˆ


F. Security analysis ๐Ÿ›ก๏ธ

The TLS protocol is designed to establish a secure connection between a client and a server communicating over an insecure channel. This document makes several traditional assumptions, including that attackers have substantial computational resources and cannot obtain secret information from sources outside the protocol. Attackers are assumed to be able to capture, modify, delete, replay, and otherwise tamper with messages sent over the communication channel. Yikes, the villain arc is real ๐Ÿ’€ This appendix outlines how TLS has been designed to resist a variety of attacks ๐Ÿ’ช

F.1. Handshake protocol

The handshake protocol is responsible for selecting a CipherSpec and generating a Master Secret, which together make up the primary cryptographic parameters for a secure session. The handshake protocol can also optionally authenticate parties who have certificates signed by a trusted certificate authority ๐ŸŽ€

F.1.1. Authentication and key exchange

TLS supports three authentication modes: authentication of both parties, server authentication with an unauthenticated client, and total anonymity. Whenever the server is authenticated, the channel is secure against man-in-the-middle attacks, but completely anonymous sessions are inherently vulnerable to such attacks. Anonymous servers cannot authenticate clients. If the server is authenticated, its certificate message must provide a valid certificate chain leading to an acceptable certificate authority. Similarly, authenticated clients must supply an acceptable certificate to the server. Each party is responsible for verifying that the other's certificate is valid and has not expired or been revoked ๐Ÿ”

The general goal of the key exchange process is to create a pre_master_secret known to the communicating parties and not to attackers. The pre_master_secret will be used to generate the master_secret (see Section 8.1). The master_secret is required to generate the certificate verify and finished messages, encryption keys, and MAC secrets (see Sections 7.4.8, 7.4.9 and 6.3). By sending a correct finished message, parties thus prove that they know the correct pre_master_secret ๐Ÿซถ

F.1.1.1. Anonymous key exchange

Completely anonymous sessions can be established using RSA or Diffie-Hellman for key exchange. With anonymous RSA, the client encrypts a pre_master_secret with the server's uncertified public key extracted from the server key exchange message. The result is sent in a client key exchange message. Since eavesdroppers don't know the server's private key, it will be infeasible for them to decode the pre_master_secret. (Note that no anonymous RSA Cipher Suites are defined in this document) ๐Ÿง

With Diffie-Hellman, the server's public parameters are contained in the server key exchange message and the client's are sent in the client key exchange message. Eavesdroppers who don't know the private values should not be able to find the Diffie-Hellman result (i.e. the pre_master_secret) ๐ŸŒ™

Warning: Completely anonymous connections only provide protection against passive eavesdropping. Unless an independent tamper-proof channel is used to verify that the finished messages were not replaced by an attacker, server authentication is required in environments where active man-in-the-middle attacks are a concern. ๐Ÿšจ

F.1.1.2. RSA key exchange and authentication

With RSA, key exchange and server authentication are combined. The public key may be either contained in the server's certificate or may be a temporary RSA key sent in a server key exchange message. When temporary RSA keys are used, they are signed by the server's RSA or DSS certificate. The signature includes the current ClientHello.random, so old signatures and temporary keys cannot be replayed. Servers may use a single temporary RSA key for multiple negotiation sessions ๐Ÿ”‘

Note: The temporary RSA key option is useful if servers need large certificates but must comply with government-imposed size limits on keys used for key exchange ๐ŸŒธ

After verifying the server's certificate, the client encrypts a pre_master_secret with the server's public key. By successfully decoding the pre_master_secret and producing a correct finished message, the server demonstrates that it knows the private key corresponding to the server certificate โœจ

When RSA is used for key exchange, clients are authenticated using the certificate verify message (see Section 7.4.8). The client signs a value derived from the master_secret and all preceding handshake messages. These handshake messages include the server certificate, which binds the signature to the server, and ServerHello.random, which binds the signature to the current handshake process ๐Ÿฆ‹

F.1.1.3. Diffie-Hellman key exchange with authentication

Okay so with Diffie-Hellman key exchange ๐Ÿ’…, the server can either hand over a certificate with fixed Diffie-Hellman parameters, or it can use the server key exchange message to send a set of temporary Diffie-Hellman parameters signed with a DSS or RSA certificate โœจ. The temporary parameters get hashed with the hello.random values before signing, so attackers can't just replay old parameters ๐Ÿ™…โ€โ™€๏ธ. Either way, the client can check the certificate or signature to make sure the parameters actually belong to the server ๐Ÿซถ.

If the client has a certificate with fixed Diffie-Hellman parameters, that certificate has everything it needs to finish the key exchange ๐ŸŽ€. Heads up though: the client and server will end up with the same Diffie-Hellman result (aka pre_master_secret) every single time they talk ๐Ÿ˜ญ. So the pre_master_secret should get turned into the master_secret as soon as possible, so it doesn't hang around in memory longer than it needs to ๐Ÿงน. Also, the client's Diffie-Hellman parameters have to be compatible with the ones the server supplied, or the key exchange won't work ๐Ÿ’œ.

If the client has a standard DSS or RSA certificate, or it's unauthenticated, it sends a set of temporary parameters to the server in the client key exchange message ๐Ÿฆ‹. After that, it can optionally use a certificate verify message to authenticate itself ๐ŸŒธ.

F.1.2. Version rollback attacks

Okay this one's giving sneaky ๐Ÿ‘€. TLS is a huge glow-up from SSL Version 2.0 โœจ, so attackers may try to trick TLS-capable clients and servers into falling back to Version 2.0. This can happen if and only if two TLS-capable parties use an SSL 2.0 handshake ๐Ÿ™ˆ.

The fix uses non-random PKCS #1 block type 2 message padding. It's kinda inelegant, ngl ๐Ÿ˜…, but it's a reasonably secure way for Version 3.0 servers to detect the attack ๐Ÿ›ก๏ธ. It's not totally bulletproof though ๐Ÿ’€: this solution isn't secure against attackers who can brute force the key and swap in a new ENCRYPTED-KEY-DATA message that has the same key (but with normal padding) before the application specified wait threshold has expired. If you're worried about attacks at that scale, you should not be using 40-bit encryption keys anyway ๐Ÿ™…โ€โ™€๏ธ.

Messing with the padding on the least-significant 8 bytes of the PKCS padding doesn't affect security for the signed hash sizes and RSA key lengths used in the protocol ๐Ÿง . That's because it's basically the same as increasing the input block size by 8 bytes โœจ.

F.1.3. Detecting attacks against the handshake protocol

Attackers might try to influence the handshake so the parties pick different encryption algorithms than they'd normally choose ๐Ÿ˜ˆ. This one's a big deal, because many implementations support 40-bit exportable encryption, and some may even support null encryption or MAC algorithms ๐Ÿ’€.

To pull this off, the attacker has to actively change one or more handshake messages ๐Ÿ•ต๏ธ. If that happens, the client and server compute different values for the handshake message hashes, so they won't accept each other's finished messages ๐Ÿ™…. And since the attacker doesn't have the master_secret, they can't repair the finished messages, so the attack gets caught ๐Ÿ™Œ.

F.1.4. Resuming sessions

When a connection is set up by resuming a session, the new ClientHello.random and ServerHello.random values get hashed with the session's master_secret โœจ. As long as the master_secret hasn't been compromised, and the secure hash operations used to produce the encryption keys and MAC secrets are secure, the connection should be secure and effectively independent from previous connections ๐Ÿฆ‹. Attackers can't use known encryption keys or MAC secrets to compromise the master_secret without breaking the secure hash operations (which use both SHA and MD5) ๐Ÿ”.

Sessions can't be resumed unless both the client and server agree ๐Ÿค. If either party suspects the session may have been compromised, or that certificates may have expired or been revoked, it should force a full handshake ๐Ÿ”„. An upper limit of 24 hours is suggested for session ID lifetimes ๐Ÿ•, since an attacker who obtains a master_secret may be able to impersonate the compromised party until the corresponding session ID is retired ๐Ÿ˜ฑ. Applications that may run in relatively insecure environments should not write session IDs to stable storage ๐Ÿšซ.

F.1.5. MD5 and SHA

TLS uses hash functions super conservatively ๐Ÿง. Where possible, MD5 and SHA are used in tandem, so non-catastrophic flaws in one algorithm won't break the overall protocol ๐Ÿ’ช.

F.2. Protecting application data

The master_secret gets hashed with the ClientHello.random and ServerHello.random to make unique data encryption keys and MAC secrets for each connection ๐Ÿ”‘.

Outgoing data is protected with a MAC before it's transmitted ๐Ÿ›ก๏ธ. To prevent message replay or modification attacks, the MAC is computed from the MAC secret, the sequence number, the message length, the message contents, and two fixed character strings ๐Ÿงฉ. The message type field makes sure messages meant for one TLS Record Layer client don't get redirected to another ๐ŸŽฏ. The sequence number means attempts to delete or reorder messages will be detected ๐Ÿ‘€. Since sequence numbers are 64-bits long, they should never overflow ๐Ÿ™Œ. Messages from one party can't be inserted into the other's output, since they use independent MAC secrets ๐Ÿšง. Similarly, the server-write and client-write keys are independent, so stream cipher keys are only used once ๐Ÿ”.

If an attacker does break an encryption key, every message encrypted with it can be read ๐Ÿ˜ฑ. Similarly, compromising a MAC key can make message modification attacks possible ๐Ÿ’€. Because MACs are also encrypted, message-alteration attacks generally require breaking the encryption algorithm as well as the MAC ๐Ÿ›ก๏ธ.

Note: MAC secrets may be larger than encryption keys, so messages can remain tamper resistant even if encryption keys are broken.

F.3. Final notes

For TLS to provide a secure connection, both the client and server systems, keys, and applications must be secure ๐Ÿ”’. On top of that, the implementation must be free of security errors ๐Ÿ›.

The system is only as strong as the weakest key exchange and authentication algorithm supported ๐Ÿ”—, and only trustworthy cryptographic functions should be used ๐Ÿ’…. Short public keys, 40-bit bulk encryption keys, and anonymous servers should be used with great caution โš ๏ธ. Implementations and users must be careful when deciding which certificates and certificate authorities are acceptable, because a dishonest certificate authority can do tremendous damage ๐Ÿ˜ญ๐Ÿ’€.

G. Patent Statement

Some of the cryptographic algorithms proposed for use in this protocol have patent claims on them ๐Ÿ“œ. In addition, Netscape Communications Corporation has a patent claim on the Secure Sockets Layer (SSL) work that this standard is based on ๐Ÿฆ‹. The Internet Standards Process, as defined in RFC 2026, requests that a statement be obtained from a Patent holder indicating that a license will be made available to applicants under reasonable terms and conditions ๐Ÿค.

The Massachusetts Institute of Technology has granted RSA Data Security, Inc., exclusive sub-licensing rights to the following patent issued in the United States:

Cryptographic Communications System and Method ("RSA"), No. 4,405,829

Netscape Communications Corporation has been issued the following patent in the United States:

Secure Socket Layer Application Program Apparatus And Method ("SSL"), No. 5,657,390

Netscape Communications has issued the following statement:

Intellectual Property Rights Secure Sockets Layer The United States Patent and Trademark Office ("the PTO") recently issued U.S. Patent No. 5,657,390 ("the SSL Patent") to Netscape for inventions described as Secure Sockets Layers ("SSL"). The IETF is currently considering adopting SSL as a transport protocol with security features. Netscape encourages the royalty-free adoption and use of the SSL protocol upon the following terms and conditions: - If you already have a valid SSL Ref license today which includes source code from Netscape, an additional patent license under the SSL patent is not required. - If you don't have an SSL Ref license, you may have a royalty free license to build implementations covered by the SSL Patent Claims or the IETF TLS specification provided that you do not to assert any patent rights against Netscape or other companies for the implementation of SSL or the IETF TLS recommendation. What are "Patent Claims": Patent claims are claims in an issued foreign or domestic patent that: 1. must be infringed in order to implement methods or build products according to the IETF TLS specification; or 2. patent claims which require the elements of the SSL patent claims and/or their equivalents to be infringed.

The Internet Society, Internet Architecture Board, Internet Engineering Steering Group and the Corporation for National Research Initiatives take no position on the validity or scope of the patents and patent applications, nor on the appropriateness of the terms of the assurance ๐Ÿง. The Internet Society and the other groups mentioned above haven't made any determination about any other intellectual property rights that may apply to the practice of this standard ๐Ÿคทโ€โ™€๏ธ. Any further consideration of these matters is the user's own responsibility ๐Ÿซถ.

Security Considerations ๐Ÿ”

Security issues are discussed throughout this memo ๐Ÿ’€โœจ.

References โœจ

Okay bestie, this is the bibliography, and honestly the reading list is where the real receipts live ๐Ÿ“š๐Ÿ’…

  • [3DES] W. Tuchman, "Hellman Presents No Shortcut Solutions To DES," IEEE Spectrum, v. 16, n. 7, July 1979, pp40-41.
  • [BLEI] Bleichenbacher D., "Chosen Ciphertext Attacks against Protocols Based on RSA Encryption Standard PKCS #1" in Advances in Cryptology -- CRYPTO'98, LNCS vol. 1462, pages: 1--12, 1998.
  • [DES] ANSI X3.106, "American National Standard for Information Systems-Data Link Encryption," American National Standards Institute, 1983.
  • [DH1] W. Diffie and M. E. Hellman, "New Directions in Cryptography," IEEE Transactions on Information Theory, V. IT-22, n. 6, Jun 1977, pp. 74-84.
  • [DSS] NIST FIPS PUB 186, "Digital Signature Standard," National Institute of Standards and Technology, U.S. Department of Commerce, May 18, 1994.
  • [FTP] Postel J., and J. Reynolds, "File Transfer Protocol", STD 9, RFC 959, October 1985.
  • [HTTP] Berners-Lee, T., Fielding, R., and H. Frystyk, "Hypertext Transfer Protocol -- HTTP/1.0", RFC 1945, May 1996.
  • [HMAC] Krawczyk, H., Bellare, M., and R. Canetti, "HMAC: Keyed-Hashing for Message Authentication," RFC 2104, February 1997.
  • [IDEA] X. Lai, "On the Design and Security of Block Ciphers," ETH Series in Information Processing, v. 1, Konstanz: Hartung-Gorre Verlag, 1992.
  • [MD2] Kaliski, B., "The MD2 Message Digest Algorithm", RFC 1319, April 1992.
  • [MD5] Rivest, R., "The MD5 Message Digest Algorithm", RFC 1321, April 1992.
  • [PKCS1] RSA Laboratories, "PKCS #1: RSA Encryption Standard," version 1.5, November 1993.
  • [PKCS6] RSA Laboratories, "PKCS #6: RSA Extended Certificate Syntax Standard," version 1.5, November 1993.
  • [PKCS7] RSA Laboratories, "PKCS #7: RSA Cryptographic Message Syntax Standard," version 1.5, November 1993.
  • [PKIX] Housley, R., Ford, W., Polk, W. and D. Solo, "Internet Public Key Infrastructure: Part I: X.509 Certificate and CRL Profile", RFC 2459, January 1999.
  • [RC2] Rivest, R., "A Description of the RC2(r) Encryption Algorithm", RFC 2268, January 1998.
  • [RC4] Thayer, R. and K. Kaukonen, A Stream Cipher Encryption Algorithm, Work in Progress.
  • [RSA] R. Rivest, A. Shamir, and L. M. Adleman, "A Method for Obtaining Digital Signatures and Public-Key Cryptosystems," Communications of the ACM, v. 21, n. 2, Feb 1978, pp. 120-126.
  • [RSADSI] Contact RSA Data Security, Inc., Tel: 415-595-8782
  • [SCH] B. Schneier. Applied Cryptography: Protocols, Algorithms, and Source Code in C, Published by John Wiley & Sons, Inc. 1994.
  • [SHA] NIST FIPS PUB 180-1, "Secure Hash Standard," National Institute of Standards and Technology, U.S. Department of Commerce, Work in Progress, May 31, 1994.
  • [SSL2] Hickman, Kipp, "The SSL Protocol", Netscape Communications Corp., Feb 9, 1995.
  • [SSL3] A. Frier, P. Karlton, and P. Kocher, "The SSL 3.0 Protocol", Netscape Communications Corp., Nov 18, 1996.
  • [TCP] Postel, J., "Transmission Control Protocol," STD 7, RFC 793, September 1981.
  • [TEL] Postel J., and J. Reynolds, "Telnet Protocol Specifications", STD 8, RFC 854, May 1993.
  • [TEL] Postel J., and J. Reynolds, "Telnet Option Specifications", STD 8, RFC 855, May 1993.
  • [X509] CCITT. Recommendation X.509: "The Directory - Authentication Framework". 1988.
  • [XDR] R. Srinivansan, Sun Microsystems, RFC-1832: XDR: External Data Representation Standard, August 1995.

Credits ๐Ÿ’–

Huge shoutout to Win Treese from Open Market for the credits, bestie ๐Ÿซถ

  • Win Treese, Open Market, EMail: treese@openmarket.com

Editors ๐ŸŽ€

The editors were Christopher Allen and Tim Dierks, both from Certicom. Iconic duo ๐Ÿ‘‘

Christopher Allen                  Tim Dierks
Certicom                           Certicom

EMail: callen@certicom.com         EMail: tdierks@certicom.com

Authors' Addresses ๐ŸŒธ

These are the authors and where to find them ๐Ÿ’Œ

Tim Dierks                         Philip L. Karlton
Certicom                           Netscape Communications

EMail: tdierks@certicom.com
Alan O. Freier                     Paul C. Kocher
Netscape Communications            Independent Consultant

EMail: freier@netscape.com         EMail: pck@netcom.com

Other contributors ๐Ÿงš

So many brilliant people helped out, and they all deserve their flowers ๐ŸŒท

Martin Abadi                       Robert Relyea
Digital Equipment Corporation      Netscape Communications

EMail: ma@pa.dec.com               EMail: relyea@netscape.com

Ran Canetti                        Jim Roskind
IBM Watson Research Center         Netscape Communications

EMail: canetti@watson.ibm.com      EMail: jar@netscape.com

Taher Elgamal                      Micheal J. Sabin, Ph. D.
Securify                           Consulting Engineer

EMail: elgamal@securify.com        EMail: msabin@netcom.com

Anil R. Gangolli                   Dan Simon
Structured Arts Computing Corp.    Microsoft

EMail: gangolli@structuredarts.com EMail:  dansimon@microsoft.com

Kipp E.B. Hickman                  Tom Weinstein
Netscape Communications            Netscape Communications

EMail: kipp@netscape.com           EMail: tomw@netscape.com

Hugo Krawczyk
IBM Watson Research Center

EMail: hugo@watson.ibm.com

Comments ๐Ÿ’ฌ

The IETF TLS working group has a discussion list where you can chat about all things TLS. Subscribing info is on the group's site too, so go join the conversation โœจ


Copyright (C) The Internet Society (1999). All Rights Reserved.

Here's the legal bit, and it's important, so read it carefully ๐Ÿ™ˆ

This document and translations of it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this paragraph are included on all such copies and derivative works. However, this document itself may not be modified in any way, such as by removing the copyright notice or references to the Internet Society or other Internet organizations, except as needed for the purpose of developing Internet standards in which case the procedures for copyrights defined in the Internet Standards process must be followed, or as required to translate it into languages other than English.

The limited permissions granted above are perpetual and will not be revoked by the Internet Society or its successors or assigns.

This document and the information contained herein is provided on an "AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.

๐Ÿ“ฆ where this page comes from