<<

dit-upm

software security

José A. Mañas < http://www.dit.upm.es/~pepe/> Information Technology Department Universidad Politécnica de Madrid

24 October 2018 dit the problem ⚫ in a world where everything contains software, if the software is not reliable, the system is not reliable ⚫ how do you build reliable software? ◼ shall predict errors and attacks from the environment ◼ shall fail safely

 shall not inform the attacker

 shall not fall into a state of unsafe behavior ⚫ security by design, security should not be an afterthought ◼ we should not for an attack to protecting us ◼ cost: design, coding, testing, distribution ◼ bad reputation

software security 2 dit why is software unreliable? 1. programmers do not know 2. is boring 3. functionality 4. reduced performance 5. benefit (ROI) is hard to estimate

⚫ adding secure components does not a secure system

⚫ insecurity is not necessarily a bug; it is an unacceptable behavior

cybersecurity 3 dit security ⚫ preventive ◼ does not occur, occurs less often ⚫ monitor and detect ◼ if something goes wrong, you need an alert ⚫ reliable logging ◼ to prosecute ◼ to learn ⚫ recovery - resilience

software security 4 dit vulnerabilidades software ⚫ Memory safety violations ◼ Buffer overflows and over-reads ◼ Dangling pointers ⚫ Input validation errors ◼ string attacks ◼ SQL injection ◼ Code injection ◼ E- injection ◼ Directory traversal ◼ Cross-site scripting in web applications ◼ HTTP header injection ◼ HTTP response splitting

https://en.wikipedia.org/wiki/Vulnerability_(computing)

software security 5 dit vulnerabilidades del software ⚫ Race conditions ◼ Time-of-check-to--of-use bugs ◼ Symlink races ⚫ Privilege-confusion ◼ Cross-site request forgery in web applications ◼ Clickjacking ◼ FTP bounce attack ⚫ Privilege escalation ⚫ User interface failures ◼ Warning fatigue or user conditioning. ◼ Blaming the victim ◼ Race Conditions https://en.wikipedia.org/wiki/Vulnerability_(computing)

software security 6 dit OWASP 10

https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project

software security 7 dit SANS top 25

https://www.sans.org/top25-software-errors/archive/2010

software security 8 dit SANS top 25

software security 9 dit SANS top 25

software security 10 dit SANS top 25

software security 11 dit top 25

Rank Score ID Name [1] 93.8 CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') [2] 83.3 CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') [3] 79 CWE-120 Buffer without Checking Size of Input ('Classic Buffer Overflow') [4] 77.7 CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') [5] 76.9 CWE-306 Missing Authentication for Critical Function [6] 76.8 CWE-862 Missing Authorization [7] 75 CWE-798 Use of Hard-coded Credentials [8] 75 CWE-311 Missing Encryption of Sensitive Data [9] 74 CWE-434 Unrestricted Upload of with Dangerous Type [10] 73.8 CWE-807 Reliance on Untrusted Inputs in a Security Decision

http://cwe.mitre.org/top25/index.html software security 12 dit SQL injection

php http sql

software security 13 dit SQL injection $username = isset($_POST['username']) ? $_POST['username'] : ""; $password = isset($_POST['password']) ? $_POST['password'] : "";

$query = sprintf("SELECT * FROM users WHERE username = '%s' AND password = '%s’;”, $username, $password); $result = $db->query($query);

$query = sprintf("SELECT * FROM users WHERE username = '%s' AND password = '%s';", SQLite3::escapeString($username), SQLite3::escapeString($password));

$stmt0 = "SELECT * FROM users " . "WHERE username = :user AND password = :pw"; $stmt = $db->prepare($stmt0); $stmt->bindValue(':user', $username, SQLITE3_TEXT); $stmt->bindValue(':pw', $password, SQLITE3_TEXT);http://sqlidemo.altervista.org/index.php $resultsoftware = $stmtsecurity->execute(); 14 dit sql injection

http://xkcd.com/327/

software security 15 dit SQL injection ⚫ root cause is to accept user input blindly ◼ no analysis ◼ no sanitization ⚫ Defenses ◼ what the user writes is not reliable ◼ stored procedures ◼ prepared statements ◼ limit access to the database (minimal surface) ◼ beware of error messages

software security 16 dit injection ⚫ generic technique ⚫ https://en.wikipedia.org/wiki/Code_injection

software security 17 dit OS command injection

$ _exs/.html

nslookup helper

$ cat _exs/nslookup.php :

nslookup ...

'; $host = $_POST["host"]; echo "nslookup " . $host . "\n"; system("nslookup " . $host); echo ''; ?> software security 18 dit rce – remote command execution

$ cat _exs/nslookup.php

nslookup ...

'; $host = $_POST["host"]; echo "nslookup " . $host . "\n"; system("nslookup " . $host); echo ''; ?> software security 19 dit [classic] buffer overflow

⚫ typical problem in y C++ lack of bound checking

software security 20 dit buffer overflow

char buff[10];

buff[10] = 'a';

strcpy(buff, “mas de 10 caracteres”);

software security 21 dit stack smash ⚫ C: when a function is called, the stack saves ◼ return address ◼ call arguments ◼ local variables ⚫ when a local buffer overflows, ◼ arguments can be modified ◼ return address can be changed (jump somewhere else)

software security 22

dit C stack

function call

software security 23 dit buffer overflow ⚫ remedies ◼ safe coding

 safe libraries ◼ tools to analyse source code (static analysis)

 no gets(), strcmp(), strcpy(), … ◼ pattern detection (nop slide, virtual nops, …)

 on download (IDS) ◼ executable space protection ◼ canary ◼ …

https://en.wikipedia.org/wiki/Buffer_overflow https://en.wikipedia.org/wiki/Buffer_overflow_protection

software security 24 dit languages Direct Language / Compiled or Strongly Safe or Memory Environment Interpreted Typed Unsafe Access Java, Java Virtual Both No Safe Machine (JVM) . Both Yes No Safe Perl Both Yes No Safe Python - interpreted Intepreted Yes No Safe Ruby Interpreted Yes No Safe C/C++ Compiled No Yes Unsafe Assembly Compiled No Yes Unsafe COBOL Compiled Yes No Safe

https://www.owasp.org/index.php/Buffer_Overflows

software security 25 dit XSS - cross-site scripting

⚫ when the attacker succeeds to execute javascript on user’s browser ◼ when the server copies attacker’s text into web response ◼ reflected ◼ stored ◼ DOM-based

 dynamic modification of html ⚫ typical usage: send session ids (i.e. cookies)

software security 26 dit stored xss (persistent)

https://excess-xss.com/

software security 27 dit reflected xss

https://excess-xss.com/

software security 28 dit DOM-based xss (client-side)

https://excess-xss.com/

software security 29 dit XSS - defenses ⚫ difficult to remove entirely

⚫ input validation (stored) ⚫ encoded output

⚫ https://excess-xss.com/ ⚫ https://www.google.com/about/appsecurity/learning/xss/

software security 30 Authentication & authorization dit

⚫ when we step into a critical task without sound authentication ◼ sensible data leak ◼ denial of service ⚫ when the server blindly trust clinet side authentication

⚫ remedy ◼ design

 task classification: normal, priviledged, administrative

 environment authentication ◼ source code inspection: revise critical areas

software security 31 dit Use of Hard-coded Credentials

⚫ crypto keys or passwords in … ◼ in code (source or executable) ◼ in configuration files (obfuscated) ◼ in registry (obfuscated) ⚫ reverse engineer to access ◼ decompile ◼ memory ◼ step by step execution ⚫ if the secret is revealed, (white hat | black hat) it is very difficult to repair ◼ downloaded programs ◼ client-server coordination

software security 32 dit Use of Hard-coded Credentials ⚫ remedies (partial) ◼ store to check correct data input ◼ limit the life of the key in ◼ OTP – reduced lifetime

software security 33 dit secrets in code

$ cat EncodedPW.java $ EncodedPW.class public class EncodedPW { user private String user= "pepe"; Ljava/lang/String; private String pw= "my key"; Code } LineNumberTable SourceFile EncodedPW.java pepe my key EncodedPW java/lang/Object

software security 34 dit secrets in code $ cat EncodedPW.java public class EncodedPW { private String user= "pepe"; private String pw= “my key"; $ javap -c EncodedPW.class } Compiled from "EncodedPW.java" public class EncodedPW { public EncodedPW(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."":() 4: aload_0 5: ldc #2 // String pepe 7: putfield #3 // Field user:Ljava/lang/String; 10: aload_0 11: ldc #4 // String my key 13: putfield #5 // Field pw:Ljava/lang/String; 16: return }

software security 35 dit secrets in code $ cat EncodedPW.java public class EncodedPW { private String user= "pepe"; private String pw= “my key"; }

http://www.javadecompilers.com/

software security 36 dit secrets in code

$ cat check_admin.c

#include #include $ strings check_admin.exe int main(int argc, char* argv[]) { … … … char* password= argv[0]; @B/70 if (strcmp(password, "Mew!")) { B/81 ("Incorrect Password!\n"); B/92 return(0); tgr5 } cyggcj-16.dll printf("Entering Diagnostic Mode...\n");_Jv_RegisterClasses return(1); Mew! } Incorrect Password! Entering Diagnostic Mode... GCC: (GNU) 5.4.0 20160603 (Fedora Cygwin 5.4.0-2) GCC: (GNU) 5.4.0 … … …

software security 37 dit hide a secret in SW ⚫ no way is 100% secure if the attacker can access sw ⚫ never: clear Strings ⚫ binary encoding ⚫ parts to be rebuild ⚫ …

software security 38 dit hide a secret in hw ⚫ USB ◼ have to steal the usb ⚫ sw encrypted USB ◼ steal and get the key ◼ when mounted, clear access ⚫ hw encrypted USB ◼ when mounted, clear access ⚫ challenge response ◼ signature = DNIe.Ks.sign(X)

software security 39 dit DNIe ⚫ guarantees ◼ the signer cannot be impersonated

 two factors

 something I have

 something I know ◼ the keys are concealed in the card ◼ the signing software is concealed in the card ⚫ weaknesses ◼ the hash is calculated in the PC ◼ the certificates may not come from a trusted entity ◼ the certificates may change from signing to validation time LTV ◼ the clock is provided by the PC

software security 40 dit HSM – hardware security module ⚫ … cryptographic device that generates, stores, and performs cryptographic operations internally ⚫ anti tamper

https://en.wikipedia.org/wiki/Hardware_security_module

software security 41 dit clear data

⚫ clear channel ⚫ unauthenticated peer (man in the middle) ⚫ clear attachments ⚫ local files, temporal files, ⚫ weak cryptography ⚫ poor key management ◼ predictable ◼ weak access control Bruce Schneier: “Currently encryption is the strongest we have. Everything else is worse: software, networks, people. There's absolutely no value in taking the strongest link software security and making it even stronger42 ” dit clear data

software security 43 dit top 25 Rank Score ID Name [11] 73.1 CWE-250 Execution with Unnecessary Privileges [12] 70.1 CWE-352 Cross-Site Request Forgery (CSRF) [13] 69.3 CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') [14] 68.5 CWE-494 Download of Code Without Integrity Check [15] 67.8 CWE-863 Incorrect Authorization [16] 66 CWE-829 Inclusion of Functionality from Untrusted Control Sphere [17] 65.5 CWE-732 Incorrect Permission Assignment for Critical Resource [18] 64.6 CWE-676 Use of Potentially Dangerous Function [19] 64.1 CWE-327 Use of a Broken or Risky Cryptographic Algorithm [20] 62.4 CWE-131 Incorrect Calculation of Buffer Size

http://cwe.mitre.org/top25/index.html software security 44 dit csrf – cross site request forgery

⚫ session riding ⚫ send requests as if coming from valid user

software security 45 dit CSRF - Example Attack Scenarios ⚫ The application allows a user to submit a state changing request that does not include anything secret. For example: ◼ http://example.com/app/transferFunds?amount=1500&destinationAccount=46 73243243 ⚫ So, the attacker constructs a request that will transfer money from the victim’s account to the attacker’s account, and then embeds this attack in an image request or iframe stored on various sites under the attacker’s control: ◼ ⚫ If the victim visits any of the attacker’s sites while already authenticated to example.com, these forged requests will automatically include the user’s session , authorizing the attacker’s request.

www.owasp.org

software security 46 dit defenses ⚫ check same origin ◼ url of the source form ◼ url of the POST target ⚫ CSRF token ◼ unique token per request

 non predictable ◼ e.g. hidden field in form ◼

www.owasp.org

software security 47 dit traversal

An anonymous FTP implementation parsed the requested file name to screen requests for files. If a file was in a not publicly accessible directory, then the file name would tell, and the access could be denied.

Of course, /etc/ is not allowed.

But carefully crafted requests could trick the parser into allowing access. Assume that /put/acc is an allowed folder. By typing in get /pub/acc/../../../etc/passwd the parser (in this implementation) would parse the first part of the string ("/pub/acc") and decide to allow access.

The Unix environment would however parse the complete string to correctly point to /etc/passwd. The vendor had to change the screening code softwareseveral security times to fix this and other vulnerabilities. 48 dit directory traversal / path traversal

https://en.wikipedia.org/wiki/Directory_traversal_attack software security 49 dit code downloads

⚫ problem ◼ download and execute from unauthenticated source, or without integrity guarantee ⚫ Solution ◼ signed code (integrity) ◼ trustable certificate (authenticity)

software security 50 dit signed code

software security 51 dit top 25 Rank Score ID Name [21] 61.5 CWE-307 Improper Restriction of Excessive Authentication Attempts [22] 61.1 CWE-601 URL to Untrusted Site ('Open Redirect') [23] 61 CWE-134 Uncontrolled Format String [24] 60.3 CWE-190 Integer Overflow or Wraparound [25] 59.9 CWE-759 Use of a One-Way Hash without a Salt

http://cwe.mitre.org/top25/index.html software security 52 dit format string

mal bien int func (char *user) { int func (char *user) { printf (user); printf ("%s", user); } }

• problem: if the user may introduce a tuned String • printf uses stack for argumenys

• tutorial: http://julianor.tripod.com/bc/formatstring-1.2.pdf

software security 53 dit format string #include

int main(int argc, char **argv) { printf(argv[1]); return 0; }

$ ./echo3.exe "bye bye" bye bye

$ ./echo3.exe "bye bye %d %s" bye bye 0 (null)

$ ./echo3.exe "%08x %08x %08x %08x %08x" 00000000 00000000 00000000 ffffccc0 800479a2 software security 54 dit integer overflow

software security 55 dit integer overflow ⚫ example: reading from socket ◼ problem with attacker tuned packes

software security 56 dit Arithmetic Over/Under Flows blockchain – smart contracts contract Token { mapping(address => uint) balances; uint public totalSupply;

function Token(uint _initialSupply) { balances[msg.sender] = totalSupply = _initialSupply; }

function transfer(address _to, uint _value) public returns (bool) { require(balances[msg.sender] - _value >= 0); balances[msg.sender] -= _value; balances[_to] += _value; return true; }

function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } } smart contracts security Vaibhav Saini 57 dit integer overflow ⚫ after an operation it is not possible to know if it is an overflow ⚫ may cause faulty buffer size allocation, then buffer overflow ◼ buffer | stack | heap overflow ⚫ languages ◼ C/C++ - memory overflow ◼ java: no exception

 java 8: Math.addExact(), Math.mulExact() ◼ Ada raises an exception ⚫ closed issues ◼ casting

software security 58 dit hash functions

⚫ usage ◼ password hashing ◼ key derivation functions (KDF)

⚫ y = hash(x) is hard to invert ◼ but it is easy to check a guessed x ⚫ dictionary attacks (pre calculation)

software security 59 dit https://crackstation.net

software security 60 dit the 25 popular passwords

software security https://www.teamsid.com/worst-passwords-2016/61 dit salt + hash 1. salt: random 2. hash = H(salt || H(salt || secret)) 3. store (salt, hash)

⚫ PBKDF2 - Password-Based Key Derivation Function 2 ◼ CPU intensive; attack: GPU, ASIC, FPGA ⚫ bcrypt ◼ CPU & RAM intensive; attack: GPU, ASIC, FPGA ⚫ scrypt ◼ … exponential cycles and memory; attack: GPU, ASIC, FPGA

software security 62 dit scrypt ~ 2002 technology

http://www.tarsnap.com/scrypt/scrypt.pdf

software security 63 dit Software Security, G. McGraw

software security 64 dit secure programming ⚫ a problem beyond our means ◼ too much code / too many programmers / too many versions ◼ creative attackerd ◼ slow and costly solutions ⚫ to be pragmatic ◼ use tested libraries and services ◼ priorise ◼ wrap fragile parts

 secure environment, no public exposition

 never never trust user input (input validation) ◼ detect violations, and have a contingency plan

software security 65 dit risk analysis

https://en.wikipedia.org/wiki/Vulnerability_(computing)

software security 66 dit risk analysis

impact

risk

likelihood

software security 67 dit fuzz testing Fuzz testing or fuzzing is a software testing technique used to discover coding errors and security loopholes in software, operating systems or networks by inputting massive amounts of random data, called fuzz, to the system in an attempt to make it crash. If a vulnerability is found, a tool called a fuzz tester (or fuzzer), indicates potential causes. Fuzz testing was originally developed by Barton Miller the University of Wisconsin in 1989.

Fuzzers work best for problems that can cause a program to crash, such as buffer overflow, cross-site scripting, denial of service attacks, format bugs and SQL injection.

Fuzz testing is simple and offers a high benefit-to-cost ratio. Fuzz testing can often reveal defects that are overlooked when software is written and debugged. Nevertheless, fuzz testing usually finds only the most serious faults. Fuzz testing alone cannot provide a complete picture of the overall security, quality or effectiveness of a program in a particular situation or application. Fuzzers are most effective when used in conjunction with extensive black box testing, beta testing and other proven debugging methods.software security 68 dit to conclude ⚫ functionality: it works as expected ◼ good service ⚫ security: it does not work as unexpected ◼ no devil

software security 69