1 / 24

Web Security Programming I

A Simple Web Server. To illustrate what can go wrong if we do not design for security in our web applications from the start, consider a simple web server implemented in Java. All this program does is serve documents using HTTP.We will walkthrough the code in the following slides.. Some Preliminaries

Antony
Télécharger la présentation

Web Security Programming I

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


    1. Web Security Programming I Building Security in from the Start

    2. A Simple Web Server To illustrate what can go wrong if we do not design for security in our web applications from the start, consider a simple web server implemented in Java. All this program does is serve documents using HTTP. We will walkthrough the code in the following slides.

    3. Some Preliminaries (HyperText Transfer Protocol): The communications protocol used to connect to servers on the Web. Its primary function is to establish a connection with a Web server and transmit HTML pages to the client browser or any other files required by an HTTP application. Addresses of Web sites begin with an http:// prefix.

    4. Some Preliminaries A typical HTTP request that a browser makes to a web server: Get / HTTP/1.0 When the server receives this request for filename / (which means the root document on the web server), it attempts to load index.html. It sends back: HTTP/1.0 200 OK followed by the document contents.

    5. SimpleWebServer: main() /* This method is called when the program is run from the command line. */ public static void main (String argv[]) throws Exception { /* Create a SimpleWebServer object, and run it */ SimpleWebServer sws = new SimpleWebServer(); sws.run(); } Now we walk through the code Main() creates a SimpleWebServer object and calls its run() method. The run() method is just an infinite loop that waits for a connection from a client, and then attempts to process the request.Now we walk through the code Main() creates a SimpleWebServer object and calls its run() method. The run() method is just an infinite loop that waits for a connection from a client, and then attempts to process the request.

    6. SimpleWebServer Object public class SimpleWebServer { /* Run the HTTP server on this TCP port. */ private static final int PORT = 8080; /* The socket used to process incoming connections from web clients */ private static ServerSocket dServerSocket; public SimpleWebServer () throws Exception { dServerSocket = new ServerSocket (PORT); } public void run() throws Exception { while (true) { /* wait for a connection from a client */ Socket s = dServerSocket.accept(); /* then process the client's request */ processRequest(s); } } Here is the SimpleWebServer object. First we initialize a variable that holds the port number the web server should listen to for connections from clients. Then we initialize a ServerSocket. Socket: The method of directing data to the appropriate application in a TCP/IP network. The combination of the IP address of the station and a port number make up a socket. Think of this like an electrical socket. A web server and a web client both have a virtual power strip with many sockets on it. A web client can talk to a server by selecting one of its sockets, and then selecting a server socket and plugging a virtual wire into each end. The run() method has an infinite loop waiting for a connection from a client. The call to ServerSocket accept() returns a socket object that corresponds to a unique socket on the server. This allows the server to communicate with the client. Once the communication is established, the clients request is processed.Here is the SimpleWebServer object. First we initialize a variable that holds the port number the web server should listen to for connections from clients. Then we initialize a ServerSocket. Socket: The method of directing data to the appropriate application in a TCP/IP network. The combination of the IP address of the station and a port number make up a socket. Think of this like an electrical socket. A web server and a web client both have a virtual power strip with many sockets on it. A web client can talk to a server by selecting one of its sockets, and then selecting a server socket and plugging a virtual wire into each end. The run() method has an infinite loop waiting for a connection from a client. The call to ServerSocket accept() returns a socket object that corresponds to a unique socket on the server. This allows the server to communicate with the client. Once the communication is established, the clients request is processed.

    7. SimpleWebServer: processRequest 1 /* Reads the HTTP request from the client, and responds with the file the user requested or a HTTP error code. */ public void processRequest(Socket s) throws Exception { /* used to read data from the client */ BufferedReader br = new BufferedReader (new InputStreamReader (s.getInputStream())); /* used to write data to the client */ OutputStreamWriter osw = new OutputStreamWriter (s.getOutputStream()); /* read the HTTP request from the client */ String request = br.readLine(); String command = null; String pathname = null; processRequest() takes the client socket as input. It uses this socket to create BufferedReader and OutputStreamWriter objects. Once these communication objects are created, the method attempts to read a line of input from the client using the BufferedReader. We expect this line of input to be an HTTP GET request (as discussed earlier).processRequest() takes the client socket as input. It uses this socket to create BufferedReader and OutputStreamWriter objects. Once these communication objects are created, the method attempts to read a line of input from the client using the BufferedReader. We expect this line of input to be an HTTP GET request (as discussed earlier).

    8. SimpleWebServer: processRequest 2 /* parse the HTTP request */ StringTokenizer st = new StringTokenizer (request, " "); command = st.nextToken(); pathname = st.nextToken(); if (command.equals("GET")) { /* if the request is a GET try to respond with the file the user is requesting */ serveFile (osw,pathname); } else { /* if the request is a NOT a GET, return an error saying this server does not implement the requested command */ osw.write ("HTTP/1.0 501 Not Implemented\n\n"); } /* close the connection to the client */ osw.close(); The StringTokenizer object is used to break up the request into its constituent parts: GET, the pathname to the file the client would like to download. If the command is a GET, we call the serveFile() method, else we issue an error. Then we close the connection to the client.The StringTokenizer object is used to break up the request into its constituent parts: GET, the pathname to the file the client would like to download. If the command is a GET, we call the serveFile() method, else we issue an error. Then we close the connection to the client.

    9. SimpleWebServer: serveFile 1 public void serveFile (OutputStreamWriter osw, String pathname) throws Exception { FileReader fr=null; int c=-1; StringBuffer sb = new StringBuffer(); /* remove the initial slash at the beginning of the pathname in the request */ if (pathname.charAt(0)=='/') pathname=pathname.substring(1); /* if there was no filename specified by the client, serve the "index.html" file */ if (pathname.equals("")) pathname="index.html"; The first if removes the initial slash at the beginning of the pathname, and the second if sets the file to be downloaded = index.html, if another file was not specified.The first if removes the initial slash at the beginning of the pathname, and the second if sets the file to be downloaded = index.html, if another file was not specified.

    10. SimpleWebServer: serveFile 2 /* try to open file specified by pathname */ try { fr = new FileReader (pathname); c = fr.read(); } catch (Exception e) { /* if the file is not found,return the appropriate HTTP response code */ osw.write ("HTTP/1.0 404 Not Found\n\n"); return; } Now the method attempts to open the file and read it into the web servers memory. If the FileReader object is unable to open the file and read a byte from it, it issues an error message.Now the method attempts to open the file and read it into the web servers memory. If the FileReader object is unable to open the file and read a byte from it, it issues an error message.

    11. SimpleWebServer: serveFile 3 /* if the requested file can be successfully opened and read, then return an OK response code and send the contents of the file */ osw.write ("HTTP/1.0 200 OK\n\n"); while (c != -1) { sb.append((char)c); c = fr.read(); } osw.write (sb.toString()); If the file was successfully opened, send the HTTP/1.0 200 OK message and then the method enters a while loop that reads bytes from the file and appends them to a StringBuffer, until the end of the file is reached. Then this StringBuffer is sent to the client.If the file was successfully opened, send the HTTP/1.0 200 OK message and then the method enters a while loop that reads bytes from the file and appends them to a StringBuffer, until the end of the file is reached. Then this StringBuffer is sent to the client.

    12. Can you identify any security vulnerabilities in SimpleWebServer?

    13. What Can Go Wrong? Denial of Service (DoS): An attacker makes a web server unavailable. Example: an online bookstores web server crashes and the bookstore loses revenue

    14. DoS on SimpleWebServer? Just send a carriage return as the first message instead of a properly formatted GET message

    15. DoS on SimpleWebServer? processRequest(): /* read the HTTP request from the client */ String request = br.readLine(); String command = null; String pathname = null; /* parse the HTTP request */ StringTokenizer st = new StringTokenizer (request, " "); command = st.nextToken(); pathname = st.nextToken(); Trace the code, assuming a CR sent from the client. We read the line of input from the client. When we tokenize, the line: command = st.nextToken(); results in an exception. Control is returned to run() which does not handle the exception; then control is returned to main() which does not handle the exception either. Java terminates the application.Trace the code, assuming a CR sent from the client. We read the line of input from the client. When we tokenize, the line: command = st.nextToken(); results in an exception. Control is returned to run() which does not handle the exception; then control is returned to main() which does not handle the exception either. Java terminates the application.

    16. DoS on SimpleWebServer? The web server crashes Service to all subsequent clients is denied until the web server is restarted

    17. How Do We Fix This? The web server should immediately disconnect from any web client that sends a malformed HTTP request to the server. The programmer needs to carefully handle exceptions to deal with malformed requests.

    18. How would you fix this code? processRequest(): /* read the HTTP request from the client */ String request = br.readLine(); String command = null; String pathname = null; /* parse the HTTP request */ StringTokenizer st = new StringTokenizer (request, " "); command = st.nextToken(); pathname = st.nextToken();

    19. A possible solution /* read the HTTP request from the client */ String request = br.readLine(); String command = null; String pathname = null; try { /* parse the HTTP request */ StringTokenizer st = new StringTokenizer (request, " "); command = st.nextToken(); pathname = st.nextToken(); } catch (Exception e) { osw.write (HTTP/1.0 400 Bad Request\n\n); osw.close(); return; } Close the connection to the client, rather than crash the serverClose the connection to the client, rather than crash the server

    20. Importance of Careful Exception Handling Error messages and observable behavior can tip off an attacker to vulnerabilities Fault Injection: Providing a program with input that it does not expect (as in the CR for SimpleWebServer) and observing behavior

    21. Careful Exception Handling Two possible designs for int checkPassword (String username, String password) The function could fail, so what exception should the function return? ERROR_ACCESS_DENIED ERROR_PASS_FILE_NOT_FOUND ERROR_OUT_OF_MEMORY NO_ERROR_ACCESS_ALLOWED NO_ERROR ERROR int getError () Be careful to not provide more information to a user than is needed.

    22. Careful Exception Handling int result = checkPassword ( ) if (result == ERROR_ACCESS_DENIED) { abort(); } else { // Complete login } Problem: result != ERROR_ACCESS_DENIED does not infer ERROR_ACCESS_ALLOWED Result could have been: ERROR_PASS_FILE_NOT_FOUND or ERROR_OUT_OF_MEMORY ! We also need to make sure the function fails in a secure manner.We also need to make sure the function fails in a secure manner.

    23. Fail-Safe int result = checkPassword ( ) if (result == NO_ERROR) { // Complete login } else { int reason = getError(); abort(); } Much better less error prone! checkPassword failure occurs securely! This is also a good example of a fail-safe approach: even if one or more components of a system fail, there is still some level of security. This is also a good example of a fail-safe approach: even if one or more components of a system fail, there is still some level of security.

    24. Summary Effective exception handling is essential in designing security in from the start Next time, we look at other vulnerabilities in the SimpleWebServer

    25. Sources The content of these slides was adapted from: "Foundations of Security: What Every Programmer Needs To Know" (ISBN 1590597842) by Neil Daswani, Christoph Kern, and Anita Kesavan. http://www.learnsecurity.com/ntk

More Related