JavaFest. Nanne Baars. Web application security for developers

F
FestGroupFestGroup
SECURITY FOR DEVELOPERS
Nanne Baars
About me
¨ Java developer
¨ Developer à Security consultant à Developer
¨ Project lead of WebGoat à
https://github.com/WebGoat/
WebGoat is…
¨ A deliberately vulnerable web application maintained
by OWASP designed to teach web application security lessons.
¨ In each lesson, users must demonstrate their understanding of a
security issue by exploiting a real vulnerability in the WebGoat
application
https://webgoat.github.io/WebGoat/
Learn in 3 steps
JavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developers
- Examples
- Background
- How to prevent
https://www.pentestpartners.com/security-blog/hacking-ski-helmet-audio/
https://www.pentestpartners.com/security-blog/hacking-ski-helmet-audio/
JavaFest. Nanne Baars. Web application security for developers
Secret management
Still a problem
https://darkport.co.uk/blog/ahh-shhgit!/
https://darkport.co.uk/blog/ahh-shhgit!/
JavaFest. Nanne Baars. Web application security for developers
https://blog.milessteele.com/posts/2013-07-07-hiding-djangos-secret-key.html
JavaFest. Nanne Baars. Web application security for developers
Within projects as developers…
¨ Make sure secrets do not end up in Git
¤ Encrypt your secrets (for example like Travis CI)
¤ More fancy use Vault, KeyCloak etc
¨ Use tooling to scan your repository
¨ Define a policy what should be done in case it happens
¤ Git history
As a team…
¨ Think about what to do when a team member leaves…
¤ Think about how many systems you have access to, is the access to AWS,
Kubernetes, Github, Gitlab, Jira etc centrally provided?
¨ Again, have a clear policy in place
Easy to automate
Cryptography
private static final byte[] ENCRYPT_IV = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
public static String encrypt(String dataPassword, String cleartext) throws Exception
{
IvParameterSpec zeroIv = new IvParameterSpec(ENCRYPT_IV);
SecretKeySpec key = new SecretKeySpec(dataPassword.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
…
}
private static final byte[] ENCRYPT_IV = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 };
public static String encrypt(String dataPassword, String cleartext) throws Exception
{
IvParameterSpec zeroIv = new IvParameterSpec(ENCRYPT_IV);
SecretKeySpec key = new SecretKeySpec(dataPassword.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
…
}
Cryptography vs developers
“In this post I will show you how to use RSA in Java…..”
public static String encrypt(String plainText, PublicKey publicKey) {
Cipher encryptCipher = Cipher.getInstance("RSA");
encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] cipherText = encryptCipher.doFinal(plainText.getBytes(UTF_8));
return Base64.getEncoder().encodeToString(cipherText);
}
public static void main(String [] args) throws Exception {
// generate public and private keys
…
// sign the message
byte [] signed = encrypt(privateKey, "This is a secret message");
System.out.println(new String(signed)); // <<signed message>>
// verify the message
byte[] verified = decrypt(pubKey, encrypted);
System.out.println(new String(verified)); // This is a secret message
}
public static byte[] encrypt(PrivateKey privateKey, String message) {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
return cipher.doFinal(message.getBytes());
}
public static byte[] decrypt(PublicKey publicKey, byte [] encrypted) {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
return cipher.doFinal(encrypted);
}
JavaFest. Nanne Baars. Web application security for developers
Solution - Libsodium or Google Tink
https://github.com/google/tink
Path traversal
¨ A path(directory) traversal is a vulnerability where an attacker is able
to access or store files and directories outside the location where the
application is running.
¨ For example: http://example.com/file=report.pdf
¨ Change into: http://example.com/file=../../../../../etc/passwd
¨ In case of a file upload you might be able to overwrite other files
https://hackerone.com/reports/827052
https://snyk.io/research/zip-slip-vulnerability
Mitigation in file upload
var multiPartFile = ...
var targetFile = new File("/tmp", multiPartFile.getOriginalName());
var canonicalPath = targetFile.getCanonicalPath();
if (!canonicalPath.startWith("/tmp") {
throw new IllegalArgumentException("Invalid filename");
}
IOUtils.copy(multiPartFile.getBytes(), targetFile);
Input validation
¨ Check for ../
¨ Be aware of encoding: %2e%2e/%2f
¨ Spring Security has: StrictHttpFirewall which automatically drops a
request if the path variable contains ../
@Getter("/f")
public void f(@RequestParam("name") String name) {
//name is automatically decoded so %2E%2E%2F%2E%2E%2Ftest
//will become ../../test
}
@Getter("/g")
public void g(HttpServletRequest request) {
var queryString = request.getQueryString();
// will return %2E%2E%2F%2E%2E%2Ftest
}
@Getter("/h")
public void h(HttpServletRequest request) {
var name = request.getParam("name");
//will return ../../test
Host-Header Injection
¨ In web applications, developers use the HTTP Host header available in
HTTP request
¨ A remote attacker can exploit this by sending a fake header with a
domain name under the attackers control.
Often found during password reset
curl 'https://webgoat-cloud.net/create-password-reset-link' --data-raw 'email=test1234@webgoat-cloud.net'
Let’s do that again…
curl 'http://webgoat-cloud.net/create-password-reset-link'
-H'Host: attacker.com'
--data-raw 'email=test1234@webgoat.org'
JavaFest. Nanne Baars. Web application security for developers
JavaFest. Nanne Baars. Web application security for developers
Example 2: Azure Authentication / Spring Boot
Example.com
Easy to setup
¨ Standard Spring Boot / Azure auto configuration provided
1. Register your application with your Azure Active Directory Tenant
2. Configure application.properties
spring.security.oauth2.client.registration.azure.client-id=xxxxxx-your-client-id-xxxxxx
spring.security.oauth2.client.registration.azure.client-secret=xxxxxx-your-client-secret-xxxxxx
azure.activedirectory.tenant-id=xxxxxx-your-tenant-id-xxxxxx
azure.activedirectory.active-directory-groups=group1, group2
Spring Boot configuration
¨ We enabled this setting in the application.properties:
server.use-forward-headers=true
curl -i http://localhost:8080
HTTP/1.1 302 Found
Location: http://localhost:8080/oauth2/authorization/azure
curl -i http://localhost:8080/oauth2/authorization/azure
HTTP/1.1 302 Found
Location:
https://login.microsoftonline.com/common/oauth2/authorize?response_type=code
https://graph.microsoft.com/user.read&state=&
redirect_uri=http://localhost:8080/login/oauth2/code/azure
Now let’s try
curl -i -H"X-Forwarded-Host: attacker.com" http://localhost:8080/
HTTP/1.1 302 Found
Location: http://attacker.com/oauth2/authorization/azure
But wait how does the redirect_uri work?
curl -i http://localhost:8080/oauth2/authorization/azure
HTTP/1.1 302 Found
Location:
https://login.microsoftonline.com/common/oauth2/authorize?response_type=codehttps://graph.
microsoft.com/user.read&state=&redirect_uri=http://localhost:8080/login/oauth2/code/azure
spring.security.oauth2.client.registration.azure.redirect-uri-template={baseUrl}/login/oauth2/code/{registrationId}
curl -i -H"X-Forwarded-Host: attacker.com" http://localhost:8080/oauth2/authorization/azure
HTTP/1.1 302 Found
Location:
https://login.microsoftonline.com/common/oauth2/authorize?response_type=code
https://graph.microsoft.com/user.read&state=&
redirect_uri=http://attacker.com/login/oauth2/code/azure
(Un)fortunately this does not work J
https://tools.ietf.org/html/rfc6749#section-10.6
JavaFest. Nanne Baars. Web application security for developers
Recap
¨ This is not a bug in Spring security
¨ Something which happened because we added:
server.use-forward-headers=true
Solution
/**
* <p>
* Determines which hostnames should be allowed. The default is to allow any
* hostname.
* </p>
*
* @param allowedHostnames the predicate for testing hostnames
* @since 5.2
*/
public void setAllowedHostnames(Predicate<String> allowedHostnames) {
if (allowedHostnames == null) {
throw new IllegalArgumentException("allowedHostnames cannot be null");
}
this.allowedHostnames = allowedHostnames;
}
@Bean
public HttpFirewall firewall() {
StrictHttpFirewall firewall = new StrictHttpFirewall();
firewall.setAllowedHttpMethods(Arrays.asList("GET", "POST"));
firewall.setAllowedHostnames(s -> s.equals("localhost"));
curl -i -H"X-Forwarded-Host: attacker.com" http://localhost:8080/
java.lang.RuntimeException: org.springframework.security.web.firewall.RequestRejectedException:
The request was rejected because the domain attacker.com is untrusted.
at io.undertow.servlet.spec.RequestDispatcherImpl.error(RequestDispatcherImpl.java:507)
at io.undertow.servlet.spec.RequestDispatcherImpl.error(RequestDispatcherImpl.java:427)
Solution
¨ As developers we are responsible to validate those headers
¨ Verify all headers you can receive from the outside.
¤ This includes: X-Forwarded-For, X-Forwarded-Host etc
¨ Do not rely on thinking reversed proxy will solve this!
¨ Check to see whether the framework has built in protection
Where to start...
1. Make developers security aware
n Code review
n Practice / learn / adapt
2. Adopt a security guideline in your team
3. Test your own application
4. Start using tools to find to most obvious mistakes
1 of 55

Recommended

Different Methodology To Recon Your Targets by
Different Methodology To Recon Your TargetsDifferent Methodology To Recon Your Targets
Different Methodology To Recon Your TargetsEslamAkl
647 views17 slides
Kablosuz Ağ Saldırı Araçları by
Kablosuz Ağ Saldırı AraçlarıKablosuz Ağ Saldırı Araçları
Kablosuz Ağ Saldırı AraçlarıBGA Cyber Security
13.7K views31 slides
Kablosuz Ağlara Yapılan Saldırılar by
Kablosuz Ağlara Yapılan SaldırılarKablosuz Ağlara Yapılan Saldırılar
Kablosuz Ağlara Yapılan SaldırılarBGA Cyber Security
5.7K views13 slides
Cyber Threat Intelligence.pptx by
Cyber Threat Intelligence.pptxCyber Threat Intelligence.pptx
Cyber Threat Intelligence.pptxAbimbolaFisher1
232 views10 slides
Fantastic Red Team Attacks and How to Find Them by
Fantastic Red Team Attacks and How to Find ThemFantastic Red Team Attacks and How to Find Them
Fantastic Red Team Attacks and How to Find ThemRoss Wolf
896 views88 slides
Firewall by
FirewallFirewall
FirewallApo
13.7K views33 slides

More Related Content

What's hot

Empire Kurulumu ve Kullanımı by
Empire Kurulumu ve Kullanımı Empire Kurulumu ve Kullanımı
Empire Kurulumu ve Kullanımı BGA Cyber Security
1.7K views53 slides
IPSec VPN tunnel by
IPSec VPN tunnelIPSec VPN tunnel
IPSec VPN tunnelArunKumar Subbiah
776 views6 slides
Offensive Security basics part 1 by
Offensive Security basics  part 1Offensive Security basics  part 1
Offensive Security basics part 1wharpreet
364 views39 slides
Responding to Cobalt Strike by
Responding to Cobalt StrikeResponding to Cobalt Strike
Responding to Cobalt StrikeChristopher Gerritz
405 views18 slides
A5-Security misconfiguration-OWASP 2013 by
A5-Security misconfiguration-OWASP 2013   A5-Security misconfiguration-OWASP 2013
A5-Security misconfiguration-OWASP 2013 Sorina Chirilă
4.3K views10 slides
Living off the land and fileless attack techniques by
Living off the land and fileless attack techniquesLiving off the land and fileless attack techniques
Living off the land and fileless attack techniquesSymantec Security Response
4K views40 slides

What's hot(20)

Offensive Security basics part 1 by wharpreet
Offensive Security basics  part 1Offensive Security basics  part 1
Offensive Security basics part 1
wharpreet364 views
A5-Security misconfiguration-OWASP 2013 by Sorina Chirilă
A5-Security misconfiguration-OWASP 2013   A5-Security misconfiguration-OWASP 2013
A5-Security misconfiguration-OWASP 2013
Sorina Chirilă4.3K views
Wpa2 psk security measure by Shivam Singh
Wpa2 psk security measureWpa2 psk security measure
Wpa2 psk security measure
Shivam Singh956 views
Protecting Java EE Web Apps with Secure HTTP Headers by Frank Kim
Protecting Java EE Web Apps with Secure HTTP HeadersProtecting Java EE Web Apps with Secure HTTP Headers
Protecting Java EE Web Apps with Secure HTTP Headers
Frank Kim13.7K views
Beginner's Guide to SIEM by AlienVault
Beginner's Guide to SIEM Beginner's Guide to SIEM
Beginner's Guide to SIEM
AlienVault24.8K views
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 7, 8, 9 by BGA Cyber Security
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 7, 8, 9Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 7, 8, 9
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 7, 8, 9
BGA Cyber Security33.8K views
Ch 11: Hacking Wireless Networks by Sam Bowne
Ch 11: Hacking Wireless NetworksCh 11: Hacking Wireless Networks
Ch 11: Hacking Wireless Networks
Sam Bowne4.8K views
iOS Application Static Analysis - Deepika Kumari.pptx by deepikakumari643428
iOS Application Static Analysis - Deepika Kumari.pptxiOS Application Static Analysis - Deepika Kumari.pptx
iOS Application Static Analysis - Deepika Kumari.pptx
Introduction to Offensive Security.pptx by MaaitrayoDas
Introduction to Offensive Security.pptxIntroduction to Offensive Security.pptx
Introduction to Offensive Security.pptx
MaaitrayoDas59 views
Threat Hunting with Splunk by Splunk
Threat Hunting with SplunkThreat Hunting with Splunk
Threat Hunting with Splunk
Splunk8.8K views
Network access control by Sinem Altan
Network access controlNetwork access control
Network access control
Sinem Altan2.9K views
Weaponizing Recon - Smashing Applications for Security Vulnerabilities & Profits by Harsh Bothra
Weaponizing Recon - Smashing Applications for Security Vulnerabilities & ProfitsWeaponizing Recon - Smashing Applications for Security Vulnerabilities & Profits
Weaponizing Recon - Smashing Applications for Security Vulnerabilities & Profits
Harsh Bothra747 views
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 4, 5, 6 by BGA Cyber Security
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 4, 5, 6Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 4, 5, 6
Beyaz Şapkalı Hacker CEH Eğitimi - Bölüm 4, 5, 6
BGA Cyber Security34.5K views

Similar to JavaFest. Nanne Baars. Web application security for developers

10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020 by
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020Matt Raible
177 views65 slides
Secure Coding for NodeJS by
Secure Coding for NodeJSSecure Coding for NodeJS
Secure Coding for NodeJSThang Chung
2K views55 slides
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi by
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiGrâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiJérémy Derussé
2.6K views29 slides
Step-by-step Development of an Application for the Java Card Connected Platform by
Step-by-step Development of an Application for the Java Card Connected PlatformStep-by-step Development of an Application for the Java Card Connected Platform
Step-by-step Development of an Application for the Java Card Connected PlatformEric Vétillard
1.8K views51 slides
Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013 by
Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013
Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013Carlos Sanchez
16.9K views63 slides
Hardening cassandra q2_2016 by
Hardening cassandra q2_2016Hardening cassandra q2_2016
Hardening cassandra q2_2016zznate
871 views90 slides

Similar to JavaFest. Nanne Baars. Web application security for developers(20)

10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020 by Matt Raible
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
Matt Raible177 views
Secure Coding for NodeJS by Thang Chung
Secure Coding for NodeJSSecure Coding for NodeJS
Secure Coding for NodeJS
Thang Chung2K views
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi by Jérémy Derussé
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry PiGrâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Grâce aux tags Varnish, j'ai switché ma prod sur Raspberry Pi
Jérémy Derussé2.6K views
Step-by-step Development of an Application for the Java Card Connected Platform by Eric Vétillard
Step-by-step Development of an Application for the Java Card Connected PlatformStep-by-step Development of an Application for the Java Card Connected Platform
Step-by-step Development of an Application for the Java Card Connected Platform
Eric Vétillard1.8K views
Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013 by Carlos Sanchez
Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013
Continuous Delivery with Maven, Puppet and Tomcat - ApacheCon NA 2013
Carlos Sanchez16.9K views
Hardening cassandra q2_2016 by zznate
Hardening cassandra q2_2016Hardening cassandra q2_2016
Hardening cassandra q2_2016
zznate871 views
Securing Cassandra for Compliance by DataStax
Securing Cassandra for ComplianceSecuring Cassandra for Compliance
Securing Cassandra for Compliance
DataStax14.3K views
Service Worker - Reliability bits by jungkees
Service Worker - Reliability bitsService Worker - Reliability bits
Service Worker - Reliability bits
jungkees821 views
Building Your Own IoT Platform using FIWARE GEis by FIWARE
Building Your Own IoT Platform using FIWARE GEisBuilding Your Own IoT Platform using FIWARE GEis
Building Your Own IoT Platform using FIWARE GEis
FIWARE803 views
AWS Study Group - Chapter 03 - Elasticity and Scalability Concepts [Solution ... by QCloudMentor
AWS Study Group - Chapter 03 - Elasticity and Scalability Concepts [Solution ...AWS Study Group - Chapter 03 - Elasticity and Scalability Concepts [Solution ...
AWS Study Group - Chapter 03 - Elasticity and Scalability Concepts [Solution ...
QCloudMentor134 views
FIWARE Wednesday Webinars - How to Secure IoT Devices by FIWARE
FIWARE Wednesday Webinars - How to Secure IoT DevicesFIWARE Wednesday Webinars - How to Secure IoT Devices
FIWARE Wednesday Webinars - How to Secure IoT Devices
FIWARE785 views
Fun With Spring Security by Burt Beckwith
Fun With Spring SecurityFun With Spring Security
Fun With Spring Security
Burt Beckwith3.4K views
PHP SA 2014 - Releasing Your Open Source Project by xsist10
PHP SA 2014 - Releasing Your Open Source ProjectPHP SA 2014 - Releasing Your Open Source Project
PHP SA 2014 - Releasing Your Open Source Project
xsist101.9K views
I/O Extended 2019 WebTech - New capabilities for the web by HanboramRobinJang
I/O Extended 2019 WebTech - New capabilities for the webI/O Extended 2019 WebTech - New capabilities for the web
I/O Extended 2019 WebTech - New capabilities for the web
HanboramRobinJang110 views
Burn down the silos! Helping dev and ops gel on high availability websites by Lindsay Holmwood
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
Lindsay Holmwood1.6K views
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019 by Matt Raible
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 201910 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
10 Excellent Ways to Secure Your Spring Boot Application - Devoxx Belgium 2019
Matt Raible473 views
Deploying Django with Ansible by andrewmirskynet
Deploying Django with AnsibleDeploying Django with Ansible
Deploying Django with Ansible
andrewmirskynet4.9K views
2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub... by Andrey Devyatkin
2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub...2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub...
2020-02-20 - HashiCorpUserGroup Madring - Integrating HashiCorp Vault and Kub...
Andrey Devyatkin84 views

More from FestGroup

JavaFest. Барух Садогурский. DevOps для разработчиков (или против них?!) by
JavaFest. Барух Садогурский. DevOps для разработчиков (или против них?!)JavaFest. Барух Садогурский. DevOps для разработчиков (или против них?!)
JavaFest. Барух Садогурский. DevOps для разработчиков (или против них?!)FestGroup
235 views113 slides
JavaFest. Виктор Полищук. Legacy: как победить в гонке by
JavaFest. Виктор Полищук. Legacy: как победить в гонкеJavaFest. Виктор Полищук. Legacy: как победить в гонке
JavaFest. Виктор Полищук. Legacy: как победить в гонкеFestGroup
199 views62 slides
JavaFest. Cedrick Lunven. Build APIS with SpringBoot - REST, GRPC, GRAPHQL wh... by
JavaFest. Cedrick Lunven. Build APIS with SpringBoot - REST, GRPC, GRAPHQL wh...JavaFest. Cedrick Lunven. Build APIS with SpringBoot - REST, GRPC, GRAPHQL wh...
JavaFest. Cedrick Lunven. Build APIS with SpringBoot - REST, GRPC, GRAPHQL wh...FestGroup
283 views55 slides
JavaFest. Philipp Krenn. Scale Elasticsearch for Your Java Applications by
JavaFest. Philipp Krenn. Scale Elasticsearch for Your Java ApplicationsJavaFest. Philipp Krenn. Scale Elasticsearch for Your Java Applications
JavaFest. Philipp Krenn. Scale Elasticsearch for Your Java ApplicationsFestGroup
175 views54 slides
JavaFest. Grzegorz Piwowarek. Hazelcast - Hitchhiker’s Guide by
JavaFest. Grzegorz Piwowarek. Hazelcast - Hitchhiker’s GuideJavaFest. Grzegorz Piwowarek. Hazelcast - Hitchhiker’s Guide
JavaFest. Grzegorz Piwowarek. Hazelcast - Hitchhiker’s GuideFestGroup
122 views61 slides
JavaFest. Денис Макогон. 6 заблуждений относительно современной Java by
JavaFest. Денис Макогон. 6 заблуждений относительно современной JavaJavaFest. Денис Макогон. 6 заблуждений относительно современной Java
JavaFest. Денис Макогон. 6 заблуждений относительно современной JavaFestGroup
176 views44 slides

More from FestGroup(10)

JavaFest. Барух Садогурский. DevOps для разработчиков (или против них?!) by FestGroup
JavaFest. Барух Садогурский. DevOps для разработчиков (или против них?!)JavaFest. Барух Садогурский. DevOps для разработчиков (или против них?!)
JavaFest. Барух Садогурский. DevOps для разработчиков (или против них?!)
FestGroup235 views
JavaFest. Виктор Полищук. Legacy: как победить в гонке by FestGroup
JavaFest. Виктор Полищук. Legacy: как победить в гонкеJavaFest. Виктор Полищук. Legacy: как победить в гонке
JavaFest. Виктор Полищук. Legacy: как победить в гонке
FestGroup199 views
JavaFest. Cedrick Lunven. Build APIS with SpringBoot - REST, GRPC, GRAPHQL wh... by FestGroup
JavaFest. Cedrick Lunven. Build APIS with SpringBoot - REST, GRPC, GRAPHQL wh...JavaFest. Cedrick Lunven. Build APIS with SpringBoot - REST, GRPC, GRAPHQL wh...
JavaFest. Cedrick Lunven. Build APIS with SpringBoot - REST, GRPC, GRAPHQL wh...
FestGroup283 views
JavaFest. Philipp Krenn. Scale Elasticsearch for Your Java Applications by FestGroup
JavaFest. Philipp Krenn. Scale Elasticsearch for Your Java ApplicationsJavaFest. Philipp Krenn. Scale Elasticsearch for Your Java Applications
JavaFest. Philipp Krenn. Scale Elasticsearch for Your Java Applications
FestGroup175 views
JavaFest. Grzegorz Piwowarek. Hazelcast - Hitchhiker’s Guide by FestGroup
JavaFest. Grzegorz Piwowarek. Hazelcast - Hitchhiker’s GuideJavaFest. Grzegorz Piwowarek. Hazelcast - Hitchhiker’s Guide
JavaFest. Grzegorz Piwowarek. Hazelcast - Hitchhiker’s Guide
FestGroup122 views
JavaFest. Денис Макогон. 6 заблуждений относительно современной Java by FestGroup
JavaFest. Денис Макогон. 6 заблуждений относительно современной JavaJavaFest. Денис Макогон. 6 заблуждений относительно современной Java
JavaFest. Денис Макогон. 6 заблуждений относительно современной Java
FestGroup176 views
JavaFest. Taras Boychuk. There is always a choice. Spring Data JDBC vs. Hiber... by FestGroup
JavaFest. Taras Boychuk. There is always a choice. Spring Data JDBC vs. Hiber...JavaFest. Taras Boychuk. There is always a choice. Spring Data JDBC vs. Hiber...
JavaFest. Taras Boychuk. There is always a choice. Spring Data JDBC vs. Hiber...
FestGroup183 views
JavaFest. Вадим Казулькин. Projects Valhalla, Loom and GraalVM by FestGroup
JavaFest. Вадим Казулькин. Projects Valhalla, Loom and GraalVMJavaFest. Вадим Казулькин. Projects Valhalla, Loom and GraalVM
JavaFest. Вадим Казулькин. Projects Valhalla, Loom and GraalVM
FestGroup180 views
JavaFest. Антон Лемешко. Model-Driven Development in the Open Java Universe by FestGroup
JavaFest. Антон Лемешко. Model-Driven Development in the Open Java UniverseJavaFest. Антон Лемешко. Model-Driven Development in the Open Java Universe
JavaFest. Антон Лемешко. Model-Driven Development in the Open Java Universe
FestGroup132 views
JavaFest. Дмитрий Сергеев. Data processing with Kafka Streams and Spring Fram... by FestGroup
JavaFest. Дмитрий Сергеев. Data processing with Kafka Streams and Spring Fram...JavaFest. Дмитрий Сергеев. Data processing with Kafka Streams and Spring Fram...
JavaFest. Дмитрий Сергеев. Data processing with Kafka Streams and Spring Fram...
FestGroup225 views

Recently uploaded

Drama KS5 Breakdown by
Drama KS5 BreakdownDrama KS5 Breakdown
Drama KS5 BreakdownWestHatch
79 views2 slides
231112 (WR) v1 ChatGPT OEB 2023.pdf by
231112 (WR) v1  ChatGPT OEB 2023.pdf231112 (WR) v1  ChatGPT OEB 2023.pdf
231112 (WR) v1 ChatGPT OEB 2023.pdfWilfredRubens.com
157 views21 slides
Community-led Open Access Publishing webinar.pptx by
Community-led Open Access Publishing webinar.pptxCommunity-led Open Access Publishing webinar.pptx
Community-led Open Access Publishing webinar.pptxJisc
93 views9 slides
Class 10 English lesson plans by
Class 10 English  lesson plansClass 10 English  lesson plans
Class 10 English lesson plansTARIQ KHAN
288 views53 slides
Narration lesson plan.docx by
Narration lesson plan.docxNarration lesson plan.docx
Narration lesson plan.docxTARIQ KHAN
112 views11 slides
Classification of crude drugs.pptx by
Classification of crude drugs.pptxClassification of crude drugs.pptx
Classification of crude drugs.pptxGayatriPatra14
86 views13 slides

Recently uploaded(20)

Drama KS5 Breakdown by WestHatch
Drama KS5 BreakdownDrama KS5 Breakdown
Drama KS5 Breakdown
WestHatch79 views
Community-led Open Access Publishing webinar.pptx by Jisc
Community-led Open Access Publishing webinar.pptxCommunity-led Open Access Publishing webinar.pptx
Community-led Open Access Publishing webinar.pptx
Jisc93 views
Class 10 English lesson plans by TARIQ KHAN
Class 10 English  lesson plansClass 10 English  lesson plans
Class 10 English lesson plans
TARIQ KHAN288 views
Narration lesson plan.docx by TARIQ KHAN
Narration lesson plan.docxNarration lesson plan.docx
Narration lesson plan.docx
TARIQ KHAN112 views
Classification of crude drugs.pptx by GayatriPatra14
Classification of crude drugs.pptxClassification of crude drugs.pptx
Classification of crude drugs.pptx
GayatriPatra1486 views
AUDIENCE - BANDURA.pptx by iammrhaywood
AUDIENCE - BANDURA.pptxAUDIENCE - BANDURA.pptx
AUDIENCE - BANDURA.pptx
iammrhaywood84 views
Sociology KS5 by WestHatch
Sociology KS5Sociology KS5
Sociology KS5
WestHatch70 views
Narration ppt.pptx by TARIQ KHAN
Narration  ppt.pptxNarration  ppt.pptx
Narration ppt.pptx
TARIQ KHAN135 views
Create a Structure in VBNet.pptx by Breach_P
Create a Structure in VBNet.pptxCreate a Structure in VBNet.pptx
Create a Structure in VBNet.pptx
Breach_P75 views
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptx by ISSIP
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptxEIT-Digital_Spohrer_AI_Intro 20231128 v1.pptx
EIT-Digital_Spohrer_AI_Intro 20231128 v1.pptx
ISSIP369 views
Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant... by Ms. Pooja Bhandare
Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant...Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant...
Pharmaceutical Inorganic Chemistry Unit IVMiscellaneous compounds Expectorant...
The basics - information, data, technology and systems.pdf by JonathanCovena1
The basics - information, data, technology and systems.pdfThe basics - information, data, technology and systems.pdf
The basics - information, data, technology and systems.pdf
JonathanCovena1115 views
Structure and Functions of Cell.pdf by Nithya Murugan
Structure and Functions of Cell.pdfStructure and Functions of Cell.pdf
Structure and Functions of Cell.pdf
Nithya Murugan545 views
When Sex Gets Complicated: Porn, Affairs, & Cybersex by Marlene Maheu
When Sex Gets Complicated: Porn, Affairs, & CybersexWhen Sex Gets Complicated: Porn, Affairs, & Cybersex
When Sex Gets Complicated: Porn, Affairs, & Cybersex
Marlene Maheu67 views
Solar System and Galaxies.pptx by DrHafizKosar
Solar System and Galaxies.pptxSolar System and Galaxies.pptx
Solar System and Galaxies.pptx
DrHafizKosar91 views
The Open Access Community Framework (OACF) 2023 (1).pptx by Jisc
The Open Access Community Framework (OACF) 2023 (1).pptxThe Open Access Community Framework (OACF) 2023 (1).pptx
The Open Access Community Framework (OACF) 2023 (1).pptx
Jisc110 views

JavaFest. Nanne Baars. Web application security for developers

  • 2. About me ¨ Java developer ¨ Developer à Security consultant à Developer ¨ Project lead of WebGoat à https://github.com/WebGoat/
  • 3. WebGoat is… ¨ A deliberately vulnerable web application maintained by OWASP designed to teach web application security lessons. ¨ In each lesson, users must demonstrate their understanding of a security issue by exploiting a real vulnerability in the WebGoat application
  • 10. - Examples - Background - How to prevent
  • 20. Within projects as developers… ¨ Make sure secrets do not end up in Git ¤ Encrypt your secrets (for example like Travis CI) ¤ More fancy use Vault, KeyCloak etc ¨ Use tooling to scan your repository ¨ Define a policy what should be done in case it happens ¤ Git history
  • 21. As a team… ¨ Think about what to do when a team member leaves… ¤ Think about how many systems you have access to, is the access to AWS, Kubernetes, Github, Gitlab, Jira etc centrally provided? ¨ Again, have a clear policy in place
  • 24. private static final byte[] ENCRYPT_IV = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }; public static String encrypt(String dataPassword, String cleartext) throws Exception { IvParameterSpec zeroIv = new IvParameterSpec(ENCRYPT_IV); SecretKeySpec key = new SecretKeySpec(dataPassword.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv); … } private static final byte[] ENCRYPT_IV = { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 }; public static String encrypt(String dataPassword, String cleartext) throws Exception { IvParameterSpec zeroIv = new IvParameterSpec(ENCRYPT_IV); SecretKeySpec key = new SecretKeySpec(dataPassword.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv); … }
  • 26. “In this post I will show you how to use RSA in Java…..” public static String encrypt(String plainText, PublicKey publicKey) { Cipher encryptCipher = Cipher.getInstance("RSA"); encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] cipherText = encryptCipher.doFinal(plainText.getBytes(UTF_8)); return Base64.getEncoder().encodeToString(cipherText); }
  • 27. public static void main(String [] args) throws Exception { // generate public and private keys … // sign the message byte [] signed = encrypt(privateKey, "This is a secret message"); System.out.println(new String(signed)); // <<signed message>> // verify the message byte[] verified = decrypt(pubKey, encrypted); System.out.println(new String(verified)); // This is a secret message } public static byte[] encrypt(PrivateKey privateKey, String message) { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); return cipher.doFinal(message.getBytes()); } public static byte[] decrypt(PublicKey publicKey, byte [] encrypted) { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, publicKey); return cipher.doFinal(encrypted); }
  • 29. Solution - Libsodium or Google Tink
  • 31. Path traversal ¨ A path(directory) traversal is a vulnerability where an attacker is able to access or store files and directories outside the location where the application is running. ¨ For example: http://example.com/file=report.pdf ¨ Change into: http://example.com/file=../../../../../etc/passwd ¨ In case of a file upload you might be able to overwrite other files
  • 34. Mitigation in file upload var multiPartFile = ... var targetFile = new File("/tmp", multiPartFile.getOriginalName()); var canonicalPath = targetFile.getCanonicalPath(); if (!canonicalPath.startWith("/tmp") { throw new IllegalArgumentException("Invalid filename"); } IOUtils.copy(multiPartFile.getBytes(), targetFile);
  • 35. Input validation ¨ Check for ../ ¨ Be aware of encoding: %2e%2e/%2f ¨ Spring Security has: StrictHttpFirewall which automatically drops a request if the path variable contains ../
  • 36. @Getter("/f") public void f(@RequestParam("name") String name) { //name is automatically decoded so %2E%2E%2F%2E%2E%2Ftest //will become ../../test } @Getter("/g") public void g(HttpServletRequest request) { var queryString = request.getQueryString(); // will return %2E%2E%2F%2E%2E%2Ftest } @Getter("/h") public void h(HttpServletRequest request) { var name = request.getParam("name"); //will return ../../test
  • 37. Host-Header Injection ¨ In web applications, developers use the HTTP Host header available in HTTP request ¨ A remote attacker can exploit this by sending a fake header with a domain name under the attackers control.
  • 38. Often found during password reset curl 'https://webgoat-cloud.net/create-password-reset-link' --data-raw 'email=test1234@webgoat-cloud.net'
  • 39. Let’s do that again… curl 'http://webgoat-cloud.net/create-password-reset-link' -H'Host: attacker.com' --data-raw 'email=test1234@webgoat.org'
  • 42. Example 2: Azure Authentication / Spring Boot Example.com
  • 43. Easy to setup ¨ Standard Spring Boot / Azure auto configuration provided 1. Register your application with your Azure Active Directory Tenant 2. Configure application.properties spring.security.oauth2.client.registration.azure.client-id=xxxxxx-your-client-id-xxxxxx spring.security.oauth2.client.registration.azure.client-secret=xxxxxx-your-client-secret-xxxxxx azure.activedirectory.tenant-id=xxxxxx-your-tenant-id-xxxxxx azure.activedirectory.active-directory-groups=group1, group2
  • 44. Spring Boot configuration ¨ We enabled this setting in the application.properties: server.use-forward-headers=true
  • 45. curl -i http://localhost:8080 HTTP/1.1 302 Found Location: http://localhost:8080/oauth2/authorization/azure curl -i http://localhost:8080/oauth2/authorization/azure HTTP/1.1 302 Found Location: https://login.microsoftonline.com/common/oauth2/authorize?response_type=code https://graph.microsoft.com/user.read&state=& redirect_uri=http://localhost:8080/login/oauth2/code/azure
  • 46. Now let’s try curl -i -H"X-Forwarded-Host: attacker.com" http://localhost:8080/ HTTP/1.1 302 Found Location: http://attacker.com/oauth2/authorization/azure
  • 47. But wait how does the redirect_uri work? curl -i http://localhost:8080/oauth2/authorization/azure HTTP/1.1 302 Found Location: https://login.microsoftonline.com/common/oauth2/authorize?response_type=codehttps://graph. microsoft.com/user.read&state=&redirect_uri=http://localhost:8080/login/oauth2/code/azure spring.security.oauth2.client.registration.azure.redirect-uri-template={baseUrl}/login/oauth2/code/{registrationId}
  • 48. curl -i -H"X-Forwarded-Host: attacker.com" http://localhost:8080/oauth2/authorization/azure HTTP/1.1 302 Found Location: https://login.microsoftonline.com/common/oauth2/authorize?response_type=code https://graph.microsoft.com/user.read&state=& redirect_uri=http://attacker.com/login/oauth2/code/azure
  • 49. (Un)fortunately this does not work J https://tools.ietf.org/html/rfc6749#section-10.6
  • 51. Recap ¨ This is not a bug in Spring security ¨ Something which happened because we added: server.use-forward-headers=true
  • 52. Solution /** * <p> * Determines which hostnames should be allowed. The default is to allow any * hostname. * </p> * * @param allowedHostnames the predicate for testing hostnames * @since 5.2 */ public void setAllowedHostnames(Predicate<String> allowedHostnames) { if (allowedHostnames == null) { throw new IllegalArgumentException("allowedHostnames cannot be null"); } this.allowedHostnames = allowedHostnames; }
  • 53. @Bean public HttpFirewall firewall() { StrictHttpFirewall firewall = new StrictHttpFirewall(); firewall.setAllowedHttpMethods(Arrays.asList("GET", "POST")); firewall.setAllowedHostnames(s -> s.equals("localhost")); curl -i -H"X-Forwarded-Host: attacker.com" http://localhost:8080/ java.lang.RuntimeException: org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the domain attacker.com is untrusted. at io.undertow.servlet.spec.RequestDispatcherImpl.error(RequestDispatcherImpl.java:507) at io.undertow.servlet.spec.RequestDispatcherImpl.error(RequestDispatcherImpl.java:427)
  • 54. Solution ¨ As developers we are responsible to validate those headers ¨ Verify all headers you can receive from the outside. ¤ This includes: X-Forwarded-For, X-Forwarded-Host etc ¨ Do not rely on thinking reversed proxy will solve this! ¨ Check to see whether the framework has built in protection
  • 55. Where to start... 1. Make developers security aware n Code review n Practice / learn / adapt 2. Adopt a security guideline in your team 3. Test your own application 4. Start using tools to find to most obvious mistakes