## 0. What is TLS and why does it matter
Transport Layer Security (TLS)
- Confidentiality
- Integrity
- Authentication (w/ mTLS powered by client certificates)
## 1. Brief History of the Internet
- **1960s**: ARPANET origins, connecting a few academic institutions.
- **1983**: Introduction of **TCP/IP**, which formed the basis for the modern Internet.
- **1990s**: Web expansion, focus on data security (confidentiality, integrity and authentication) emerged.
- **1995**: **SSL 2.0** was introduced to secure online communications.
- **Late 1990s - 2000s**: **TLS 1.0** succeeded SSL, improving security.
## 2. Cryptography: Public and Private Key Crypto
- **Symmetric vs Asymmetric Encryption**:
- **Symmetric**: Same key used for encryption and decryption. Simple but less secure for communication.
- **Asymmetric (Public/Private Key)**: Uses a **public key** to encrypt data and a **private key** to decrypt it. This is the core of secure internet communications.
- **How Asymmetric Encryption Works**:
- **Public Key**: Available to everyone to encrypt messages.
- **Private Key**: Only known to the owner for decryption.
- **Use Case**: Digital signatures and secure key exchange.
Mermaid Diagram to Show Key Exchange:
```mermaid
sequenceDiagram
participant A as Client (Alice)
participant B as Server (Bob)
A->>B: Send Public Key
B->>A: Encrypt Data with Public Key
A->>A: Decrypt Data with Private Key
```
## 3. TLS/SSL
- **TCP/IP and the OSI Model**:
- **OSI Model**: A conceptual framework used to understand network interactions in seven layers: **Physical**, **Data Link**, **Network**, **Transport**, **Session**, **Presentation**, and **Application**.
- **TCP/IP**: A suite of communication protocols used to interconnect network devices on the internet. It consists of four layers: **Link**, **Internet**, **Transport**, and **Application**.
- **Data is segmented at the transport layer**: When a message or data is ready to be sent from an application, TCP breaks the data into smaller segments called packets. Each packet includes a header containing information like sequence numbers and error-checking data.
- **Data is encapsulated at the internet layer**: TCP segments are then encapsulated into IP packets. Each packet receives an IP header containing source and destination IP addresses, making it possible to route the packets through different networks.
- **Packets are transmitted over the network interface layer**: The IP packets are further encapsulated into frames suitable for the physical network (e.g., Ethernet frames) and are then transmitted over the network.
- **Routing occurs at the internet layer**: As packets move through various routers on their way to the destination, each router reads the destination IP address and forwards the packets to the next hop in the network path.
- **Reassembly and error checking**: At the destination, the receiving TCP layer reassembles the packets in the correct order using sequence numbers and checks for any errors. If a packet is missing or corrupted, TCP requests a retransmission.
- **Data is delivered to the application**: After reassembling and verifying the packets, TCP sends the data to the application that requested it.
- **TLS** works at the **Transport Layer (Layer 4)** in the OSI model, providing secure communication between client and server.
![[Pasted image 20241016145445.png]]
- **X.509v3 Certificates**:
- Digital documents that use **public key infrastructure** (PKI) to establish identity and trust.
- Consist of information like **subject (CN or SAN)**, **issuer (self or CA)**, **validity period**, **public key**, etc.
- **TLS Handshake**:
- **TCP Connection Establishment**: Before TLS can begin, TCP first establishes a connection using a process called the three-way handshake:
- The client sends a `SYN` packet to the server, requesting a connection.
- The server responds with a `SYN-ACK` packet.
- The client sends an `ACK` packet, confirming the connection.
At this point, a reliable TCP connection is established, ready for data exchange.
- **TLS Handshake**: Once the TCP connection is established, the TLS handshake begins to secure the connection. During this handshake:
- **ClientHello**: The client sends a message to the server, listing supported encryption algorithms (cipher suites) and TLS versions.
- **ServerHello**: The server responds with its chosen cipher suite and sends its digital certificate (containing the server’s public key) to the client.
- **Certificate Validation**:
- After receiving the server's certificate during the TLS handshake, the client extracts the CN and SAN fields.
- The client compares the domain name or IP address it is trying to connect to (e.g., `example.com`) with the values in the CN and SAN fields.
- If the domain or IP matches any of the values in the SAN list (or the CN if SAN is absent), the validation succeeds.
- If there is no match, the client will reject the certificate, typically resulting in an error like "hostname does not match the certificate."
- The client verifies the server’s certificate against trusted Certificate Authorities (CAs). This step ensures that the client is communicating with the intended server.
- The client checks that the server’s certificate is signed by an intermediate CA.
- It then verifies that this intermediate CA is, in turn, signed by a higher-level CA, and so on, until it reaches a root CA.
- The client must already have a copy of the root CA’s certificate in its trusted certificate store (typically pre-installed by operating systems or browsers).
- Each certificate in the chain is validated in order:
- The client checks the signatures on each certificate to ensure that they match the issuer's public key.
- It also verifies that the certificates are not expired and that they are not revoked (via mechanisms like OCSP or CRL).
- If any part of this chain is missing or cannot be validated, the handshake fails, and the connection is not established.
- **Key Exchange**: The client generates a pre-master secret (a random key) and encrypts it using the server’s public key, then sends it to the server. Only the server can decrypt this pre-master secret with its private key.
- **Session Keys Generation**: Both the client and server use the pre-master secret to generate symmetric encryption keys, which will be used for encrypting and decrypting the actual data exchanged in the session.
- **Secure Data Transmission**: After the handshake, both parties have generated symmetric keys for encryption. The client and server use these keys to encrypt and decrypt the data they exchange:
- Data is encrypted on the client side and sent over the established TCP connection.
- The server decrypts the data using the shared session key and responds with encrypted data.
- **Integrity Checks**: TLS includes mechanisms like HMAC (Hash-based Message Authentication Code) to ensure that data has not been tampered with during transmission. If data is modified in transit, the integrity check will fail, and the packet will be considered invalid.
- During a TLS session, each encrypted message sent between the client and the server includes an HMAC.
- The client and server share a symmetric key derived during the TLS handshake, which is used as the key for HMAC.
- The sender (either client or server) computes the HMAC over the data they are about to send and appends the HMAC to the message.
- The recipient (either server or client) decrypts the message and recomputes the HMAC using the same key. If the computed HMAC matches the one sent with the message, the data is considered intact and untampered.
- This ensures that any tampering or data corruption during transit is detected, as the HMACs will not match if the data is altered.
- **Session Closure**: Once the communication is finished, either party can initiate a closure, and the TCP connection is gracefully closed.
```mermaid
sequenceDiagram
participant Client
participant Server
Note over Client,Server: TCP Connection Establishment
Client->>Server: SYN (TCP connection request)
Server->>Client: SYN-ACK (TCP acknowledgment)
Client->>Server: ACK (TCP connection established)
Note over Client,Server: TLS Handshake Begins
Client->>Server: ClientHello (Cipher suites, TLS version)
Server->>Client: ServerHello (Chosen cipher suite, TLS version)
Server->>Client: Certificate (Server's digital certificate)
Note over Client: Certificate Validation
Client->>Client: Validate CN/SAN with domain/IP
alt CN/SAN Valid
Client->>Client: Verify certificate chain with root CA
alt Certificate chain valid
Client->>Server: Pre-master secret (Encrypted with server's public key)
Note over Client,Server: Key Exchange and Session Keys Generation
Client->>Client: Generate session keys
Server->>Server: Generate session keys
else Certificate chain invalid
Client->>Client: Reject certificate, terminate connection
end
else CN/SAN Invalid
Client->>Client: Reject certificate, terminate connection
end
Note over Client,Server: Secure Data Transmission
Client->>Server: Encrypted data (using session keys)
Server->>Client: Encrypted data (using session keys)
Note over Client,Server: Integrity Checks with HMAC
Client->>Server: HMAC-validated encrypted message
Server->>Client: HMAC-validated encrypted message
alt Integrity check fails
Client->>Server: Request data retransmission
end
Note over Client,Server: Session Closure
Client->>Server: FIN (Close connection request)
Server->>Client: FIN-ACK (Acknowledge close)
Client->>Server: ACK (Connection closed)
```
- **Common Encryption Algorithms Used in TLS**:
- **AES (Advanced Encryption Standard)**: A symmetric encryption algorithm commonly used for encrypting data during TLS sessions.
- **RSA (Rivest-Shamir-Adleman)**: Often used during the handshake for key exchange and digital signatures.
- **ECDHE (Elliptic Curve Diffie-Hellman Ephemeral)**: Provides perfect forward secrecy during the key exchange process.
- **ChaCha20-Poly1305**: An alternative to AES, often used in environments where AES hardware acceleration is not available, providing both encryption and integrity.
## 4. mTLS (Mutual TLS)
- **What is mTLS?**:
- In **mTLS**, both client and server authenticate each other using X.509 certificates.
- Used not only for securing communication (data encryption and integrity) but as a form of authenticating clients with the server.
- **How it works**:
- Both client and server present certificates during the TLS handshake.
- Each verifies the other's certificate using trusted CAs.
## 5. Practical Guides
## Using OpenSSL to Create Certificates:
- Generate a Private Key:
```sh
openssl genrsa -out private_key.pem 2048
```
- Create a Self-Signed Certificate:
```sh
openssl req -x509 -new -nodes -key private_key.pem -sha256 -days 365 -out self_signed_cert.pem
```
### Create a CA and Issue Certificates
- Create CA Private Key:
```sh
openssl genrsa -out ca_key.pem 2048
```
- Create CA Certificate:
```sh
openssl req -x509 -new -key ca_key.pem -days 3650 -out ca_cert.pem
```
- Issue a Certificate:
```sh
openssl x509 -req -in server.csr -CA ca_cert.pem -CAkey ca_key.pem -CAcreateserial -out server_cert.pem -days 365 -sha256
```
### Create Client Certificates
- Generate CSR for Client:
```sh
openssl req -new -key client_key.pem -out client.csr
```
- Issue Client Certificate:
```sh
openssl x509 -req -in client.csr -CA ca_cert.pem -CAkey ca_key.pem -CAcreateserial -out client_cert.pem -days 365 -sha256
```
- Validating Certificates:
```sh
openssl verify -CAfile ca_cert.pem server_cert.pem
```
### Requesting ACME Certificates with Certbot
- Install Certbot (Ubuntu Example):
```sh
sudo apt install certbot
```
- Generate Certificate for Domain:
- Host validation can either be done with HTTP or DNS
- HTTP: The CA will communicate with a web server host via port 80 (initiated by the ACME client) during the issuance process to validate host control
- DNS: The ACME client will create a txt record on the target domain and the CA will do a DNS query to validate the value to prove domain control
```sh
sudo certbot certonly --standalone -d example.com
```
- Automatic Certificate Renewal:
```sh
sudo certbot renew
```
- Inspect remote host certificate:
```sh
openssl s_client -connect <host>:<port>
```
- Save fullchain certificate from remote host:
```sh
openssl s_client -connect <host>:<port> -showcerts </dev/null 2>/dev/null | awk '/BEGIN/,/END/{ if(/BEGIN/){a++}; out="cert"a".pem"; print >out}' | cat cert*.pem > fullchain.pem
```
# Resources
- [**Cheatsheet for implementing TLS**](https://cheatsheetseries.owasp.org/cheatsheets/Transport_Layer_Security_Cheat_Sheet.html)