Add the rest of university notes

This commit is contained in:
John Gatward committed 2026-10-04 14:02:35 +01:00
1 parent c1b84c7f7d
commit d0f27f276b
366 files changed
+9844 -110

No files matched your search

+157
View File
@@ -0,0 +1,157 @@
# Security
#### What is security?
Security is about the **protection of assets**
- **Prevention**: Preventing access and damage to assets
- **Detection**: Steps to detect the access or damage of assets
- **Recovery**: Measures allowing us to recover from asset damage
Assets could be physical or virtual data
##### Historic Computer Security
- Historically systems have been built to serve single users
- Often only a few highly trusted users were permitted to access a system
- This makes mistakes made by trusted users still a concern
- Current multi-user systems have completely different security concerns
##### Modern Computer Security
- Possibly thousands of users
- Distributed over wide networks
- Not all users are inherently trust worthy
- More and more things are moving to electronic
- Requiring protocols to manage them
### Attacks
- Monetary transaction need security
This is what most interactions look like and therefore attacks are based on this communication
#### Eavesdropping
To prevent this we use encryption, using `HTTPS` or `TLS`
But how do we privately agree on an encryption key
###### User authentication
Is the client who they say they are
What if the server gets hacked, we can use **hash functions**
###### Digital Certificates
However, this can be bypassed if the clients machine is hacked
We have to ensure the client is running anti virus software and practices good avoidance.
###### Insider attacks
To stop this the company must practice good security such as:
- Database security Controls
- File access controls
- Intruder detection
- Security Auditing
## Definitions
There is no solid definition for *security*
- Unbreakable?
- Secure enough?
It is often simply an arms race between developers & researchers and malicious users
#### Managing Security
- Within organisations, management are responsible for defining security needs
- Developers implement these policies
- A concise document explaining the needs is called a *Security Policy*
- What should be protected?
- How should we protect it?
- UoN security policy
- https://www.nottingham.ac.uk/dts/security/it-security.aspx
#### Computer Security
- Usually defined as three keys areas (**CIA**)
1. Confidentiality
- Prevention of unauthorised *disclosure* of information
- This involves unauthorised users reading private or secret information
- Medical records or credit card details
2. Integrity
- Prevention of unauthorised *modification* of information
- Also the assurance that data remains *unmodified*
- Distributed bank transactions or database records
- Just because we have **integrity**, doesn’t mean we have **authenticity**
- Can we verify the sender? does it have freshness?
- Authenticity = Intercity + Freshness
3. Availability
- Prevention of unauthorised *withholding* of information or resources
- The property of being accessible is an usable upon demand by an authorised entity
- In other words prevent DoS attacks
- e.g. redundant power supplies, firewall packet filtering
#### Accountability
- Users should be held responsible for their actions
- The system should identify and authenticate users and ensure compliance
- Audit trails must be kept
#### Non-repudiation
- Provides unforgeable evidence that someone did something
- Mostly a legal concept
- Evidence verifiable by a trusted third party
- e.g notaries, digital certificates
- Applies to physical security as well
- Like key cards
##### The security Dilemma
> “Security-unaware users have specific security requirements but no security expertise”
- There is a trade off between security and ease of use
- Increased resource demands
- Interferes with working patterns
###### Added complexity
- Often user experience is place at the forefront of software engineering
- This is usually not compatible with security
- Security can be seen as controlling access to information
- This is hard, we usually control access to data instead
- Data - a means to represent information
- Information - an interpretation of that data
- Focusing on data can still leave information vulnerable
- for example: Mikes criminal record not found
- vs you do not have permission to access mikes criminal record
#### Security Design
- Computer Security is **not** rocket science if:
- Approached in a systematic, disciplined and well planned manner
- From the inception / design of a system
- However, if added as an afterthought, will often lead to disaster
- Good security design focuses on these principles
1. Focus of control
- In a given application, should the focus of protection mechanisms be:
- Data - permitted manipulation of data
- consistency check
- Operations - permitted invocations
- Users - permissions for specific users
2. Complexity vs assurance
- Would we prefer a simple approach with *high assurance*? or a feature rich environment
3. Centralised or decentralised controls
- Should defining and enforcing security be performed by central entity, or be left to individual components in a system
- **Central entity** - possible bottleneck
- **Distributed solution** - more efficient, but harder to manage
4. Layered security
- We can visualise our security model in layers
- Each layer protects a boundary, and relies on the security of the layers below
@@ -0,0 +1,95 @@
# Security Management
> “Information security is the protection of information from a wide range of threats in order to ensure business continuity, minimise business risk, and maximise return on investments and business opportunities” - ISO/IEC 17799 Code of practice for information security management, 2005
> “The concepts, techniques, technical measures, and administrative measures used to protect information assets from deliberate or inadvertent unauthorised acquisition, damage, disclosure, manipulation, modification, loss, or use” - IBM Dictionary of Computing, 1994
**Informational Security:** preservation of **confidentiality**, **integrity** and **availability** of information. In addition, other properties such as authenticity, accountability, non-repudiation and reliability can also be involved
> “Cybersecurity is how individuals and organisations reduce the risk of cyber attack.
>
> Cybersecurity's core function is to protect the devices we all use (smartphones, laptops, tablets and computers), and the services we access - both online and at work - from theft or damage.
>
> It's also about preventing unauthorised access to the vast amounts of personal information we store on these devices, and online” - UK National Cyber Security Centre www.ncsc.gov.uk/section/about-ncsc/what-is-cyber-security
### Security Policy
- A statement of overall intent and commitment to security
- Provides a *foundation* for other aspects
- High level policy applies to the organisation and everyone in it
- more focused policies may apply to specific departments, systems etc
- Identifies what but not how
- the *how* part would be covered by accompanying guidelines
#### Characteristics of a good policy
- Is short and backed from the top of the organisation
- Ensure everyone reads it
- Recognises that information is critical & must be protected
- Emphasises the importance of security awareness & training
- Emphasises compliance with legal and regulatory requirements
- Emphasises relations with third parties
- States roles and responsibilities for information security
- Outlines standards and procedures
- States the consequences of violations and non-compliance
Note the lack of policies on personally owned devices, considering ~100% of people have one or more.
### Recognising Risk
**Removal**
System is modified so that a particular feature, and the associated risk is removed.
**Reduction**
Security measures are used to reduce risk to an acceptable level.
**Retention**
Nothing is done - the risk is small and insignificant
**Relocation**
The system is unchanged, but risk is transferred to another party e.g. an insurance
###### Management need to know
- What’s at risk
- The cost incurred if the risk becomes a breach
- Safeguards that can be implemented
- The cost of safeguards
- The risk reduction that will result from implementation of specific safeguards
### Baseline Security
- A minimum level of protection that should be considered by all organisations ulitilising IT systems
- Although many organisation will require protection considerably above baseline
- Can provide a *common* basis for mutual trust
###### Cyber Essentials
- Enables organisations to be certified independently for having met a good practice standard in cyber security
- Addresses five technical control themes:
1. Firewalls
2. Secure configuration
3. User access control
4. Malware protection
5. Security Update management
###### ISO 27001
- the central element of the ISO 27000 series
- describes best practice for an ISMS (information security management system)
- outlines of each aspect of an ISMS, and other standards provide further detail (e.g. 27002 for controls, 27003 for implementation, 27004 for evaluation)
###### ISO 27002
- provides advice on how to implement security controls listed in Annex A of ISO 27001
### The need for Professional Skills
- Although simplified at the abstract level, actually following even the baseline controls is non-trivial
- Simply knowing about them does not tell you *how* to comply
- Still requires the ability to assess the current environment and understand the appropriate protection and how to apply it
- Organisations require professionals with appropriate security knowledge, skills and competence.
+120
View File
@@ -0,0 +1,120 @@
# Symmetric Cryptography
- Symmetric encryption gives us confidentiality
- Implemented using block ciphers or stream ciphers
- Lightweight and fast
- Used for general communication
![1644517237.png](img/1644517237.png)
### Stream Cipher
- Stream ciphers use an initial seed key to generate an infinite keystream of random looking bits
- The message and keystream are usually combined using an `xor` ($\oplus$) which is reversible if applied twice
- How ever using the same keystream to encrypt two messages makes messages easy to break
- A random *number used once* nonce is added as an additional seed
- The nonce is not a secret, it simply ensures the keystream is new
##### Pros and Cons
✅ Encrypting long continuous streams, possibly of unknown length
✅ Extremely fast with low memory footprint, ideal for low-power battery devices
✅ If designed well, can seek to any location in the stream
❌ The keystream must appear statistically random
❌ You must **never** reuse a key & nonce
❌ Stream ciphers do not protect the cipher-text
#### Block Ciphers
- Block ciphers use a key to encrypt a fixed size block of plain text into a *fixed-sized block* of cipher-text
- Changing and permuting the bits of the block depending on the key
- Different lengths of messages can be handled by splitting the message up, and padding
##### SP-Network
- Repeated substitution and permutation
![1644517216.png](img/1644517216.png)
- This round will be run multiple times (around 10-15 times)
###### Key Mixing
- Mixing in the key prevents attackers from reversing the process
![1644517396.png](img/1644517396.png)
- To decrypt, reverse the process
#### Symmetric Algorithms
- `DES` was used from 1970s to 2000s
- `3DES` (using DES 3 times) is sometimes found in legacy systems
- `AES` and `ChaCha20` are the only two ciphers used in `TLS 1.3`
| Algorithm | Cipher type | Design | Block Size (bits) | Speed | Memory Footprint | Safe Implementation Difficulty | Key Sizes |
| ---------- | ----------- | ------------ | ----------------- | --------- | ---------------- | ------------------------------ | --------- |
| `DES` | Block | `Feistel` | 64 | Fast | Low | Easy | 56 |
| `3DES` | Block | `Feistel` | 64 | Slow | Low | Easy | 112 |
| `AES` | Block | `SP-Network` | 128 | very fast | medium | Hard | 128/192 |
| `ChaCha20` | Stream | add-xor-rot | N/A | Very fast | very low | Easy | 256 |
### Attack Models
1. Brute force
- Weakest attack, guessing the key
- If the key is $2^{128}$, on a super computer would take $10^9$ years
2. Cipher text only
- Static analysis on the cipher text, frequency analysis etc
- e.g. looking at the enginma machine and recognising a letter cannot be itself
3. Known plaintext
- Where you know some plaintext and the corresponding ciphertext
- e.g. Enigma being broken using “heil hitler”
4. Chosen plaintext
- Seeing if certain plain-texts takes the algorithm longer/shorter
5. Chosen ciphertext
6. Related-key attack
- Get the same message encrypted in different keys
- More of a theoretical attack
Modern algorithms are expected to overcome these attacks trivially
## Asymmetric Encryption
- Two keys, a public & private key
- Public-key asymmetric cryptography hinges upon the premuse that:
- It is computationally infeasible to calculate a private key from a public key
- In practice this is achieved through intractable mathematical problems
#### Key Exchange
- Diffie-Hellman key exchange allows two parties to mathematically agree a shared secret over an insecure channel
![1644518533.png](img/1644518533.png)
It is extremely easy to go from a -> A but extremely difficult to go backwards.
- Encryption performed by the **public** key can only be decrypted by the corresponding **private** key
#### Public key Encryption
- Client encrypts message with servers public key, now only the server’s private key can be used to read it.
- The authenticity of signatures generated by the private key can be verified by the public key
![1644519300.png](img/1644519300.png)
##### Public key Algorithms
| Algorithm | Key Exchange | Encryption | Digital Signitures | Mathematical Problem | Elliptic Curves | Typical Key Size |
| :------------- | :----------: | :--------: | :----------------: | --------------------- | :-------------: | ---------------- |
| Diffie-Hellmen | ✅ | ❌ | ❌ | Discrete Logs | ✅ | 256 |
| `RSA` | ❌ | ✅ | ✅ | Integer Factorisation | ❌ | 2048/4096 |
| `Elgamal` | ❌ | ✅ | ✅ | Discrete Logs | ✅ | 2048 |
| `DSA` | ❌ | ❌ | ✅ | Discrete Logs | ✅ | 256 |
@@ -0,0 +1,159 @@
# Users and Authentication
- Users must be *identified* to enable:
- User specific access controls
- Individuals accountability for activities
- Claimed identities must be authenticated
- First line of system protection
- Safeguards against abuse by external parties or unauthorised insiders
##### Authentication Methods
1. Something the user *knows*
- passwords, PINs
2. Something the user *has*
- a card, a token
3. Something the user *is*
- a bio-metric so a finger print or the users face
#### Passwords
On one level they are very usable
- Easy to understand the idea
- Familiar across different systems
- high degree of cross device applicability
- perceived to be low cost
Ease of use is often because users have not been made to use them properly
- Users make poor selections
- Dictionary words
- things that people could guess or social engineer
- Use the same password on multiple systems
- Share them with other people
- Write them down in discoverable places
![1645037376.png](img/1645037376.png)
#### Current Guidance on Password Systems
- The latest NIST recommendation advise:
- Against automatic password expiry
- Passwords should only be changed when there’s a reason
- Against imposing rules for complex passwords
- Length matters more than complexity
- Against password hints or knowledge-based authentication
- Social media means these can be socially engineered
- To enable “show password while typing” and to allow paste-in password fields
> Passwords are a **broken mechanism**
>
> - The *method* itself won’t naturally improve over time
> - User *behaviour* won’t naturally improve either
> - Change the method or support people better
Browsers can now auto-generate passwords for us
- Avoids users making poor decisions
- But also avoids us
- Knowing what the password is
- Needing to know the good practice
Some devices may not support password entry
- For example dictating a password to an Alexa or google home
- Mobile devices with small keyboards can be tricky
#### Token-based Authentication
###### Examples
- Magnetic cards
- Smart cards
- Code generators
- Wearable devices
- Smartphones
Often combined with a secret knowledge to form a 2-stage / 2-factor authentication
- e.g. using an ATM requires card and pin
Smartphone apps can proveide the same functionality as authentication tokens (i.e. computing OTP)
- The users no longer need a separate, dedicated device
- Think nationwide card reader for transfers
- Relies on the security of the smartphone
- User authentication on the device and or the app
- Prevention of compromise via attacks
#### Biometrics
- Theoretically far more usable
- Nothing for the user to remember
- Nothing for them to lose or leave behind
![1645038798.png](img/1645038798.png)
![1645038972.png](img/1645038972.png)
Biometrics can be copied, but not easily
###### Desirable Characteristics
- **Circumvention** - the ease with which an impostor may be able to duplicate or imitate the characteristic in order to gain unauthorised access;
- **Collectability** - the ease with which a sensor is able to collect the sample;
- **Performance** – the accuracy, speed and robustness of the technique;
- **Permanence** - the ability for the characteristic to remain consistent over time;
- **Acceptability** - the degree to which the technique is found to be acceptable by those that are expected to be using it;
- **Universality** - the ability for a technique to be applied to a whole population of users;
- **Uniqueness** - the ability to successfully discriminate between different individuals within the target population
![1645039235.png](img/1645039235.png)
###### Biometrics Errors
- **F**alse **R**ejection **R**ate (**FRR**)
- Errors where the system falsely identifies the legitimate user as an imposter
- Also known as False Alarm Rate or Type I error
- **F**alse **A**cceptance **R**ate (**FAR**)
- Errors where imposters are falsely believed to be legitimate users
- Also known as Impostor Pass Rate or Type II error
- **E**qual **E**rror **R**ate (**EER**)
- The point at which FAR and FRR coincide
- The measure normally used to assess biometric products
- Failure to Enroll
- Errors in which the system is unable to establish as biometric template for a proposed user
- e.g. some people don’t have finger prints, some reglions require face covering
- Failure to Acquire
- Errors in which the system is unable to successfully acquire the information required to make a decision
A legitimate user’s experience of biometrics will be informed by:
- The combined FRR and FAR
- The throughput (speed & responsiveness) of the system.
Developers focus can change on implementation. For example if being used as a password replacement, FAR should be minimised.
![1645039834.png](img/1645039834.png)
##### Modes of Use
- **Verification**
- User claims an identity - authentication against that identity
- One-to-one match (1:1)
- Less unique characteristics can be ultised
- **Identification**
- Users’ biometric sample is compared against all in database
- One-to-Many match (1:N)
- Only the more unique biometrics can be ultised - fingerprints, iris, retina etc
### 2-Factor Authentication
Two-factor and multi-factor Authentication
- Combine two or more elements together to enable stronger authentication assurance
- Typical implementations have been a password & token
- Ideally you want factors from different categories
![1645040432.png](img/1645040432.png)
@@ -0,0 +1,121 @@
# Authentication
- To allow some access to an asset we must ensure:
- They are permitted to access that asset
- They are who they say they are
- We can attempt to verify identity using credentials
- Something the user *is*
- Something the user *has*
- Something the user *knows*
#### Usernames and Passwords
- Identification - who are you
- Authentication - verify that identity
- Authentication should expire
- *Remember my credentials* turns this into something you have
- **T**ime **o**f **c**heck **t**o **t**ime **o**f **u**se - **TOCTTOU**
- Repeated authentication
- At the start and during a session
##### Problems with passwords
- People forget them
- They can be guessed
- Spoofing and phishing
- Compromising password files
- Key-logging
- Many of these are made many times worse by weak passwords
### Hash Functions
- Another crptographic primitive
- Takes a message of any length, and returns a pseudorandom hash of fixed length
$$
h(M):\{0,1\}^n \rightarrow \{0,1\}^{128}
$$
- Hash functions are used everywhere. Message authentication, integrity, passwords etc
#### Strong Hash Functions
- The output must be indistinguishable from random noise
- Bit changes must be diffused through the entire output
![1645467875.png](img/1645467875.png)
For a hash function to be useful, we need it to have some important properties:
1. Given a hash, we can’t reverse it
2. It is impractical to find messages that produce the same hash - a *hash collision*
##### Password Authentication (wrong way)
![1645468046.png](img/1645468046.png)
If database is breached, passwords are stored in plaintext
- Storing passwords in plaintext is a terrible idea
- Administrators can read them
- Storing encrypted passwords is better, but not perfect
- Where are keys stored?
- Administrators can read them
Using a **one-way hash function** is a much better solution
![1645468195.png](img/1645468195.png)
#### Password & Shadow Files
- Operating systems have taken steps to stop people reading hashes for offline attacks
- Linux stores hashes in a shadow file `/etc/shadow`
- These files are now **read-protected**
#### Cracking Passwords
- Cracking a password isn’t always illegal
- Password cracking falls into two basic types:
- Offline: you have a copy of the password hash locally
- This is trying possible passwords and seeing if we have a hash collision with the password list
- Usually done via brute force however difficulty is $\{char\space count\}^{length}$
- Online: You do not have the hash, and are instead attempting to gain access to an actual login terminal
- Online is usually atempted via phising
![1645468857.png](img/1645468857.png)
##### Dictionary Attacks
- Most password cracking is now achieved using **dictionary attacks** rather than brute force
- Using a dictionary of common words and passwords
- Apply small variations to this list, trying them all
- Combine words from two different lists
- `qwerty1234password1` is unbreakable using brute force, but won’t last against a dictionary attack
##### Password Salting
- We can improve security by pre-pending a random *salt* to a password before hashing
- The salt is stored unencrpted with the hash
- If a hacker has a list of hashed passwords, and three of them are the same, he can summise they’re all a common password.
- Salting adds non-secrete randomness to passwords
![1645469711.png](img/1645469711.png)
- If we use a different random salt for each user, we get the following security benefits:
1. Cracking multiple passwords is slower - a hit is for a single user, not all users with that password
2. Prevents **rainbow table** attacks - we can’t pre-compute that many password combinations
- Salting has no effect on the speed of cracking a single password
#### Hashing Speed
- When password cracking, the most important factor is *hashing speed*
- New algorithms take longer
- Partly because they’re more complex
- But some have been specifically designed to take a while
- Iterate to increase complexity
##### Social Cracking
- Obtaining private details by offering some *pretext* as a reason for needing them
- We continue to rely on email addresses, DOB and Mother’s maiden names as our *last line of defence* for security
- How much information do we need to ring up a company as someone else
@@ -0,0 +1,186 @@
# Reference Monitors
The reference monitor is an abstract concept
> An access control concept that refers to an abstract machine that mediates all access to objects by subjects
- Must be tamper proof
- Must *always be invoked* when access to an object is required
- Must be small enough to be verifiable / subject to analysis to ensure correctness
##### Placement
- Can be placed anywhere within the system
- Hardware - dedicated registers for defining privileges
- Operating system kernel - virtual machine hyper-visor
- Operating system - Windows security reference monitor
- Services layer - `JVM`, `.NET`
- Application layer - Firewalls
Reference monitors could be placed in a variety of locations relative to the program being run
![1645471173.png](img/1645471173.png)
The last example where the program contains its own reference monitor, as found in Windows XP, is a terrible idea - it leaves permissions down to the developer.
###### Lower is better
- Using a reference monitor or other security features at a lower level means:
- We can **assure** a higher degree of security
- Usually **simple structures** to implement
- Reduced performance **overheads**
- Has to be extremely quick as many calls will be made
- Fewer layer below attack possibilities
- However
- Access control decisions are far removed from applications
#### OS Integrity
- The operating system
- Arbitrates access requests
- Is itself a resource that must be accessed
- This is a conflict, we want to use the OS but not mess with it
> Users must not be able to modify the operating system
- Modes of operation
- Defines which actions are permitted in which mode e.g. system calls, machine instructions, I/O
- Controlled Invocation
- Allows us to execute privileged instructions safely, before returning to user code
We must distinguish computations done on behalf of:
- The OS
- The user
A status flag within the CPU allows the OS to operate in different modes
![1645471731.png](img/1645471731.png)
In practice, Windows and Unix only use Ring 0&3 to save on overhead
### Controlled Invocation
- Many functions are helf at kernel level, but are quite reasonably called from within user level code
- Network and File IO
- Memory allocation
- Halting the CPU (at shutdown only)
- We need a mechanism to transfer safely between kernel mode (ring 0) and user mode (ring 3)
> We don’t actually perform privileged operations, we asking the operating system to perform them for us - The operating system can refuse to do it
##### Interrupts
- Exceptions or Interrupts
- In many ways is the hardware equivalent to a software exception - not always bad
- Handled by an interrupt handler which resolves the issue and returns to the original code
Processing an Interrupt
- Given an interrupt, the CPU will switch execution to location given in an interrupt descriptor table
![1645472211.png](img/1645472211.png)
#### Descriptors and Selectors
- Descriptors hold information on crucial system objects like kernel structure locations
- Descriptors are held in descriptor tables
- Contain a Descriptor Privilege Level (DPL)
- Descriptors are indexed by selectors
- Loaded when required (jump calls)
- The CPU protects the kernel by checking the Current Privilege Level (CPL) when a Selector is loaded
##### Interrupt Gates
- The code segment (CS) register in x86 CPUs has 2-bits reserved for the Current Privilege Level (CPL)
- Descriptors that have a privilege level higher than where they point are called gates
- Since these descriptors are created by the kernel, they offer a secure means of entry into ring 0
![1645472444.png](img/1645472444.png)
###### Modern Kernels
- Intel introduced the `sysenter` and `sysexit` operations with the Pentium II
- performs with much less overhead
![1645472755.png](img/1645472755.png)
We got immediately in to ring 0
However where we go next is dictated by the `sysenter` pointer, users cannot write to `sysenter`
#### Patching the Kernel
- If you can run custom PL 0 code, you can insert your own handler - **Rootkit**
![1645473063.png](img/1645473063.png)
## Memory Protection
- A process is a program being executed currently
- Important unit of control
- Exists in its own address space
- Communicates with other processes via the OS
- Separation for security
- A thread is a strand of execution within a process
- Share a common address space
- Segmentation - divides data into logical units
- Good for security
- Challenging memory management
- Not used much in modern OSs
- Modern OSs only have two segments, one for user space, the other for kernel space
- Paging - divides memory into pages of equal size
- Efficient memory management
- Less good for access control
- Extremely common in modern OSs
##### Page Tables
- All processes see an individual linear address space
- Page tables map from a linear address space to the physical address space
![1645473936.png](img/1645473936.png)
###### Meltdown
- In most operating systems, the entire kernel is stored in the upper address space
- Pages in this area are flagged as supervisor, and cannot be access outside ring 0
- Meltdown is an exploit that allows us to read this privileged memory
- We do this using a *side-channel*
![1645474135.png](img/1645474135.png)
- In Intel CPUs, it’s common to speculatively evaluate code prior reaching it
- E.g. conditionals
- **Significant** speed up
- No harm done, changes are just rolled back
- But the **cache isn’t rolled back**
- This is called side-channelling and cache timing
```java
...
w = illegal_instruction;
x = memory[data * 4096];
...
```
- When the CPU runs this code, it will take a significant amount of time to determine that `w` shouldn’t be run, however by that point the speculative code has run `memory[data*4096]`.
- We won’t see the result as it’ll be discarded once it is discovered `w` was an illegal instruction, although it will appear in cache
![1645474511.png](img/1645474511.png)
- When all the cache is loaded, one page will load significantly quicker than others as it was loaded during speculative running.
###### Attack steps
1. Flush the cache
2. CPU speculatively evaluates our read using *data*
3. Read all pages pointed to by `memory[]` and time it
4. Page 117 was quicker
- Meltdown attempts to read a value from kernel memory
- Read from kernel
- Mask out single bit
- Access user memory at that location
- If we repeat we can read all memory in kernel space
+165
View File
@@ -0,0 +1,165 @@
# Unix and Linux Security
### Role of the OS
- Identification
- Authentication
- Lets us verify who we are to the system
- Some files are private, some are public
- System files must be protected
- We need to be able to access applications
- Access control
- Auditing
#### Authentication & Authorisation
- Subject / Principle - an active entity
- Object - resource being accessed
- Access operation
- Reference monitor - grants or denies access
![1645720842.png](img/1645720842.png)
**Principle**
> “An entity that can be granted access to objects or can make statements affecting access control decisions”
- e.g. user identity in an OS
- Used when discussing security policies
**Subject**
> “An active entity within an IT system”
- e.g. process running under a user identity
- Used when discussing operational systems enforcing policies
**Objects**
Files or resources - memory, printers, directories
- Two options for focusing control:
1. What a subject is allowed to do
2. What may be done to an object
#### General Model
- We’ll settle on some common access files:
- **Read** - Simply viewing (**confidentiality**)
- **Write** - Includes changing, appending, deleting (**integrity**)
- **Execute** - Can run a file without knowing its contents
##### Ownership
- Who is in charge of setting security policies
- **Discretionary**: Owner can be defined for each resource
- Owner controls who gets access
- **Mandatory**: There could be a system-wide policy
- e.g. a government with different levels of security (top secret, level 3 clearance, etc)
- Not commonly used for businesses
- Most OS’s support the concept of ownership
### Unix
- Unix simplifies access control by considering only the *user*, *group* and *others*
- User is the current owner
- Group is the named group entity
- Everyone else
- Unix offers read, write and execute access controls
##### Groups
- Users with similar access rights can be collected into groups
- Groups are given permissions to access objects
![1645721584.png](img/1645721584.png)
##### UID & GID
- Usernames in unix are soft aliases, your UID is what determines permissions
- User identities: UID
- Group identities: GID
- Your IDs are stored in `/etc/passwd`
- This stores user accounts, not just passwords
- Root has a special UID of 0
###### The Shadow File
- In an attempt to improve password security, we can store password hashes in a shadow file
- Readable only by root users
- `/etc/shadow` stores the hashed passwords needed to authenticate users
#### Root (Unix Superuser)
- Root’s UID 0 is actually hard coded into the Linux kernel at multiple points
- In 2003, this anonymous change was made to the error value return in the `wait4` function is Linux:
```
if ((options == (_WCLONE|__WALL)) && (current->uid = 0))
retval = -EINVAL
```
Note: single `=`. This was a backdoor which sets the current uid to 0, giving root perms
###### Root Management
- Write protect `/etc/passwd` and `/etc/group`
- Separate superuser duties (e.g. daemon, uucp)
- Never use root as normal user
- Audit `su` and `sudo` usage
- In unix, everything is a file
- Files really represent resources
- Organised in a tree structure, with alterations depending on the file system
- I-nodes store permission information
- Every resource as a owner and a group
###### I-nodes
- I-nodes in unix store the metadata for files
- Each file name links to an i-node which stores security information
```
❯ stat /etc/passwd
File: /etc/passwd
Size: 1543 Blocks: 8 IO Block: 4096 regular file
Device: 8,3 Inode: 27799243 Links: 1
Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2022-02-23 20:19:14.126528209 +0000
Modify: 2022-02-11 21:26:48.253868839 +0000
Change: 2022-02-11 21:26:48.260535505 +0000
Birth: 2022-02-11 21:26:48.253868839 +0000
```
##### Permissions
- Every resource has permission bits - held in the i-node metadata
- Permissions for the user / group / others
- Octal representation
- Bit 3: read
- Bit 2: write
- Bit 1: execute
- Permissions are changed using `chmod` and passing three octal values
![1645722860.png](img/1645722860.png)
Directory permissions are slightly different to files:
- `r` - list files within the directory
- `w` - add or remove files
- `x` - traverse the directory, open files in the directory
#### SUID
- Set UID: set the effective user to be the file owner when executed
- Necessary to allow non-privileged access to privileged e.g. passwords
### Linux Security Modules
- SInce 2.6, linux provides the ability to hook into security calls
- This adds the ability to perform more complex Mandatory Access Control after standard Unix DAC
- DAC check happens irrespective of whether SM is operationa.
![1645723378.png](img/1645723378.png)
- If the security module fails, it does not matter as the discretionary access check has already run.
@@ -0,0 +1,163 @@
# Windows Security
Windows Architecture
![1646408037.png](img/1646408037.png)
Note: windows has `kernel mode drivers` and `user mode drivers`
### Security Subsystem
- Runs in user mode
- `Logon` processes (`winlogon`, `LogonUI`)
- Local security authority (`LSA`)
- Checks Users accounts
- Provides access token
- Responsible for auditing
- Security Account manager (`SAM`)
- Maintains user account database used by `LSA`
- Encrypts / hashes passwords
- Windows predominantly uses **Access Control Lists**, and has done since Windows NT
- Extends the usual read, write and execute with:
- Take ownership
- Change permissions
- Delete
- This allows finer control over files for example a user will be able to read a file but not delete it
- 32-bit access masks (unlike Unix’s 9 bits)
- A higher degree of control, with the associated complexity increase
### Access Control Matrix
- Access rights are defined individually for each combination of subject and object
- Quite an abstract concept, bit would allow for very fine grained control
- Not practical, think of the memory required in scaling it up
![1646409469.png](img/1646409469.png)
##### Capabilities
- A list of capabilities defined per user, equivalent to a row in the access control matrix
![1646409614.png](img/1646409614.png)
Windows doesn’t do this, it does the opposite storing columns called the **Access Control List**
##### Access Control List
- Stored with an object itself, corresponding to a column of an ACM
![1646409753.png](img/1646409753.png)
The access control list can be found by right clicking on a file -> properties -> security.
### Access Control
- Access control in windows treats more than just files, also:
- Registry keys
- Active directory objects
- Groups
- Inheritance is implemented
- File can inherit ACLs from parent directories
#### Principles
- Principles are more broadly defined as well:
- Local users
- Domain users
- Groups
- Machines
Each principles has a human readable name and security ID (`SID`)
```
S-1-5-21-2475811070-2421845406-3333283485-1005
S-1-5-21-1664130791-3153540899-3044996548-279530
```
These are examples of `SID` from windows, but why are they so long?
This is a form of future proofing. Imagine company A buys company B, you can merge the users onto one active directory without two `SID`s clashing. (also 96 bits of memory isn’t a lot in the grand scheme of things)
##### Local / Domain Principles
- LSA creates local principles
- principle = `MACHINE\principal`
- Domain principles adminstered on DC by domain admins
- principle@domain = DOMAIN\principle
- net user /domain
- net group /domain
- net localgroup /domain
#### Groups
- Groups are collections of `SID`s (object-orientated)
- Group can itself be an `SID`
- Groups can thus be nested
- Groups are not nest-able on local machines
- Managed by a domain controller within Active Directory
#### Objects
- Objects are passive entities in access operations
- In windows:
- Executive objects (processes, threads, etc)
- Private objects (files, directories)
- Securable objects have a security descriptor
- Built-in securable objects managed by the OS
- Private objects managed by the application software
### Access Tokens
- Instead of passing a number as in linux, we pass an access token
- It is the security credentials for a login session stored in the **access token**
- Identifies the user, the user’s groups, and the user’s privileges
#### Subjects
- Windows subjects: Processes and threads
- New processes get a **copy** of the parent access token, possibly modified
- Individual access token are immutable and can live beyond policy changes
- The access token checked is the one given at login, not the current access token
- This is a TOCTTOU issue (Time-of-check to Time-of-use)
- Admins can force a user to logoff to update their access token
### User Account Control
- After Vista, administrator users do not use an administrative access token by default
- Users have two tokens, one heavily restricted and used by default
- A prompt allows a user to spawn a process with the adminstrative token, or switch a process’ token.
- Similar to `sudo`
- Can be swapped mid-execution
#### Domains
- Single sing-on for network resources
- Centralised security administration
- Domain controller (DC)
- Handles user accounts and access control
- Trusted 3rd party for authentication
- Multiple DCs allow for decentralisation by design
#### Interactive Logon
- The windows interactive logon allows a user to authenticate
- Windows logon begins with the Secure Attention Sequence `Ctrl+Alt+Del`
- Can prevent spoofing - is tied directly to `winlogon`
- The logon process differs slightly for local and domain authentication
##### Local Logon
1. `Ctrl+Alt+Del` initiates a login prompt using `GINA`
2. These collect credentials which are passed to the `LSA`
3. The `LSA` uses `NTLM` to check the credentials against the `SAM` database
4. Successful login an access token, which is used to spawn a shell (explorer.exe)
![1646411476.png](img/1646411476.png)
##### Domain Logon
- Replaces `NTLM` with `Kerberos`
- Replaces `SAM` with an Active Directory Domain Controller
- Checks of a user are now performed on the remote `LSA`
![1646411494.png](img/1646411494.png)
+141
View File
@@ -0,0 +1,141 @@
# Malware
**Malware** - **Mal**icious Soft**ware**
- A very general term, malware is usually categorised based on
- How it proliferates
- What it does
![1646673601.png](img/1646673601.png)
**Rootkit** - backdoor that installs itself in the kernel which makes it undetectable
### Vectors
- Vectors are the mechanism through which malware infects a machine
- Usually the vector will be a *software vulnerability*
- Or someone clicked something they shouldn’t have
### Payload
- Payloads are the actual malware deposited on the machine, or the harmful results
- They range in severity
- Essentially do nothing
- Messages and adverts
- Recruited into botnets or mail spam
- Stealing private information
- System destruction
- Ransomware & Crypto-jacking
#### Virus
- A piece of self-replicating code
- Propagates by attaching itself to a disk, file or document
- When the file is run, the virus runs and attempts to proliferate
- Installs without the users knowledge or consent
##### Notable Viruses
- 1981: `Elk Cloner`, the first known virus found *in the wild* that affected Apple II computers
- 1986: `Brain`, the first MS-DOS computer virus
- 1989: `Ghostball`, the first multipartite virus - affects both `exe`s and the boot sector
- 1995: First macro virus, `Concept`, affects MS Word documents
- 1996: First linux virus, `Staog`, uses bugs in the linux kernel
#### Worms
- Viruses traditionally require a human to spread
- Worms are self-replicating and stand-alone programs
- Do not require human intervention
- Scanning worms or email worms
- Exploit known software vulnerabilities in order to spread
##### Notable Worms
- 1988: The Morris Worm, affects BSD unix machines. One of the first known buffer overruns
- 2000: The `ILOVEYOU` worm, one of the most damaging worms ever, used social engineering to get people to install it.
- Used the file name `LOVE-LETTER-FOR-YOU.txt.vbs` as windows didn’t show the file type in the file name
![1646674683.png](img/1646674683.png)
### 2003-2004
- During 2003 and 2004 worms were everywhere
- SQL Slammer - fastest spreading worm, crashed the internet (only 376 bytes or 1 UDP packet)
- Even when the network was crippled, the occasional UDP packet could be transmitted and further damage the network
- MS Blaster - Windows XP mainly, crashes RPC and reboots your machine
- Spreading between machines on a internal network easily, no port filtering
- Used a buffer overflow in a windows Remote Procedure Call (RPC) service - spreads without the user clicking
- Compromised machines performed DDOS on `windowsupdate.com`
- Netsky - Infected email attachment, actually removed other worms as part of a *worm war*
- Sasser - From the author of Netsky, attacks windows `LSASS`
- Spread 17 days after a patch to the vulnerability was released by Microsoft
- Buffer overflow in the Local Security and Authority Subsystem Service `LSASS`
- Scans IP addresses and infects via port 445
#### Exploit Life Cycle
- Many exploits are reverse engineered from patches, or developed simultaneously to patches
![1646675422.png](img/1646675422.png)
##### Zero-day Exploits
- An exploit that is previously unknown - by far the most dangerous
![1646675515.png](img/1646675515.png)
###### Stuxnet
- Believed to be an American-Israeli cyber weapon
1. Uses *four zero-day flaws* to infect Windows
2. Seeks out any instance of `Siemens Step7`
3. Finds programmable logic controllers (PLC)
4. Detects attached centrifuges and spins them to destruction
5. Reports that the centrifuges are fine
### Trojans
- A malicious program pretending to be a legitimate application
- Often obtained in email attachments or at malicious websites
- Don’t replicated themselves - *user error*
- Randomware is the most common form of Trojan now
#### Notable Trojans
- 1989: The AIDS Trojan, encrypts all files filenames on the system and request random
- 2002: Beast, affects windows machines from 95-XP and provides the attack with a remote admin tool (RAT) - there are a lot of these types
- 2013: Cryptolocker - massive randomware
##### Ransomware
- Will usually encrypt or block access to files and demand ransom
- It is a clever solution, because if an anti-virus removes it, it is often too late
- Usually distributed on malicious websites, or to already infected machines
- The file decryption keys are protected by encrpyting using the *public key of a C&C server*
###### Ransomware Variants
- Most the challenge in successfully using randomware is tricking a user into running it, and bypassing anti-virus and browser protection
- Fake emails
- Malicious web pages
- Obfuscated javascript attachments
- Deployed using *exploit kits*
##### CryptoWall JS Example
![1646676226.png](img/1646676226.png)
- Everything is obfuscated
#### Crypto-jacking
- Coinhive is a Monero mining API released in September 2017
- It is a legitimate company, with an aim of replacing advertising on websites with currency mining
![1646676407.png](img/1646676407.png)
- This was exploited almost immediately
- Extremely easy to use the API
- Monero mining is pretty easy even on a CPU
- JavaScript is easy to inject onto websites via adverts
+147
View File
@@ -0,0 +1,147 @@
# Exploits
- The easiest way of getting access to a machine is having the user install something for you
- A software or hardware bug that allows an attacker to circumvent an OS’ security perimeter
#### Memory Management
- In C and C++, the programmer performs memory management
- Flexible, powerful, fast but dangerous
- Buffer Overruns
- Stack Overruns
- Heap Overruns
- Memory-managed languages avoid this, but of course may have their own vulnerabilities
### Buffer Overflows
- When a program is executed, contiguous blocks of memory can be allocated to store arrays (buffers)
- If data is written into a buffer that exceeds its size, an overflow occurs
- The data will overwrite the memory beyond the buffer
#### Program Memory
- Memory is stored in virtual address space from `0x0000...` to `0xFFFF...`
- Parts of the program are held in different regions by convention
- Different restrictions are placed on these regions
![1646677005.png](img/1646677005.png)
##### The Stack
The stack holds information on local variables and function calls (stack frames)
1. A function call will push a new frame onto the stack
2. A return will pop it off, and go to `ret`
```c
void function(int a, int b, int c)
{
char buffer1[5];
char buffer2[10];
}
void main()
{
function(1,2,3);
}
```
![1646677112.png](img/1646677112.png)
###### Stack Smashing
- In C and C++, low level functions like `strcpy` perform no bounds checking at all
- This is partly due to the fact strings are null terminated, if we provide no null character `strcpy` will continue to run
- If `str` is long, we can write into other memory
```c
void function(char *str)
{
// allocate local buffer
char buffer[128];
// Copy str into local buffer
strcpy(buffer, str);
}
```
![1646677357.png](img/1646677357.png)
###### Stack Canaries
- Stack canaries modify the prologue and epilogue of all functions to check a value ion front of the return address is unchanged
![1646679244.png](img/1646679244.png)
- If you can work out the canary value, there is no issue
###### Data Execution Prevention (NX)
- Modern operating systems will mark the stack as non-executable
- `NX` on AMD, `XD` on Intel and `XN` on arm
- An `NX` stack means that adding in our exploit code won’t work
- We can circumvent this using a `return-to-libc` attack
###### Further Protection
- To defeat `ret2lib2` various `0x0` null bytes are inserted into standard library addresses
- Developers also restrict access to obvious system calls
- Address Space Layout Randomisation (`ASLR`) moves the address of library and programs around
- They don’t have to move too much before your hand-crafted `ret` addresses will break
###### Return-Oriented Programming
- Lets forget about injecting code, how about just using existing code in the actual exploitable program
- No individual section of this program will do what we want
- Find short sections, *gadgets* and link them together
![1646679620.png](img/1646679620.png)
##### Race Conditions
- With concurrent threads or processes, timing can lead to security vulnerabilities
![1646679670.png](img/1646679670.png)
- Here the victim unknowingly modifies the wrong file
- This can happen because the CPU context switches and can execute these two processes simultaneously
- Running this continuously for about 10 minutes, this will work once
##### Heartbleed
- Heartbleed is a bug in `OpenSSL`
- Open source `SSL` library
- Started in `OpenBSD`
- Used almost *everywhere*
- Specifically targeted the heartbeat extension
- Extension to regular `SSL` and used for keep-alive purposes, to stop quiet connections being closed
- Client sends a message to the server to say it’s alive
- Server responds (also alive)
![1646679952.png](img/1646679952.png)
**The Bug**
```c
buffer = OPENSSL_malloc(1 + 2 + payload + padding);
bp = buffer;
/* Enter response type, length and copy payload */
*bp++ = TLS1_HB_RESPONSE;
s2n(payload, bp);
memcpy(bp, p1, payload); //BAD
bp += payload;
/* Random padding */
RAND_pseudo_bytes(bp, padding);
r = ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload +
padding);
if (r >= 0 && s->msg_callback)
s->msg_callback(1, s->version, TLS1_RT_HEARTBEAT,
buffer, 3 + payload + padding,
s, s->msg_callback_arg);
```
This bug would just memcpy a bunch of the server’s ram and send it back to the client. This can expose RSA keys.
This is called a **buffer overread** attack.
@@ -0,0 +1,161 @@
# Network Security
### TCP/IP
- Each protocol carries the protocol in the layer above by appending headers to it
![1647096411.png](img/1647096411.png)
- IP is connection-less and state-less
- Best effort service
- No delivery guarantee
- No order guarantee
- IPv4 No guaranteed security support
- IPv6 security support is guaranteed - IPSec
#### IPSec
- Optional in IPv4, mandatory support in IPv6
- Two major security mechanisms
- IP Authentication Header (AH)
- IP Encapsulation Security Payload (ESP)
- Does not contain any mechanisms to prevent traffic analysis
##### Encapsulation Security Payload
- Includes an additional header within the IP packet that describes what encryption and authentication is in use
![1647096765.png](img/1647096765.png)
##### Security Parameter Index
- Stores security parameters e.g. crypto protocol and keys
- Established by Internet Security association and key management protocol (ISAKMP) during the Internet Key Exchange (IKE) handshake
- Uses Diffie-Hellman for key exchange
- The SPI references the entry in a table that corresponds to this session’s parameters
- ESP uses either *transport* or *tunnel* modes
Transport mode
![1647096990.png](img/1647096990.png)
Tunnel mode
![1647097202.png](img/1647097202.png)
#### Transport vs Tunnel
- Transport mode simply encrypts packets, providing host-to-host encryption but using the original header
- Prevents contents being read, but does not stop traffic analysis or manipulation of the header
- Tunnel mode (usually gateway-to-gateway) protects some segment of a channel with encryption
- Provides some resistance to traffic analysis, and completely protects manipulation of the payload
- VPNs are commonly implemented this way
![1647097501.png](img/1647097501.png)
### Network Attacks
#### ARP
- ARP is a protocol used to obtain physical MAC addresses for given IPs
- It is used prior to constructing IP and TCP packets for communication
- Network layer
![1647097704.png](img/1647097704.png)
##### ARP Cache Poisoning
- We can simply send an unrequested ARP reply, and overwrite the MAC address in a hosts ARP cache with our own
![1647097845.png](img/1647097845.png)
##### ARP Protection
- Some OSs ignore unsolicited ARP requests, or can be configured to use ARP differently
- Some software, such as intrusion detection packages, will include ARP spoofing detection
- Maintain a log of current MAC:IP assignments and ARP requests / replies
#### DNS
- DNS translates domain names into IP addresses
- DNS packets are UDP
- Stateless on the transport layer
- DNS resolvers will cache the IP for awhile
##### DNS Spoofing
- If we poison the cache of a nameserver people are using, we can replace a website lookup with our IP
- Can be achieved through prior ARP cache poisoning, a reply flood or a Kaminsky attack
![1647103405.png](img/1647103405.png)
###### DNS Protection
- *Random query numbers* help protect against spoof replies
- Since the Kaminsky attack, most resolvers now *randomise the source port* too
- DNSSEC aims to tackle DNS exploits by authenticating the name server and providing integrity for the messages
### Denial of Service
- A denial of service attack is an attempt to make a machine or network resource unavaliable to its authorised / intended users
- This will usually involve flooding a machine with enough requests that it can’t server its legitimate purpose
- ping flood
- A distributed denial of service occurs where there is more than one attacking machine
#### TCP Syn Flooding
- Attacker initiates a genuine connection but then immediately breaks it
- Attack never finishes 3-way handshake
- Victim is busy with the timeout
- Attack initiates large number of syn requests
- Victim reaches it’s half-open connection limit
![1647104111.png](img/1647104111.png)
#### Amplification Attacks
- Regular attacks are your bandwidth vs your targets
- Amplification attacks utilise some aspect of a network protocol to *increase the bandwidth* of an attack
![1647104236.png](img/1647104236.png)
##### Smurf and Fraggle Attacks
- Smurf attacks broadcast an ICMP ping request to a router, but with a spoofed IP belonging to the victim
- A fraggle attack is identical in principle, using UDP echo packets
![1647104391.png](img/1647104391.png)
##### DNS Amplification
- Recursive resolvers respond to DNS queries then return a response
- This response can be many times larger than the query
![1647104517.png](img/1647104517.png)
- In an ideal world, all DNS resolvers would:
- Use an authorised list of requesters
- e.g. ISPs allowing requests from only their customers
- Egress filtering
- Many DNS servers are set up incorrectly, and will happily amplify your traffic - **Open resolvers**
- Botnets maintain lists of these open resolvers and there are projects attempting to shut these down
##### NTP Amplification
- NTP is a protocol for synchronsing time between machines
- Extremely similar to DNS amplification
- `MON_GETLIST` request returns the list of the last 600 contacts
- Gives 200x amplification
- `MON_GETLIST` is deprecated because of this attack
##### Slow Loris
- Opens numerous connections to a server
- Begin an HTTP request
- Send just enough traffic to stop the connection from closing
- Apache2 creates a new thread for each connection
- More connections slow the server down significantly
- The attack only sends bytes of data at a time making it extremely easy to do
+194
View File
@@ -0,0 +1,194 @@
# Firewalls
- A hardware and/or software system
- Prevents unauthorised access of packets from one network to another
- All data leave any subnet must pass through it
![1647287782.png](img/1647287782.png)
### Firewall Functions
- Implements *single point* security measures
- Security event monitoring through packet analysis and *logging*
- Network-based access control through implementation of a rules set
**Network Firewalls** - placed between a subnet and the internet
**Host-based Firewalls** - placed on individual machines
- A standard home router is a good example of a network firewall
![1647288145.png](img/1647288145.png)
#### DMZ
- A demilitarised zone is a small subnet that separates exrternally facing services from the internal network
![1647288286.png](img/1647288286.png)
- Imagine we have a web and email server running, these servers need different firewall rules to personal machines on the network
##### Basic Function
- Defends a network against parties accessing *internal services*
- Can also restrict access from *inside to outside* services
- Network Address Translation
- Hides the internal machines with private addresses
**Firewalls are not enough**
- Cannot protect against attacks that bypass the firewall
- e.g. tunneling
- Cannot protect against internal threats or insiders
- Might help a bit by egress filtering
- Network firewalls cannot always protect against the transfer of virus-infected programs or files
#### Packet Filters
- Specify which packets are *allowed or dropped*
- Rules based on:
- Source / destination IP
- TCP / UDP port numbers
- Possible for both *inbound* and *outbound* traffic
- Can be implemented in a router by only examining packet headers (**IP / TCP**)
##### Packet Filter Rules
- Rule execution depends on implementation
- `IPTABLES`: **First** rule to match is applied
- `PF`: All rules are examined, **last** match is applied
- Rules are organised in *chains*, which are logical subgroups of rules
- Depending on the packet, different chains are activated
###### IPTABLES
- An application that provides access to the Linux firewall rule tables
- Not actually a firewall, but configures the firewall
- The firewall is mostly implemented as `netfilter` modules
###### Tables and Chains
- `IPTABLES` uses tables to store chains
- Default is the filtering table
- Chains are ordered in lists of rules
- Rules match, or they don’t
- Matches result in a **jump**, else we check the next rule.
![1647289401.png](img/1647289401.png)
Default policy on this chain is `DROP`
- There can be multiple chains per table
- e.g. a `TCP` handling chain
- Jumps can go to `ACCEPT`, `DROP`, `LOG` or another chain
- Complex behaviour can be built up
![1647289523.png](img/1647289523.png)
##### Defaults
- There are four built-in tables in `IPTABLES`
- Filter
- `NAT`
- Mangle - packet alteration
- Raw - skips connection tracking
- The default table is the filtering table, including input, output and forward chains
![1647289692.png](img/1647289692.png)
###### Rules Examples
- Using the command line, we add rules onto the end of chains
```bash
$ iptables -A INPUT -i eht0 -p tcp --dport 80 -j ACCEPT
$ iptables -A OUTPUT -i eht0 -p tcp --sport 80 -j ACCEPT
```
- Remember `http` requests are not sent from the client’s port 80, it is sent from a random high numbered port
- This is how clients can have multiple web requests open at the same time
##### Policies
- **Permissive** - allow everything by default except dangerous services
- Make a black list
- Easy to make a mistake or forget something
```bash
iptables -p INPUT ACCEPT
iptables -p FORWARD ACCEPT
iptables -p OUTPUT ACCEPT
iptables -A INPUT -s X.X.X.X -j DROP
iptables -A OUTPUT -p tcp --dport ssh -j DROP
```
- **Restrictive** - block everything except designated useful services
- Make a white list
- More secure by default
```bash
iptables -p INPUT DROP
iptables -p FORWARD DROP
iptables -p OUTPUT DROP
iptables -A INPUT -p tcp --dport ssh -j ACCEPT
iptables -A OUTPUT -s 192.168.0.2 -j ACCEPT
```
#### Packet Filter Issues
- Packet filters are simple, low-level and have high assurance
- However they cannot:
- Prevent attacks that employ application specific vulnerabilities
- Do not support higher-level authentication schemes
- Easy to accidentally allow or deny packets incorrectly
### Stateful Packet Filters
- Understand requests and replies (`ACK/SYN`)
- Dynamically generate rules
- Based on what it sees from TCP handshakes (can be FTP or SSH etc)
- Can support policies for a wider range or protocols
- `IPTABLES` has a module for stateful packet filtering
- Allow incoming / outgoing SSH connections
![1647290573.png](img/1647290573.png)
#### Connection Tables
![1647290603.png](img/1647290603.png)
- `ACK` packets are used to keep track of the session - the connection is ongoing
- Packets without the `ACK` are the connection establishment messages
#### Application-level Gateways
- Packet filters have limited criteria that allow data in and out
- An application gateway considers the *application-layer* protocol that is in use
- For example if someone sends an `HTTP` request to port 22, it is blocked
##### Proxy Server
- Proxy servers initiate a connection on our behalf
- They can block certain access, and scan for malicious files or web pages
![1647290781.png](img/1647290781.png)
**Issues**:
- Large overhead per connection
- More expensive than packet filtering
- Configuration is complex
- A separate server is required for each service
### Network Address Translation
The shortage of IP addresses mean that most routers now perform NAT automatically
![1647290897.png](img/1647290897.png)
- The implicit advantage in NAT is that your machine is almost totally hidden from the internet
- Only **established connections** are forwarded to your internal machine
- Or, specific **port forwarding** rules
- This prevents any unsolicited attacks on random ports, but no other types of attack
@@ -0,0 +1,100 @@
# Internet Security
#### Internet Treat Models
- Different to other treat models:
- The attacker isn’t in control of the network
- The attacker hasn’t got access to the target’s OS
## Cookies
- `HTTP` is a **stateless** protocol
- Most of what we do online is **stateful**
- Cookies are small text files used to provide *persistence*
- Servers can provide cookies during HTTP responses, using `Set-Cookie`
- Browsers will return any cookies for a given domain in `GET` and `POST` requests
![1647531804.png](img/1647531804.png)
### Types of Cookie
- **Session** - Deleted when the browser exits, contain no expiration date
- **Persistent** - Expire at a given time
- **Secure** - Can only be used over `HTTPS`
- `HTTPOnly` - Inaccessible to `js`
- Makes it harder to steal
##### Third Party Cookies
- Cookies are associated with the domains that produced them
- `amazon.com` cookies don’t go to `google.com`
- Some websites include request to other domains, such as 3rd party advertisers
- These serve cookies *a lot*
- This is how advertiser companies know what ads you’ve been served and what adverts you’ve clicked on
### Cookie Vulnerabilities
- How a website uses a cookies is up to the server
- Many create a `SID` to authenticate users, for example to *keep me logged on*
- Obtaining this cookie - *cookie stealing* - lets you **hijack** their session
- `HTTP` Cookies can be stolen simply by monitoring
- `HTTPS` will require cross-site scripting attacks or DNS poisoning
#### Cross-site Scripting (XSS)
- A type of *injection attack*, similar in many ways to an SQL injection
- HTML is read by a browser and is a combination of content and structure
- If we can inject `html` structures into the content of a website, the browser will simply execute these
- e.g. a `<script>` tag
##### Reflected XSS
- A malicious URL that inserts an exploit directly into the page returned by a server
- Consider a 404 page at some address
- If we embed code into the url
- ![1647532522.png](img/1647532522.png)
- Modern browsers will throw up a warning
##### Persistent XSS
- Even worse, no need to trick people into clicking links
- Any website that doesn’t properly sanitise `html` tags from user input is vulnerable
- Blog posts with comment sections are obvious targets
- Forums, web comments, shopping reviews
###### The Samy Worm
- In 2005 Samy Kamkar wrote an XSS-based attack on MySpace
- ![1647532776.png](img/1647532776.png)
- Fastest spreading virus of all time
### Preventing XSS
- Wesbites must aggressively escape html characters from *any* user input / output
1. Locate all positions in which a website handles untrusted data
2. Escape appropriately depending on type of input
- When you consider all of the things people input on interactive websites, this can be a rela problem
- You also need to find all of the bizarre obfuscated versions of XSS
- Use an encoding library, which will handle all of these edge cases
### Cross site Request Forgery (XSRF)
- When a user puts in a `HTTP` request, they will also send any relevant session cookies
- e.g. an `SID` from having logged in
- If the user has already authenticated, a malicious URl can then perform some action on their account
- `http://shop.com/account.php?act=editemail&e=attacker@mail.com`
#### XSRF in POST
- Most websites use POST, this is little defence
- The phishing email just points to a convincing website with a malicious form on it
- ![1647534757.png](img/1647534757.png)
#### Preventing XSRF
- XSS vulenerabilties make XSRF a lot easier
- Use **synchroniser tokens**
- Each website form has a one-time token that the server validates when the form is submitted
@@ -0,0 +1,127 @@
# Database Security
- OS security is quite data oriented
- Usually isn’t concerned with file contents
- Database security is concerned with information
- Can look at content
- Can often be inferred even when stringent access policies are in place
#### SQL Security
- Three entities
1. Users
2. Actions
3. Objects
- Users invoke actions on objects
- Newly created objects are owned by the creator
- Privileges can be granted
- Granter, grantee, object, action, grant-able
#### View-Based Security
- Views are derived relations
```SQL
CREATE VIEW pharm_order AS
SELECT DrugDB.Name, SUM(Total)
FROM Patients, DrugDB
GROUP BY (DrugDB.Name)
WITH CHECK OPTION
```
This view abstracts the drugs away from the patients, so that the admin can order the correct amount of drugs without violating doctor-patient privilege
##### Why use Views
- Views are a flexible way of creating policies closer to application requirements
- Views can implement **controlled invocation**
- Data can easily be reclassified
- Deleting views instead of changing permissions is much easier
- Never have a situation where an application has access to raw data
##### Why Not?
- `INSERT` / `UPDATE` actions depends on the `CHECK` options, else might be **blind inserts**
- This is where someone can’t access the data, but can update it
- Completeness and consistency are not achieved automatically
- Can quickly become very inefficient
- Views can be cached, if not can become very slow
#### Statistical Databases
- Where access to data is restricted access to aggregates is permitted
- This means averages, sums can be looked at
- However, individual records cannot be viewed
##### Inference
- Since individual items are sensitive, we cannot permit access
- Statistical queries are useful, but by definition refer to data
- Some queries can reveal information on the underlying data - *Covert Channel*
###### Example: Salaries
- S = The sum of all salaries in the department
- T = The sum of all salaries for the department except those who have “Department Head” as “Position”
- Boss’ salary = S - T
Solution: Do not allow sets of just one
- S = Sum of all salaries
- T = Sum of all salaries of women, and anyone whose first name is Albert
- U = The sum of all men’s department salaries
- Albert’s salary = T + U - S
Solution: Do not allow conditions that refer to just one
- S = Sum of all salaries
- Number of department heads named Albert not allowed
- T = sum of all salaries for those named Albert
- U = The sum of all salaries for department heads
- V = The sum of all salaries for those who are not department heads, or named Albert
Salary = V + T + U - S
##### Further Defences
- Data swapping - swap records but keep stats the same
- Noise addition - alter aggregate output (a little bit)
- Table Splitting - Separate data completely
- User Tracking - Log queries
### SQL Injections
- It’s common for user input to be read and then used within an SQL query
- Unexpected user input can completely rewrite the query
- Nears striking similarities to XSS attack
- An application or website is vulnerable to an injection if it doesn’t filter SQL control characters:
- `‘` Represents the beginning or end of a string
- `;` represents end of a command
- `/*...*/` - comments
- `–` - comment a line
- Login pages will request hashes from the database
#### Blind SQL Injection
- Most servers won’t directly output SQL errors to the screen
- A *blind* SQL injection performs database analysis without any actual output
#### Fingerprinting the DB
- Some commands are specific to an individual DBMS
`http://shop.com/items.php?id=2; waitfor delay '0:0:10'--`
This will work on `MS SQL` but not `MySQL`
- Once you know the DB, access the system tables
##### Union
- `UNION` appends (not joins) two tables together
- They must have the same number of columns
#### Second Order SQL Injection
- Entry points may be checked for speical characters, but internal functions?
- Store the exploit in one pass, then have it executed later
@@ -0,0 +1,137 @@
### Anti-Virus
- Signature-based detection
- Store some small code signature for each virus
- Scan files either in bulk or at run-time, compare with the signatures on file
- Generic signatures
- Hashing the entire file is a bad idea, the author only needs to add a `nop` to completely change the signature
- Also hashing every executable is slow
- Instead we identify key pieces of the malware and hash that
- ![1648478154.png](img/1648478154.png)
- This method is never going to catch a virus it’s never seen before
- Heuristics
- Determine what actions and rules a virus program will normally adopt
- Start the program in a `VM` and see what it does
- Theoretically could detect a virus that doesn’t strictly match some signature
- Only if it does the same thing as a virus its seen before
- A lot slower than signature detection as it needs to be run in a VM before the user is allowed to open it
- What if the virus sleeps for 20 seconds before doing anything? very hard to detect
- Machine learning
- ![1648478649.png](img/1648478649.png)
### Network Attack Models
- Firewalls don’t protect against
- Attacks using valid protocols
- Insider attacks
Intrusion **Detection** Systems (IDS)
- Detects possible intrusion attempts
- Generates alerts and logs for administrators
Intrusion **Prevention** Systems (IPS)
- Identical to IDS except also stops the attack
#### IDS Deployment
- Host-based (HIDS)
- Monitors a *single host* to find suspicious activity including resource / app usage
- In many ways modern anti-virus does this
- Additional layer of security software running on a host within a protected LAN or VPN
- Creates a profile of usage for specific users
- Can monitor CPU, memory use, application use and the network stack
- Network-based (NIDS)
- Monitors **network traffic** and analyses packets from different protocols to identify suspicious activity
- Placed at a viewpoint on a network to examine and analyse traffic
- Installed on a firewall or in a DMZ
- Installed behind a screened subnet
- May perform deeper analysis than many firewalls
- like stateful protocol analysis and deep packet inspection
##### Components of a IDS
- Sensors / Agents: collect and collate data from multiple viewpoints on a network
- Analysers: ascertain if an intrusion has taken place
- Reporting: notify the administrators via alerts on a console or graphical interface
> Multiple sensors allow us to **distribute capture**, but **centralise** computing **overhead**
##### Detection Modes
- **Stateful Protocol analysis**
- More complex version of a stateful packet filter
- Hold detailed session information on protocols being used, examine for attacks
- Why is this user logging on as root?
- Why is this command being send a 1000 byte buffer as a parameter (buffer overflow)
- Computationally costly and requires the IDS have all possible versions of these protocols defined in its database
- **Signature-based**
- Fingerprinting sequences of operations or packets
- Like antivirus, signatures are created and stored in a database - operations as well as binaries
- If operations match a defined singature, then an alarm is triggered
- Include some form of attack language
- Mechanisms to describe sequences of events
- Maintain and monitor intermediate states and event transitions
- The pros and cons of these systems are identical to their anti-virus counterpart
- Computationally efficient
- Always spots know attacks
- Always misses unknown attacks
- Detailed signature databases must be kept up-to-date
- Example: If there is a large amount of `ICMP` traffic, many `TCP` packets (`SYN` packets)
- These connections going to a variety of other hosts
- *If a host establishes more than 3 tcp connections to different hosts in 5 seconds, its port scanning*
- **Anomaly-based**
- Built a model of *normal* and find deviations
- Anomaly detection has wide-ranging application from IDS to banking fraud
- Build up a picture of normal usage, and detect when usage moves beyond what is normal
- Always a trade off between **false positives** and **false negatives**
- ![1648481248.png](img/1648481248.png)
- Run a host within a quarantined environment and collect training data
- Constructed by monitoring audit logs
- Sometimes rely on analysis of sequences of system calls through normal behaviour
- ![1648481362.png](img/1648481362.png)
- However network traffic is more complex than a normal curve
- ![1648481744.png](img/1648481744.png)
- Very hard to decide if network traffic is nefarious or not
###### Snort
- Snort is a powerful and well established IDS
- Also free!
- Uses rules to analyse network packets, and then can provide alerts or logging
- Snort has built in rules for detecting `nmap`m a logged scan may look like this:
- ![1648480866.png](img/1648480866.png)
- The machine `10.0.4.1` is sending out packets with incremented port numbers
- The time stamps on the data show the packets are being sent extremely quickly
- All these packets are synchronised packets, its not waiting for `ACK` packets
###### Nmap Timings
- You can avoid detection when using `nmap` by reducing the speed of the scan
- The makes port scanning very hard to distinguish from general network noise
- `nmap` contains 6 timing options
- paranoid mode leaves 5 minutes between packets
- insane mode is basically a DDOS attack
#### Machine Learning
- Machine learning approaches train a model to make predictions on data
- Support vector machines, neural networks etc
##### Neural Networks for ID
- A network can be pre-trained
- Sensor measurements are then passed through the network
- Activations in the specific output neuron signal an alert
![1648481908.png](img/1648481908.png)
- Scales badly
- Search space can increase exponentially
- Real-time data
- False negatives
- Limits in the representation
- What is normal can change
- Do we retrain and risk learning an intruders behaviour?
@@ -0,0 +1,96 @@
## Cyber Threat Intelligence
- Broad Definition
- Any information about threats that can assist decisions for preventing and mitigating an attack
- Examples
- Reading new papers
- Read incident reports
> “Cyber Threat intelligence is information about threats and threat actors that helps mitigate harmful events in cyberspace.” [Wikipedia, 2021; Pierluigi Paganini, 2020].
#### Threat Inelligence Type
![1648755300.png](img/1648755300.png)
#### Threat Intelligence Sharing
- Standardised language
- **S**tructured **T**hread **I**nformation e**X**pression (STIX)
- Standardised Exchange Mechanism
- Trusted automated Exchange of Indicator Information (TAXII)
- STIX and TAXII are to enable automated cyber threat information exchange across organisation and product boundaries
##### Structured Threat Information Expression
- Designed for sharing and analysing threat intelligence
- Can be understood by humans
- Structured language for automation.
- Can be understood by security technology
- Active community of developer and analyst
- International standard in OASIS
![1648755739.png](img/1648755739.png)
![1648755749.png](img/1648755749.png)
###### Flexible Sharing Models
- Most sharing models are variants of these three basic models
![1648755842.png](img/1648755842.png)
![1648755851.png](img/1648755851.png)
![1648755869.png](img/1648755869.png)
#### Cyber Kill Chain
- Kill chain is a term used bu the US military
- Lockheed Martin’s process to explain and defensively mitigate future threat
- Deconstructs a threat to individual components
##### Reconnaissance
- The attacker research on the target before the actual attack starts
- Through Internet Search, and social media
##### Weaponisation
- The attacker develops a malicious payload and send to the victim
- This setp happens at the attacker side, without contact with the victim
- Difficult to interrupt for prevention
- No longer requires advanced skills
##### Delivery
- The attacker sends the malicious payload to the victim by email or other means
##### Exploitation
- Triggers the intruders’ code
- Targets can be
- Application or host system
- An operating system feature that auto-executes code
- User’s themselves
##### Installation
- Installs malware, remote access Trojan or backdoor on victim system
- Allows the adversary to maintain persistence inside the environment
- Point in time within a much more elaborate attack process that may take months to operate
##### Command and Control
- The attacker creates a C2 channel in order to control the system remotely
- This step is relevant throughout the attack life-cycle, not just when malware is installed
##### Action on Objectives
- The attacker takes actions to achieve his original objective inside the victim’s network
- Elaborate active attack process that may take months
- Information Theft
- Hacker Fame / Hactivism - Defacement
- Extortion - Ransomware
- Nation State Leverage
- Destructive malware
- A point to compromise additional systems
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 412 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 294 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 204 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 229 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 113 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 131 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 37 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Loaded 100 of 366 files, more files were not shown because too many files have changed in this diff. Show more