Security in Computer Networks
===
###### tags: `Notes`, `Computer Networks`, `Networks`
## Symmetric Key Cryptography
### 1. Caesar Cipher
* Fixed mapping following a pattern
* 25 possible key values
*Example:*
```
k = 2
Plaintext: a b c ..... z
Ciphertext: c d e ..... b
```
### 2. Monoalphabetic Cipher
* Fixed mapping but randomly decided for each letter
* 26! possible key values
*Example:*
```
Plaintext: a b c d ..... z
Ciphertext: m n b v ..... p
```
Easily prone to attacks in the following ways:
* Ciphertext-only attack: Intruder has access to only the ciphertext and not the original message. Using statistical analysis the intruder can break the code.
* Known-plaintext attack: Intruder knows some of the plaintext-ciphertext pairings
* Chosen-plaintext attack: Intruder choses the plaintext message to obtain the ciphertext and can break the code
### 3. Polyalphabetic Cipher
```
Plaintext: a b c d ..... z
C1(k=5): f g h i ..... e
C2(k=19): t u v w ..... s
```
* Ciphers are chosen in repeating patterns, for instance, C1, C2, C2, C1, C2.
* This ensures that there will be different ciphertext for the same plaintext message
#### There are two broad categories of Symmetric Key Cryptography:
1. Block Ciphers
2. Stream Ciphers
---
### Block Cipher
* Input is divided into k-bit blocks
* A function is used to further divide the k-bit blocks into n-bit chunks
* Each chunk is processed through n-bit to n-bit table T
* Output of these chunks is reassembled to k-bit block
* This output is then run through a scrambler which scrambles the position of bits in the k-bit block
* The result of this scrambled block is then fed as input to the k-bit input for the next cycles
The key for this block cipher algorithm is the n-bit to n-bit permutation table. It is assumed that the scramble function is publicly known.
*An algorithm's key determines the specific mini-table mappings and permutations within the algorithm's internals.*
*Examples of popular block ciphers:* DES (Data Encryption Standard), 3DES and AES(Advanced Encryption Standard)
**Number of possible mappings for k-block cipher: (2^k)!**
### Cipher-Block Chaining
```
m(i) = ith plaintext block
c(i) = ith ciphertext block
Ks = block-cipher encryption algorithm with key S
r(i) = random k-bit number for ith block
^ = symbol for XOR
c(i) = Ks(m(i) ^ r(i))
```
* Sender sends c(i) and r(i) to receiver
* Receiver decrypts m(i) using `m(i) = Ks(c(i) ^ r(i))`
This method ensures that the same cipher value is not generated for same input message as long as the random numbers for those chosen blocks are different.
*Problem:* Alice has to send c(i) and r(i) to Bob in order to communicate. This causes 2x bandwidth to send a message.
*Solution:* Chaining!
* Before encrypting the message sender generates a random k-bit string called **Initialization Vector(IV)** c(0).
* Sender calculates m(1) ^ c(0) i.e. COR of first block of clear text. This result is run through the cipher-block algorithm to get `c(1) = Ks(m(1) ^ c(0))`. Sender sends c(1) to the receiver.
* For the ith block, the sender sends `Ks(m(i) ^ c(i-1))`
* Receiver gets `s(i) = Ks(m(i) ^ c(i-1))`. Since the receiver also knows `c(i-1)`, it can get the original message by doing `m(i) = s(i) ^ c(i-1)`
**Benefits:**
* Even if two identical clear text blocks are sent to the receiver the cipher will be different
* Although the sends sends IV in cleartext, the intruder will not be able to decrypt the cipher block because he/she does not know the secret key S
### Problem with using symmetric keys: *There should be a secure way to share the symmetric key*
---
## Public Key Encryption
* Public key (Kb+) and Private key (Kb-) for Bob
* Public key is exposed to everyone and Private key is only with Bob
* Alice encrypts her message with Bob's public key: `Kb+(m)` and sends it to Bob.
* Bob decrypts it with his private key: `m = Kb-(Kb+(m))`
#### Problems with public key encryption:
1. Trudy can mount a chosen plain-text attack using Bob's public key and the known encryption algorithm to encode any message she chooses.
2. Bob's public key is can be used by anyone to send an encrypted message to Bob pretending to be Alice.
### RSA
Algorithm for public key cryptography. There are two components of RSA:
1. Choice of public key and private key
Steps to choose the keys are as follows:
1. Take two very large prime numbers `p` and `q`
2. Compute `n = pq` and `z = (p-1)(q-1)`
3. Find a value `e < n` such that `e` does not have any common factors with `z` except 1. This value "e" will be used for encryption
4. Find a value `d` such that `ed - 1` is exactly divisible by `z` i.e. `ed mod z = 1`. This value "d" will be used for decryption
5. The number pair (n, e) is the public key (Kb+) and the number pair (n, d) is the private key (Kb-)
2. Encryption and Decryption algorithm:
Suppose Alice wants to send a message(m) to Bob. The message is represented as the integer value of the bit representation of the message.
Following steps are performed for encryption and decryption:
1. Encode the message with Bob's public key: `c = (m^e mod n)`
2. This cipher is sent to Bob
3. Bob decrypts the message by using his private key: `m = (c^d mod n)`
### Why RSA works?
```
m is always less than n
c = (m^e mod n)
=> (m^e mod n)^d mod n = m^ed mod n [From modulo properties]
=> m^ed mod n = m^(ed mod z) mod n
=> m mod n [As (ed mod z) = 1]
=> m [As m < n]
Therefore (c^d mod n) = (m^e mod n)^d mod n = m
```
### Drawbacks of RSA
RSA is a computationally intensive algorithm and hence takes a lot of time to encrypt and decrypt. Hence, it is used in conjunction with any other symmetric key encryption algorithm such as DES or AES.
It is used in the distribution of the **session key** that is used to encode the data and is shared between the two parties involved in the communication.
* Alice encrypts the session key with Bob's public key
* Bob receives the RSA encrypted session key and decrypts it with his private key
---
## Wireless LAN
### WEP (Wired Equivalent Privacy)
* It is assumed that the symmetric key is shared with the AP out-of-band.
* Uses the **RC4 algorithm** for encryption
#### WEP encryption algorithm
* Ks = 40 bit symmetric key that both client and AP know.
* 24 bit initialization vector (IV) is appended to the 40 bit key to make it 64 bit key
* Since IV will change for every frame, a differnt 64 bit key will be used for every frame
* 4 byte CRC is calculated for data payload
* Payload and CRC are encrypted using RC4 stream cipher
```
ci = di ^ ki(IV) //encryption
di = ci ^ ki(IV) //decryption
```
* IV is appended to the frame in plaintext followed by the WEP encrypted data + CRC

#### Problems with WEP
For a given symmetric key there are only 2^24 values for IV that can be possible. This means that the IV will repeat when the number of frames are larege. Therefore, an attacker can launch a known plaintext attack and get the messages.
### WPA/WPA2 (WiFi Protected Access)
* Uses **RC4 encryption algorithm** but with better key management
Two most critical security issues to handle:
* *Mutual Authentication*: Client needs to verify the identity of the AP and the AP needs to verify the identity of the wireless client
* *Encryption:* 802.11 frames need to sent in an encrypted manner over the link layer. Symmetric key encryption/decryption is used for faster performance.
Example of WPA/WPA2 - PSK (without Auth server)
![Uploading file..._3d55kvmtc]()
### WPA/WPA2 - Enterprise ( implementing EAP - Extensible Authentication Protocol)
* Uses **AES encryption algorithm**
*Authentication Server:* responsible for authenticating the client. Can be co-located with the AP but is usually separate. The AP relays auth and key derivation messages between client and AS. An AS provides authentication for all APs within its network.
Four phases of mutual auth and encryption-key derivation:
1. *Discovery:* AP advertises to all the devices in its range and shares the authentication and encryption forms it can support. A client requests a specific form of authentication and encryption it desires.
2. *Mutual authentication and shared symmetric key derivation:* Most critical step in securing the 802.11 channel. It is assumed that the client and the AS have a **shared common secret**. This is used along with **nonces** and **cryptographic hashing** for authentication. They will also derive the **shared session key** to encrypt the frames to be sent over the 802.11 link.
3. *Shared symmetric key distribution:* The **shared session key** derived by the client and AS is shared with the AP.
4. *Encrypted communication between two wireless hosts via AP:* Communication happens between hosts via AP using the shared session key with **AES** symmetric key cyrptography.
#### 802.11 Security Messaging Protocols
* EAP messages are encapsulated using EAPoL (EAP over LAN) and sent over 802.11 wireless link.
* EAP messages are decapsulated at AP then re-encapsulated using RADIUS protocol to be sent over UDP/IP to the auth server.
Authentication and key exchange for EAP:

---
## Authentication and Key Agreement (AKA) in Mobile Networks
* Mobile device(M) and base station(BS) will need to derive a shared symmetric encryption key to encrypt contents transmitted over wireless channel.
* Mobile and Network need to mutually authenticate each other
* A shared secret key is know to be present between M and HSS K<sub>HSS-M</sub>.
* A session key is derived during network attachment between M and BS K<sub>BS-M</sub>
### Steps in the AKA protocol:
1. *Authentication request to HSS:* Mobile device sends an attach request to the base station to connect. It is forwarded to the Mobility Management Entity(MME) which in turn forwards it to Home Subscriber Service(HSS) along with the IMSI(International Mobile Subscriber Identity) number and VN (Visited Networks) information.
2. *Authentication response from HSS:* HSS will perform cyrptographic functions using K<sub>HSS-M</sub> to compute the **auth token** (example: *K<sub>HSS-M</sub>(IMSI)*) and an expcted response **xres<sub>HSS</sub>**. This pair is given to the MME which keeps the xres<sub>HSS</sub> and forwards the auth token to the mobile device.
3. *Authentication response from mobile device:* M will compute K<sub>HSS-M</sub>(K<sub>HSS-M</sub>(IMSI)) to derive the auth token thus authenticating HSS. Using the secret key, the mobile device then generates **res<sub>M</sub>** using the same cryptographic function used by HSS to calculate *res<sub>HSS</sub>*. It sends this value to MME
4. *Mobile device authentication:* MME compares *xres<sub>HSS</sub>* and *xres<sub>M</sub>*. If they are equal, the mobile device is authenticated. MME informs the BS that mobile is authenticated and sends to the BS the keys to use for key derivation.
5. *Data plane and Contol plane key derivation:* M and BS will determine keys to be used for encrypting/decrypting their frames over the wireless channel. Separate keys will be used for data plane and control plane.

---
## Hyper Text Transfer Protocol (HTTP)
### Overview
* HTTP is Web's application layer protocol
* Client and server communicate with HTTP messages. HTTP defines the structure of these messages.
* Web page consists of objects such as file, image etc. If web page has 5 images and text, that page has six objects
* Base HTML file references other objects in the page with a URL
* URL has two components: *hostname* and *path*
* Browser is the client which implements client side of HTTP and Web Server is the server and implements server side of HTTP
**General idea of client server interaction:**
1. Client requests for a web page to the web server by sending an *HTTP request*
2. Server responds to the client with an *HTTP response* containing the objects that constitute that web page.
* HTTP uses TCP as the underlying transport layer protocol. So the requests from client arrive at the server in order and the response from the server arrives in order at the client.
* HTTP is a **stateless** protocol i.e. it does not keep track of the responses it has sent to the clients.
### Non Persistent and Persistent Connections
If all of the requests and their corresponding responses are sent and received over the same TCP connection, it is called a **persistent connection**.
If each of the request and corresponding response is send over separate TCP connections, it is called a **non-persistent connection**.
#### HTTP with Non-Persistent Connection
Let's say the client wants to see a webpage having a hase HTML file and 10 JPEG images and all these objects on the same server.
1. HTTP client initiates TCP connection with server on port 80. There will be a client socket and server socket created respectively.
2. HTTP client sends an HTTP request to the server via it socket and sends the path name in the request along with the hostname
3. Server receives the request and fetches the object from the path in the server. It encapsulates the object in an HTTP response message and sends it to the client via its socket.
4. Server process tries to close the TCP connection but will not happen immediately until the server is sure that all the packets have been sent on TCP to the client.
5. HTTP client receives the response. TCP connection is terminated. Client extracts file from the response message and examines the HTML file.
6. Steps 1 - 4 are repeated for all the other objects.
In the above process 11 TCP connections are created and closed corresponding to the 11 objects of the HTML page.
The time taken for one request-response is **2RTTs + transmission time**. i.e. TCP Handshake + Request-Response cycle + time to transmit the file from the server to the client.
**Drawbacks:**
1. New TCP connection has to established for every request
2. Waste of resoureces such as buffers and variables that TCP allocates at both client and server for every connection
3. Time taking as each object suffers *2RTT + transmission time* delay.
#### HTTP with Persistent Connections
* HTTP/1.1 introduced persistent connections where a TCP connection can be kept open and all the objects in that server can be served through the same connection
* These requests can be made back to back without waiting for replies for the pending reqeusts. This is called **pipelining**
* Connection closes if it is not used for a certain amount of time
* By default, HTTP/1.1 uses persistent connections with pipelining
* HTTP/2 introduced multiple requests and replies to be interleaved in the same connection and a mechanism to prioritize HTTP requests and responses within this connection.
### HTTP Message Format
#### HTTP Request Format

```
GET /some/path/index.html HTTP/1.1
Host: www.someurl.com
Connection: close
User-agent: Mozilla/5.0
Accept-language: en
```
***Method:*** examples of method are GET, POST, PUT, DELTE, HEAD, PATCH. GET is used when the browser is requesting an object from the server. **Entity body** is empty for a GET request. For a POST request entity body contains values that the programmer wishes to send to the server. When HEAD method is used, the server resonds to the request without having the object sent to the client. Ususally developers use HEAD to debug.
***Host:*** Host on which the object resides
***Connection***: *close* indicates non-persistent TCP connection. *keep-alive* indicates persistent connection.
***User-agent:*** shows the web browser that the client is using to make this reqeust
***Accept-language:*** the language in which the page needs to be shown. Default is english.
#### HTTP Response Format

```
HTTP/1.1 200 OK
Connection: close
Date: Wed, 6 Apr 2022 08:00:00 GMT
Server: Apache/2.2.3 (CentOS)
Last-Modified: Wed, 4 Apr 2022 18:23:46 GMT
Content-Length: 6821
Content-Type: text/html
(data data data data data ......)
```
***Header Line***: Version of HTTP, status code and phrase
***Connection:*** *close* indicates non-persistent TCP connection. *keep-alive* indicates persistent connection.
***Date:*** date when the response was sent by the server
***Server:*** server name and OS running on that server that has responded to the request
***Last-Modified:*** date and time when the object on that server was created or last modified
***Content-Length:*** size of the object being sent
***Content-Type:*** type of object being sent examples are text/html, text/csv, image/jpeg, application/json etc
**Some status codes:**
* ***200 OK:*** Request succeeded and a success response is returned
* ***301 Moved Permanently:*** URL has moved to the location mentioned in the *Location:* header field. Client will redirect automatically
* ***400 Bad Request:*** Request not understood by server
* ***404 Not Found:*** Requested object does not exist on the server
* ***505 HTTP Verion Not Supported:*** Requested protocol version is not supported by the server
### Cookies
Four components of cookie technology:
1. Cookie header line in HTTP response
2. Cookie header line in HTTP request
3. Cooke file kept on the user's computer and managed by the user's browser
4. A backend database at the website

* Cookies can be used to identify a user
* Cookies store information about the user that the web server can retrieve at a later request and cater to the user thigs of their interest
* Cookie can be used to create user-session layer on top of stateless HTTP
* Some consider cookies as an invasion of their privacy
### Web Caching (Proxiy Server)
* A **web cache** is also called **proxy server**
* It serves the HTTP request on behalf of an origin web server
**How it works:**
1. Browser establishes a TCP connection with the proxy server and then sends the HTTP request to it
2. Web cache checks to see if it has a copy of the object stored locally. If yes, it responds to the cliend with the HTTP response containing that object
3. If the web cache does not have that objec then it creates a TCP connection with the origin server, makes an HTTP reqeust to the origin server and then fetches the object from the origin server. It creates a copy of that object and sends the object as an HTTP response to the client over the existing TCP connection between client and proxy server.
**Advantages:**
1. It can substantially reduce the response time for the client request
2. It can reduce traffic on an institution's access link to the internet. This also ensures that there will not be a need to constantly upgrade bandwith for the institution thereby reducing costs
3. It can reduce web traffic in the internet as a whole
**Problem:**
By using a web cache it is possible that stale objects might be served to the client since the objects are cached by the proxy server. To tacke this problem, **Conditional GET** request can be sent to the web cache.
*First Request by Client:*
```
GET /fruit/kiwi.gif HTTP/1.1
Host: www.someurl.com
```
*Response by Web Cache:*
```
HTTP/1.1 200 OK
Connection: keep-alive
Date: Wed, 6 Apr 2022 08:00:00 GMT
Server: Apache/2.2.3 (CentOS)
Last-Modified: Wed, 4 Apr 2022 18:23:46 GMT
Content-Length: 6821
Content-Type: image/gif
(data data data data data ......)
```
**One week later**
*Conditional GET by client: *
```
GET /fruit/kiwi.gif HTTP/1.1
Host: www.someurl.com
If-modified-since: Wed, 4 Apr 2022 18:23:46 GMT
```
*Proxy Server Response:*
```
HTTP/1.1 304 Not Modified
Date: Wed, 13 Apr 2022 08:00:00 GMT
Server: Apache/2.2.3 (CentOS)
(empty entity body)
```
**Note:** The *If-modified-since* will have the same date as the *Last-Modified* sent by server one week ago. If the object has not been modified then server returns 304 with empty body.
### HTTP/2
The ability to break down an HTTP header into independent frames, interleave them and reassemble them on the other end is the most important feature of HTTP/2.
Goals of HTTP/2:
* Reduce latencies by enabling request/response multiplexing in a single TCP connection
* Request prioritization
* Server push
* Efficient compression of HTTP header fields
HTTP/2 does not change the header fields, status codes, URLs etc. It changes how data is formatted and transported between client and server
**Motivation:**
HTTP/1.1 provided persistent connections but also introduced the problem of **Head Of Line (HOL) blocking**. When a large number of objects are requested by the client then sometimes a bottleneck is created where one file takes too long to be transmitted over TCP. HTTP/1.1 circumvented this problem by allowing multiple parallel TCP connections to be open and then diverted the traffic of sending other small objects in those parallel connections. TCP congestion provides incentives to the parallel TCP connections by giving each of them 1/n<super>th</super> of the bandwith. By doing so, the many HTTP/1.1 browsers opened up multiple parallel TCP connections not just to circumvent HOL blocking but to obtain bandwidth as well.
HTTP/2 aims to get rid of parallel TCP connections. This reduces number of sockets to be opened for every request and also allows TCP congestion control to work as expected.
#### HTTP/2 Framing
* Framing is done by *framing sub-layer*
* When server wants to send an HTTP response, the response is processed by the framing sublayer where it is broken down into frames
* Header field is one frame and body is broken into additional frames
* Frames of responses are interleaved by framing sublayer with frames of other responses and send over single TCP connection
* As frames arrive at client, they are first reassembled into original response at the framing sublayer and then processed by the browser as usual
#### Response Message Prioritization
* Developers can prioritize the request to optimize the application performance
* When a client sends multiple requests to the server, it can assign a weight to the request ranging from a number between 1 and 256. Higher number = Higher priority
* Using these weights the server can send frames for responses with higher priority
* Client can also set dependency of one request on another by specifying the ID of the message on which it depends
#### Server Pushing
* Provides the ability for the server to push a response to the client without the client having to request for one.
* For example, the server can analyze the base HTML page and identify the objects that will be needed to load that page in the client. The sever can then send those objects to the client without having to wait for the client to request for those objects. This reduces the latency caused by waiting for a request.
### HTTP/3
* HTTP/3 was designed to operate over the QUIC protocol. It is essentially HTTP/2 but on QUIC
### QUIC (Quick UDP Internet Connections)
* QUIC is an application layer protocol using UDP as it underlying transport layer protocol
* In the near future HTTP/3 will natively incorporate QUIC
**Features of QUIC:**
1. ***Connection-oriented and secure:*** QUIC is a connection oriented protocol between two endpoints. Two pieces of connection state are the source and destination connection ID. QUIC combines the handshake required to establish the connection and the handshake required for authentication and encryption. This makes it faster than HTTP1.1 where two RTTs are requied to establish the TCP connection and then establish the TLS connection as well.
2. ***Streams:*** QUIC allows multiple application level streams to multiplex through a single QUIC connection. A stream is an abstraction for **reliable, in-order, bi-directional** data delivery between two QUIC endpoints. In context of HTTP/3, every object would have its own stream. Each connection has a connectio ID and each stream having a connection has a stream ID which are contained in the QUICK packet header. Data from multiple streams may be contained in a single QUIC connection and sent over UDP. The Stream Control Trasmission Protocol is responsible for multiplexing multiple streams through a single QUIC connection
3. ***Reliable, TCP Friendly, Congestion Controllerd Data Transfer:*** QUIC provides reliable data transfer to each QUIC stream separately. In HTTP/1.1 if multiple requests arrive in the same TCP connection, they are received in order and served in order. This means that if one segment is lost then all the other TCP segments will not be served until data from the lost segment is retransmitted. This causes the **HOL blocking** problem. On the other hand, QUIC provides reliable data transfer for every stream. If one of the UDP segments do not arrive then only those streams are affected whose data did not arrive in that segment. The rest of the streams will be delivered to the application. QUIC's congestion control is based on TCP New Reno (slight modification to TCP Reno)