---
# System prepended metadata

title: HW 3 SS

---

# HW 3 SS

# 1


To check for the max cache for the tcp syn backlog, the following command is executed.
![](https://i.imgur.com/YVjnKAs.png)



Before any attack is launched, `netstat -na` returns the following after a telnet connection:

![](https://i.imgur.com/DPD1oY1.png)


It can be seen that there is 1 established tcp connection from 10.0.2.6 connected to port 23. This is the current connection from the client machine. Currently, there are no syn flood attacks happening.

When syn cookie is not active:

![](https://i.imgur.com/j4Wn2f7.png)

Attacker attacks the server (victim) machine with a syn flood attack which can be seen from the packet sniffer. The command used is 
```
sudo netwox 76 -i 10.0.2.5 -p 23 -s raw
```
(which basically calls out the netwox synflood tool):
![](https://i.imgur.com/hnxcbkL.png)

![](https://i.imgur.com/vDjC82I.png)
This shows that using the netwox synflood tool, the attacker is able to continuously send out syn packets to the victim htrough random IP Addresses.


Server receives a `SYN_RECV` status from the attacker from different IPs
![](https://i.imgur.com/XIprcVh.png)

![](https://i.imgur.com/1giYlPb.png)

Client trying to connect to the server again.
![](https://i.imgur.com/sAwe5qV.png)
The Screenshot shows that the client times out in trying to connect to the server. This is because the continuous barrage of syn packets create a state where the server drops the packet and doesn't allow for the client (our true machine) to be connected since server machine does not have the capacity to host the connection since it has received so many new connection from random IPs (though it is just randomly generated)

When syn cookie is active:

![](https://i.imgur.com/eq9eIA1.png)


Attacker can still launch a syn flood attack as seen in the following:
![](https://i.imgur.com/KH5zuvv.png)

However, it is limited to the cookies value (128 in this case).

![](https://i.imgur.com/4IQVLc1.png)


Client can still connect when syn cookie is active without timing out. This is because the syn cookie feature prevents the syn flood attack. In particular, the use of SYN cookies allows a server to avoid dropping connections when the SYN queue fills up. This allows for the client (our true machine) to connect without the telnet packet being dropped.

![](https://i.imgur.com/zdNJIty.png)


The way SYN Cookies solves SYN Flood attack problem is to use a function that uses some information from the client’s SYN packet and some information from server-side to calculate a random initial sequence number. Let us assume this number as y-1, y-1 is sent to the client in an SYN + ACK message. If an ACK packet is received with a sequence number y, with the help of some packet header fields and some server-side information, a reverse function can verify that acknowledgement number is valid. If it is valid, a TCB is created and a connection is established. If it is invalid, the connection is refused. The advantage of SYN cookies is that the server doesn’t have to create and store a TCB upon reception of the SYN segment.

# 2

```python=
import os
import sys

import random
import pandas as pd
from pprint import pprint


import ssl
import urllib
from OpenSSL import crypto # pip install pyopenssl
import pydig #check for DNSSEC

import dns.resolver
from socket import socket
from OpenSSL.SSL import TLSv1_METHOD, Context, Connection


def test():
    #Printing simple SSL cert to try 
    url = 'https://google.com'
    addr = urllib.parse.urlsplit(url).hostname
    port = 443
    cert = ssl.get_server_certificate((addr, port)) #if cert exists and no error means SSL exists
    
    return cert, addr, type(cert)

def get_CAA(domain):
     '''
     Function to get CAA
     '''
     answers = dns.resolver.resolve(domain, 'CAA')
     for rdata in answers:
         return (rdata.value.decode('UTF-8'))


def read_csv():
    '''
    Function to read the csv and returns the sample websites.

    Args:

    - None

    Returns

    - result : dict
    '''
    dir_path = os.path.dirname(os.path.realpath(__file__))
    filename = os.path.join(dir_path, 'files', 'top-1m.csv')
    df = pd.read_csv(filename, header=None)

    website_dict = dict( df.iloc[:, -1] )

    samples = random.sample(range(1, len(website_dict)), 200)
    samples.sort()
    #pprint(dict( df.iloc[:, -1] ))

    result = {}

    for s in samples:
        result[ s ]= website_dict[s]

    return result

def check_signature(results):
    '''
    Function to check for port 443

    Args:
    - results : dict

    Returns:
    - None : Saves a file in the folder
    '''
    port = 443
    dir_path = os.path.dirname(os.path.realpath(__file__))
    output_filename = os.path.join(dir_path, 'files', 'HW3Q2_Results.csv')
    df = pd.DataFrame(columns = ['idx', 'website', 'SSL', 'DNSSEC', 'CA', 'CAA'])

    for idx, website in results.items():
        row = []
        url = f'https://{website}'

        # Get server cert if no server cert then will go into exception
        try:
            addr = urllib.parse.urlsplit(url).hostname
            cert = ssl.get_server_certificate((addr, port))
            cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)
            print(f" {website} SSL: {cert}")
            issuer = cert.get_issuer()
            CA = issuer.get_components()
            print(f"{website} CA is: {CA}")
        except:
            cert = None
            CA = None
            print(f"No SSL cert for {website}")
            print(f"No CA for  {website}")

        # Get CAA
        try:
            caa = get_CAA(url)
            print(f"The website : {website}is in CAA: {caa}")
        except:
            caa = None
            print(f"There is no CAA for {website}")

        dnssec = pydig.query(website, "A")
        if dnssec == []:
            dnssec = None
            print("No DNSSEC")
        else:   
            print(f"The DNSSEC is: {dnssec}")

        row_append = [idx, website, cert, dnssec, CA, caa]

        df.loc[len(df)] = row_append

        print('-' * 80 )
    df.to_csv(output_filename)

def main():
    print('*' * 30)
    cert, addr, tcert = test()
    print('Testing : ', cert, addr)
    results = read_csv()
    pprint(results)

    print('*' *30)

    check_signature(results)
    print('*' * 30)

    print('FINISHED')


if __name__ == '__main__':
    main()
```

#### SSL query
```
cert = ssl.get_server_certificate((addr, port))
cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert)

-----------------------------------

If there is no SSL, an error will be returned. 
If there is an SSL, object 
<OpenSSL.crypto.X509 object at 0x7fa641907e80> will be returned. 
```
##### DNSSEC

```
pydig.query (python equivalent of dig) 

-----------------------------------

If address is returned, means DNSSEC is present. 
If empty list is returned, then there is no DNSSEC

```


#### CA

```
issuer = cert.get_issuer()
CA = issuer.get_components()
-----------------------------------
Same as SSL, name of CA will be returned. 
If there are no components then an error will be returned. 

```



Sample Output:

![](https://i.imgur.com/naooHbJ.png)



OUTPUT CSV:

https://drive.google.com/file/d/1m6IutEibkZj3w393tp8zeGTV4fig5r2W/view?usp=share_link
