---
# System prepended metadata

title: HW 1 System Security

---

# HW 1 System Security

## 1

### 1.1

- Minimum Exposure:
    - Information about the non matching password (`check` function) is exposed. The length of the password is exposed as well as the left-most incorrect byte by the `check` function.
    - Returning messages indicating for errors on the length and the index exposes information about password, hence violating the minimum exposure principle.
- Tracability:
    - None of the errors are logged and documented, which makes the attempts to guess the password untraceable, therefore violating the traceability principle.
- Complete Mediation:
    - Checking the password length and the index is not monitored or controlled, therefore violating the complete mediation principle.


### 1.2 

```python=
import os
import random

'''
Default Class
'''
class BlackBox(object):
	def __init__(self):
		len_ = random.randint(100, 1000)
		self._passwd = os.urandom(len_)

	def check(self, user_passwd):
		if len(user_passwd) != len(self._passwd):
			return "Error:len"

		for i in range(len(user_passwd)):
			if user_passwd[i] != self._passwd[i]:
				return "Error:idx:%d" % i
		return "OK"


def check_pw_length(bb_pw):
	'''
	Find the password length
	'''

	# Generate a string of length 100 - 1000 ( assuming this is given )
	for i in range(100, 1001):
		len_check = os.urandom(i)

		if bb_pw.check(len_check) != "Error:len":
			return i

def brute_force(bb_pw, pw_len):
	pw_list = [0] * pw_len 

	for i in range(pw_len):
		byte_correct = False
		while not byte_correct:
			pw_int = int.from_bytes(pw_list, byteorder='big')
			pw_guess = pw_int.to_bytes(pw_len, byteorder='big')

			result = bb_pw.check(pw_guess)
			if f"Error:idx:{i}" in result:
				pw_list[i] += 1

			else:
				byte_correct = True

	return result, pw_guess

def main():
	blackbox_pw = BlackBox()
	pw_len = check_pw_length(blackbox_pw)
	print(f'Guessing length of password : {pw_len}, Actual length of password : {len(blackbox_pw._passwd)}')

	result, pw_guess = brute_force(blackbox_pw, pw_len)


	print(f'Guessed password : {pw_guess} and the results is {result}')



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

##### Result:

```
Guessing length of password : 146, Actual length of password : 146
Guessed password : b'!,\x00\xce\x9c\xb5ajN\xc4\x08\xa9\x82(\xe6\xa8s}\xa4\x07\xf4\xf9\x02\xd2E\x1f\xc4\xcc\xc7|\xb4O\xf4RN\x0b\xc6\x0cC~\x8dr\xe5\xbf\x12~\x1a\xc6\x89\xcd\x16H$\x03\xaag]?\x0b\x02cu\x9e\x0f\x80\xe0~A\x88\xeb\xf6Q\x9b*\x17\x00\xeb\xafy\xd1<\x90\xe5\xa7#$\xc8\xcd\x16\x1b\x8b+\x04\x1f\xdc`A\xb4\x9d\x81\xfe\xa6\x18v\xce\x82d\xa9R\xc9\xfb\xdcxk\xe1\x0b\xf98\x0e\x95^\xda\xfch\x98\x07\x89\xcc\x16\x14\xa4\x18\x8e\xa9\xae\x89JsPQfJ\xee2\xb2\x82' and the results is OK
```



### 1.3a

- No information about what is wrong should be displayed to the users or guessers ( Prevents brute-force as well as minimising exposure ). 
- Loggings and counters on how many tries should be created in order to check for unusal failures and errors.
- Program should go to sleep to reduce time avaiable for brute force attacks.


### 1.3b

```python=
import os
import random
from time import sleep


class SecureBlackBox(object):
	def __init__(self):
		self._error = 0
		len_ = random.randint(100, 1000)
		self._passwd = os.urandom(len_)

	def check(self, user_passwd):
		filename = 'log.txt'
		if user_passwd == self._passwd:
			self._error = 0

			if os.path.isfile(filename):
				with open('log.txt', 'w+') as f:
					f.write(f'Password Correct.\n')
			else:
				with open('log.txt', 'a+') as f:
					f.write(f'Password Correct.\n')
			return "OK"

		elif self._error >= 3:
			# Pause the program to control bruteforce attacks
			print(f"Too many consecutive errors. Please wait {self._error * 10} seconds before trying again.")            
			sleep(10 * self._error)
			
			self._error += 1

			if os.path.isfile(filename):
				with open('log.txt', 'w+') as f:
					f.write(f'Too many errors, Error : {self._error}, Tried with : {user_passwd}\n')
			else:
				with open('log.txt', 'a+') as f:
					f.write(f'Too many errors, Error : {self._error}, Tried with : {user_passwd}\n')
			return "Error."

		# 2 or fewer consecutive errors => return simple "Error" message
		else:
			if os.path.isfile(filename):
				with open('log.txt', 'w+') as f:
					f.write(f'Error : {self._error}, Tried with : {user_passwd}\n')
			else:
				with open('log.txt', 'a+') as f:
					f.write(f'Error : {self._error}, Tried with : {user_passwd}\n')
			self._error += 1
			return "Error."
```

## 2

```python=
import os

def get_username(uid, passwd):
    for line in passwd:
        data = line.split(':')
        if int(data[2]) == uid:
            return data[0]
    return None

def get_password_hash(username, shadow):
    for line in shadow:
        data = line.split(':')
        if data[0] == username:
            return data[1]
    return None


if __name__ == "__main__":
    with open("/etc/passwd", 'r') as f:
        passwd = [line.strip() for line in f.readlines()]
    with open("/etc/shadow", 'r') as f:
        shadow = [line.strip() for line in f.readlines()]
    
    uid = os.getuid()
    username = get_username(uid, passwd)
    print(get_password_hash(username, shadow))
```

The python code opens and reads from both `/etc/passwd` and `/etc/shadow`, then gets the uid of the current process. It then correlates the uid with the username in the `/etc/passwd` file, and looks for that username in `/etc/shadow` to obtain the hash of the user.


## 3


Linux mechanism that keeps docker isolated:

- AppArmor security profiles for Docker
    - AppArmor is a Linux security module that provides a way to restrict the actions that a program can perform on the system. AppArmor profiles define the permissions that a program has, such as which files it can access and which system calls it can execute. By restricting the actions of a program, AppArmor helps to reduce the attack surface of the system and increase security. Docker can use AppArmor to restrict the actions that a container can perform on the host system. By creating an AppArmor profile for a container, the administrator can control which files the container can access and which system calls it can execute. This helps to reduce the attack surface of the container and increase its security. In summary, AppArmor is a Linux security module that provides a way to restrict the actions that a program can perform on the system, and Docker can use AppArmor to restrict the actions that a container can perform on the host system, increasing security.


- Linux NameSpace:
    - A Docker container gets its own namespace from the host kernel, that means the program in the container can't try to read kernel memory or eat more RAM than allowed. Linux Namespaces are a Linux kernel feature that provide isolated environments for system resources such as processes, network, user IDs, and file systems. It allows for the creation of isolated containers, each with its own view of the system resources. Docker uses Linux namespaces to create isolated containers for each Docker container. Docker is a platform for developers and system administrators to easily create, deploy, and run applications in containers. Docker containers are isolated from each other and from the host system, and they provide a consistent environment for application deployment and execution. Docker leverages Linux namespaces to provide the isolation and control over system resources required to run multiple containers on the same host. In summary, Linux namespaces provide the basic building blocks for containerization, and Docker uses these namespaces to create isolated containers for application deployment and execution.
- Linux control groups:
    - Linux control groups (cgroups) is a Linux kernel feature that provides a way to manage and allocate system resources, such as CPU time, memory, and I/O bandwidth, among groups of processes. cgroups allow you to limit, prioritize, and distribute system resources to processes, helping to ensure that each process has the resources it needs to run effectively. Docker uses cgroups to manage the resources of containers. When a Docker container is created, it is assigned to a cgroup, which sets limits and constraints on the resources the container can access. This helps ensure that each container receives the resources it needs to run, and prevents one container from monopolizing the resources of the host system or interfering with other containers. In summary, Linux cgroups provide a way to manage and allocate system resources among groups of processes, and Docker uses cgroups to manage the resources of containers. This allows Docker to ensure that each container has the resources it needs to run effectively, while also preventing one container from interfering with other containers or the host system.
- Linux capabilities:
    - Linux capabilities is a Linux kernel feature that provides a way to control the permissions of processes, by dividing the traditional root permissions into smaller, more fine-grained capabilities. For example, a process can be granted the capability to bind to a privileged network port, but not the capability to execute a privileged system call. Docker uses Linux capabilities to control the permissions of containers. When a Docker container is created, its capabilities can be limited, allowing the container to perform only the actions it needs to carry out its intended purpose. This helps to reduce the attack surface of containers, making them more secure, by limiting the actions a malicious container could perform. In summary, Linux capabilities provide a way to control the permissions of processes, by dividing the traditional root permissions into smaller, more fine-grained capabilities. Docker uses Linux capabilities to control the permissions of containers, reducing the attack surface of containers and making them more secure.

## 4

### 4.1
![https://www.pluralsight.com/blog/it-ops/linux-file-permissions](https://i.imgur.com/GI5lda8.png)
Taken from `https://www.pluralsight.com/blog/it-ops/linux-file-permissions`

```csvpreview
,manual.txt, report.txt, microedit, src/code.c, src/code.h
alex,R/W,W,R/W,R,-
benn,R,R,R/W,R/W,-
cloe,-,R/W,R,R,R/W
```
------------------

Alex and manual.txt - can be seen from -rw (owner for manual.txt)
Alex and report.txt - can be seen from -w- (other user from report.txt)
Alex and microedit - can be seen from r-x (other user from microedit)
Alex and src/code.c - can be seen from src/code.c (other user from src/code.c)
Alex and src/code.h - can be seen from src/code.h (other users can read the file)

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

Benn and manual.txt - can be seen from r-- (other user)
Benn and report.txt - can be seen from -r-- (owner)
Benn and microedit - can be seen from rws (owner)
Benn and src/code.c - can be seen from -rw- (owner)
Benn and src/code.h - can be seen from --- (group)

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

Cloe and manual.txt - can be seen from --- (group)
Cloe and report.txt - can be seen from rw- (group)
Cloe and microedit - can be seen from  r-- (group)
Cloe and src/code.c - can be seen from r-- (group and other user)
Cloe and src/code.h - can be seen from rw (group and owner)


#### 4.2


![](https://i.imgur.com/p1auZ7d.png)
![](https://i.imgur.com/2ouMLyI.png)
![](https://i.imgur.com/60FYqpZ.png)


```
#/bin/bash

echo Creating the folder and files

mkdir hw
touch hw/manual.txt
touch hw/report.txt
touch hw/microedit
mkdir hw/src
touch hw/src/code.c
touch hw/src/code.h

echo Creating users and groups
sudo adduser alex
sudo adduser benn
sudo adduser cloe

sudo groupadd -f gurus
sudo groupadd -f staff

sudo usermod -a -G staff alex
sudo usermod -a -G staff benn
sudo usermod -a -G staff cloe
sudo usermod -a -G gurus cloe


echo Change Ownership

sudo chown alex:staff hw
sudo chown benn:staff hw/src

sudo chown alex:gurus hw/manual.txt
sudo chown benn:staff hw/report.txt
sudo chown benn:gurus hw/microedit
sudo chown benn:staff hw/src/code.c
sudo chown cloe:gurus hw/src/code.h

echo Change Permissions

sudo chmod 755 hw
sudo chmod 455 hw/src

sudo chmod 604 hw/manual.txt
sudo chmod 462 hw/report.txt
sudo chmod 644 hw/src/code.c
sudo chmod 460 hw/src/code.h

sudo chmod 745 hw/microedit
sudo chmod u+s hw/microedit

```

## 5

```
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]){
    int arg1, arg2;
    printf("Running\n");
    if (argc != 3)
        return -1;
    arg1 = atoi(argv[1]);
    arg2 = atoi(argv[2]);
    printf("Argument 1: %d \n",arg1);
    printf("Argument 2: %d \n", arg2);
    if (arg1 < 0 || arg2 < 0)
        return -1;
    if (arg1 + arg2 >= 0)
        return -1;
    printf("ACCESS GRANTED\n");
}
```


```
Running
Argument 1: 2147483647 
Argument 2: 1 
ACCESS GRANTED
```


The problem for this code is that the only scenario where access granted is achieved is when there's an int overflow, which can be done using the arguments above. 

To prevent int overflow,
- Actually consider how large/small a number it will ever contain.
- Actually consider if it needs to be signed or unsigned. Unsigned is usually less problematic.
- Pick the smallest type of intn_t or uintn_t types from stdint.h that will satisfy the above (or the ...fast_t etc flavours if you wish).
- If needed, come up with integer constants that contain the maximum and/or minimum value the variable will hold and check against those whenever you do arithmetic.



## 6


```
void fun3(void){
    char a[8];
    double b;
    return;
    }
void fun2(void){
    fun3();
    }
void fun1(void){
    char a[16];
    int b;
    float c;
    fun2();
}
int main(void){
    fun1();
}
```

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


## 7

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



- Executing gdb with vuln1 after compiling it

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

- Getting buffer start locations in memory

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

- Set break point

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


- To override EIP with ‘FFFF’, we print an array of ‘F’ with length of 144 bytes. This will write in to the EIP : `run $(python -c "print('F'*144)")`
![](https://i.imgur.com/Woe2Kb7.png)


- To find the offset of EIP: `run $(python -c "print('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABCDEFGHIJKLMNOPQRSTUVWXYZ')")`
- This is done to check and replace where the eip is.
- 

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


- To override EBP with ‘FFFF’ and EIP with ‘PPPP’, the code is modified to :`run $(python -c "print ('F'*140+'P'*4)")`


![](https://i.imgur.com/yG6yrvN.png)
![](https://i.imgur.com/4rZjcFD.png)
![](https://i.imgur.com/DfsaK6g.png)
