SlideShare a Scribd company logo
1 of 69
Source Code Analysis with
SAST
Source Code Analytics
SCAs: How do they work?
Open source example
By methodology employed
• Style-checking
• Semantic Analysis
• Deep flow analysis
Methodology: Semantic Analysis
• Semantic Analysis
– looks for violations that represent a statically
detectable fault
– discovers basic structure and relation of each
function within the application
– Build abstract syntax tree to run simulations of
each function to calculate how the application will
execute after a build
– this additional information is then validated
against a set of rules
Methodology: Deep-flow Analysis
• Deep flow analysis
– extends semantic analysis to include control flow
graph generation and data flow analysis.
– can capture faults related to race conditions and
deadlocks, pointer misuses.
– employs meta compilation and abstract
interpretation to further improve analysis
capabilities
SCA Techniques
• Simplest tools
– search source code for text pattern matches
– calculate basic program metrics
(Cyclomatic complexity, Halstead complexity)
• Advanced tools
– act as advanced compiler for source code
– deeply analyze execution, data flow for faults
– include link information to determine higher-level
problems
Traditional checks
void temp( char *pszIn )
{
char szBuff[10];
strcpy(szBuff, pszIn);
. . .
}
Analyzing Source File
• It is possible to analyze source itself
• Source is in clear text
• Source is having methods, variables and calls
• One functionality or parameter may be
touching many files
• Code is on back burner or embedded
• Presentation is simple but code is complex at
the back
Simple presentation ASP.NET
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Cmdexec.aspx.cs" Inherits="Cmdexec" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body style="font-size: 12pt">
<form id="form1" runat="server">
<div>
Enter the filename to view your contract:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="Submit" /><br />
<br />
<asp:Label ID="Label1" runat="server" Height="355px" Text="Label" Width="544px"></asp:Label></div>
</form>
</body>
</html>
Code behind calls
using System;
…
…
using System.IO;
public partial class Cmdexec : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Visible = false;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
Label1.Visible = true;
Label1.Text = "";
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName = @"C:WINDOWSsystem32cmd.exe";
psi.Arguments = @"/c type c:contracts" + TextBox1.Text + @" > c:contractscontract.txt";
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process.Start(psi);
System.Threading.Thread.Sleep(3000);
TextReader textRead = new StreamReader("c:contractscontract.txt");
Label1.Text = textRead.ReadToEnd();
textRead.Close();
}
}
Running on Object Code
D:cmddeploy>dir /S
Volume in drive D has no label.
Volume Serial Number is 0859-A6D9
Directory of D:cmddeploy
12/09/2008 01:58 PM <DIR> .
12/09/2008 01:58 PM <DIR> ..
12/09/2008 01:58 PM <DIR> bin
12/09/2008 01:58 PM 86 Cmdexec.aspx
12/09/2008 01:58 PM 50 PrecompiledApp.config
2 File(s) 136 bytes
Directory of D:cmddeploybin
12/09/2008 01:58 PM <DIR> .
12/09/2008 01:58 PM <DIR> ..
12/09/2008 01:58 PM 7,680 App_Web_t_pyp492.dll
12/09/2008 01:58 PM 341 cmdexec.aspx.cdcab7d2.compiled
2 File(s) 8,021 bytes
Total Files Listed:
4 File(s) 8,157 bytes
5 Dir(s) 282,451,968 bytes free
Vulnerable and Exploit
Running on reverse engineering
D:cmddeploybin>ildasm /TEXT App_Web_t_pyp492.dll | grep System.Diagnostics.Pro
cess
.locals init (class [System]System.Diagnostics.ProcessStartInfo V_0,
IL_001c: newobj instance void [System]System.Diagnostics.ProcessStartIn
fo::.ctor()
IL_0028: callvirt instance void [System]System.Diagnostics.ProcessStartIn
fo::set_FileName(string)
IL_0048: callvirt instance void [System]System.Diagnostics.ProcessStartIn
fo::set_Arguments(string)
IL_004f: callvirt instance void [System]System.Diagnostics.ProcessStartIn
fo::set_WindowStyle(valuetype [System]System.Diagnostics.ProcessWindowStyle)
IL_0055: call class [System]System.Diagnostics.Process [System]System
.Diagnostics.Process::Start(class [System]System.Diagnostics.ProcessStartInfo)
Attack Surface
Attack Surface
• Source Code is having probable attack surface
• Attack surface is defined by entry points
• Entry points are exploited by attackers
• Attacker passes payload from these points
and try to exploit the system
• Attack surface determination and entry point
identification are very critical
Attack & Entry
GET/POST
GET /login.aspx?username=shah HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.9.0.1) Gecko/2008070208
Firefox/3.0.1
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
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
POST http://example.com/cgi-bin/search.cgi HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; rv:1.7.3) Gecko/20040913 Firefox/0.10
Accept: text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png,
*/*;q=0.5
Keep-Alive: 300
Referer: http://example.com/
Content-Type: application/x-www-form-urlencoded
Content-Length: 17
search=searchtext
XML-RPC
POST /trade-rpc/getquote.rem HTTP/1.0
TE: deflate,gzip;q=0.3
Connection: TE, close
Host: xmlrpc.example.com
Content-Type: text/xml
Content-Length: 161
<?xml version="1.0"?>
<methodCall>
<methodName>stocks.getquote</methodName>
<params>
<param><value><string>MSFT</string></value></param>
</params>
</methodCall>
SOAP
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<getQuotes xmlns="http://tempuri.org/">
<compid>MSFT</compid>
</getQuotes>
</soap:Body>
</soap:Envelope>
REST
<?xml version="1.0"?>
<p:Laptops xmlns:p="http://laptops.example.com"
xmlns:xl="http://www.w3.org/1999/xlink">
<Laptop id="0123" xl:href="http://www.parts-depot.com/laptops/0123"/>
< Laptop id="0348" xl:href="http://www.parts-depot.com laptops /0348"/>
< Laptop id="0321" xl:href="http://www.parts-depot.com/ laptops /0321"/>
…
…
</p:Laptops>
JSON
message = {
from : "john@example.com",
to : "jerry@example.com",
subject : "I am fine",
body : "Long message here",
showsubject : function(){document.write(this.subject)}
};
File calls
<form name="Form1" method="post"
action="ContractUpload.aspx" id="Form1"
enctype="multipart/form-data">
It is taking input as file as below,
<input name="uplTheFile" type="file"
id="uplTheFile" />
RSS - Feed
<rss version="2.0">
<channel>
<title>Example News</title>
<link>http://example.com/</link>
<description>News feed</description>
<language>en-us</language>
<pubDate>Tue, 10 Jun 2006 04:00:00 GMT</pubDate>
<lastBuildDate>Tue, 10 Jun 2006 09:41:01
GMT</lastBuildDate>
<docs>http://example.com/rss</docs>
<generator>Weblog Editor 2.0</generator>
<item>
<title>Today's title</title>
<link>http://example.com/10thjune.asp</link>
<description>News goes here</description>
<pubDate>Tue, 03 Jun 2006 09:39:21 GMT</pubDate>
<guid>http://example.com/news.html#item300</guid>
</item>
...
</item>
App Walk
Entry Points – Client Side
• HTTP response – All headers as well as HTML
content
• JavaScripts coming from server
• Ajax/RIA calls consuming different structures which
we have discussed like JSON, XML, JS-Object etc.
• Callbacks – Modern days applications are using
callback mechanism so data coming from browser
can be injected into DOM using script functions.
• Browser making API calls across domains
HTTP processing
Request
IIS
aspnet_isapi.dll
HttpApplication
HttpHandler
HttpModule
HttpModule
HttpModule
Response
Web Application Resource
Web Application Client
Request / Response
HTTP to Source
http://192.168.1.50/Searchresult.aspx?ReferenceId=microsoft
GET /Searchresult.aspx?ReferenceId=microsoft HTTP/1.1
Host: 192.168.1.50
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.9.0.1) Gecko/2008070208
Firefox/3.0.1
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
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cache-Control: max-age=0
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bindresult(Request.QueryString["ReferenceId"].ToString());
}
}
Interesting…
• Request.Cookie – To access cookie values
• Request.Form – Form parameters
• Request.File – File parameter
• Request.ServerVariables – Access to server
variables
In compiled code
IL_0007: callvirt instance class
[System]System.Collections.Specialized.Name
ValueCollection
[System.Web]System.Web.HttpRequest::get_
QueryString()
IL_000c: ldstr "id"
Scanning for Entry Points
Simple scan…
import sys
import os
import re
def scan4request(file):
infile = open(file,"r")
s = infile.readlines()
linenum = 0
print 'Request Object Entry:'
for line in s:
linenum += 1
p = re.compile(".*.[Rr]equest.*[^n]n")
m = p.match(line)
if m:
print linenum,":",m.group()
file = sys.argv[1]
scan4request(file)
Rules…
# Rules file for AppCodeScan
# This file is specific for ASP/ASP.NET applications (Just a sample
rules) - all regex patterns
#Scanning for Request Object Entry Points
.*.Request.*
#Scanning for ASP.NET app entry points
.*.<asp:FileUpload.*?>
.*.<asp:TextBox.*?>
.*.<asp:HiddenField.*?>
.*.<asp:Login.*?>
.*.<asp:PasswordRecovery.*?>
.*.<asp:ChangePassword.*?>
Java
• <% if ( request.getParameter("username") != null )
{%>
• HttpServletRequest
• doGet
• doPost
• Request
• Struts
– public class NameAction extends Action {
PHP/Coldfusion
• PHP
– $_GET[“var”]
– $_POST[“var”]
– $_REQUEST[“var”]
• Coldfusion
– #URL.name# - Getting from querystring “name”
– Similarly we can identify entry points for other aspects like
POST or such by following list of key words
– FORM/form
– SERVER/server
– CLIENT/client
– SESSION/session
Web 2.0
• Web Services and SOA entry points
Making POST
POST /ws/dvds4less.asmx HTTP/1.0
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.1433)
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://tempuri.org/getProductInfo"
Host: 192.168.1.50
Content-Length: 317
Expect: 100-continue
Connection: Keep-Alive
<?xml version="1.0" encoding="utf-8"?><soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><getProductInfo
xmlns="http://tempuri.org/"><id>1</id></getProductInfo></soap:Body></soap:Envelope>
Code for Web Services
<%@ WebService Language="c#" Class="dvds4less" %>
<%@ Assembly name="Microsoft.Data.SqlXml" %>
using Microsoft.Data.SqlXml;
using System.Xml;
using System;
using System.Web.Services;
using System.Data.SqlClient;
using System.IO;
public class dvds4less
{
[WebMethod]
public string Intro()
{
return "DVDs4LESS - Information APIs for web application usage and other business usage";
}
[WebMethod]
public string getProductInfo(string id)
{
…. Code for this function
}
JSON-RPC
<%@ WebHandler Class="JayrockWeb.DemoService" Language="C#" %>
namespace JayrockWeb
{
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Specialized;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using Jayrock.Json;
using Jayrock.JsonRpc;
using Jayrock.JsonRpc.Web;
[ JsonRpcHelp("This is a JSON-RPC service that demonstrates the basic features of the Jayrock library.") ]
public class DemoService : JsonRpcHandler, IRequiresSessionState
{
[JsonRpcMethod("getProduct", Idempotent = true)]
[ JsonRpcHelp("Returns Product Info") ]
public DataSet GetProductSet(string id)
{
…. Code goes here…
}
Java based
import org.apache.axis.AxisFault;
import org.apache.axis.MessageContext;
import org.apache.axis.transport.http.HTTPConstants;
public class echo {
public String echowebservices(String echo) {
return echo;
}
}
PHP
<?php
require_once('nusoap/nusoap.php');
// ------ Implemention of method
// ---- getLang(langTo)
------------------------------------------------------
function getLang($langTo) {
$trText = array(
"bonjour" => "french",
"ciao" => "italian",
"hallo" => "german",
"namaste" => "hindi"
);
$greeting = "";
$key = array_search($langTo, $trText);
$greeting = array_keys($trText[$langTo]);
return $greeting;
}
Entry Scans
Entry Points & Sinks
Entry Points…
• Entry points are source to the application
• Each source hits at some sink or end point in
the source code
• It traverses across the source code
• Entry point can be traced to its sink
• This tracing is very important aspect for code
analytics
Tainted variables
• If variable or entry point is injected with
payload then it can have significant impact
• Impact analysis needs to be done
• Impact is dependent on the hit points across
application
• Interesting for vulnerability scanning
perspective
Impact Analysis
End points / Sinks
• Language Calls – Application language say for example C# or
Java provides various classes and interfaces to access
resources from the system.
• These resources are outside application boundary.
Application may be passing value to SQL interface or system
level command.
• File system calls (Read/Write)
• Operating system calls
• Network/Socket calls
• SQL interfaces
• LDAP/Authentication interfaces
End points / Sinks
• Third party/Vendor interfaces – Application is using
some third party components and these are in binary
form.
• Applications to application – In recent time’s
applications are doing lot of intercommunication
across cross domains. In this case sink or end point
can be another application.
• Middleware call – Applications like banking or
trading uses middle ware extensively and several end
points are terminating into these middle ware calls.
End points / Sinks
• Response call back – In some cases entry point or
information coming through it is going back to the
client as response.
• Audit and Logs – In some cases application
information is going to logs or audit resources.
• Exception/Error message – This end point is special
and lot of application are taking value of entry point
and putting into exception or error message block.
End points / Sinks
• Business logic – Certain entry points are not
going out side application boundary but
staying in business logic space and get
processed inside application.
• Reflection level calls – Applications are
running in virtual machines and there are
certain reflection APIs which are responsible
for virtual machine processing.
Sink Scans
Impact & Tracing
Types - Impact
• Three important aspects of entry points and process
towards end point,
– Data point – entry points are bringing simple new data to
the application and based on that it is going to database or
file system.
– Logic point – It has information which get consumed in the
business logic and it makes business decisions
– Event points – Certain information coming from user can
trigger an event inside the application. These are event
points, like calling LDAP server or such.
State Analysis
• Expected/Desired state – This is expected state by developer
and application’s behavior is absolutely legitimate.
• Unexpected legitimate state – In this state application goes to
unexpected state but it is legitimate and no objection with it.
• Exception/Error state – In this application ends with error or
exception and state may end up doing information leakage.
• Vulnerable state – In this state application goes into
vulnerable position where successful exploitation is possible.
Vulnerable state is our major concern.
Impact = Entry Point + End Point + State
Impact
Impact
Tracing
Simple tracing…
import sys
import os
import re
def scan4trace(file,var):
infile = open(file,"r")
s = infile.readlines()
print 'Tracing variable:'+var
linenum=0
for line in s:
linenum += 1
p = re.compile(".*."+var+".*")
m = p.match(line)
if m:
print "[",linenum,"]",line
file = sys.argv[1]
var = sys.argv[2]
scan4trace(file,var)
Running…
D:sca-rb>trace.py d:cmdCmdexec.aspx.cs TextBox1
Tracing variable:TextBox1
[ 33 ] psi.Arguments = @"/c type c:contracts" + TextBox1.Text + @" >
c:contractscontract.txt";
D:sca-rb>trace.py d:cmdCmdexec.aspx.cs psi
Tracing variable:psi
[ 31 ] System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.
ProcessStartInfo();
[ 32 ] psi.FileName = @"C:WINDOWSsystem32cmd.exe";
[ 33 ] psi.Arguments = @"/c type c:contracts" + TextBox1.Text + @" >
c:contractscontract.txt";
[ 34 ] psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
[ 35 ] System.Diagnostics.Process.Start(psi);
Security Domains/Controls
• Authentication
• Authorization
• Error Handling
• Input Validations
• Data Validation
• Crypto and Secret Handling
• Business Logic Handling
• Session and Identity Handling
• Client Side Controls
• Auditing and Logging
Authentication
• Authentication disclosing sensitive information
• Not having auditing on the authentication
• No user lockdown policy in place
• Authentication bypass (SQL / LDAP interface)
• Password strength is poor
• No deployment of CAPTCHA or similar identification product
• Credential are not securely transmitted
• Credential are stored on client side which can be retrieved
• Authentication token or cookies are not well crafted
• Single Sign On (SSO) can be abused
• Deliberated backdoors are created
• Hidden fields and information exposure
Authorization
• Session tokens are insecure
• Weak authorization mechanism
• Client side tampering and manipulation possible
• Possible data and SQL injections
• Access to system level bypass
• Single place authorization bypass
• URL forcing and manipulation
• Guessable resources and access
• Role-based bypass exploitation and weakness
Error Handling
• Information leakage
• Logic bypass
• Internal logic and routine disclosure
• Stack trace enumeration
Input Validations
• Various injection vectors (SQL, LDAP, XPATH etc.)
• Cross Site Scripting (XSS)
• Cross Site Request Forgery (CSRF)
• Buffer overflows
• Denial of Services (DoS)
• Integer and logical boundary overrun
• Canonicalization issues
• Validation bypass (Client side)
• Serialization attacks
• Information leakage
Data Validations
• Proxy injections from third party stream
• XSS injection with RSS feeds
• Client side logic bypass
• Upload/download stream injections
• Remote command/code injection and
execution
• Callback manipulation in JavaScript
Crypto & Secrets
• Poor key generation
• Database fields are not well encrypted (password,
social security number etc.)
• Poor encryption (customized)
• Checksum spoofing
• Some secrets in source code itself
• Configuration file containing secrets
• Secret getting revealed in error message or some
other means
Business Logic
• Data type bypass
• ACLs manipulation
• Read/Write access
• Privilege escalation on application layer
• API abuse
• Cross Domain Call and API manipulation
• Client Side Logic reverse engineering
Session and Identity
• Session hijacking by eavesdropping
• Man in the middle attack
• Poor session identifier generation
• Browser hacks like XSS to gain cookies
• Predictable session identifier
• Session bypass and access
• Cookie scope and time abuse
• Abusing URL rewriting
• Local session storing access
Client Side Controls
• Client side validation bypass
• Reverse engineering of client side components
• Decompilation and knowledge gathering
• Cross Site Injections
• Abusing streams like JSON or RSS
• Local memory access and manipulation
• Desktop based offline module exploitation
• Browser exploits and hacking
• Information and identity theft
• Cross Site Request Forgery
• Exploiting callbacks and JavaScripts
Auditing and Logging
• Hacker’s attacks go without notice
• Successful hacks in the application
• No tracing of events
• Application layer bruteforcing
• Error message abuse
Conclusion

More Related Content

What's hot

Continuous Application Security at Scale with IAST and RASP -- Transforming D...
Continuous Application Security at Scale with IAST and RASP -- Transforming D...Continuous Application Security at Scale with IAST and RASP -- Transforming D...
Continuous Application Security at Scale with IAST and RASP -- Transforming D...
Jeff Williams
 

What's hot (20)

DevSecOps 101
DevSecOps 101DevSecOps 101
DevSecOps 101
 
Threat Modeling Everything
Threat Modeling EverythingThreat Modeling Everything
Threat Modeling Everything
 
DevSecOps in Baby Steps
DevSecOps in Baby StepsDevSecOps in Baby Steps
DevSecOps in Baby Steps
 
Secure coding practices
Secure coding practicesSecure coding practices
Secure coding practices
 
Application Security
Application SecurityApplication Security
Application Security
 
Secure Your Code Implement DevSecOps in Azure
Secure Your Code Implement DevSecOps in AzureSecure Your Code Implement DevSecOps in Azure
Secure Your Code Implement DevSecOps in Azure
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
 
security misconfigurations
security misconfigurationssecurity misconfigurations
security misconfigurations
 
OWASP Secure Coding
OWASP Secure CodingOWASP Secure Coding
OWASP Secure Coding
 
Threat Modelling
Threat ModellingThreat Modelling
Threat Modelling
 
Implementing DevSecOps
Implementing DevSecOpsImplementing DevSecOps
Implementing DevSecOps
 
DevSecOps: What Why and How : Blackhat 2019
DevSecOps: What Why and How : Blackhat 2019DevSecOps: What Why and How : Blackhat 2019
DevSecOps: What Why and How : Blackhat 2019
 
Continuous Application Security at Scale with IAST and RASP -- Transforming D...
Continuous Application Security at Scale with IAST and RASP -- Transforming D...Continuous Application Security at Scale with IAST and RASP -- Transforming D...
Continuous Application Security at Scale with IAST and RASP -- Transforming D...
 
OWASP Top Ten
OWASP Top TenOWASP Top Ten
OWASP Top Ten
 
Snyk Intro - Developer Security Essentials 2022
Snyk Intro - Developer Security Essentials 2022Snyk Intro - Developer Security Essentials 2022
Snyk Intro - Developer Security Essentials 2022
 
Coding Security: Code Mania 101
Coding Security: Code Mania 101Coding Security: Code Mania 101
Coding Security: Code Mania 101
 
OWASP Top 10 2021 What's New
OWASP Top 10 2021 What's NewOWASP Top 10 2021 What's New
OWASP Top 10 2021 What's New
 
Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020Secure coding presentation Oct 3 2020
Secure coding presentation Oct 3 2020
 
Threat Modeling Using STRIDE
Threat Modeling Using STRIDEThreat Modeling Using STRIDE
Threat Modeling Using STRIDE
 
Shift Left Security - The What, Why and How
Shift Left Security - The What, Why and HowShift Left Security - The What, Why and How
Shift Left Security - The What, Why and How
 

Viewers also liked

RIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHPRIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHP
Sorina Chirilă
 
Simplified Security Code Review Process
Simplified Security Code Review ProcessSimplified Security Code Review Process
Simplified Security Code Review Process
Sherif Koussa
 

Viewers also liked (20)

Static Code Analysis
Static Code AnalysisStatic Code Analysis
Static Code Analysis
 
Современные подходы к SAST
Современные подходы к SASTСовременные подходы к SAST
Современные подходы к SAST
 
Best Practices of Static Code Analysis in the SDLC
Best Practices of Static Code Analysis in the SDLCBest Practices of Static Code Analysis in the SDLC
Best Practices of Static Code Analysis in the SDLC
 
Static Analysis and Code Optimizations in Glasgow Haskell Compiler
Static Analysis and Code Optimizations in Glasgow Haskell CompilerStatic Analysis and Code Optimizations in Glasgow Haskell Compiler
Static Analysis and Code Optimizations in Glasgow Haskell Compiler
 
Poster Analysis Source Code
Poster Analysis Source CodePoster Analysis Source Code
Poster Analysis Source Code
 
Безопасная разработка для руководителей
Безопасная разработка для руководителейБезопасная разработка для руководителей
Безопасная разработка для руководителей
 
Подходы к сигнатурному статическому анализу
Подходы к сигнатурному статическому анализуПодходы к сигнатурному статическому анализу
Подходы к сигнатурному статическому анализу
 
Построение процесса безопасной разработки
Построение процесса безопасной разработкиПостроение процесса безопасной разработки
Построение процесса безопасной разработки
 
RIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHPRIPS - static code analyzer for vulnerabilities in PHP
RIPS - static code analyzer for vulnerabilities in PHP
 
Hp fortify source code analyzer(sca)
Hp fortify source code analyzer(sca)Hp fortify source code analyzer(sca)
Hp fortify source code analyzer(sca)
 
A2 - broken authentication and session management(OWASP thailand chapter Apri...
A2 - broken authentication and session management(OWASP thailand chapter Apri...A2 - broken authentication and session management(OWASP thailand chapter Apri...
A2 - broken authentication and session management(OWASP thailand chapter Apri...
 
Static Code Analysis
Static Code AnalysisStatic Code Analysis
Static Code Analysis
 
A8 cross site request forgery (csrf) it 6873 presentation
A8 cross site request forgery (csrf)   it 6873 presentationA8 cross site request forgery (csrf)   it 6873 presentation
A8 cross site request forgery (csrf) it 6873 presentation
 
Simplified Security Code Review Process
Simplified Security Code Review ProcessSimplified Security Code Review Process
Simplified Security Code Review Process
 
Java Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQubeJava Source Code Analysis using SonarQube
Java Source Code Analysis using SonarQube
 
Static Analysis For Security and DevOps Happiness w/ Justin Collins
Static Analysis For Security and DevOps Happiness w/ Justin CollinsStatic Analysis For Security and DevOps Happiness w/ Justin Collins
Static Analysis For Security and DevOps Happiness w/ Justin Collins
 
Practical steps to mitigate DDoS attacks
Practical steps to mitigate DDoS attacksPractical steps to mitigate DDoS attacks
Practical steps to mitigate DDoS attacks
 
Ch13 security engineering
Ch13 security engineeringCh13 security engineering
Ch13 security engineering
 
OWASP A1 - Injection | The art of manipulation
OWASP A1 - Injection | The art of manipulationOWASP A1 - Injection | The art of manipulation
OWASP A1 - Injection | The art of manipulation
 
OWASP A7 and A8
OWASP A7 and A8OWASP A7 and A8
OWASP A7 and A8
 

Similar to Source Code Analysis with SAST

User controls
User controlsUser controls
User controls
aspnet123
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
hamzadamani7
 
Yogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’sYogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’s
Yogesh Kushwah
 

Similar to Source Code Analysis with SAST (20)

Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0Continuous Application with Structured Streaming 2.0
Continuous Application with Structured Streaming 2.0
 
TO Hack an ASP .NET website?
TO Hack an ASP .NET website?  TO Hack an ASP .NET website?
TO Hack an ASP .NET website?
 
Hack ASP.NET website
Hack ASP.NET websiteHack ASP.NET website
Hack ASP.NET website
 
A Deep Dive into Structured Streaming in Apache Spark
A Deep Dive into Structured Streaming in Apache Spark A Deep Dive into Structured Streaming in Apache Spark
A Deep Dive into Structured Streaming in Apache Spark
 
A Deep Dive into Structured Streaming: Apache Spark Meetup at Bloomberg 2016
A Deep Dive into Structured Streaming:  Apache Spark Meetup at Bloomberg 2016 A Deep Dive into Structured Streaming:  Apache Spark Meetup at Bloomberg 2016
A Deep Dive into Structured Streaming: Apache Spark Meetup at Bloomberg 2016
 
A mobile web app for Android in 75 minutes
A mobile web app for Android in 75 minutesA mobile web app for Android in 75 minutes
A mobile web app for Android in 75 minutes
 
User controls
User controlsUser controls
User controls
 
540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf540slidesofnodejsbackendhopeitworkforu.pdf
540slidesofnodejsbackendhopeitworkforu.pdf
 
Yogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’sYogesh kumar kushwah represent’s
Yogesh kumar kushwah represent’s
 
Dataservices: Processing (Big) Data the Microservice Way
Dataservices: Processing (Big) Data the Microservice WayDataservices: Processing (Big) Data the Microservice Way
Dataservices: Processing (Big) Data the Microservice Way
 
Android L01 - Warm Up
Android L01 - Warm UpAndroid L01 - Warm Up
Android L01 - Warm Up
 
Java script
Java scriptJava script
Java script
 
Asp.net tips
Asp.net tipsAsp.net tips
Asp.net tips
 
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
Building AOL's High Performance, Enterprise Wide Mail Application With Silver...
 
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
(WEB301) Operational Web Log Analysis | AWS re:Invent 2014
 
Workshop: Building a Streaming Data Platform on AWS
Workshop: Building a Streaming Data Platform on AWSWorkshop: Building a Streaming Data Platform on AWS
Workshop: Building a Streaming Data Platform on AWS
 
Migration from ASP to ASP.NET
Migration from ASP to ASP.NETMigration from ASP to ASP.NET
Migration from ASP to ASP.NET
 
2310 b 05
2310 b 052310 b 05
2310 b 05
 
Streams
StreamsStreams
Streams
 
Intrusion Discovery on Windows
Intrusion Discovery on WindowsIntrusion Discovery on Windows
Intrusion Discovery on Windows
 

More from Blueinfy Solutions

More from Blueinfy Solutions (20)

Mobile Application Scan and Testing
Mobile Application Scan and TestingMobile Application Scan and Testing
Mobile Application Scan and Testing
 
Mobile security chess board - attacks & defense
Mobile security chess board - attacks & defenseMobile security chess board - attacks & defense
Mobile security chess board - attacks & defense
 
Mobile code mining for discovery and exploits nullcongoa2013
Mobile code mining for discovery and exploits nullcongoa2013Mobile code mining for discovery and exploits nullcongoa2013
Mobile code mining for discovery and exploits nullcongoa2013
 
iOS Application Security Testing
iOS Application Security TestingiOS Application Security Testing
iOS Application Security Testing
 
Html5 on mobile
Html5 on mobileHtml5 on mobile
Html5 on mobile
 
Android secure coding
Android secure codingAndroid secure coding
Android secure coding
 
Android attacks
Android attacksAndroid attacks
Android attacks
 
Automation In Android & iOS Application Review
Automation In Android & iOS 	Application Review�Automation In Android & iOS 	Application Review�
Automation In Android & iOS Application Review
 
Web Services Hacking and Security
Web Services Hacking and SecurityWeb Services Hacking and Security
Web Services Hacking and Security
 
HTML5 hacking
HTML5 hackingHTML5 hacking
HTML5 hacking
 
CSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open RedirectCSRF, ClickJacking & Open Redirect
CSRF, ClickJacking & Open Redirect
 
XSS - Attacks & Defense
XSS - Attacks & DefenseXSS - Attacks & Defense
XSS - Attacks & Defense
 
Defending against Injections
Defending against InjectionsDefending against Injections
Defending against Injections
 
XPATH, LDAP and Path Traversal Injection
XPATH, LDAP and Path Traversal InjectionXPATH, LDAP and Path Traversal Injection
XPATH, LDAP and Path Traversal Injection
 
Blind SQL Injection
Blind SQL InjectionBlind SQL Injection
Blind SQL Injection
 
Application fuzzing
Application fuzzingApplication fuzzing
Application fuzzing
 
SQL injection basics
SQL injection basicsSQL injection basics
SQL injection basics
 
Applciation footprinting, discovery and enumeration
Applciation footprinting, discovery and enumerationApplciation footprinting, discovery and enumeration
Applciation footprinting, discovery and enumeration
 
Assessment methodology and approach
Assessment methodology and approachAssessment methodology and approach
Assessment methodology and approach
 
HTTP protocol and Streams Security
HTTP protocol and Streams SecurityHTTP protocol and Streams Security
HTTP protocol and Streams Security
 

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

Source Code Analysis with SAST

  • 3. SCAs: How do they work? Open source example
  • 4. By methodology employed • Style-checking • Semantic Analysis • Deep flow analysis
  • 5. Methodology: Semantic Analysis • Semantic Analysis – looks for violations that represent a statically detectable fault – discovers basic structure and relation of each function within the application – Build abstract syntax tree to run simulations of each function to calculate how the application will execute after a build – this additional information is then validated against a set of rules
  • 6. Methodology: Deep-flow Analysis • Deep flow analysis – extends semantic analysis to include control flow graph generation and data flow analysis. – can capture faults related to race conditions and deadlocks, pointer misuses. – employs meta compilation and abstract interpretation to further improve analysis capabilities
  • 7. SCA Techniques • Simplest tools – search source code for text pattern matches – calculate basic program metrics (Cyclomatic complexity, Halstead complexity) • Advanced tools – act as advanced compiler for source code – deeply analyze execution, data flow for faults – include link information to determine higher-level problems
  • 8. Traditional checks void temp( char *pszIn ) { char szBuff[10]; strcpy(szBuff, pszIn); . . . }
  • 9. Analyzing Source File • It is possible to analyze source itself • Source is in clear text • Source is having methods, variables and calls • One functionality or parameter may be touching many files • Code is on back burner or embedded • Presentation is simple but code is complex at the back
  • 10. Simple presentation ASP.NET <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Cmdexec.aspx.cs" Inherits="Cmdexec" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body style="font-size: 12pt"> <form id="form1" runat="server"> <div> Enter the filename to view your contract: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click1" Text="Submit" /><br /> <br /> <asp:Label ID="Label1" runat="server" Height="355px" Text="Label" Width="544px"></asp:Label></div> </form> </body> </html>
  • 11. Code behind calls using System; … … using System.IO; public partial class Cmdexec : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Label1.Visible = false; } protected void Calendar1_SelectionChanged(object sender, EventArgs e) { } protected void Button1_Click1(object sender, EventArgs e) { Label1.Visible = true; Label1.Text = ""; System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(); psi.FileName = @"C:WINDOWSsystem32cmd.exe"; psi.Arguments = @"/c type c:contracts" + TextBox1.Text + @" > c:contractscontract.txt"; psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; System.Diagnostics.Process.Start(psi); System.Threading.Thread.Sleep(3000); TextReader textRead = new StreamReader("c:contractscontract.txt"); Label1.Text = textRead.ReadToEnd(); textRead.Close(); } }
  • 12. Running on Object Code D:cmddeploy>dir /S Volume in drive D has no label. Volume Serial Number is 0859-A6D9 Directory of D:cmddeploy 12/09/2008 01:58 PM <DIR> . 12/09/2008 01:58 PM <DIR> .. 12/09/2008 01:58 PM <DIR> bin 12/09/2008 01:58 PM 86 Cmdexec.aspx 12/09/2008 01:58 PM 50 PrecompiledApp.config 2 File(s) 136 bytes Directory of D:cmddeploybin 12/09/2008 01:58 PM <DIR> . 12/09/2008 01:58 PM <DIR> .. 12/09/2008 01:58 PM 7,680 App_Web_t_pyp492.dll 12/09/2008 01:58 PM 341 cmdexec.aspx.cdcab7d2.compiled 2 File(s) 8,021 bytes Total Files Listed: 4 File(s) 8,157 bytes 5 Dir(s) 282,451,968 bytes free
  • 14. Running on reverse engineering D:cmddeploybin>ildasm /TEXT App_Web_t_pyp492.dll | grep System.Diagnostics.Pro cess .locals init (class [System]System.Diagnostics.ProcessStartInfo V_0, IL_001c: newobj instance void [System]System.Diagnostics.ProcessStartIn fo::.ctor() IL_0028: callvirt instance void [System]System.Diagnostics.ProcessStartIn fo::set_FileName(string) IL_0048: callvirt instance void [System]System.Diagnostics.ProcessStartIn fo::set_Arguments(string) IL_004f: callvirt instance void [System]System.Diagnostics.ProcessStartIn fo::set_WindowStyle(valuetype [System]System.Diagnostics.ProcessWindowStyle) IL_0055: call class [System]System.Diagnostics.Process [System]System .Diagnostics.Process::Start(class [System]System.Diagnostics.ProcessStartInfo)
  • 16. Attack Surface • Source Code is having probable attack surface • Attack surface is defined by entry points • Entry points are exploited by attackers • Attacker passes payload from these points and try to exploit the system • Attack surface determination and entry point identification are very critical
  • 18. GET/POST GET /login.aspx?username=shah HTTP/1.1 Host: example.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1 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 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive POST http://example.com/cgi-bin/search.cgi HTTP/1.1 Host: example.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.0; rv:1.7.3) Gecko/20040913 Firefox/0.10 Accept: text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, text/plain;q=0.8, image/png, */*;q=0.5 Keep-Alive: 300 Referer: http://example.com/ Content-Type: application/x-www-form-urlencoded Content-Length: 17 search=searchtext
  • 19. XML-RPC POST /trade-rpc/getquote.rem HTTP/1.0 TE: deflate,gzip;q=0.3 Connection: TE, close Host: xmlrpc.example.com Content-Type: text/xml Content-Length: 161 <?xml version="1.0"?> <methodCall> <methodName>stocks.getquote</methodName> <params> <param><value><string>MSFT</string></value></param> </params> </methodCall>
  • 20. SOAP <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <getQuotes xmlns="http://tempuri.org/"> <compid>MSFT</compid> </getQuotes> </soap:Body> </soap:Envelope>
  • 21. REST <?xml version="1.0"?> <p:Laptops xmlns:p="http://laptops.example.com" xmlns:xl="http://www.w3.org/1999/xlink"> <Laptop id="0123" xl:href="http://www.parts-depot.com/laptops/0123"/> < Laptop id="0348" xl:href="http://www.parts-depot.com laptops /0348"/> < Laptop id="0321" xl:href="http://www.parts-depot.com/ laptops /0321"/> … … </p:Laptops>
  • 22. JSON message = { from : "john@example.com", to : "jerry@example.com", subject : "I am fine", body : "Long message here", showsubject : function(){document.write(this.subject)} };
  • 23. File calls <form name="Form1" method="post" action="ContractUpload.aspx" id="Form1" enctype="multipart/form-data"> It is taking input as file as below, <input name="uplTheFile" type="file" id="uplTheFile" />
  • 24. RSS - Feed <rss version="2.0"> <channel> <title>Example News</title> <link>http://example.com/</link> <description>News feed</description> <language>en-us</language> <pubDate>Tue, 10 Jun 2006 04:00:00 GMT</pubDate> <lastBuildDate>Tue, 10 Jun 2006 09:41:01 GMT</lastBuildDate> <docs>http://example.com/rss</docs> <generator>Weblog Editor 2.0</generator> <item> <title>Today's title</title> <link>http://example.com/10thjune.asp</link> <description>News goes here</description> <pubDate>Tue, 03 Jun 2006 09:39:21 GMT</pubDate> <guid>http://example.com/news.html#item300</guid> </item> ... </item> App Walk
  • 25. Entry Points – Client Side • HTTP response – All headers as well as HTML content • JavaScripts coming from server • Ajax/RIA calls consuming different structures which we have discussed like JSON, XML, JS-Object etc. • Callbacks – Modern days applications are using callback mechanism so data coming from browser can be injected into DOM using script functions. • Browser making API calls across domains
  • 28. HTTP to Source http://192.168.1.50/Searchresult.aspx?ReferenceId=microsoft GET /Searchresult.aspx?ReferenceId=microsoft HTTP/1.1 Host: 192.168.1.50 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1 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 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Cache-Control: max-age=0 protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { bindresult(Request.QueryString["ReferenceId"].ToString()); } }
  • 29. Interesting… • Request.Cookie – To access cookie values • Request.Form – Form parameters • Request.File – File parameter • Request.ServerVariables – Access to server variables
  • 30. In compiled code IL_0007: callvirt instance class [System]System.Collections.Specialized.Name ValueCollection [System.Web]System.Web.HttpRequest::get_ QueryString() IL_000c: ldstr "id"
  • 32. Simple scan… import sys import os import re def scan4request(file): infile = open(file,"r") s = infile.readlines() linenum = 0 print 'Request Object Entry:' for line in s: linenum += 1 p = re.compile(".*.[Rr]equest.*[^n]n") m = p.match(line) if m: print linenum,":",m.group() file = sys.argv[1] scan4request(file)
  • 33. Rules… # Rules file for AppCodeScan # This file is specific for ASP/ASP.NET applications (Just a sample rules) - all regex patterns #Scanning for Request Object Entry Points .*.Request.* #Scanning for ASP.NET app entry points .*.<asp:FileUpload.*?> .*.<asp:TextBox.*?> .*.<asp:HiddenField.*?> .*.<asp:Login.*?> .*.<asp:PasswordRecovery.*?> .*.<asp:ChangePassword.*?>
  • 34. Java • <% if ( request.getParameter("username") != null ) {%> • HttpServletRequest • doGet • doPost • Request • Struts – public class NameAction extends Action {
  • 35. PHP/Coldfusion • PHP – $_GET[“var”] – $_POST[“var”] – $_REQUEST[“var”] • Coldfusion – #URL.name# - Getting from querystring “name” – Similarly we can identify entry points for other aspects like POST or such by following list of key words – FORM/form – SERVER/server – CLIENT/client – SESSION/session
  • 36. Web 2.0 • Web Services and SOA entry points
  • 37. Making POST POST /ws/dvds4less.asmx HTTP/1.0 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.1433) Content-Type: text/xml; charset=utf-8 SOAPAction: "http://tempuri.org/getProductInfo" Host: 192.168.1.50 Content-Length: 317 Expect: 100-continue Connection: Keep-Alive <?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><getProductInfo xmlns="http://tempuri.org/"><id>1</id></getProductInfo></soap:Body></soap:Envelope>
  • 38. Code for Web Services <%@ WebService Language="c#" Class="dvds4less" %> <%@ Assembly name="Microsoft.Data.SqlXml" %> using Microsoft.Data.SqlXml; using System.Xml; using System; using System.Web.Services; using System.Data.SqlClient; using System.IO; public class dvds4less { [WebMethod] public string Intro() { return "DVDs4LESS - Information APIs for web application usage and other business usage"; } [WebMethod] public string getProductInfo(string id) { …. Code for this function }
  • 39. JSON-RPC <%@ WebHandler Class="JayrockWeb.DemoService" Language="C#" %> namespace JayrockWeb { using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Collections; using System.Collections.Specialized; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Drawing; using Jayrock.Json; using Jayrock.JsonRpc; using Jayrock.JsonRpc.Web; [ JsonRpcHelp("This is a JSON-RPC service that demonstrates the basic features of the Jayrock library.") ] public class DemoService : JsonRpcHandler, IRequiresSessionState { [JsonRpcMethod("getProduct", Idempotent = true)] [ JsonRpcHelp("Returns Product Info") ] public DataSet GetProductSet(string id) { …. Code goes here… }
  • 40. Java based import org.apache.axis.AxisFault; import org.apache.axis.MessageContext; import org.apache.axis.transport.http.HTTPConstants; public class echo { public String echowebservices(String echo) { return echo; } }
  • 41. PHP <?php require_once('nusoap/nusoap.php'); // ------ Implemention of method // ---- getLang(langTo) ------------------------------------------------------ function getLang($langTo) { $trText = array( "bonjour" => "french", "ciao" => "italian", "hallo" => "german", "namaste" => "hindi" ); $greeting = ""; $key = array_search($langTo, $trText); $greeting = array_keys($trText[$langTo]); return $greeting; } Entry Scans
  • 42. Entry Points & Sinks
  • 43. Entry Points… • Entry points are source to the application • Each source hits at some sink or end point in the source code • It traverses across the source code • Entry point can be traced to its sink • This tracing is very important aspect for code analytics
  • 44. Tainted variables • If variable or entry point is injected with payload then it can have significant impact • Impact analysis needs to be done • Impact is dependent on the hit points across application • Interesting for vulnerability scanning perspective
  • 46. End points / Sinks • Language Calls – Application language say for example C# or Java provides various classes and interfaces to access resources from the system. • These resources are outside application boundary. Application may be passing value to SQL interface or system level command. • File system calls (Read/Write) • Operating system calls • Network/Socket calls • SQL interfaces • LDAP/Authentication interfaces
  • 47. End points / Sinks • Third party/Vendor interfaces – Application is using some third party components and these are in binary form. • Applications to application – In recent time’s applications are doing lot of intercommunication across cross domains. In this case sink or end point can be another application. • Middleware call – Applications like banking or trading uses middle ware extensively and several end points are terminating into these middle ware calls.
  • 48. End points / Sinks • Response call back – In some cases entry point or information coming through it is going back to the client as response. • Audit and Logs – In some cases application information is going to logs or audit resources. • Exception/Error message – This end point is special and lot of application are taking value of entry point and putting into exception or error message block.
  • 49. End points / Sinks • Business logic – Certain entry points are not going out side application boundary but staying in business logic space and get processed inside application. • Reflection level calls – Applications are running in virtual machines and there are certain reflection APIs which are responsible for virtual machine processing. Sink Scans
  • 51. Types - Impact • Three important aspects of entry points and process towards end point, – Data point – entry points are bringing simple new data to the application and based on that it is going to database or file system. – Logic point – It has information which get consumed in the business logic and it makes business decisions – Event points – Certain information coming from user can trigger an event inside the application. These are event points, like calling LDAP server or such.
  • 52. State Analysis • Expected/Desired state – This is expected state by developer and application’s behavior is absolutely legitimate. • Unexpected legitimate state – In this state application goes to unexpected state but it is legitimate and no objection with it. • Exception/Error state – In this application ends with error or exception and state may end up doing information leakage. • Vulnerable state – In this state application goes into vulnerable position where successful exploitation is possible. Vulnerable state is our major concern. Impact = Entry Point + End Point + State
  • 56. Simple tracing… import sys import os import re def scan4trace(file,var): infile = open(file,"r") s = infile.readlines() print 'Tracing variable:'+var linenum=0 for line in s: linenum += 1 p = re.compile(".*."+var+".*") m = p.match(line) if m: print "[",linenum,"]",line file = sys.argv[1] var = sys.argv[2] scan4trace(file,var)
  • 57. Running… D:sca-rb>trace.py d:cmdCmdexec.aspx.cs TextBox1 Tracing variable:TextBox1 [ 33 ] psi.Arguments = @"/c type c:contracts" + TextBox1.Text + @" > c:contractscontract.txt"; D:sca-rb>trace.py d:cmdCmdexec.aspx.cs psi Tracing variable:psi [ 31 ] System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics. ProcessStartInfo(); [ 32 ] psi.FileName = @"C:WINDOWSsystem32cmd.exe"; [ 33 ] psi.Arguments = @"/c type c:contracts" + TextBox1.Text + @" > c:contractscontract.txt"; [ 34 ] psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; [ 35 ] System.Diagnostics.Process.Start(psi);
  • 58. Security Domains/Controls • Authentication • Authorization • Error Handling • Input Validations • Data Validation • Crypto and Secret Handling • Business Logic Handling • Session and Identity Handling • Client Side Controls • Auditing and Logging
  • 59. Authentication • Authentication disclosing sensitive information • Not having auditing on the authentication • No user lockdown policy in place • Authentication bypass (SQL / LDAP interface) • Password strength is poor • No deployment of CAPTCHA or similar identification product • Credential are not securely transmitted • Credential are stored on client side which can be retrieved • Authentication token or cookies are not well crafted • Single Sign On (SSO) can be abused • Deliberated backdoors are created • Hidden fields and information exposure
  • 60. Authorization • Session tokens are insecure • Weak authorization mechanism • Client side tampering and manipulation possible • Possible data and SQL injections • Access to system level bypass • Single place authorization bypass • URL forcing and manipulation • Guessable resources and access • Role-based bypass exploitation and weakness
  • 61. Error Handling • Information leakage • Logic bypass • Internal logic and routine disclosure • Stack trace enumeration
  • 62. Input Validations • Various injection vectors (SQL, LDAP, XPATH etc.) • Cross Site Scripting (XSS) • Cross Site Request Forgery (CSRF) • Buffer overflows • Denial of Services (DoS) • Integer and logical boundary overrun • Canonicalization issues • Validation bypass (Client side) • Serialization attacks • Information leakage
  • 63. Data Validations • Proxy injections from third party stream • XSS injection with RSS feeds • Client side logic bypass • Upload/download stream injections • Remote command/code injection and execution • Callback manipulation in JavaScript
  • 64. Crypto & Secrets • Poor key generation • Database fields are not well encrypted (password, social security number etc.) • Poor encryption (customized) • Checksum spoofing • Some secrets in source code itself • Configuration file containing secrets • Secret getting revealed in error message or some other means
  • 65. Business Logic • Data type bypass • ACLs manipulation • Read/Write access • Privilege escalation on application layer • API abuse • Cross Domain Call and API manipulation • Client Side Logic reverse engineering
  • 66. Session and Identity • Session hijacking by eavesdropping • Man in the middle attack • Poor session identifier generation • Browser hacks like XSS to gain cookies • Predictable session identifier • Session bypass and access • Cookie scope and time abuse • Abusing URL rewriting • Local session storing access
  • 67. Client Side Controls • Client side validation bypass • Reverse engineering of client side components • Decompilation and knowledge gathering • Cross Site Injections • Abusing streams like JSON or RSS • Local memory access and manipulation • Desktop based offline module exploitation • Browser exploits and hacking • Information and identity theft • Cross Site Request Forgery • Exploiting callbacks and JavaScripts
  • 68. Auditing and Logging • Hacker’s attacks go without notice • Successful hacks in the application • No tracing of events • Application layer bruteforcing • Error message abuse

Editor's Notes

  1. To determine the likelihood of problems arising from a given code segment Simplest tools: search source code for text pattern matches calculate basic program metrics (Cyclomatic complexity, Halstead complexity) Advanced tools: - act as advanced compiler for the source code - deeply analyze execution and data flow for faults - include link information to determine higher-level problems