Wednesday, November 14, 2012

Code Reviewing in Software Development Lifecycle

Overview


Software vulnerabilities is a reality in today's world. Every day we can read news in Information Security magazines and websites reporting a zero-day vulnerability. Software vulnerabilities occur due to numerous reasons, but the most significant are: lack of security awareness of developers and deadline pressure. Lack in awareness of security issues is usually depicted in some statements such as: "We will not get hacked", "Our services reside on internal network", "We trust our internal users (eg employees, partners)", "We have a very expensive web application firewall (waf) protecting us", etc. But nowadays, when industrial espionage is a reality, trust can cost money and reputation.
 
Code review generally is the process when examining the source code of an application for vulnerabilities. It is a necessity in order to develop secure software and contributes in the Software Development Life Cycle (SDLC). We can examine one of the most famous SDLC guide providing guidelines in developing secure software: Microsoft Security Development Lifecycle (SDL).
 

Security flavour in SDL

The phases of Microsoft SDL:
 
 
Security is integrated in almost all phases. Further details can be found on SDL's website.
Code review resides mainly in "Verification" phase. In SDL website, Microsoft provides a list of tools for code reviewing, but in this current article I am going to present a demo of Yasca, an open source code review tool.
 

Yasca

From Yasca website:
"Yasca is a source code analysis tool that I started writing in 2007. It could best be described as a "glorified grep script" plus an aggregator of other open-source tools.
Yasca can scan source code written in Java, C/C++, HTML, JavaScript, ASP, ColdFusion, PHP, COBOL, .NET, and other languages."
 
The main advantage of Yasca is that collaborates perfectly with a wide list of static code review tools such as: FindBugs, PMD, JLint, JavaScript Lint, PHPLint, CppCheck, ClamAV, RATS, Pixy.
Personally, I have installed Yasca in a Windows 7 Ultimate and works perfectly in command line, whereas I have abandoned the installation in Backtrack 5 R3 because of numerous errors.
 

Demo

I extracted the vulnerable code (guess from where?! Of course from OWASP broken web applications VM where there is a tone of vulnerable code just waiting to be hacked!). The vulnerable code is from WebGoat web application found on the path:
/owaspbwa/WebGoat-svn/src/main/java/org/owasp/webgoat/lessons
 
Here is a sample of Yasca's report:
 
 
 

Wrap-up

Code review should be included in every software deployment project. It is an essential safeguard in order to produce secure software and minimize the risk from potential vulnerabilities. Besides, we should always apply security techniques in every layer of our web application (code review, web application firewall, access control, etc).
 
  

Further reading

 

Saturday, November 10, 2012

Setting up a ModSecurity powered Reverse Proxy

Overview

Following the series of my ModSecurity related posts, in this one, I explain how we can set up a reverse proxy that will process all the requests received by any browser and then forward them to the web applications we want to protect. This reverse proxy will be an autonomous VM that is very flexible to deploy in front of numerous web applications. For example, we can write generic ModSecurity rules and then we can copy and apply the VM to multiple places in order to process the requests. Afterwards, we can parameterize each VM according to the application that resides behind it.

Infrastructure

I used the following VMs for this demo:
  • Debian 6 64-bit (2 processors, 1024MB RAM), acting as reverse proxy with ModSecurity 2.5.12. Installed Apache version: 2.2.16.
  • OWASP Broken Web Applications VM. Just the guarenteed solution! Download it here.
  • Windows XP Pro with Hacme bank vulnerable web application installed. Installation instructions can be found here.
My aim is to create a reverse proxy that handles more than one web application's requests.
Below, there is a schematic of the VM infrastructure that I have described earlier.



Architecture

Advantages

  • Unified Rules. With this architecture we have a VM that is charged with filtering every HTTP request to our web applications and therefore, we can edit the rules and parameterize it in order to filter possibly malicious requests. Core rule sets can be used in order to have a generic protection and, on the meanwhile, we can paramiterize the rules for specific fields and functions of our web applications.
  • Network Security. The security of our network becomes more robust and solid. The web applications are isolated, they receive only HTTP request from the reverse proxy.
  • Cost Free! I have used only freeware software, no money are needed for this architecture and infrastracture.

Disadvantages

  • Time Consuming. ModSecurity needs dedicated professionals in order to write rules and parameterize the product.
  • Single point of Failure. ModSecurity VM is a single point of failure, meaning that if VM is down, the web applications will be unavailable and unaccessible.


Configuration

First of all, we need to install ModSecurity at our Debian VM which will be acting as a reverse proxy. Then we enable it and then we download the OWASP Core Rule Set which can be found here.
More specifically, we follow these steps:
€ > apt-get install libapache-mod-security
€ > a2enmod mod-security
Now, we need to set up the reverse proxy. We create a file at the location /etc/apache2/sites-available and we enable it by creating a soft link to it a the location /etc/apache2/sites-enabled. Below you can see a sample site. This is only a sample, you can parameterize it and customize it as you wish.
LoadModule proxy_module /usr/lib/apache2/modules/mod_proxy.so
LoadModule proxy_http_module /usr/lib/apache2/modules/mod_proxy_http.so
<IfModule security2_module>
        Include /etc/apache2/crs/activated_rules/*.conf
</IfModule>
<VirtualHost *:80>
        ServerName modsecurity
        ProxyRequests Off
        ProxyPass               /HacmeBank_v2_Website/  http://192.168.200.15/HacmeBank_v2_Website/
        ProxyPassReverse        /HacmeBank_v2_Website/  http://192.168.200.15/HacmeBank_v2_Website/
        ProxyPass               /owaspbwa/      http://192.168.200.12/
        ProxyPassReverse        /owaspbwa/      http://192.168.200.12/
</VirtualHost>

Now, every request to the web applications is examined by ModSecurity and then, proxied to the appropriate IP inside our LAN.

Example

I am going to omit a demo attack to the OWASP BWA VM because I have already examined it on a previous post in my blog. Therefore, the scenario I am going to follow, is to send a simple SQL injection payload to the Hacme Bank web application.



The logs generated by ModSecurity:

--84b6cd1e-A--
[09/Nov/2012:15:19:50 +0200] UJ0C9X8AAQEAAB0xAVcAAAAC 192.168.200.1 6177 192.168.200.18 80
--84b6cd1e-B--
POST /HacmeBank_v2_Website/aspx/login.aspx HTTP/1.1
Host: 192.168.200.18
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:16.0) Gecko/20100101 Firefox/16.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Proxy-Connection: keep-alive
Referer: http://192.168.200.18/HacmeBank_v2_Website/aspx/login.aspx
Cookie: PHPSESSID=saafok2s1qn7tkf1ln7800isg3; ASP.NET_SessionId=tgsda3mibmrqgluhkzms4u55; CookieLoginAttempts=5
Content-Type: application/x-www-form-urlencoded
Content-Length: 120
--84b6cd1e-C--
__VIEWSTATE=dDwtNDI1MDU4NDs7Pr7Z3yoqTxmFlpDLZYX86TQOF%2Fbz&txtUserName=x%27+or+1%3D1--&txtPassword=test&btnSubmit=Submit
--84b6cd1e-F--
And the log that activated the ModSecurity rule:

Message: Warning. Pattern match "(?i:([\s'"`Β΄ββ\(\)]*)?([\d\w]+)([\s'"`Β΄ββ\(\)]*)?(?:=|<=>|r?like|sounds\s+like|regexp)([\s'"`Β΄ββ\(\)]*)?\2|([\s'"`Β΄ββ\(\)]*)?([\d\w]+)([\s'"`Β΄ββ\(\)]*)?(?:!=|<=|>=|<>|<|>|\^|is\s+not|not\s+like|not\s+regexp)([\s'"`Β΄ββ\(\)] ..." at ARGS:txtUserName. [file "/etc/apache2/crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "77"] [id "950901"] [rev "2.2.5"] [msg "SQL Injection Attack"] [data " 1=1"] [severity "CRITICAL"] [tag "WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"]
Message: Warning. Pattern match "(?i:\bor\b ?(?:\d{1,10}|[\'"][^=]{1,10}[\'"]) ?[=<>]+|(?i:'\s+x?or\s+.{1,20}[+\-!<>=])|\b(?i:x?or)\b\s+(\d{1,10}|'[^=]{1,10}')|\b(?i:x?or)\b\s+(\d{1,10}|'[^=]{1,10}')\s*[=<>])" at ARGS:txtUserName. [file "/etc/apache2/crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "134"] [id "959071"] [rev "2.2.5"] [msg "SQL Injection Attack"] [data "' or 1=1--"] [severity "CRITICAL"] [tag "WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"]
Message: Warning. Pattern match "([\~\!\@\#\$\%\^\&\*\(\)\-\+\=\{\}\[\]\|\:\;"\'\Β΄\β\β\`\<\>].*){4,}" at ARGS:txtUserName. [file "/etc/apache2/crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "171"] [id "981173"] [rev "2.2.5"] [msg "Restricted SQL Character Anomaly Detection Alert - Total # of special characters exceeded"] [data "-"]
Message: Warning. Pattern match "(?i:(?i:\d["'`Β΄ββ]\s+["'`Β΄ββ]\s+\d)|(?:^admin\s*?["'`Β΄ββ]|(\/\*)+["'`Β΄ββ]+\s?(?:--|#|\/\*|{)?)|(?:["'`Β΄ββ]\s*?(x?or|div|like|between|and)[\w\s-]+\s*?[+<>=(),-]\s*?[\d"'`Β΄ββ])|(?:["'`Β΄ββ]\s*?[^\w\s]?=\s*?["'`Β΄ββ]) ..." at ARGS:txtUserName. [file "/etc/apache2/crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "217"] [id "981244"] [msg "Detects basic SQL authentication bypass attempts 1/3"] [data "' or 1=1"] [severity "CRITICAL"] [tag "WEB_ATTACK/SQLI"]
Message: Warning. Pattern match "(?i:(?:["'`Β΄ββ]\s*?(x?or|div|like|between|and)\s*?["'`Β΄ββ]?\d)|(?:\\x(?:23|27|3d))|(?:^.?["'`Β΄ββ]$)|(?:(?:^["'`Β΄ββ\\]*?(?:[\d"'`Β΄ββ]+|[^"'`Β΄ββ]+["'`Β΄ββ]))+\s*?(?:n?and|x?x?or|div|like|between|and|not|\|\||\&\&)\s*?[\w ..." at ARGS:txtUserName. [file "/etc/apache2/crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "249"] [id "981242"] [msg "Detects classic SQL injection probings 1/2"] [data "' or 1"] [severity "CRITICAL"] [tag "WEB_ATTACK/SQLI"]
Apache-Handler: proxy-server
Stopwatch: 1352467189580612 738276 (1537* 9311 -)
Response-Body-Transformed: Dechunked
Producer: ModSecurity for Apache/2.5.12 (http://www.modsecurity.org/); core ruleset/2.1.2.
Server: Apache/2.2.16 (Debian)
--84b6cd1e-Z--

Conclusion

A reverse proxy running ModSecurity can be used to protect server farms that host critical web applications. This architecture is a low cost that could offer significant security protection if ModSecurity is parameterized correctly.

References - Further reading

http://httpd.apache.org/docs/2.2/mod/mod_proxy.html
http://www.ibm.com/developerworks/web/library/wa-lampsec/
http://www.apachetutor.org/admin/reverseproxies
http://www.f5.com/glossary/reverse-proxy.html
http://en.wikipedia.org/wiki/Reverse_proxy

Tuesday, November 6, 2012

Securing OWASP Broken Web Apps with ModSecurity

Overview

In this blog entry I am going to secure the Apache deployed in OWASP broken web apps VM with Trustwave's ModSecurity. OWASP broken web apps VM comes with ModSecurity integrated. The only thing we have to do, is to enable it.
The main goal for this post, is to help IT professionals enable ModSecurity, an open source waf, and then, get acquainted with it.

Enabling ModSecurity Module

ModSecurity module is not enabled by default in OWASP broken web apps VM. Some actions are needed by our side in order to make the module functional.
First of all we need to shutdown Apache server:
/etc/init.d/apache2 stop
We need to edit httpd.conf located at  /etc/apache2 and add the following lines:
<IfModule security2_module>
        Include /etc/apache2/modsecurity-crs/activated_rules/*.conf

</IfModule>

Create soft links of the rules we want to activate to the activated rules folder. In our example we are going to copy the whole base rule set by issuing the command:
ln -s /etc/apache2/modsecurity-crs/base_rules/* /etc/apache2/modsecurity-crs/activated_rules/
ln -s /etc/apache2/modsecurity_crs_10_config_log.conf /etc/apache2/modsecurity-crs/activated_rules/ (for the log settings)

Next, we have to edit modsecurity_crs_10_config_log.conf in order to parameterize the loggin engine.
  • If we need the ModSecurity waf to block the requests that violate any of the activated rules we have to alter the directive "SecRuleEngine" from "DetectionOnly" to "On".
  • Change the directive "SecDefaultAction" to "phase:2,deny,nolog,auditlog" in order to log at at a different file.
  • At the end of the file, un-comment the directive "SecAuditEngine" and if you wish, alter the log file location and name by changing the value at the "SecAuditLog" directive.
Finally, we start Apache server:
/etc/init.d/apache2 start
Now, ModSecurity is fully operational and logs every rule violation.


Attack Example

At this point, we send a simple SQL payload in order to test ModSecurity rules:



The ModSecurity logs are populated by the module. Here we can see the logs generated after our request:
Message: Rule b853e718 [id "950901"][file "/etc/apache2/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"][line "77"] - Execution error - PCRE limits exceeded (-8): (null).
Message: Rule b853e718 [id "950901"][file "/etc/apache2/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"][line "77"] - Execution error - PCRE limits exceeded (-8): (null).
Message: Pattern match "(?i:([\\s'\"`\xc2\xb4\xe2\x80\x99\xe2\x80\x98\\(
\\)]*)?([\\d\\w]+)([\\s'\"`\xc2\xb4\xe2\x80\x99\xe2\x80\x98\\(\\)]*)?(?:=|<=>|r?like|sounds\\s+like|regexp)([\\s'\"`\xc2\xb4\xe2\x80\x99\xe2\x80\x98\\(\\)]*)?\\2|([\\s'\"`\xc2\xb4\xe2\x80\x99\xe2\x80\x98\ ..." at ARGS:id. [file "/etc/apache2/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "77"] [id "950901"] [rev "2.2.5"] [msg "SQL Injection Attack"] [data " 1=1"] [severity "CRITICAL"] [tag "WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"]
Message: Pattern match "(?i:\\bor\\b ?(?:\\d{1,10}|[\\'\"][^=]{1,10}[\\'\"]) ?[=<>]+|(?i:'\\s+x?or\\s+.{1,20}[+\\-!<>=])|\\b(?i:x?or)\\b\\s+(
\\d{1,10}|'[^=]{1,10}')|\\b(?i:x?or)\\b\\s+(\\d{1,10}|'[^=]{1,10}')\\s*[=<>])" at ARGS:id. [file "/etc/apache2/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "134"] [id "959071"] [rev "2.2.5"] [msg "SQL Injection Attack"] [data "' or 1=1--"] [severity "CRITICAL"] [tag "WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"]
Message: Pattern match "([\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(
\\)\\-\\+\\=\\{\\}\\[\\]\\|\\:\\;\"\\'\\\xc2\xb4\\\xe2\x80\x99\\\xe2\x80\x98\\`\\<\\>].*){4,}" at ARGS:id. [file "/etc/apache2/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "171"] [id "981173"] [rev "2.2.5"] [msg "Restricted SQL Character Anomaly Detection Alert - Total # of special characters exceeded"] [data "-"]
Message: Pattern match "(?i:(?i:\\d[\"'`\xc2\xb4\xe2\x80\x99\xe2\x80\x98]\\s+[\"'`\xc2\xb4\xe2\x80\x99\xe2\x80\x98]\\s+\\d)|(?:^admin\\s*?[\"'`\xc2\xb4\xe2\x80\x99\xe2\x80\x98]|(
\\/\\*)+[\"'`\xc2\xb4\xe2\x80\x99\xe2\x80\x98]+\\s?(?:--|#|\\/\\*|{)?)|(?:[\"'`\xc2\xb4\xe2\x80\x9 ..." at ARGS:id. [file "/etc/apache2/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "217"] [id "981244"] [msg "Detects basic SQL authentication bypass attempts 1/3"] [data "' or 1=1"] [severity "CRITICAL"] [tag "WEB_ATTACK/SQLI"]
Message: Pattern match "(?i:(?:[\"'`\xc2\xb4\xe2\x80\x99\xe2\x80\x98]\\s*?(x?or|div|like|between|and)\\s*?[\"'`\xc2\xb4\xe2\x80\x99\xe2\x80\x98]?\\d)|(?:\\\\x(?:23|27|3d))|(?:^.?[\"'`\xc2\xb4\xe2\x80\x99\xe2\x80\x98]$)|(?:(?:^[\"'`\xc2\xb4\xe2\x80\x99\xe2\x80\x98\\\\]*?(?:[\\ ..." at ARGS:id. [file "/etc/apache2/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "249"] [id "981242"] [msg "Detects classic SQL injection probings 1/2"] [data "' or 1"] [severity "CRITICAL"] [tag "WEB_ATTACK/SQLI"]
Message: Warning. Operator GE matched 5 at TX:inbound_anomaly_score. [file "/etc/apache2/modsecurity-crs/activated_rules/modsecurity_crs_60_correlation.conf"] [line "37"] [id "981204"] [msg "Inbound Anomaly Score Exceeded (Total Inbound Score: 23, SQLi=13, XSS=): 981242-Detects classic SQL injection probings 1/2"]
Apache-Handler: application/x-httpd-php
Stopwatch: 1352206441253338 16368 (- - -)
Stopwatch2: 1352206441253338 16368; combined=11385, p1=165, p2=10807, p3=3, p4=91, p5=318, sr=20, sw=1, l=0, gc=0
Response-Body-Transformed: Dechunked
Producer: ModSecurity for Apache/2.7.0trunk (
http://www.modsecurity.org/); core ruleset/2.1.2.
Server: Apache/2.2.14 (Ubuntu) mod_mono/2.4.3 PHP/5.3.2-1ubuntu4.5 with Suhosin-Patch mod_python/3.3.1 Python/2.6.5

Conclusion

By enabling ModSecurity in OWASP Broken web apps VM is a good hands-on opportunity for waf administrations to get used to configuring and parametrizing ModSecurity open source web application firewall.

References

Saturday, November 3, 2012

Cross Site Request Forgery - Legitimazing Forged Requests

For my first -real- blog post, I chose to analyse a common vulnerability found in many web applications; the Cross Site Request Forgery (CSRF) attack.

Overview

CSRF? Gime the big picture!

CSRF is rated among the 10 most critical web application security flaws in OWASP's Top 10 project. In simple words, CSRF vulnerabilities occur when the web application cannot distinguish legitimate requests from forged requests. In simple words, a user can perform actions in his account without his explicit permission and consent.
In the following picture you can see how a CSRF attack is performed, in a simple graphic:

 

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.

Attack Scenario

Ok. And how's that done?...

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 populates 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!)
In 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.



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




Impact

And what I am supposed to lose?

CSRF vulnerabilities affect the Application Business Logic and the Session Management of a web application. We can understand this in the following -in purpose- trivial scenario in order to understand the nature of the impact.
Let's assume we have an ebanking web application that needs two steps to perform a bank transfer; the first one is the details of the transfer and the second one is confirmation. Now, imagine an attacker who is logged in on his account, and reaches the second step (confirmation), but with receiver of the bank transfer himself, and sender of the bank transfer the victim. What if he could create such a request, host it on his web server and trick the victim click on it? The victim's bank account would be charged the amount defined by the attacker, and sent to the victim's bank account! With this trivial scenario, we can see how Application Business Logic can be bypassed.
The attacker, upon a successful exploitation of a CSRF attack can achieve elevation of privileges with significant business impact and reputation loss to the organization hosting the web application.

Am I vulnerable to CSRF?

I am safe?

Web applications are vulnerable to CSRF attacks if their requests are not "unique" or "pegged" to one user's session. Remember, in the overview section I mentioned that: "CSRF vulnerabilities occur when the web application cannot distinguish legitimate requests from forged requests". Therefore, we can question ourselves if each request is made "unique" through our session. In most web applications, browsers tend to include any authentication token (e.g. sessionid) while sending the requests associated with the web application.
As a second step, we can examine our web application by using a proxy tool and by scrutinizing every request sent to the web application. Furthermore, web developer firefox add-on offers numerous capabilities to inspect and alter forms and cookies interchanged between the web server and the web application.

Prevention Techniques

Protection! NOW!

In order to prevent CSRF attacks to our web application, we should deploy technologies that would differentiate legitimate from forged requests.
According to this mentality, 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."
In the web there are numerous references regarding the implementation of anti-CSRF tokens.
Few examples:

Conclusion

As you have seen, patching existing code or creating non-vulnerable code can be really time consuming. Nevertheless, CSRF attacks can cause serious business impact if successfully deployed. That's why it is imperative to guard our web applications against CSRF attacks.

References

https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet
https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project