09/03/2013

The Hackers Guide To Dismantling IPhone (Part 1)



Introduction

Hello everybody, it has been a while since I made a post, but this time is going to be a really long long post (that is why I am going to brake it in many parts). Lately my interest has significantly increased as far as the iOS platform is concerned.  The iOS is becoming more and more popular among the financial business sector companies so it came for me the time to expand my knowledge on IPhone devices. Plus since the complete industrialization of hacking (mostly because of the Chinese government, unit something is doing a good job) nowadays knowledge in iOS platforms is critical (they pay good money for iHacking). This post is going to include only hardening information and explain what the security measures are to block exploits and prevent buffer overflows etc. The second post is going to include network attacks and the third post is going to include attacks in the data of an iDevice.


Note: iOS the most advanced OS for mobile devices ever created (just kidding, I love Apple).

This blog post is going to focus on how to perform a complete penetration test on an iOS application, no time is going to be wasted on how to pentest the server component since the threat land scape is almost identical to that of a Web Application or a Web Service, and since you read my blog (if you don't start doing it) you should know by now that I covered most types of attacks for Web Applications and Web Services so far.

The iOS history

Since the release of the original iPhone in 2007, Apple has engaged in a cat-and-mouse game with hackers to secure their suite of devices for what has grown to nearly 100 million end users. Over this time, many improvements have been made to the security of the iOS, and the stakes have been raised by their introduction into circles with far greater security requirements.

What iOS is

iOS is Apple's mobile operating system, which is derived from Mac OS X, with which it shares the Darwin foundation, and is therefore a Unix-like operating system. Being developed originally for the iPhone, it then has been used on the iPod Touch, iPad and Apple TV as well. So in this article the iOS term specifically refers to the mini-operation system that run on all the iDevices (iPhone, iPod, iPad and Apple TV. In this little apple operation system, there are four abstraction layers: the Core OS layer, the Core Services layer, the Media layer, and the Cocoa Touch layer, which in total will roughly use 500 megabytes of the devices storage.


Note: The Core OS layer is written in C, while the higher layers that runs all interesting applications is written in Objective-C. The higher layer is the most interesting as far as the attacks are concerned.

For security and commercial reasons and considerations, Apple does not permit the OS to run on third- party hardware and also has a limitation on the usage of iOS on these iDevices. Therefore iOS has been subject to a variety of different hacking methods focusing on attaching functionality not supported by Apple. This hacking procedure is called iOS Jailbreak.

The iOS security architecture

While Apple was designing iOS operating system decided to increase the security by using various "tricks", (obviously iOS is based on the same core technologies as OS X) to reduce the attack surface. The attack surface is the code that processes attacker supplied input (e.g. SMS messages, Safari Web Pages etc.).  One of the many ways it did that was by not including various software packages in iOS (e.g. Java and Flash are unavailable). This automatically translates to iOS not processing Java and Flash input (Java and Flash have a history of security vulnerabilities). Another trick that Apple did to reduce the attack surface was to striped off part the functionality provided by the default software that comes installed with the iOS (e.g. Mobile Safari does not support some Adobe features).  Also the iOS OS was also stripped off from many applications compared to OS X e.g. the /bin/sh software is not included in iOS, which translates that if you write an exploit for iOS you would have to implant your own shell to your exploit, which means that your exploit would have to increase its size etc.

More on iOS security

Some of the core security features referenced per layer are: 
  • System architecture: The secure platform and hardware foundations of iPhone, iPad, and iPod touch.
  • Encryption and Data Protection: The architecture and design that protects the user’s data when the device is lost or stolen, or when an unauthorized person attempts to use or modify it.
  • Network security: Industry-standard networking protocols that provide secure authentication and encryption of data in transmission.
  • Device access: Methods that prevent unauthorized use of the device and enable it to be remotely wiped if lost or stolen.
Layered security mechanisms allow for the validation of activities across all layers of the device. From initial boot-up to iOS software installation and through to third-party apps, each step is analyzed and vetted to ensure that each activity is trusted and uses resources properly.

The following picture shows the security model of iOS, as described from above:


Note: Check out that the Apple root certificate installed in the iDevice ROM. Also that iDevices contain their own hardware crypto engines (impressive ee?). Once the system is running, this integrated security architecture depends on the integrity and trustworthiness of XNU (the iOS kernel). XNU enforces security features at run-time and is essential to being able to trust higher-level functions and apps.

More More on iOS security

Apple takes security very seriously and this is obvious from the security controls that are enforced during the execution of third party applications and iOS default pre-installed applications. The security controls explained here is required knowledge to understand how to pentest an iDevice and to later on set the threat landscape. The iOS OS basically enforces Mandatory Access Control (MAC) using the  security controls explained below.

The security controls enforced are listed below:

Least Privilege Principle: System files and resources are also shielded from the user’s apps. The majority of iOS runs as the non-privileged user "mobile", as do all third-party apps. The entire OS partition is mounted read-only. Unnecessary tools, such as remote login services, aren’t included in the system software, and APIs do not allow apps to escalate their own privileges to modify other apps or iOS itself.

Access by third-party apps to user information and features such as iCloud is controlled using declared entitlements. Entitlements are key/value pairs that are signed in to an app and allow authentication beyond run-time factors like unix user ID. Since entitlements are digitally signed, they cannot be changed. Entitlements are used extensively by system apps and daemons to perform specific privileged operations that would otherwise require the process to run as root. This greatly reduces the potential for privilege escalation by a compromised system application or daemon. 

Code Signing: To ensure that all apps come from a known and approved source and have not been tampered with, iOS requires that all executable code be signed using an Apple-issued certificate. Now given that individual developers need to test out their applications on iDevices and enterprises need to distribute apps just to their devices, there is a need to run apps without being signed by Apple. The method to allow this is called provisioning. An individual developer, a company, an enterprise or a university may sign up for one or more of the programs offered by Apple for this reason, in order to enable signing their code.

As part of the program, each developer generates a certificate request for a development and a distribution certificate from a set of private keys generated locally (e.g. by using openssl or a local certificate authority etc.). Apple then replies back with these two certificates. For more information see iOS developer program link.

Through the iOS developer portal then you can generate a provisioning profile. A provisioning profile is nothing more than a .plist file signed by Apple. The .plist file all is doing is list certificates, devices and entitlements (entitlement are configuration files describing what an app is allowed and not allowed to do). When this provisioning profile is installed (e,g, through the IPhone Configuration Utility or a third party Mobile Device Management software). 

The  developer provisioning profile can be used only for 100 devices (the devices listed have to be specific), while the enterprise provisioning does not have that limitation. Essentially provisioning adds accountability to all the apps that are allowed to be installed to an iDevice. 

The following screenshot shows the IPhone Configuration Utility:


Note:  This is obviously is not a signed profile, configured locally from my IPhone Configuration Utility.

The following picture show an enterprise configuration installed and how it shows through the iPhone configuration:


Note: See how the certificate show in the screenshot. This demonstrates the BOMGAR MDM software, that enforces a custom configuration profile.

Sand-boxing: All third-party apps are "sandboxed", so they are restricted from accessing files stored by other apps or from making changes to the device. This prevents apps from gathering or modifying information stored by other apps. Each app has a unique home directory for its files, which is randomly assigned when the app is installed. If a third-party app needs to access information other than its own, it does so only by using application programming interfaces (APIs) and services provided by iOS. The downside of this security model is that same rules apply for all apps (a third party app is not allowed to have more restrictive rules than another).  

Address space layout randomization (ASLR): ASLR protects against the exploitation of memory corruption bugs. Built-in apps use ASLR to ensure that all memory regions are randomized upon launch. Additionally, system shared library locations are randomized at each device start-up. Xcode, the iOS development environment, automatically compiles third-party programs with ASLR support turned on.

NX Flag:  Further protection is provided by iOS using ARM’s Execute Never (XN) feature, which marks memory pages as non-executable. Memory pages marked as both writable and executable can be used only by apps under tightly controlled conditions: The kernel checks for the presence of the Apple-only “dynamic-codesigning” entitlement. Even then, only a single mmap call can be made to request an executable and writable page, which is given a randomized address. Safari uses this functionality for its JavaScript JIT compiler.

Jailbreaking your iOS

Jailbreaking is a process that allows these iDevices users to gain the infamous root access to the command line of the iOS operating system, in order to remove usage and access limitations imposed by Apple. Once jailbroken, iPhone users are able to download extensions and themes that are unavailable through the App Store (via installers such as Cydia) and perform other tasks that are not possible on store-bought devices, including installing non-Apple operating systems such as Linux, running multi-task on old version of iDevices (the new Generation of store-bought devices includes this function). Through the authentication server developed by Aurik (a Ph.d student from UCSB) built up to sign old firmware of iOS, Cydia creator Jay Freeman estimates that over 10% of all iPhones are jailbroken.

Tools you can use for jailbreaking your iPhone are listed alphabetically below (found in theiphonewiki.com):

A
    •    Absinthe
B
    •    Blackra1n
C
    •    Corona
D
    •    Dual Boot Exploit
E
    •    Evasi0n
G
    •    Greenpois0n (jailbreak)
I
    •    IBrickr
    •    ILiberty+
    •    INdependence
J
    •    JailbreakMe
L
    •    Limera1n
M
    •    Mknod
P
    •    Pwnage
    •    PwnageTool
R
    •    Ramdisk Hack
    •    Redsn0w
    •    Redsn0w Lite
    •    Restore Mode
S
    •    Seas0nPass
    •    Sn0wbreeze
    •    Soft Upgrade
    •    Spirit
    •    Star
    •    Symlinks
Z
    •    ZiPhone

Note1: This tutorial was written on 09/March/2013 so an update by performing a research is also required.

Note2: The real question here is do you need to jailbreak your iDevice to pentest it?  The answer is it depends, for example if the app you are testing has anti-jailbreaking countermeasures then maybe no, if the app you are testing has no anti-jailbreaking countermeasures then definitely yes. Jailbreak the the testing target iPhone is must when applicable.

Settings the threat landscape for iOS

What most iOS developers/security consultants do not understand is the threat landscape that is currently associated with the iOS platforms is not clearly defined in their minds, some of them do not even have a clue what is that it should be taken into consideration when performing a Security Assurance, Risk Assessment or Penetration Test to iOS related platform. An iDevice should be treated the thick client on steroids. The features provide from an iOS device are amazing and very rich.

A good source that can be used as a starting point for developing a threat model for iOS should be the OWASP Mobile Security Project found here. The Top 10 Mobile Risks, Release Candidate v1.0 covers pretty much all risks that are associated with an iOS device. The following picture summarizes all risks identified: 


 Note: Risk M2, M5 and M6 are mostly server side related and I am not going to focus on these issue a lot.

Risk M1, M4, M8, M7, M9 and M10 are the most interesting of all the issue and I am going to spend a lot of time analyzing these issues. But before we do that it would be wise to focus a little in the type of interaction an iDevice has with the server component.  Given the nature of the iOS based devices, and their willingness to blindly accept new configuration, hijacking both cellular traffic and WiFi traffic can usually be performed much more easily than a similar attack to a desktop machine. It is so easy, in fact that, that a device's traffic can be hijacked without even compromising the device itself. There are a number of ways to intercept network traffic across local networks; dozens of articles have been written on the subject.  

The following picture shows a typical Web Server iPhone interaction:


Note: This is a simple Web Server, iPhone interaction.

The following pictures shows a typical attack scenarios that can be implemented very easily by exploiting the iPhone configuration of blindly accepting any wireless access points.


The following pictures shows a typical Man In The Middle attack scenarios that can be implemented again very easily due to the nature of the mobile (which by the way are mobile).



Note: The types of attacks that can be performed using the methodology of a rouge access point or the Man In The Middle attack scenarios are going to be explained in the next post.

Epilogue

This article covered the threat land scape for iDevices, which is identical for all mobile devices (e.g. iPhone, iPad, iTouch, iPad mini, Android devices etc.). The next part is going to cover Internet/Wireless attacks and the third is going to cover iDevice data attacks (e.g. attacking unencrypted and encrypted attacks). There might be though a fourth part that sums up all attack patterns together.   

See part 2 

Reference:
  1. Hacking and Securing iOS Applications (1st Edition).
  2. iOS Hacker's Handbook 
  3. http://theiphonewiki.com/wiki/Main_Page
  4. http://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=2&ved=0CFgQFjAB&url=http%3A%2F%2Fwww.mcafee.com%2Fuk%2Fresources%2Fwhite-papers%2Ffoundstone%2Fwp-pen-testing-iphone-ipad-apps.pdf&ei=Qao3UdfuIsi0PN_igZgL&usg=AFQjCNEcgkmrLlHGnZAbIqsMAUZo7AV40Q&sig2=SVQsXTDllnOzoSiE0b9xnQ&bvm=bv.43287494,d.ZWU&cad=rja
  5. http://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&ved=0CEEQFjAC&url=http%3A%2F%2Freverse.put.as%2Fwp-content%2Fuploads%2F2011%2F06%2Fios_jailbreak_analysis.pdf&ei=Lq03UbeEG4vTPICwgZAF&usg=AFQjCNFEFYQasjKS015rXOIscZcD7gt0SQ&sig2=b9zMPuqnxltdEjscnBw9kA&bvm=bv.43287494,d.d2k&cad=rja
  6. http://www.google.com/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&cad=rja&docid=uXJZS5Ygd8EA2M&tbnid=bBuu1xIxavm7BM:&ved=0CAUQjRw&url=http%3A%2F%2Finstitute.mobileappmastery.com%2Fiostrainingpack%2Fios-training-pack-orientation%2F&ei=f_c4Ueq4GMbM0AXHwIH4CA&psig=AFQjCNGXxNtGeXVosrZpTPL02jXebHN5KA&ust=1362774242464377 
  7. http://www.techotopia.com/index.php/Working_with_iOS_6_iPhone_Databases_using_Core_Data 
  8. https://www.owasp.org/index.php/OWASP_Mobile_Security_Project
  9. http://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&sqi=2&ved=0CDEQFjAA&url=http%3A%2F%2Fimages.apple.com%2Fipad%2Fbusiness%2Fdocs%2FiOS_Security_May12.pdf&ei=E407UZH6Io2o0AXp1oDoDA&usg=AFQjCNEEEm92vnkqK28D_y3D60VtJiYOTg&sig2=go27HN00qxc7oZ3cXgFecw&bvm=bv.43287494,d.d2k&cad=rja 
  10. http://support.apple.com/kb/HT1808 
  11. https://developer.apple.com/programs/ios/ 

26/12/2012

CSRFing the Web...

Introduction

Nowadays hacking, as already mentioned in my previous articles, has been industrialized, meaning that professional hackers are constantly hired to make money out of practically anything and therefore all Web Application vulnerabilities have to be understood and defeated.

This article is going to talk about what Cross Site Request Forgery (CSRF) is, explain how can someone perform a successful CSRF attack and describe how to amplify a CSRF attack (e.g. combine CSRF with other vulnerabilities). CSRF is an attack which forces an end user to execute unwanted actions on a web application in which he/she is currently authenticated (simplistically speaking). With a little help from social engineering (like sending a link via email/chat), an attacker may force the users of a web application to execute actions of the attacker's choosing.

A successful CSRF exploit can compromise end user data and operation in case of a normal user. If the targeted end user is the administrator account, this can compromise the entire web application. More specifically CSRF is a Web Application vulnerability that has to exploit more than one design flaws in order to be successful. The design flaws that a CSRF attack can take advantage of are:
  1. Input Validation (e.g. Convert POST to GET) 
  2. Access Control (e.g. Session Fixation) 
  3. Privilege Assignment (e.g. Horizontal Privilege Escalation)
Note: Of course depending on the situation other type of vulnerabilities can be combined with a CSRF as part of a post exploitation process such as SQL Injection (e.g. SQL Inject the cookie and get access to valid cookie repository in the database).

History of CSRF

CSRF vulnerabilities have been known and in some cases exploited since 2001. Because it is carried out from the user's IP address, some website logs might not have evidence of CSRF. Exploits are under-reported, at least publicly, and as of 2007 there are few well-documented examples. About 18 million users of eBay's Internet Auction Co. at Auction.co.kr in Korea lost personal information in February 2008. Customers of a bank in Mexico were attacked in early 2008 with an image tag in email. The link in the image tag changed the DNS entry for the bank in their ADSL router to point to a malicious website impersonating the bank.

Severity of CSRF

According to the United States Department Of Homeland Security the most dangerous CSRF vulnerability ranks in at the 909th most dangerous software bug ever found. Other severity metrics have been issued for CSRF vulnerabilities that result in remote code execution with root privileges as well as a vulnerability that can compromise a root certificate, which will completely undermine a public key infrastructure.

But what exactly is a CSRF

CSRF is a form of confused deputy attack. Imagine you’re a malcontent who wants to harm another person in a maximum security jail. You’re probably going to have a tough time reaching that person due to your lack of proper credentials. A potentially easier approach to accomplish your misdeed is to confuse a deputy to misuse his authority to commit the dastardly act on your behalf. That’s a much more effective strategy for causing mayhem.

In the case of a CSRF attack, the confused deputy is your browser. After logging into a website, the website will issue your browser an authentication token within a cookie (well not always). Within each subsequent http POST or GET requests send, the cookie bind to the request will let the site know that you are authorized to take whatever action you’re taking. Here I am referring to a typical authentication and authorization scheme that most Web Application use.

Suppose you visit a malicious website soon after visiting your bank website or visit another website while being logged to your bank web account. Your session on the previous site might still be valid (btw please de-validate session before closing the browser). Thus, visiting a carefully crafted malicious website (perhaps you clicked on a spam link) could cause an Html form post to the previous website. Your browser would send the authentication cookie back to that site and appear to be making a request on your behalf, even though you did not intend to do so.

Yes but what is a CSRF

A CSRF is a POST or GET http request that when send to the vulnerable Web Application under certain conditions can cause the Web Application to perform an action on behalf of the user. Now meaningful CSRF attacks are those that can cause loss of Integrity or Confidentiality or Availability of the victim user data. For example if an e-Banking Web site is vulnerable to CSRF and the function of the Web Site that is vulnerable is responsible for transferring money, then this is a CSRF with high severity and should be fixed.

This is an example of a simple CSRF:

http://www.vulnerable.com/?transferEuros=3000?maliciousUserAccount=9832487   

Note: The link displayed above when clicked can authorize a malicious user to transfer 3000 euros from of the victim user account to the malicious user account with id 9832487, assuming of course that no proper counter measures have been taken.

The following diagram shows how can this happen more analytically:   




Note: The diagram above shows the steps an attacker can take to exploit the vulnerability (step 4 designtes the execution of the CSRF payload that performs the malicious action). It is pretty much similar to a Cross Site Script attack scenario. An attacker sends an e-mail to an Html enabled e-mail client that contains some sample images deliberately uploaded to a malicious server (controlled by the attacker), along with the malicious URL (or a malicious html form) that performs the CSRF function, waits until the user opens the e-mail and downloads the images or sets his/her e-mail to receive a notification when the victim user reads his/her e-mail. Thens he/she waits infront of the logs of the malicious image server or waits to receive a read e-mail receipt in his/her mailbox. After the image is downloaded or the read receipt is received he/she will try to verify that the malicious function was executed. Another scenario would be to calculate what times user interact with the web site and calculate the attack times before sending the malicious URL/Html form.

The diagram above explains that the CSRF (meaning the vulnerable link described previously) can be injected into an HTML enabled e-mail and be executed by a legitimate user. Now if the link (or else the CSRF vulnerable link) is bind to the Web Application session (which it should be) then the victim user would have to be logged to the vulnerable Web Application for the attack to be successful. If the link is not bind to the Web Application session then the this is not a CSRF vulnerability, is an Insecure Direct Object References vulnerability or Failure to Restrict URL Access also described by OWASP top 10 chart. Both vulnerabilities have to do with inappropriate access control and are completely irrelevant to CSRF or CSRF like vulnerabilities.

Now that you got a better grasp of what a CSRF attack is I can be more technical and explain more on how a CSRF attack look like by using http requests. So again the link described above looks as a Http request like that:

GET /homepage/transferEuros=3000?maliciousUserAccount=9832487 HTTP/1.1
Host: victim.com
Keep-Alive: timeout=15
Connection: Keep-Alive
Cookie: Authentication-Token
Accept: */*

Note: The vulnerable link when clicked will generate the GET request shown above and will, if it is successful, generate a 200 Http response message saying that the transaction was completed successfully.

Explaining more what a CSRF is

The following diagram shows thoroughly how a CSRF can be exploited:



Step 1: Mallory sends a phishing email to Bob, inviting him to visit her web server in order, for example, to win an iPhone 5. She has already created a web page at her web server with a hidden request to the Web Application where Bob is logged in. She has added some buttons to lure the victim in order to click on her page and win the iPhone!

Step 2: Bob visits the page at Mallory's Web server. Maybe he is greedy or he may not, however he clicks on the button in order to win the iPhone!...

Step 3: The forged request is "legitimized" with Bob's logged-in session and is executed at the web application.

A real-world analogy would be the following: Mallory presented a bank cheque to Bob and Bob puts under his name and signature, but haven't examined what sum of money is written on the cheque.In the following attack scenario, we can see how a malicious user can add a user to a web application just by fooling a logged-in administrator to click on a link.

A different approach to CSRF

Now that I explained a simple CSRF attack it is time to explain a more advanced scenario on how to exploit a CSRF. A CSRF most of the time is not easily recognizable and that is why lots of people cannot identify a CSRF unless it is really obvious, just like the one I just described. A CSRF issue raises when:
  1. A Web Application performs critical functions using GET Http requests (e.g. to transfer money, add users by just clicking a link etc).
  2. Does not distinguish between POST and GET requests (e.g. a Html form can be easily converted into a GET request, meaning that a Html POST request can be converted to a link etc). 
  3. Has a loose association or else not tight access control (e.g. does not use AntiCSRF tokens, is vulnerable to session fixation e.t.c).
  4. Is vulnerable to Cross Site Scripting (e.g. someone can use JavaScript to formate a valid Html POST form by using the XMLHTTP object along with an auto submit script etc). 
  5. The application is passing the session to the URL along with the AntiCSRF token.
  6. The session can be fixated and the AntiCSRF token is predictable or static.
Note: There are a lot more ways to perform a CSRF attack, but there are out of scope.

CSRF and POST to GET Interchange

It is common knowledge that when the Web Application does not distinguish between POST and GET requests an attacker can convert a POST Http request to a GET Http request and generate a link equivalent to the one described previously. Burp Suite does that automatically that from the proxy tab by right clicking the request and doing a change method (it also recalculates the Http request size in the content size field).

The attack just described is can be enhanced by using an auto submit script such as this one:

"JavaScript"> setTimeout('document.CSRFHtmlForm.submit()',5000);

Note: A very useful tool is the CSRF PoC tool also found in Burp Suite. Burp Suit CSRF PoC will generate a quick CSRF PoC for you (most of the time you would have to modify that to be realistic).

CSRF and Cross Site Scripting (XSS)

Cross-Site Scripting (XSS) attacks are a type of injection problem, in which malicious scripts are injected into the otherwise benign and trusted web sites. Cross-site scripting (XSS) attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to a different end user. Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user in the output it generates without validating or encoding it.

An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by your browser and used with that site. These scripts can even rewrite the content of the HTML page. But can also inject an Html form with an auto submit script to execute the malicious CSRF. The example is very easy to understand so I wont have to give an example.

Note1: You can see how an XSS vulnerability can be combined with a CSRF  attack at the CSRF tool section (e.g. by injection also the auto submit javascript code along with the CSRF).

Note2: Of course an XSS can be combined with a CSRF attack using the XMLHTTP and auto submit javascript features. A very good XSS (XMLHTTP)/CSRF example can be found here. The specific post explains an XSS/CSRF bug found in gmail.

CSRF and Session Fixation

Session Fixation is an attack that permits an attacker to hijack a valid user session. The attack explores a limitation in the way the web application manages the session ID, more specifically the vulnerable web application. When authenticating a user, it doesn’t assign a new session ID, making it possible to use an existent session ID. The attack consists of inducing a user to authenticate himself with a known session ID, and then hijacking the user-validated session by the knowledge of the used session ID. The attacker has to provide a legitimate Web application session ID and try to make the victim's browser use it.

The session fixation attack is a class of Session Hijacking, which steals the established session between the client and the Web Server after the user logs in. Instead, the Session Fixation attack fixes an established session on the victim's browser, so the attack starts before the user logs in. There are several techniques to execute the attack; it depends on how the Web application deals with session tokens. Below are some of the most common technique:
  • Session token in the URL argument: The Session ID is sent to the victim in a hyperlink and the victim accesses the site through the malicious URL.
  • Session token in a hidden form field: In this method, the victim must be tricked to authenticate in the target Web Server, using a login form developed for the attacker. The form could be hosted in the evil web server or directly in html formatted e-mail.
  • Session ID in a cookie:
    • Client-side script:
      • Most browsers support the execution of client-side scripting. In this case, the aggressor could use attacks of code injection as the XSS (Cross-site scripting) attack to insert a malicious code in the hyperlink sent to the victim and fix a Session ID in its cookie. Using the function document.cookie, the browser which executes the command becomes capable of fixing values inside of the cookie that it will use to keep a session between the client and the Web Applicatio
    • <META> tag:
      • <META> tag also is considered a code injection attack, however, different from the XSS attack where undesirable scripts can be disabled, or the execution can be denied. The attack using this method becomes much more efficient because it's impossible to disable the processing of these tags in the browsers.
After describing the Session Fixation attack I will explain the attack scenario described in the picture using new chain of vulnerabilities (e.g. Session Fixation -> CSRF). An attacker sends an e-mail to an Html enabled e-mail client that contains some sample images uploaded to a malicious server, along with the malicious URL that performs the CSRF function and this time is bind to the fixed session (by using one or more of the techniques described above), waits until the user opens the e-mail and downloads the images or sets his/her e-mail to receive a notification when the victim user reads his/her e-mail. Thens he/she waits the logs of the malicious image server to be updated or waits to receive a read e-mail receipt in his/her mailbox. After the image is downloaded (and he/she sees that from e.g. /www/var/apache.logs etc) or the read receipt is received he/she will try to verify that the malicious function was executed.

The link with the fixated token will produce a GET Http request that looks like this:

GET /homepage/transferEuros=3000?maliciousUserAccount=9832487 HTTP/1.1
Host: victim.com
Keep-Alive: timeout=15
Connection: Keep-Alive
Cookie: Fixated Session

Note1: Obviously a Session Fixation attack can have devastating results even without the use of CSRF flaw. What I am saying here is that a Session Fixation combined with a CSRF attack amplifies the attack (e.g. the attacker will optimize his/her time attack frame by exploiting a chain of vulnerabilities rather than a single vulnerability).

Note2: Similar exploitation scenarios you can have when the web application does not provide the user with an authentication mechanism e.g. open registration forms used for submitting credit card details.

CSRF and bad architecture design

Although this category might not be exactly a CSRF issue, it is still very similar to a CSRF attack. This type of attack refers to the occasions were no proper random values are generated (based on user credentials) or values that are generated but do not have a session like behavior e.g. lack of authorization,  none random CAPTCHA, lack of entity authentication etc. By integrating this type of behavior to your application you endanger the application to became victim to multiple type of attacks.   

CSRF and Clickjaking

Clickjacking, also known as a "UI redress attack", happens is when an attacker uses multiple transparent or opaque layers to trick a user into clicking on a button or link on another page when they were intending to click on the the top level page. Thus, the attacker is "hijacking" clicks meant for their page and routing them to other another page, most likely owned by another application, domain, or both. Using a similar technique, keystrokes can also be hijacked. With a carefully crafted combination of stylesheets, iframes, and text boxes, a user can be led to believe they are typing in the password to their email or bank account, but are instead typing into an invisible frame controlled by the attacker.

For example, imagine an attacker who builds a web site that has a button on it that says "click here for a free iPod". However, on top of that web page, the attacker has loaded an iframe with your vulnerable e-banking account, and lined up exactly the "transfer money" button directly on top of the "free iPod" button. The victim tries to click on the "free iPod" button but instead actually clicked on the invisible "transfer money" button. In essence, the attacker has "hijacked" the user's click, hence the name "Clickjacking". Again the attack scenario would be the similar to the ones just described above so there is no need for me to modify and explain again the attack scenarion. What is interesting though would be to show you an iframe that performs a CSRF attack.

Well an iframe that performs a CSRF attack would look something like that:

<iframe src="http://www.victim.com/homepage/transferEuros=3000?maliciousUserAccount=9832487">

Note: You can see how beautiful this attack is and how simple and smooth can be implemented.

CSRF and Exposed Session Variables

By simply passing the session or other session variables in the URL e.g. such the AntiCSRF token, means asking for trouble. The Session Tokens (Cookie, SessionID, Hidden Field), if exposed, will usually enable an attacker to impersonate a victim and access the application illegitimately. As such, it is important that they are protected from eavesdropping at all times – particularly whilst in transit between the Client browser and the application servers.

The information here relates to how transport security applies to the transfer of sensitive Session ID data rather than data in general, and may be stricter than the caching and transport policies applied to the data served by the site. Using a personal proxy, it is possible to ascertain the following about each request and response:
  • Protocol used (e.g., HTTP vs. HTTPS)
  • HTTP Headers
  • Message Body (e.g., POST or page content)
Each time Session ID data is passed between the client and the server, the protocol, cache, and privacy directives and body should be examined. Transport security here refers to Session IDs passed in GET or POST requests, message bodies, or other means over valid HTTP requests. As you already understand stealing the Session ID and/or the AntiCSRF token might result in the attacker being able to form links such as the following one:

http://www.vulnerable.com/?sessionid=ligdlgkjdng?anticsrftoken=kjnsdldfksjdnk?transferEuros=3000?maliciousUserAccount=9832487   

Note: The above information can be used to generate a link for a malicious user.

The attack scenario?

For my demo I choose multidae vulnerable web application which can be found on OWASP's Vulnerable Apps VM, an intercepting proxy tool (I used Portswigger's Burp Proxy, however it is not essential, just a "View Source" from any browser can work on most cases) and an Apache web server.

In the following picture you can see the main page of Multidae's web application as it can be browsed by any -non authenticated- user.




In this web application any user can register an account, but our goal is to register the account with the administrator's privileges. Below is the "register user" page that any, unauthenticated user can see.




If we view the source of the "Register Account" page, we can identify the forms (and therefore the POST request) that are being sent to the web application. That data are then processed by the application and the user is created.


Now, the attacker can create his own form at his web server and populate the HTML fields with the data of the user he wants to create on the system. (Note: no code expertise is needed in order to create this HTML page!). The following picture, you can see the HTML page that creates on his web server. He creates a user named "andrew", with password "qwerty".


Now he launches the web server (192.168.200.14) hosting this page. At this point, he needs the user's interaction. This could be accomplished, for example, by a phishing attack scenario: the victim receives an email inviting the victim to visit the attacker's page saying "click here to win an iPhone 5", or he could attach this message this "iPhone 5 message" at the page he created!

Just imagine:



And this is how it will appear on the victim's web browser:


The victim, which is at the same time logged in with this account at Multidae web application, is now tricked to click on the button and submit a register user form with the username and password set by the attacker.

 Now user "andrew" can log in with the password set during the CSRF request.


At point the CSRF attack scenario is completed. We sucessfuly managed to exploit a CSRF vulnerability and add a user to the vulnerable web application.

The CASE studies for CSRF

This site here contains many popular web sites that were vulnerable to CSRF attacks. An interesting extract from the article can be found here:

"1. ING Direct (ingdirect.com)
Status: Fixed
We found a vulnerability on ING’s website that allowed additional accounts to be created on behalf of an arbitrary user. We were also able to transfer funds out of users’ bank accounts. We believe this is the first CSRF vulnerability to allow the transfer of funds from a financial institution. Specific details are described in our paper.
2. YouTube (youtube.com)
Status: Fixed
We discovered CSRF vulnerabilities in nearly every action a user could perform on YouTube. An attacker could have added videos to a user’s "Favorites," added himself to a user’s "Friend" or "Family" list, sent arbitrary messages on the user’s behalf, flagged videos as inappropriate, automatically shared a video with a user’s contacts, subscribed a user to a "channel" (a set of videos published by one person or group) and added videos to a user’s "QuickList" (a list of videos a user intends to watch at a later point). Specific details are described in our paper.
3. MetaFilter (metafilter.com)
Status: Fixed
A vulnerability existed on Metafilter that allowed an attacker to take control of a user’s account. A forged request could be used to set a user’s email address to the attacker’s address. A second forged request could then be used to activate the "Forgot Password" action, which would send the user’s password to the attacker’s email address. Specific details are described in our paper.
(MetaFilter fixed this vulnerability in less than two days. We appreciate the fact that MetaFilter contacted us to let us know the problem had been fixed.)
4. The New York Times (nytimes.com)
Status: Not Fixed. We contacted the New York Times in September, 2007As of September 24, 2008, this vulnerability still exists. This problem has been fixed."

Note: You can see from the above extract that CSRF issues are very popular these days.

Tools for CSRFing the Web

The Burp Proxy tool (the Pro version of course) can be used to generate a proof-of-concept (PoC) cross-site request forgery (CSRF) attack for a given request.To access this function, select a URL or HTTP request anywhere within Burp, and choose "Generate CSRF PoC" within "Engagement tools" in the context menu.

When you execute this function, Burp shows the full request you selected in the top panel, and the generated CSRF HTML in the lower panel. The HTML uses a form with a suitable action URL, encoding type and parameters, to generate the required request when the browser submits the form.You can edit the request manually, and click the "Regenerate" button to regenerate the CSRF HTML based on the updated request.

You can test the effectiveness of the generated PoC in your browser, using the "Test in browser" button. When you select this option, Burp gives you a unique URL that you can paste into your browser (configured to use the current instance of Burp as its proxy). The resulting browser request is served by Burp with the currently displayed HTML, and you can then determine whether the PoC is effective by monitoring the resulting request(s) that are made through the Proxy.Some points should be noted regarding form encoding:

    •    Some requests (e.g. those containing raw XML or JSON) have bodies that can only be generated using a form with plain text encoding. With each type of form submission using the POST method, the browser will include a Content-Type header indicating the encoding type of the form that generated the request. In some cases, although the message body exactly matches that required for the attack request, the application may reject the request due to an unexpected Content-Type header. Such CSRF-like conditions might not be practically exploitable. Burp will display a warning in the CSRF PoC generator if this is liable to occur.

    •    If you manually select a form encoding type that cannot be used to produce the required request, Burp will generate a best effort at a PoC and will display a warning.

    •    If the CSRF PoC generator is using plain text encoding, then the request body must contain an equals character in order for Burp to generate an HTML form which results in that exact body. If the original request does not contain an equals character, then you may be able to introduce one into a suitable position in the request, without affecting the server's processing of it.

CSRF PoC Options

The following options are available:

    •    Include auto-submit script - Using this option causes Burp to include a small script in the HTML that causes a JavaScript-enabled browser to automatically submit the form (causing the CSRF request) when the page is loaded.

    •    Form encoding - This option lets you specify the type of encoding to use in the form that generates the CSRF request. The "Auto" option is generally preferred, and causes Burp to select the most appropriate encoding capable of generating the required request. 

The following picture shows a screen shot from Burp CSRF PoC tool while doing right click on an intercepted request:


The following picture shows the generated CSRF PoC:


Note: Right click the intercepted Http GET or POST request and click CSRF PoC. It should not be a problem if the web application accepts POST to GET interchanges for obvious reasons.


Prevention Measures That Do NOT Work

Using a Secret Cookie:

Remember that all cookies, even the secret ones, will be submitted with every request. All authentication tokens will be submitted regardless of whether or not the end-user was tricked into submitting the request. Furthermore, session identifiers are simply used by the application container to associate the request with a specific session object. The session identifier does not verify that the end-user intended to submit the request.

Only Accepting POST Requests:

Applications can be developed to only accept POST requests for the execution of business logic. The misconception is that since the attacker cannot construct a malicious link, a CSRF attack cannot be executed. Unfortunately, this logic is incorrect. There are numerous methods in which an attacker can trick a victim into submitting a forged POST request, such as a simple form hosted in an attacker's Website with hidden values. This form can be triggered automatically by JavaScript or can be triggered by the victim who thinks the form will do something else.

Multi-Step Transactions:

Multi-Step transactions are not an adequate prevention of CSRF. As long as an attacker can predict or deduce each step of the completed transaction, then CSRF is possible.

URL Rewriting:


This might be seen as a useful CSRF prevention technique as the attacker can not guess the victim's session ID. However, the user’s credential is exposed over the URL.

CSRF countermeasures 

CSRF attacks are very hard to trace and probably are not traceable unless one the two or more of the following conditions are met:
  1. Detailed Web Application user auditing exists and is enabled.
  2. Concurrent logins are not allowed (allowing concurrent logins would remove none repudiation).
  3. The Web Application binds the Web Application session with the user IP (that way if the user is behind a NAT only users from the same intranet would be able to perform a CSRF attack).
  4. AntiCSRF tokens are used per Web Application function. An AntiCSRF token in order to be effective would have to be:
    • Truly Random.
    • Bind to every Web Application function (different per Web Application function).
    • Behave like a session (e.g. expire after a certain time, expire e.t.c).
    • Use a two factor authentication per token (e.g make of a RSA token to generate the AntiCSRF to perform a transaction etc).
Other technologies for protecting against CSRF

In the web there are numerous references regarding the implementation of anti-CSRF tokens. Some examples can be found here: 
The mentality promoted by the above technologies is abvious, we should deploy a mechanism that would make unique every session initiated by the user. This can be achieved by sending the browser an anti-CSRF token that would be appended in every request the browser sends to the server. The above technique is being explained in more technical terms in OWASP's CSRF Prevention cheat sheet:

"These challenge tokens are the inserted within the HTML forms and links associated with sensitive server-side operations. When the user wishes to invoke these sensitive operations, the HTTP request should include this challenge token. It is then the responsibility of the server application to verify the existence and correctness of this token. By including a challenge token with each request, the developer has a strong control to verify that the user actually intended to submit the desired requests. Inclusion of a required security token in HTTP requests associated with sensitive business functions helps mitigate CSRF attacks as successful exploitation assumes the attacker knows the randomly generated token for the target victim's session. This is analogous to the attacker being able to guess the target victim's session identifier."

Epilogue

This blog post attempted to cover thoroughly the subject of CSRF and I believe that I managed to do that. Now there are obviously a lot more things to say about how to protect against a CSRF but for the purposes of this post is out of scope. Merry Christmas and a Happy New year.

References:
  1. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)
  2. http://en.wikipedia.org/wiki/Cross-site_request_forgery
  3. https://www.owasp.org/index.php/Testing_for_Exposed_Session_Variables_(OWASP-SM-004)
  4. http://haacked.com/archive/2009/04/02/anatomy-of-csrf-attack.aspx
  5. https://www.owasp.org/index.php/Session_fixation
  6. http://ajaxian.com/archives/gmail-csrf-security-flaw
  7. http://www.portswigger.net/burp/help/suite_functions_csrfpoc.html
  8. https://nealpoole.com/blog/2012/03/csrf-clickjacking-and-the-role-of-x-frame-options/
  9. http://fragilesecurity.blogspot.gr/2012/11/cross-site-request-forgery-legitimazing.html
  10. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
  11. https://blogs.apache.org/infra/entry/apache_org_04_09_2010
  12. https://freedom-to-tinker.com/blog/wzeller/popular-websites-vulnerable-cross-site-request-forgery-attacks/
  13. https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Viewstate_.28ASP.NET.29

06/11/2012

The Da Vinci Cod(e) Review

Introduction

This article is going to talk about performing Web Application security code reviews the proper way (also known as my way). The best approach to perform a Web Application security code review would be to have at your disposal the Web Application (uploaded and running in a Web Server) and of course the Web Application code itself, because you would be able to verify your findings in real time (e.g. exploit a Cross Site Scripting issue immediately after you identify the issue in the code). Ideally this happens within a CI/CD pipeline where your SAST tool flags a finding, and you can spin up a local or staging instance to validate whether that finding is actually exploitable — that feedback loop is where the real security value lives.


But first lets define what is a security source code review. A security code review is a systematic examination of a Web Application source code that is intended to find and fix security mistakes overlooked in the initial development phase, improving both the overall security of the software. Reviews are done in various forms such as pair programming, informal walkthroughs, and formal inspections. It is often done by independent contractors or an internal security team, hiring a third independent party to perform the code review adds value because it gives to the company the chance to examine its code by a person that has been engaged in the last stage of the development process and has no "emotional attachments to the code" therefore has a unique perspective on the subject.

In a modern DevSecOps context, security code review is no longer a one-off event. It is a continuous activity embedded in the Software Development Lifecycle (SDLC). Pull Request (PR) reviews, automated SAST scans triggered on every commit, and periodic deep-dive manual reviews all coexist. The key shift in recent years is treating security code review as a living process rather than a checkpoint gate.

Types of code review

Code review practices fall into three main categories: 1) pair programming, 2) formal code review and 3) lightweight code review. Formal code review, such as a Fagan inspection, involves a careful and detailed process with multiple participants and multiple phases. Formal code reviews are the traditional method of review, in which software developers attend a series of meetings and review code line by line, usually using printed copies of the material. Formal inspections are extremely thorough and have been proven effective at finding defects in the code under review. Lightweight code review typically requires less overhead than formal code inspections, though it can be equally effective when done properly.

Lightweight reviews are often conducted as part of the normal development process:
  1. Over-the-shoulder – One developer looks over the author's shoulder as the latter walks through the code.
  2. Email pass-around – Source code management system emails code to reviewers automatically after checkin is made.
  3. Pair Programming – Two authors develop code together at the same workstation, such is common in Extreme Programming.
  4. Tool-assisted code review – Authors and reviewers use specialized tools designed for peer code review (e.g. GitHub Pull Requests, GitLab Merge Requests, Gerrit).
A fourth category has emerged in recent years: AI-assisted code review. Tools like GitHub Copilot, Semgrep Assistant, and Snyk Code now provide real-time security feedback directly in the IDE or during PR review. These AI-driven tools can detect patterns, suggest fixes, and even auto-remediate certain vulnerability classes. However, the same fundamental rule applies — they still require human validation.

Important note: Tools can be used to perform this task but they always need human verification. Tools do not understand context, which is the keystone of security code review. Tools are good at assessing large amounts of code and pointing out possible issues but a person needs to verify every single result to determine if it is a real issue, if it is actually exploitable, and calculate the risk to the enterprise. This is even more critical in the age of AI-generated code — studies suggest that AI-generated code contains security vulnerabilities in approximately 25-40% of cases, often including SQL injection, XSS, and insecure authentication patterns. Your SAST tool will flag them, but only a human reviewer can determine whether the context makes them exploitable.

What is the most important thing in a code review

The most important is applying the proper Threat Modeling. Threat modeling is an approach for analyzing the security of an application. It is a structured approach that enables you to identify, quantify, and address the security risks associated with an application. Threat modeling is not an approach to reviewing code but it does complement the security code review process. The inclusion of threat modeling in the SDLC can help to ensure that applications are being developed with security built-in from the very beginning. This, combined with the documentation produced as part of the threat modeling process, can give the reviewer a greater understanding of the system. This allows the reviewer to see where the entry points to the application are and the associated threats with each entry point.

In 2020, a group of threat modeling practitioners, researchers and authors published the Threat Modeling Manifesto — a document that distills the collective knowledge of the community into values and principles, similar to the Agile Manifesto. The Manifesto anchors all threat modeling around four fundamental questions:
  1. What are we building? — Understand the system through diagrams (DFDs, architecture diagrams).
  2. What can go wrong? — Identify threats using frameworks like STRIDE, PASTA, LINDDUN, or Attack Trees.
  3. What are we going to do about it? — Define countermeasures and mitigations.
  4. Did we do a good enough job? — Validate and iterate on the threat model.
These four questions should be your north star regardless of which specific methodology you choose. The concept of threat modeling is not new but there has been a clear mindset change in recent years. Modern threat modeling looks at a system from a potential attacker's perspective, as opposed to a defender's viewpoint. The industry has also recognized that threat modeling is not just a security team exercise — it requires cross-functional collaboration involving developers, architects, business analysts, DevOps engineers, and security professionals.

Threat Modeling Frameworks: A Modern Overview

There are several established frameworks for threat modeling. Choosing the right one depends on your organization's maturity, the type of system being analyzed, and whether your primary concern is security, privacy, or business risk. Below is an overview of the most relevant frameworks in 2025.

STRIDE

STRIDE is the most widely adopted threat modeling framework, originally developed by Microsoft. It categorizes threats into six types:
  • Spoofing — Can an attacker impersonate another user or system?
  • Tampering — Can an attacker modify data in transit or at rest?
  • Repudiation — Can an attacker deny having performed an action?
  • Information Disclosure — Can sensitive data leak to unauthorized parties?
  • Denial of Service — Can an attacker degrade or disrupt service availability?
  • Elevation of Privilege — Can an attacker gain unauthorized access to higher-level functions?
STRIDE is a strong fit for teams that are new to threat modeling. It is easy to teach, quick to adopt, and integrates well into agile development practices. You apply it by creating a Data Flow Diagram (DFD) of your system, then systematically asking "can this element be affected by Spoofing? Tampering?" and so on for each element. Microsoft made STRIDE a core component of their Security Development Lifecycle (SDL), which they credit as one of the reasons for the increased security of their products.

Limitation: STRIDE focuses exclusively on security threats. It does not address privacy concerns, business risk alignment, or attacker motivation. It is also a static framework that works best at design time — it does not inherently adapt to runtime threat intelligence.

PASTA (Process for Attack Simulation and Threat Analysis)

PASTA is a seven-stage, risk-centric threat modeling methodology created by Tony UcedaVélez and Marco M. Morana. Unlike STRIDE, which focuses on categorizing threat types, PASTA takes a holistic view by considering both business impact and technical risk. It connects technical threats directly to business objectives, making it particularly valuable in enterprise environments where security decisions must be justified by business value.

The seven stages of PASTA are:
  1. Define Objectives — Identify business objectives, security requirements, compliance requirements, and data classification for the application in scope.
  2. Define Technical Scope — Map all system components, their relationships, interdependencies, and the attack surface.
  3. Application Decomposition — Break down the system into data flows, processes, trust boundaries, user roles, and permissions.
  4. Threat Analysis — Identify threat actors, their motivations, and create Attack Trees to model how they could achieve their goals.
  5. Vulnerability Analysis — Correlate threats with known vulnerabilities using data from vulnerability scanners, penetration test reports, and threat intelligence feeds.
  6. Attack Modeling — Simulate attack scenarios to test the viability of identified threats against existing countermeasures.
  7. Risk and Impact Analysis — Calculate residual risk, prioritize findings by business impact, and define remediation strategies.
PASTA is ideal for mature organizations that want to link their security activities to broader business risk. It provides the depth and structure needed for high-assurance systems, especially in finance, healthcare, and critical infrastructure. The key advantage of PASTA over STRIDE is its collaborative, cross-functional nature — it brings together developers, architects, business analysts, risk professionals, and SOC team members in a way that STRIDE's developer-centric approach does not.

Limitation: PASTA is more complex to execute and requires a higher level of expertise. The accuracy of the methodology depends heavily on the availability and quality of data regarding the system and its architecture. It is not a "quick start" framework — expect a significant investment of time and stakeholder coordination.

Attack Trees

Attack Trees are a complementary technique that can be used alongside STRIDE, PASTA, or any other framework. Originally formalized by Bruce Schneier in 1999 (building on earlier work by Edward Amoroso and the NSA), Attack Trees provide a visual, hierarchical representation of how an attacker might achieve a specific goal.

The structure is simple:
  • The root node represents the attacker's goal (e.g., "Steal user credentials").
  • Child nodes represent the different ways to achieve that goal.
  • Nodes are connected using AND/OR logic: OR nodes represent alternatives (any one path suffices), AND nodes represent steps that must all be completed.
  • Each node can carry additional metadata: likelihood, cost, required skill level, detectability.
For example, an Attack Tree for "Bypass Authentication" might look like:

Bypass Authentication [ROOT - OR]
├── Brute Force Password [OR]
│   ├── Online brute force (if no rate limiting)
│   └── Offline brute force (if password hashes leaked)
├── Credential Stuffing [OR]
│   └── Use credentials from previous breaches
├── Session Hijacking [OR]
│   ├── Steal session cookie via XSS
│   └── Session fixation attack
├── Exploit Password Reset [OR]
│   ├── Predictable reset tokens
│   └── Account takeover via email compromise
└── SQL Injection on Login [OR]
    └── Bypass authentication via tautology (e.g. ' OR '1'='1)

Attack Trees are powerful because they go beyond graphical representation — they provide tactical insights that enable targeted defenses. They also serve as excellent communication tools for presenting security risks to leadership or non-technical stakeholders. Within PASTA specifically, Attack Trees are created during the fourth stage (Threat Analysis) to model how identified threat actors might achieve their goals.

Tip: Tools like OWASP Threat Dragon, Microsoft Threat Modeling Tool, IriusRisk, and Devici can help you build and maintain Attack Trees as living documents that evolve with your application.

LINDDUN (Privacy Threat Modeling)

LINDDUN is a privacy-focused threat modeling framework developed by researchers at KU Leuven. While STRIDE addresses security (confidentiality, integrity, availability), LINDDUN addresses privacy-specific concerns that traditional security frameworks overlook. With regulations like GDPR, CCPA, and HIPAA becoming stricter, privacy threat modeling is no longer optional for applications handling personal data.

LINDDUN stands for:
  • Linking — Can an adversary combine data to learn more about an individual?
  • Identifying — Can the identity of a data subject be determined?
  • Non-repudiation — Can a user be unable to deny an action (sometimes a privacy threat, not just a security feature)?
  • Detecting — Can an adversary detect that a user is using a system?
  • Data Disclosure — Can personal data leak to unauthorized parties?
  • Unawareness — Are users insufficiently informed about data collection and processing?
  • Non-compliance — Does the system fail to comply with privacy regulations and best practices?
LINDDUN follows the same four fundamental questions as the Threat Modeling Manifesto and can operate alongside STRIDE on a single DFD, enabling organizations to perform comprehensive privacy and security analysis without duplicating work. It comes in multiple flavors: LINDDUN GO (a gamified card-based approach for lean brainstorming sessions), LINDDUN PRO (a systematic, exhaustive approach starting from DFD analysis), and LINDDUN MAESTRO (an advanced approach with enriched system descriptions).

When to use it: If your application processes personal data — user profiles, health records, financial information, location data — you should be running LINDDUN alongside STRIDE. The cost of privacy violations (both regulatory fines and loss of user trust) now frequently exceeds the cost of traditional security breaches.

Choosing Your Framework

You do not have to pick only one framework. Many security teams begin with STRIDE to cover general threats, then layer in LINDDUN for privacy analysis. PASTA can be introduced later as the organization matures and seeks deeper insights into how threats connect to business objectives. Attack Trees can be used within any of these frameworks to drill deeper into specific attack scenarios. The most effective programs evolve from lightweight models into more integrated, cross-functional strategies.

The Threat Modeling Process

Regardless of which framework you choose, the threat modeling process can be decomposed into 3 high level steps:

Step 1: Decompose the Application:
  • Create use-cases to understand how the application is used.
  • Identify entry points (APIs, web forms, file uploads, message queues, webhooks).
  • Identify assets (databases, secrets, PII, session tokens, cryptographic keys).
  • Identify trust levels and trust boundaries between external entities.
  • Map data flows using DFDs or sequence diagrams.
Note: This stage has to do with understanding the context of the Web Application and its surrounding entities. In modern architectures, this includes microservices communication, API gateways, third-party integrations, cloud provider boundaries, and container orchestration layers.

The following images show the Business Architecture (Business Owner's Perspective) and Business Architecture Behavior of a Web Application:


Note: Lists the entities important to the business. Business entities can be a person, a thing or a concept that is part of or interacts with the business process (Proforma 2003). In the example of "XYZ-Match", the business entities include the following: Investors, Entrepreneurs, "XYZ-Match" web system.


Note: Lists the processes in which the business operates. In the example of "XYZ-Match", "Investor listing information to Venture Capital Directory" is one of such business processes.

Step 2: Determine and rank threats using your chosen categorization methodology:
  • Authentication and Identity Management
  • Authorization and Access Control
  • Session Management
  • Input Validation and Output Encoding
  • Data Protection in Storage and Transit (encryption at rest, TLS, key management)
  • Auditing, Logging, and Monitoring
  • Configuration Management and Secrets Management
  • Error Handling and Exception Management
  • Supply Chain and Dependency Security
Note: This stage has to do with mapping the vulnerabilities to a category. Threat listing is an important part of a Web Application code audit. Threat lists based on the STRIDE model are useful for identifying threats against attacker goals. Categorizing and grouping the Web Application threats will help to see which security controls have the majority of the problems — it is like a blinking led that says "Hey I have multiple problems, save me please I am a poor cod dying out, save me".

Step 3: Determine countermeasures and mitigation.

Note: Such countermeasures can be identified using threat-countermeasure mapping lists. The risk mitigation strategy might involve evaluating these threats from the business impact that they pose and reducing the risk.

The objective of risk management should be to reduce the impact that the exploitation of a threat can have to the application (not to necessarily mitigate the risk!). This can be done by responding to a threat with a risk mitigation strategy. In general there are five options to mitigate threats:
  1. Do nothing: for example, hoping for the best.
  2. Informing about the risk: for example, warning user population about the risk.
  3. Mitigate the risk: for example, by putting countermeasures in place.
  4. Accept the risk: for example, after evaluating the impact of the exploitation (business impact).
  5. Transfer the risk: for example, through contractual agreements and insurance.
The decision of which strategy is most appropriate depends on the impact an exploitation of a threat can have, the likelihood of its occurrence, and the costs for transferring or avoiding it.

  • Define the application requirements:
  1. Identify business objectives
  2. Identify user roles that will interact with the application
  3. Identify the data the application will manipulate
  4. Identify the use cases for operating on that data that the application will facilitate
  • Model the application architecture:
    • Model the components of the application
    • Model the service roles that the components will act under
    • Model any external dependencies (third-party APIs, open-source libraries, cloud services)
    • Model the calls from roles, to components and eventually to the data store for each use case
  • Identify any threats to the confidentiality, availability and integrity of the data and the application based on the data access control matrix that your application should be enforcing
  • Assign risk values and determine the risk responses
  • Determine the countermeasures to implement based on your chosen risk responses
  • Continually update the threat model based on the emerging security landscape — threat modeling is not a one-time activity, it must evolve as the application, its dependencies, and the threat landscape change.

Modern Tools for Security Code Auditing

The tooling landscape for security code review has evolved dramatically. In the early days, tools like Graudit (a grep-based signature scanner), RATS, and findstr were the go-to options. While these still have educational value for understanding how pattern matching works, modern SAST (Static Application Security Testing) tools have moved far beyond simple regex-based detection.

Here is the current state of the art:

Semgrep

Semgrep is a lightweight, open-source static analysis tool that uses semantic pattern matching rather than simple text matching. This means it understands code structure — not just text patterns — enabling fast processing while maintaining accuracy. Developers can write custom rules in YAML that look like the code they want to find, making rule creation intuitive.

semgrep scan --config=auto /path/to/code

Key strengths: fast scanning (no compilation required), supports 20+ languages, integrates into CI/CD pipelines, IDE plugins, and PR checks. The commercial Semgrep AppSec Platform adds cross-file/cross-function dataflow analysis, SCA (Software Composition Analysis), secrets detection, and an AI-powered assistant for triage and autofix.

Note: In January 2025, after Semgrep changed its open-source licensing, 10+ competing vendors forked the community edition into "Opengrep." If you are evaluating Semgrep, be aware of this licensing shift and consider whether Opengrep-based alternatives (like Aikido Security) better fit your needs.

CodeQL (GitHub Advanced Security)

CodeQL is a semantic code analysis engine that compiles source code into a queryable relational database representing the AST, data flow graph, and control flow graph. Users write queries in QL (a Datalog-derived declarative language) to traverse this database. It is extremely powerful for deep, customized vulnerability hunting — CodeQL variant analysis has been used to identify over 400 CVEs in open-source projects.

codeql database create mydb --language=java --source-root=/path/to/code
codeql database analyze mydb codeql/java-queries:codeql-suites/java-security-and-quality.qls --format=sarif-latest --output=results.sarif

Key strengths: deep semantic analysis, powerful custom query language, native GitHub integration with Copilot Autofix for AI-powered fix suggestions. Free for open-source projects.

Limitation: Steep learning curve — requires specialized knowledge of QL. Requires code compilation to build the database, making it slower than Semgrep for quick scans. Best suited for security research and deep auditing rather than fast-moving DevSecOps workflows.

Other Notable Tools

  • Snyk Code — Developer-focused SAST with real-time IDE scanning and AI-trained detection engine. Strong on AI-generated code pattern detection.
  • SonarQube — Combines SAST with code quality checks. Good for teams that want security and maintainability in one platform.
  • Checkmarx / Veracode / OpenText (Fortify) — Enterprise-grade SAST platforms with deep scanning, compliance reporting, and legacy language support.
  • Bandit — Open-source Python-specific SAST tool. Lightweight and great for Python-heavy shops.
  • OWASP Dependency-Check / Trivy — SCA tools for scanning third-party dependencies for known vulnerabilities.
  • GitGuardian / Gitleaks — Secrets detection tools that scan repos for exposed credentials, API keys, and tokens.

Important: No single tool covers everything. The modern AppSec stack typically combines SAST + SCA + Secrets Detection + DAST + IaC scanning. The goal is layered defense — each tool catches what the others miss. And remember the golden rule: a tool is only as good as the human reviewing its output.

Cod(e) reviewing for SQL Injection

SQL Injection remains one of the most critical and prevalent vulnerabilities, consistently appearing in the OWASP Top 10. Despite decades of awareness, it persists because developers still make the same fundamental mistake: constructing SQL queries through string concatenation with untrusted input.

Use parameterized queries (PreparedStatements in Java) instead of dynamic SQL statements. Data validate all external input: ensure that all SQL statements recognize user inputs as variables, and that statements are precompiled before the actual inputs are substituted for the variables. A simplified way of thinking about SQL injection when talking about security code reviews would be to emphasize multiple layers of defense through the whole Web Application system. Input validation should occur at the Web Application input filter, the framework/ORM layer, and the database layer itself. Additional layers of defense can be added through a Web Application Firewall (WAF) and a Database Activity Monitor.

The following picture shows a sequence of yes and no flow chart explaining an SQL injection flow:


Note: This is a simplified SQL Injection threat model. In practice, the decision tree branches further when you consider second-order injection, blind SQLi, and out-of-band channels.

The Vulnerable Code (Java — what NOT to do)

// VULNERABLE: SQL Injection via string concatenation
// This is the classic mistake — user input directly embedded in SQL

String username = request.getParameter("USER");       // From HTTP request — UNTRUSTED
String password = request.getParameter("PASSWORD");   // From HTTP request — UNTRUSTED

// DANGER: Direct concatenation of user input into SQL query
String sql = "SELECT User_id, Username FROM USERS WHERE Username = '"
    + username + "' AND Password = '" + password + "'";

Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(sql);

// An attacker entering: Username = ' OR '1'='1' --
// Produces: SELECT User_id, Username FROM USERS
//           WHERE Username = '' OR '1'='1' --' AND Password = ''
// Result: Authentication bypass — returns all users

When SQL statements are dynamically created as software executes, there is an opportunity for a security breach as the input data can truncate, malform, or expand the original SQL query. The request.getParameter() retrieves the data for the SQL query directly from the HTTP request without any data validation (min/max length, permitted characters, malicious characters). This error gives rise to the ability to input SQL as the payload and alter the functionality of the statement.

The Secure Code (Java — PreparedStatement / Parameterized Query)

// SECURE: Parameterized query using PreparedStatement
// The SQL structure is precompiled; user input is ALWAYS treated as data

String username = request.getParameter("USER");
String password = request.getParameter("PASSWORD");

// The '?' placeholders ensure input can never alter the query structure
String sql = "SELECT User_id, Username FROM USERS WHERE Username = ? AND Password = ?";

try (PreparedStatement pstmt = connection.prepareStatement(sql)) {

    pstmt.setString(1, username);  // Bound as data, not SQL code
    pstmt.setString(2, password);  // Bound as data, not SQL code

    try (ResultSet rs = pstmt.executeQuery()) {
        if (rs.next()) {
            int userId = rs.getInt("User_id");
            String loggedUser = rs.getString("Username");
            // Authentication successful
        } else {
            // Authentication failed
        }
    }
} catch (SQLException e) {
    logger.error("Database error during authentication", e);
    // NEVER expose stack traces or SQL errors to the user
}

The PreparedStatement precompiles the SQL query with placeholder markers (?). When setString() is called, the JDBC driver ensures the input is treated strictly as a string literal — it can never be interpreted as SQL code. Even if an attacker enters ' OR '1'='1, the database will literally search for a user with that exact string as their username, which will return nothing.

Modern Alternative: Using an ORM (JPA/Hibernate)

In modern Java applications, you often interact with the database through an ORM rather than raw JDBC. Here is how the same query looks using JPA (Java Persistence API):

// SECURE: JPA Named Query — parameterized by default

@Entity
@NamedQuery(
    name = "User.findByCredentials",
    query = "SELECT u FROM User u WHERE u.username = :username AND u.password = :password"
)
public class User { ... }

// Usage:
TypedQuery<User> query = entityManager.createNamedQuery("User.findByCredentials", User.class);
query.setParameter("username", request.getParameter("USER"));
query.setParameter("password", request.getParameter("PASSWORD"));
List<User> results = query.getResultList();

Warning: ORMs are not automatically safe. If you use string concatenation to build JPQL or HQL queries, you are just as vulnerable. The rule is the same: always use parameterized queries regardless of the abstraction layer.

Python Example (for comparison)

# VULNERABLE — string formatting with untrusted input
cursor.execute(f"SELECT * FROM users WHERE username = '{username}' AND password = '{password}'")

# SECURE — parameterized query
cursor.execute("SELECT * FROM users WHERE username = %s AND password = %s", (username, password))

What to grep for during code review (SQL Injection indicators)

When performing a manual code review or writing custom SAST rules, look for these patterns:
  • Statement.execute( or Statement.executeQuery( combined with string concatenation (+)
  • "SELECT ... " + variable or "INSERT ... " + variable or "UPDATE ... " + variable
  • String.format() used to build SQL queries
  • f"SELECT ..." (Python f-strings in SQL context)
  • cursor.execute("... %s ..." % variable) (Python old-style string formatting — NOT the same as parameterized %s)
  • $"SELECT ..." (C# string interpolation in SQL context)
A Semgrep rule to detect Java SQL injection looks like this:

# semgrep-rule: java-sql-injection.yaml
rules:
  - id: java-sqli-string-concat
    patterns:
      - pattern: |
          String $QUERY = "..." + $INPUT + "...";
          ...
          $STMT.executeQuery($QUERY);
    message: >
      Potential SQL injection: user input concatenated into SQL query.
      Use PreparedStatement with parameterized queries instead.
    severity: ERROR
    languages: [java]

Epilogue

Educating developers to write secure code is the paramount goal of a secure code review. Taking code review from this standpoint is the only way to promote and improve code quality. Part of the education process is to empower developers with the knowledge in order to write better code. This can be done by providing developers with a controlled set of rules which the developer can compare their code to. Modern SAST tools like Semgrep and CodeQL embody this philosophy — they provide immediate, contextual feedback in the developer's IDE and PR workflow, turning every code review into a learning opportunity.

The landscape has changed dramatically since the days of grep-based scanning. We now have AI-assisted remediation, cross-function taint analysis, reachability-based SCA, and privacy-specific threat modeling frameworks. But the fundamental truth remains: tools augment human judgment, they do not replace it. The best security code review is one where a knowledgeable reviewer uses the right tools to focus their attention on what matters, validates findings in context, and communicates risk in business terms that drive action.

Threat model your applications. Use STRIDE for security, LINDDUN for privacy, PASTA when you need to tie threats to business impact, and Attack Trees to drill into specific attack scenarios. Embed SAST in your pipeline. Review every finding with human eyes. And never, ever concatenate user input into a SQL query.

References:

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...