johnny-dreamguns
10/7/2019 - 9:44 PM

Security Training

SECURITY TRAINING

1 Intro

Three Pillars Confidentiality - Information is only available to those users authorized to see it

Integrity - Ensures data hasn’t been tampered with

Availability - Ensure systems are available when needed

Secure Coding Principles / Practices

Input Validation Consider all input as untrusted

Validate and sanitize all input from untrusted sources

Economy of mechanism Try to keep the design of the simple as simple as possible to reduce the likelihood of bugs

Complete Mediation All accesses to resources / pages / services should be checked to ensure they are allowed

Least Privilege All entities (accounts, processes, servers) should have the least amount of privilege required to perform their job

Defence in depth Implement multiple layers of defence so if one fails it doesn’t compromise the whole system

Secure Defaults The default behavior of the software should be secure, password complexity and aging requirements should be enforced. Users may be able to turn these off but at their own risk

Open Design The security of the application should not rely on it’s code being kept secret. e.g. Linux source code is freely available but it is still secure

Fail Safe Design the security so that a failure or unexpected event should result in an operation being disallowed

Thinking Evil If I were evil, how would I abuse this feature / application

2 Authentication

Determine if a person is who they claim to be

  1. User provides proof of who they are
  2. Authenticator validates that proof
  3. Authenticator provides something to prove you are now trusted

1. User Provides proof of who they are

Real world example Providing an ID to prove you are who you say you are to gain access to a building

Web example Providing a username and password and being given a session cookie in return

Each of the 3 steps above can have vulnerabilities, credentials should always be transported over an encrypted channel such as https otherwise a suitably positioned attacker can eavesdrop

Common Flaws Authentication is sometimes not enforced at all

Directory Brute Forcing Tools can brute force request directories or pages looking for pages that haven’t been restricted. These can then be exploited by attackers

Tool example: dirbuster

How to protect All pages and resources require authentication, do not rely on hiding pages / resources

All authentication controls must be done server side, JS controls can be easily bypassed

Use established services / libraries when possible, there is no point in reinventing the wheel

Use a centralised system for authentication

Segregate authentication logic from resource being requested

All authentication controls should fail securely

2. Authenticator validates that proof

Username enumeration User name enumeration is when an attacker gathers valid usernames

To Protect: Login / forgotten password / registration pages shouldn’t give out clues when a user has provided a valid username

Error messages should be identical no matter which part of the data was incorrect

If this isn’t possible then CAPTCHA should be used

Password guessing / brute force Once an attacker has a valid username they will likely use a brute force password attack to try different combinations to gain entry

To Protect: To protect then account should lock after 5 failed attempts, better to unlock again after a period of time so as not to provide a way for attacker to inconvenience users

Should also be restrictions on frequency of attempts to slow down a machine attack

Program should raise an internal alert if this sort of activity is detected

Enforce password complexity and length requirements, deny dictionary passwords

Enforce password changes with a password history to stop users recycling them

The last successful login should be displayed to the user when they login

Use multi factor authentication for sensitive applications, PIN numbers, RSA tokens, thumbprints

3. Authenticator provides something to prove you are now trusted

After authentication is completed the web application usually sets a session cookie

This is used to identify the subsequent HTTP requests

If an attacker can get hold of a user’s session ID they can hijack the session and impersonate the user

To Protect: Use web framework to generate session ids as it will generate sufficiently random values

The session cookie should only be located in the HTTP cookie header, do not pass session id as a get parameter

Ensure sessions have an appropriate timeout

Provide logout functionality

Terminate a session if the IP address associated with it changes

Also terminate if the same user logs in when the previous session is still active

Regenerate session id for each successful login

Session cookie attributes Ensure ‘secure’ attribute is set on cookie, this instructs the browser that the cookie should be transmitted securely over an encrypted channel

Set cookie with ‘httpOnly’ attribute, this means it can’t be accessed by JavaScript during a cross site scripting attack

Set the domain and path attributes for the cookie

3 Authorisation

When authorization controls are not complete then malicious users can be get accessed to resources or functionality that they shouldn’t have access to

This can be exploited if buttons are only hidden in the interface rather than enforced server side

Once they know the URL of these pages they can access them, bypassing the security

Privilege Escalation Insecure direct object references

This is when an application exposes data such as an id in the url and the user takes it and uses it maliciously somewhere else

If authorization checks are not properly implemented then attackers can use this data

Checks server side Checks need to be performed on a trusted system (server side) to check that a user is allowed to do the requested action

Avoid using parameters that can be controlled by the user

Use per-user indirect object references

4 Client Side Attacks

These attacks target users of the application

It uses vulnerabilities in the application so if we fix the vulnerabilities the attacks aren’t possible

Can trigger a malicious payload or trigger behavior on the site without them knowing these actions are happening

## Cross Site Scripting - XSS

User input from the url or the page is included in dynamic content without validation / encoding / escaping

The malicious code injected is used in the context of the user’s session in the browser

This allows the malicious script to access the session cookie, page content, HTML5 web store

It can log the user’s key presses to gather passwords and PINS

It can alter content of the website

It can redirect to malicious websites

Types of XSS

Stored / Persistent XSS Attacker’s payload is stored on the target server such as in the database

Each time the user loads this data from the server the malicious payload is executed

Reflected XSS Attacker’s payload present in the URL is immediately returned to the user but not stored server-side

This exploitation will involve some kind of social engineering, a user would need to click on a link to go to the URL for it to happen

XSS Defence

Output Encoding Untrusted data should be encoded when output

Use a standard vetted library to do this encoding

HTML Entity Encoding Replace certain ASCII characters with their HTML entity equivalent

Input Validation Use a whitelist or regex to ensure the input is in the correct format

HTTPOnly Flag Use this flag on a cookie to ensure that JS can’t access cookie data

CSRF

Forces the victim to send an unauthorised command (HTTP request) to a vulnerable website on the attacker’s behalf

The command runs in the context of the victim user including any session cookies

The victim doesn't realise that this request has been made

If the user is authenticated on that website then the request will carry the session cookie and will trigger an unauthorized command without the user knowing it has happened

CSRF Prevention

Synchroniser Token Pattern Adding a per-session or per-request random token associated with every sensitive transaction and checking it’s validity server side

Challenge Response User may have to enter CAPTCHA on enter password again

Check Referrer / Origin headers Check where the request came from before allowing it

How not to fix CSRF Using a secret cookie Thinking it doesn’t affect POST requests, it does Multi step transactions do not prevent CSRF

Cross Site Redirects

Using a returnUrl= param in a GET request, the user can change it to redirect the user to a rogue website

The rogue website might be branded up like the real one to convince the user

Defence against Cross Site redirects Avoid using redirects in GET parameters

Use a whitelist of redirect locations

Deny protocol so redirects can only be to relative paths

5 Server Side Attacks

SQL Injection Attacks

User input is sent server side that is then executed by the database

The malicious user can include SQL in an input field that will be executed

Example Exploitation Using a UNION operator the user brings back data from all of the other tables in the database

Using trial and error the user can gather information

SQL Injection Defence The gold standard is to use parameterised queries, a dedicated API fills in the parameter values for you rather than using string concatenation

If you can’t use parameterised queries then use

Other injection attacks Injection attacks could also happen using XML, JSON, shell commands

File I/O Attacks

Insecure File Upload If the uploaded file is not validated then many security vulnerabilities can arise

Attackers may be able to upload a web shell (a web script that allows shell like functionality, JSP, ASP, PHP etc)

An attacker might be able to overwrite the files on the server or upload a huge amount of data causing a denial of service attack

Secure File Upload

Validate file extensions Do not allow .jsp, aspx, .war files as they can be used to upload web shells

html, .js shouldn’t be allowed as they can run client side attacks

Validate file content Inspect the headers or examine the content server side to ensure it is a real image

Scan content to check for malware

Safe Upload Location Store files in a different location than the web root and turn off execution privileges in the upload folder

Save images to the database

Rename uploaded files to random / unpredictable names

Explicitly set an allowed extension rather than using the one provided

Directory Traversal This happens when the app uses untrusted data to build a file path that is then used for I/O file operations

Eg taking a filename as a GET param and manipulating it to show other files on the server

Protect against this by whitelisting the allowed filenames

Avoid filenames in the GET request by using ids to look up the file

6 Cryptography

Encode Encoding transforms data into a different format for various reasons

Decoding that data requires no secret, anyone can do it

Eg HTML encode or Base64 encode

Base64 encoding is used when data needs to be reliably transferred in text format but it is not more secure than plain text

Hash A hash function is a cryptographic function that allows us to transform data

The catch is good hash functions are computationally infeasible to revert, they are ‘one way’ functions

A hash function will always output data to a set number of characters regardless of the input

A hash collision is when two inputs result in the same output

When would we use hash?

File verification Verify that a file copied or transferred has not been corrupted / tampered with

After download user can check their hash matches the one listed on the site

Password Storage Passwords should never be stored in plain text

Encrypting passwords is not recommended

Ensure password hashes are salted, salts are appended to the password before it is hashed then they are stored with the password

Salts make precomputed look up attacks harder

Newer hash functions should be used

Symmetric Encryption Two parties using a shared key that is used for encryption and decryption

The key is usually shared by a separate channel

Usually used for large files and communications

Example algorithms include Twofish, DES, 3DES, AES

Asymmetric Encryption Uses two different keys, a public key and a private key

The keys are bound by hard to solve mathematical problems

We share public keys amongst parties that want to communicate securely

Each party keeps the private key to themselves

You can encrypt a message to someone using their public key

Their message can only be decrypted using their private key

This solves the problem of securely sharing keys

Examples include RSA, DSA

**Symmetric VS Asymmetric ** Symmetric is much faster

Sharing the key is tricky

You need a key per conversation so it’s not very scaleable

Asymmetric is computationally expensive and slow

Often the solution is to use both

Asymmetric encryption can be used to share the symmetric key which can then be used for most of the work

This is how SSL works

Digital Signing Can use the private key to sign a message

Commonly approach is to hash the message and then sign the hash

Everyone can verify using their public key

A hash is small so it keeps things efficient

Digital signing is used when a Certificate Authority issues a certificate to an organisation and signs it with their private key

Browsers check the certificate against a predefined list of approved CAs

HTTPS / TLS

HTTPS is HTTP carried over an encrypted SSL (or better TLS channel)

Application Layer Use the TLS for all authenticated pages and sensitive content

Set the SECURE flag on sensitive cookies

Use HTTP Strict Transport Security header, this will instruct the browser to send all subsequent requests to that url using HTTPS

Web Server Layer Use the latest TLS

Use cipher suites with strong encryption

Prefer ciphers that support forward secrecy

Key Points Use established methods don’t roll own crypto

The use of cryptography doesn’t guarantee security, only when used well does it bring security

Use high level libraries

Understand where your weaknesses are, e.g. how to protect private key

7 Third Party Components

Frameworks can have vulnerabilities, they run on infrastructure that could have vulnerabilities too e.g. databases

If these components are vulnerable or incorrectly configured, the application and users are at risk

Common Vulnerabilities and Exposures (CVEs) A database maintained by MITRE for known vulnerabilities in public software

cvedetails.com lists vulnerabilities by product and vendor

Subscribe to security mailing lists for the components you use

When choosing new components consider their vulnerability history

Make sure you understand and enable security controls offered by web frameworks

8 Deployment Issues

In production turn off:

Information about the server version and tech used sent in responses Detailed error messages Directory listing shouldn’t be viewable

Test code and admin pages shouldn’t be accessible from production

Do not expose unneeded entry points, only the ports required should be open

Vulnerabilities - application server stack including OS and libraries can expose further vulnerabilities

Remove development and test data

Remove development and test accounts

Disable debugging features and verbose error pages

Implement secure build standards

Patch regularly

Minimise attack surface

Database Hardening Apply the principle of least privilege, ensure db users have the right level of access

Remove ‘extra’ functionality from the db server that isn’t used

Ensure the dbms runs under a low privileged account

Deny all other OS level accounts access to the db files

Ensure DBMS is patched and up to date

9 Integrating Security

Security is often the last thing that happens in the SDLC

The later a bug is caught, the higher the cost of fixing it

A vulnerability is just a bug

Design Review Catching design flaws as early as possible

Use an attacker’s mind-set

Look at entry points, data flow, interactions with other systems, trust boundaries, potential weaknesses, security controls

Code Review A great tool for catching vulnerabilities / security issues

Static Code Analysis Automatically analyze code and identify patterns that lead to vulnerabilities

An example would highlight user added content being used in a sql command, a potential SQL injection issue

Web App Vulnerability Scanners Another tool to reduce vulnerabilities

Analyses a running instance of the application

It will trigger different inputs and examine the behaviour

Complete Picture Security Requirements Design Review Manual Code Review Automated Code Review Automated Vulnerability Scanning Submit for penetration testing

10 Mobile Application Security

Mobile Threats Mobile apps are used on public and trusted wireless networks, hackers may be able to eavesdrop on communications between a client and its server

These attackers may be able to steal data or modify information

The communication channel between a client and it’s server should be treated as untrusted

An application may come under fire from an other application (malware)

Mobile devices can also be lost or stolen

Application may be tampered with and then redistributed

The device the application is running on should also be treated as untrusted

OWASP Mobile Top Ten Very similar to the non -mobile list

Insecure Data Storage Should store as little on disk as possible as device shouldn’t be trusted

Use secure OS API to store sensitive data

Otherwise it should be encrypted using a key not stored on the device

Insufficient Transport Layer Protection All communication with server should be transported over an encrypted channel

Should use https rather than http

WebViews should use encryption

Certificate pinning can be used so applications only use known endpoints

Unintended Data Leakage HTTP Caching If an application discloses what version of a library that it uses then an attacker can search for vulnerabilities in that software

Some frameworks have default caching locations. Caching server data can be very dangerous

Clipboard Sensitive information shouldn’t be copied to the clipboard where it may be stolen

Backgrounding When apps are placed in the background, other apps may be able to steal information from the thumbnail image

Logging Frameworks and 3rd party libraries should not log inform regarding app state

Keyboard Caching Keyboard apps may store info regarding spelling corrections or commonly used words

Passwords shouldn’t be stored

Analytical Info This info should not be stored locally and should be secure over the network

Broken Cryptography Use strong ciphers Use a well known established algorithm Don’t store keys on the device Keys shouldn’t be hardcoded

Client Side Injection SQL injection in local databases

Local file inclusion - restrict access to local files to stop WebViews accessing them

Interprocess Communication - Malicious applications may be able to send malformed data to crash applications

Cross Site Scripting - Disable JS on WebViews if possible, then ensure apps in web views are secure

Lack of binary protections Obfuscation - obfuscate the compiled application binary files to make reverse engineering hard

Jailbreak detection - detect when running on a device where the root user is accessible

Anti-debugging - detect if another app is attempting to debug

Anti-tamper - detect when app code has been modified