Monday, May 7, 2018

Common Application Security Attacks : Definition, Detection, Examples & Mitigation

SQL Injection:
Main reason: software doesn’t neutralize or incorrectly neutralize special elements that could modify the intended SQL command.
Detection Methods:
Automatic Static Analysis
Automatic Dynamic Analysis
Manual Analysis
Architecture/Design Review
Examples:
1)     Name’ or ‘a’ = ‘a’
2)     Commenting the limit
3)     Batch execution using ; Many DB don’t support that but if some does, attacker can execute other commands too.
4)     Use of stored procedures but still it cant provide complete care against SQL
5)     Query using shellcode
6)     Values used directly from cookies
7)     Whitlisting can cause issues too since few things has to be permitted.
Mitigations:
1)     Vetted library or frameworks : Hibernate or Enterprise Java Beans
2)     Paramterization to separate data and code
3)     Use prepared statements, parameterized queries or stored procedures.
4)     Run with lowest privileges.
5)     Security check at both client and server end
6)     Use whitelisting rather than just using blacklisting
7)     proper output encoding, escaping, and quoting is the most effective solution for preventing SQL injection, although input validation may provide some defense-in-depth.
8)     Implementation: ensure that error contains limited information about db.
9)     Use an application firewall as additional measures
10)  Environment hardening as in host process security.
11)  Detection mechanisms in case of any issues.



OS Command Injection
Same issue like SQL : No neutralization or incorrect neutralization of special elements.
There are two types of OS command injection:
1)     things are run within an application
2)     application passes the entire command to the system using exec() or createprocess().
Examples:
1)     Directory traversal attack
2)     Execution of Rm –rf commands
3)     Ls –al for web application that returns DNS information
4)     Appending & to run other application too along with the main application eg. program using other application latiLongitoLocation.
Mitigation:
1)     Use library calls rather than external processes to recreate the desired functionality.
2)     Run the code in a “jail” or “sandbox” that enforces strict restriction between process and the application. Any anomalies in the process must be quickly investigated. Unix  chroot jail or run the application using some 3rd party tools like appArmor etc. if java use java.io.FilePermission to restrict the file permission.
3)     For any data that would be used to generate the command, store the data locally in the session state rather than in cookies.
4)     Use vetted library like ESAPI etc.
5)     Use output encoding:
6)     Not encoded parameter: test<script>alert(1)</script>
7)     URL-encoded parameter: test%3Cscript%3Ealert%281%29%3C%2fscript%3E
8)     Double-encoded parameter: test%253Cscript%253Ealert%25281%2529%253C%252fscript%253E

9)     Canonanicalization is the way of creating canons of the input so that’s just data.

10)  Pass in the form of arguments rather than as application commands directly

11)  Use parameterization since it provide relevant quoting, encoding and validation automatically

12)  If some OS provides multiple way to execute a command, use whitelisting.

13)  Use input validation

14)  Use converstation as in id to filename so that path traversal would not be possible and reject other inputs.

15)  Environment hardening

16)  Error message should contain minimum info.

17)  Use firewall.

Buffer Overflow:
Mitigations:
1)     This is most common with C, C++ and Assembly language. Use language like Java, perl which has their own memory management module to avoid buffer overflow. Well if the underlying framework is not good, buffer overflow can still happen.
2)     Use vetted library : use safe string library. This is not the complete solution since for few things can be exploited without using buffer overflows.
3)     Certain programs and applications provides automatic buffer overflow protection like Microsoft Visual Studio/ProPolice/stackguard etc.
4)     Use following precautions
a.     Double check your buffer is of enough size
b.     While using loop make sure that we are not cross the size
c.      While copying the buffer from one to another, make sure they are of same size.
d.     If necessary, truncate all input strings to a reasonable length before passing.
5)     Input validation : white listing/black listing
6)     Check for values at client side and at server side too.
7)     Run or complile the program that randomly arranges the position of the executables and libraries in memory. This could make the address unpredictable and this could led to the prevention of jumping to exploitable code.
l.e : Address Space Layout Randomization and Position – Independent Executables.
      8) Use a CPU and OS that prevents DEP
     9) Replace unbounded string functions or other input functions with bounded functions
   10) Use the mapping file IDS to File name to prevent file name guessing.
   11) Use “jail” or sandboxing
  12) Run the code with least privilege.

Cross – Site scripting:
Not proper neutralization or incorrect neutralization of input that is placed in the output of web pages used by other users.
There are 3 main types of CSS:
1)     Reflected XSS or (non-persistent):
2)     Stored XSS or (persistent):
3)     DOM based XSS
For reflected XSS, hackers can encode the string with ASCII or with Unicode that makes it hard to realize users.
 Mitigation:
1)     Use a vetted library or framework like Microsoft’s anti-xss library, OWASP ESAPI etc.
2)     Escape other types of encoding and perform input validation.
3)     Perform security check at client side and at server side too.
4)     Use Parameterization
5)     Don’t allow any output encodings.
6)     HTTPONLY cookie means that the cookie is not accessible by javascript or other programming languages. This can be set by setting HTTPONLY flag set. Well this doesn’t provide complete solutions since XMLHTTPRequest and other powerful browsers can allow read access to HTTP headers though cookie field is set.
7)     Perform input validation. Peform at all the places from where user can input the values.
8)     Enforcement  by conversation.
9)     Use firewall
10)  Environment hardening.


Missing authentication for a critical function:
Example:
User is creating a bank account which has to be created by administrators only.
Mitigation:
1)     Use process authentication and authrorization approach.
2)     Perform check at client and serer side
3)     Use vetted libraries for authentication like OPENSSL or ESAPI

Missing Authorization
Use ACLS and capabilities
AuthZ stands for Authorization while AuthC stands for authentication.
Auth is not highly preferred term since that could resresent anything.
Developer can introduce this because he would feel that attack can’t modify cookies and trust the input data.
One way to avoid this is that the ID field described by the attacker matches the user fierld.
Mitigation:
Use role-based authentication access control but this would not prevent from horizontal attack.
Ensure that check is performed related to the business logic.
Use vetted libraries as in JAAS framework and OWASP ESAPI
For web application make sure that authorization is placed and every page. Make sure that all pages containing sensitive info. is not cached and every request is followed by the token.
Use a “default Deny” policy.


Use of Hard-coded credentials
There are two main variations: Inbound and outbound.
Hard-coded credentials are difficult to remove since that would require to modify the application which is time consuming process. Moreover it won’t be updated everytime.
If the credentials are hardcoded in the application, hackers could easily use that to hack other organization.

Mitigation:
Store passwords, user accounts separately from code.
Rather than providing an hardcore user account, ask user for “first Login” mode like Nessus
If the software must contain hard-coded credentials, perform access control check to make sure that no. of can see that.
Use one=way hashes with salting
Use timestamps to prevent replay attacks.

Missing encryption of sensitive data
Mitigation:
Use well-vetted algorithms.
Use threat modeling
US govermnemt requires FIPS – 140 for data protection
Use the concept of compartment and monitor any anomalies.
Don’t skip resource intensive steps
Sepreate code and data to make better protection


Unrestricted upload of File with Dangerous Type
Mitigation:
Generate a new name for the file rather than the user supplied to avoid file traversal and clients must not get any info regarding the naming convention.
Isolate the storage of files at other db to create multi-layer approach for data protection.
Do input validation and scan to avoid the upload of any malicious file
Define a very small set of allowable extensibles.
Ensure that only one extension is available. So, no one can process abc.php.gif
In case the code uses case sensitivity, make sure you convert them to specific case to avoid any issues.
Use jail or sandboxing
Run your code with lowest privilege.
Examples:
1)     Code reads the role of user from the cookie.
2)     Developer creates authenticationstatus in the cookie and uses this to determine if the user is authenticated or not. Hackers can easily modify it.
3)     Some code uses DNS queries to determine whether the request is valid or not. If someone posions DNS then attacker can change it very easily
Mitigations:
1)     Store sensitive data at the server side onlyu
2)     If information needs to be stored on client side, encrypt it and protect it using integrity to avoid any fucking. USE HMAC for doing this.
3)     With stateless protocols like HTTP use frameworks like ASP.NET view state or OWASP ESAPI session management feature to maintain the state.
4)     IF any check is performed at the client side, peforrm the same at server side too.
5)     Potential areas from where untrusted input can enter into the network:
a.     Parameters or arguments
b.     Cookies
c.      Anything read from network
d.     Environment variables
e.     Reverse DNS lookups
f.       Query results
g.      Request headers
h.     URL components
i.       E=mail
j.       Files
k.      Filenames
l.       Database
m.   Any external systems
                                                    i.     Such inputs can be inserted using api calls too. So make sure everything is kept secure


Execution with unnecessary privileges:
Examples:
1)     A code temporary raises the privilege level to root and then downgrades it to the normal users. But for that particular thread, if the executation may fail, the lowerprivilege function will never be called and the code will continue to run with higher privilege.
2)     Application uses unnecessary APIS to determine the location which is already available.
Mitigation:
1)     Lowest privilege
2)     Isolate the privilege code as much as possible.
3)     Raise the privilege as late as possible and drop it asap.
4)     Perform extensive check for such requests.
5)     When dropping privileges ensure that they are dropped successfully

CSRF
The web application does not whether the user really submitted the request or it was submitted by someone else.
Mitigation:
1)     Use vetted library or framework: anti-CSRF packages like CSRFguard by OWASP
2)     Ensure application is free from Cross site scripting
3)     Use NONCE
4)     Identify the dangerous operations and when user ask to do that, ask him again whether he really want to do that or not.
5)     Use “double submitted cookie method: Site generates a puseudorandom value along with the cookie. Due to same origin policy, malicious java-script can’t grad this value and they cant guess this pseudorandom value. But this technique requires javascript and any browsers who have disabled the javasript wont be able to work with this.
6)     Check the HTTP referer method but this is not that much effective since few browser would strip this field due to privacy issue.

Improper limitation of a pathname to a restricted directory (Path Traversal)
Software uses external input to generate the pathname without proper or improper neutralization.
If an attacker uses 0 or NULL then the string gets truncated.
Mitigation:
1)     Check the validation at client side and at server side too.
2)     Input should be decoded and canonicalized on the client side before being validated. Perform check after all the operation is performed. First validating and then canonicalizing could trigger a problem.
3)     Use build in path canonacilazation as in
a.     Realpath() for c
b.     getCanonicalPath() for java
c.      getfullpath() in ASP.net
d.     realpath() in perl
e.     realpath() in PHP
4)     Use vetted libraries that could avoid such weekness.
5)     Use an application firewall that can detect this issue in case the application cant be fixed.
6)     Run your code against lowest privileges.
7)     Create a mapping file that could check for the name to verify the intend of the user. So rather than dynamically creating the name, this can be used.
8)     Jail or sandboxing
9)     Identify and reduce the attack surface. As in store things in a separate library to avoid the reading of everything in case of hack.
10)  Error message must not present more information

Download of code without integrity check
The product or application download source code from the remote location and doesn’t check for the integrity and authenticity of the code. Performed using DNS cache poisoning or modifying the code in transmit. Use HMAC for this and encryption for confidentiality

Mitigation:
1)     Perform forward and reverse DNS lookups.
2)     Encrypt the code with reliable encryption standards.
3)     Use vetted libraries or frameworks that prevent this.
4)     When the code is to be downloaded, check using HMAC
5)     Run your code with lowest privileges.
6)     Sandboxing or jail

Incorrect authorization
A developer believes that the code can’t be changed by user inputs.
Done without proper neutralization.
Usually happens when the user is passed from single-signin to multi-signin
Mitigation:
Divide the users into multiple categories.use role based access control (RBAC) to reduce the area.
Make the check based upon business logic rather than only based on resources check as in make more granular check.
Use vetted library as in JAAS authorization framework or OWASP ESAPI
Make sure that check is performed at the client and at server side too.
Use ACLS or Capabilities and use “Default Deny”

Inclusion of functionality from untrusted control sphere
The software imports, requires or includes executables from the source outside the control sphere.
Mitigation understoodable.

Incorrect permission assignment for critical resources

Use of potential dangerous functions:
Mitigation:
This deals with using functions like APIs or other programs. So we have to include banned.h/allowed.h to avoid the loading of APIs


Use of broken or risky cryptography algorithm

Incorrect calculation of buffer size
The software doesnot calculate the size to be used when allocating a buffer.
Examples:
1)     User doesn’t include a space for a termination character
2)     Lets say we want to encode the application. Encoding of & requires 5 bytes while lets say we just allocated on a average 4 bytes. Now if someone inserts all &, that would led to buffer overflow.
3)     Lets say we want to calculate the size of the incoming packet. And by mistake we have specified the size of the integer as signed. So lets say a malicious packet provided the size of -3. Now lets say we are using malloc to generate the packets. This would fail. Or else lets say packet claims to be of some size but that’s of different size. In short heartbleed vulnerability.
4)     Then lets say, we are allocating 12 bytes for 4 data and instead of having 3, we are suppling 5 values for just 3. This could lead to buffer overflow.

Mitigation:
1)     When allocating the buffer make sure that’s of the largest size.
2)     Pay close attention to byte size discrepecies,precision, signed/unsigned, distinctions, truncation, conversations, casting, not-a-number calculation and how the languages handles this.
3)     Provide input validation
4)     Perform check at the client side and at the server side too.
5)     While working with packets, make sure that packet is of that size as in what is says and what its size is.
6)     Make sure we are including the space for null values too.
7)     Replace unbounded copy fucntions with bounded values.
8)     Use sizeof() functions
9)     Don’t use signed at every place.
10)  Use vetted libraries or frameworks like SafeInt in C++ or IntegerLib (C or C++)
11)  Environment hardening
12)  Sandboxing or jail
13)  Least privileges

Improper restriction of excessive authentication patterns

URL Redirect to untrusted site
Examples:
1)     A website uses url parameter to redirect the user to that particular website. Now, attackers can easily send the phishing link to users who would feel they are visiting the legitimate website but they would endup in fake website.
2)     A java servlet should never redirected an user to external website without verifying it.
Mitigations:
1)     Use whitelisting and not blacklisting methods
2)     Use an intermediate disclaimer page to the user that they are leaving the current page. Implement the long timeouts or force the users to click the link.
3)     Create a mapping for the ids and urls.
4)     Use CSRF mitigation techniques when we need to redirect.
5)     Do threat modeling
6)     Use application firewall.

Use of externally controlled format string
Software accepts the format string from the user.

Integer overflow:

Use of one-way hash without salt