SlideShare a Scribd company logo
Web Security Programming I Building Security in from the Start Except where otherwise noted all portions of this work are Copyright (c) 2007 Google  and are licensed under the Creative Commons Attribution 3.0 License  http://creativecommons.org/licenses/by/3.0/
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… ( H yper T ext  T ransfer  P rotocol):  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.
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.
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();  }
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);    }  }
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;
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"); }  /* close the connection to the client */ osw.close();
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";
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");    return;  }
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");  while (c != -1) {    sb.append((char)c);    c = fr.read();  }  osw.write (sb.toString());
Can you identify any security vulnerabilities in SimpleWebServer?
What Can Go Wrong? Denial of Service (DoS): An attacker makes a web server unavailable. Example: an online bookstore’s web server crashes and the bookstore loses revenue
DoS on SimpleWebServer? Just send a carriage return as the first message instead of a properly formatted GET message…
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();
DoS on SimpleWebServer? The web server crashes Service to all subsequent clients is denied until the web server is restarted
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.
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();
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”); osw.close(); return; }
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
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.
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 !
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!
Summary Effective exception handling is essential in designing security in from the start Next time, we look at other vulnerabilities in the SimpleWebServer
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 Content

What's hot

A.java
A.javaA.java
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
Ankur Agrawal
 
Socket.io (part 1)
Socket.io (part 1)Socket.io (part 1)
Socket.io (part 1)
Andrea Tarquini
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
belajarkomputer
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rack
danwrong
 
Socket.io
Socket.ioSocket.io
Socket.io
Timothy Fitz
 
Mule esb first http connector
Mule esb first http connectorMule esb first http connector
Mule esb first http connector
Germano Barba
 
JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Language
giurca
 
From Web Developer to Hardware Developer
From Web Developer to Hardware DeveloperFrom Web Developer to Hardware Developer
From Web Developer to Hardware Developer
alexshenoy
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
Sivadon Chaisiri
 
Sitecore - Deep drive into the Sitecore Client pipelines
Sitecore - Deep drive into the Sitecore Client pipelinesSitecore - Deep drive into the Sitecore Client pipelines
Sitecore - Deep drive into the Sitecore Client pipelines
Benjamin Vangansewinkel
 
Nodejs 프로그래밍 ch.3
Nodejs 프로그래밍 ch.3Nodejs 프로그래밍 ch.3
Nodejs 프로그래밍 ch.3
HyeonSeok Choi
 
Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
LittleBIGRuby
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
kamal kotecha
 
Extending Retrofit for fun and profit
Extending Retrofit for fun and profitExtending Retrofit for fun and profit
Extending Retrofit for fun and profit
Matthew Clarke
 
Sockets
SocketsSockets
Sockets
naniix21_3
 
Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.io
Arnout Kazemier
 
Acs sim errorlog
Acs sim errorlogAcs sim errorlog
Acs sim errorlog
Pankaj Debnath
 
Real Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.ioReal Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.io
Mindfire Solutions
 
Socket.IO
Socket.IOSocket.IO
Socket.IO
Arnout Kazemier
 

What's hot (20)

A.java
A.javaA.java
A.java
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
 
Socket.io (part 1)
Socket.io (part 1)Socket.io (part 1)
Socket.io (part 1)
 
Pemrograman Jaringan
Pemrograman JaringanPemrograman Jaringan
Pemrograman Jaringan
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rack
 
Socket.io
Socket.ioSocket.io
Socket.io
 
Mule esb first http connector
Mule esb first http connectorMule esb first http connector
Mule esb first http connector
 
JSON Rules Language
JSON Rules LanguageJSON Rules Language
JSON Rules Language
 
From Web Developer to Hardware Developer
From Web Developer to Hardware DeveloperFrom Web Developer to Hardware Developer
From Web Developer to Hardware Developer
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Sitecore - Deep drive into the Sitecore Client pipelines
Sitecore - Deep drive into the Sitecore Client pipelinesSitecore - Deep drive into the Sitecore Client pipelines
Sitecore - Deep drive into the Sitecore Client pipelines
 
Nodejs 프로그래밍 ch.3
Nodejs 프로그래밍 ch.3Nodejs 프로그래밍 ch.3
Nodejs 프로그래밍 ch.3
 
Rack Middleware
Rack MiddlewareRack Middleware
Rack Middleware
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Extending Retrofit for fun and profit
Extending Retrofit for fun and profitExtending Retrofit for fun and profit
Extending Retrofit for fun and profit
 
Sockets
SocketsSockets
Sockets
 
Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.io
 
Acs sim errorlog
Acs sim errorlogAcs sim errorlog
Acs sim errorlog
 
Real Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.ioReal Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.io
 
Socket.IO
Socket.IOSocket.IO
Socket.IO
 

Viewers also liked

Yy (68)
Yy (68)Yy (68)
Yy (68)
google
 
dgdgdgdgd
dgdgdgdgddgdgdgdgd
dgdgdgdgd
Thiago Sturmer
 
Hybrid cloud iaa-s_office-365-azure_sharepoint-konferenz-wien-2013_ankbs_mich...
Hybrid cloud iaa-s_office-365-azure_sharepoint-konferenz-wien-2013_ankbs_mich...Hybrid cloud iaa-s_office-365-azure_sharepoint-konferenz-wien-2013_ankbs_mich...
Hybrid cloud iaa-s_office-365-azure_sharepoint-konferenz-wien-2013_ankbs_mich...
Michael Kirst-Neshva
 
30美丽的名片
30美丽的名片30美丽的名片
30美丽的名片
zsk91186
 
осъдителна присъда кюстендилски окръжен съд
осъдителна присъда  кюстендилски окръжен съдосъдителна присъда  кюстендилски окръжен съд
осъдителна присъда кюстендилски окръжен съд
Kristiyan Petroff
 
Attom
AttomAttom
Unit 4 Saving and Investing PPT
Unit 4 Saving and Investing PPTUnit 4 Saving and Investing PPT
Unit 4 Saving and Investing PPT
Jenny Hubbard
 
sistemas
sistemas sistemas
sistemas
carloschavezsdi
 
스타토토⊙o⊙Wifi89,cOm(카톡: XaZa⊙o⊙ 실시간토토 실 시간배팅
스타토토⊙o⊙Wifi89,cOm(카톡: XaZa⊙o⊙  실시간토토  실  시간배팅스타토토⊙o⊙Wifi89,cOm(카톡: XaZa⊙o⊙  실시간토토  실  시간배팅
스타토토⊙o⊙Wifi89,cOm(카톡: XaZa⊙o⊙ 실시간토토 실 시간배팅
fdghjhj
 
Crear Unha Conta Gmail
Crear Unha Conta GmailCrear Unha Conta Gmail
Crear Unha Conta Gmail
vicente
 
Lesson #3
Lesson #3Lesson #3
Lesson #3
smith1853
 
Co Ownership And Shared Equity Arrangements
Co Ownership And Shared Equity ArrangementsCo Ownership And Shared Equity Arrangements
Co Ownership And Shared Equity Arrangements
ZCD Properties Inc
 
Case Study Analysis Lucent Technologies
Case Study Analysis Lucent TechnologiesCase Study Analysis Lucent Technologies
Case Study Analysis Lucent Technologies
Djadja Sardjana
 
Khoa van-tay-kaba e10-fingerprint doorlock
Khoa van-tay-kaba e10-fingerprint doorlockKhoa van-tay-kaba e10-fingerprint doorlock
Khoa van-tay-kaba e10-fingerprint doorlock
Protocol Corporation
 
Misawa Post Office Holiday Schedule
Misawa Post Office Holiday ScheduleMisawa Post Office Holiday Schedule
Misawa Post Office Holiday Schedule
NAF Misawa
 
WASH United India | Fellowships | Round 2
WASH United India | Fellowships | Round 2WASH United India | Fellowships | Round 2
WASH United India | Fellowships | Round 2
WASH United
 
Module english
Module englishModule english
Module english
Amer Syarifuddin
 
Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5
John Coggeshall
 

Viewers also liked (20)

Yy (68)
Yy (68)Yy (68)
Yy (68)
 
dgdgdgdgd
dgdgdgdgddgdgdgdgd
dgdgdgdgd
 
Hybrid cloud iaa-s_office-365-azure_sharepoint-konferenz-wien-2013_ankbs_mich...
Hybrid cloud iaa-s_office-365-azure_sharepoint-konferenz-wien-2013_ankbs_mich...Hybrid cloud iaa-s_office-365-azure_sharepoint-konferenz-wien-2013_ankbs_mich...
Hybrid cloud iaa-s_office-365-azure_sharepoint-konferenz-wien-2013_ankbs_mich...
 
30美丽的名片
30美丽的名片30美丽的名片
30美丽的名片
 
осъдителна присъда кюстендилски окръжен съд
осъдителна присъда  кюстендилски окръжен съдосъдителна присъда  кюстендилски окръжен съд
осъдителна присъда кюстендилски окръжен съд
 
Attom
AttomAttom
Attom
 
Daaaaaa
DaaaaaaDaaaaaa
Daaaaaa
 
Unit 4 Saving and Investing PPT
Unit 4 Saving and Investing PPTUnit 4 Saving and Investing PPT
Unit 4 Saving and Investing PPT
 
sistemas
sistemas sistemas
sistemas
 
스타토토⊙o⊙Wifi89,cOm(카톡: XaZa⊙o⊙ 실시간토토 실 시간배팅
스타토토⊙o⊙Wifi89,cOm(카톡: XaZa⊙o⊙  실시간토토  실  시간배팅스타토토⊙o⊙Wifi89,cOm(카톡: XaZa⊙o⊙  실시간토토  실  시간배팅
스타토토⊙o⊙Wifi89,cOm(카톡: XaZa⊙o⊙ 실시간토토 실 시간배팅
 
Crear Unha Conta Gmail
Crear Unha Conta GmailCrear Unha Conta Gmail
Crear Unha Conta Gmail
 
Lesson #3
Lesson #3Lesson #3
Lesson #3
 
Co Ownership And Shared Equity Arrangements
Co Ownership And Shared Equity ArrangementsCo Ownership And Shared Equity Arrangements
Co Ownership And Shared Equity Arrangements
 
Case Study Analysis Lucent Technologies
Case Study Analysis Lucent TechnologiesCase Study Analysis Lucent Technologies
Case Study Analysis Lucent Technologies
 
Khoa van-tay-kaba e10-fingerprint doorlock
Khoa van-tay-kaba e10-fingerprint doorlockKhoa van-tay-kaba e10-fingerprint doorlock
Khoa van-tay-kaba e10-fingerprint doorlock
 
The Beauty Of The Sea
The Beauty Of The SeaThe Beauty Of The Sea
The Beauty Of The Sea
 
Misawa Post Office Holiday Schedule
Misawa Post Office Holiday ScheduleMisawa Post Office Holiday Schedule
Misawa Post Office Holiday Schedule
 
WASH United India | Fellowships | Round 2
WASH United India | Fellowships | Round 2WASH United India | Fellowships | Round 2
WASH United India | Fellowships | Round 2
 
Module english
Module englishModule english
Module english
 
Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5Migrating from PHP 4 to PHP 5
Migrating from PHP 4 to PHP 5
 

Similar to Web

[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
hanneloremccaffery
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
kacie8xcheco
 
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
Bareen Shaikh
 
1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel
AgripinaBeaulieuyw
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
phanleson
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project Report
Kavita Sharma
 
Servlets
ServletsServlets
Servlets
Manav Prasad
 
Servlets
ServletsServlets
Servlets
ramesh kumar
 
T2
T2T2
T2
Mo Ch
 
Sockets
SocketsSockets
Sockets
sivindia
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
VannaSchrader3
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
alfredacavx97
 
Server Side? Swift
Server Side? SwiftServer Side? Swift
Server Side? Swift
Takaaki Tanaka
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
Haci Murat Yaman
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
Nitish Nagar
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
Adil Jafri
 
Servlets
ServletsServlets
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
arnold 7490
 
Rpi python web
Rpi python webRpi python web
Rpi python web
sewoo lee
 
03 sockets
03 sockets03 sockets
03 sockets
Pavan Illa
 

Similar to Web (20)

[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
 
Web Server.pdf
Web Server.pdfWeb Server.pdf
Web Server.pdf
 
1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel1)Building a MultiThreaded Web ServerIn this lab we will devel
1)Building a MultiThreaded Web ServerIn this lab we will devel
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 
Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project Report
 
Servlets
ServletsServlets
Servlets
 
Servlets
ServletsServlets
Servlets
 
T2
T2T2
T2
 
Sockets
SocketsSockets
Sockets
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
 
Server Side? Swift
Server Side? SwiftServer Side? Swift
Server Side? Swift
 
Node.js System: The Approach
Node.js System: The ApproachNode.js System: The Approach
Node.js System: The Approach
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Servlets
ServletsServlets
Servlets
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
Rpi python web
Rpi python webRpi python web
Rpi python web
 
03 sockets
03 sockets03 sockets
03 sockets
 

Recently uploaded

How UiPath Discovery Suite supports identification of Agentic Process Automat...
How UiPath Discovery Suite supports identification of Agentic Process Automat...How UiPath Discovery Suite supports identification of Agentic Process Automat...
How UiPath Discovery Suite supports identification of Agentic Process Automat...
DianaGray10
 
Finetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and DefendingFinetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and Defending
Priyanka Aash
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
bhumivarma35300
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
sunilverma7884
 
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
FIDO Alliance
 
The History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal EmbeddingsThe History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal Embeddings
Zilliz
 
Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3
DianaGray10
 
Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024
siddu769252
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
maigasapphire
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
SubhamMandal40
 
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdfLeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
SelfMade bd
 
Camunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptxCamunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptx
ZachWylie3
 
It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...
Zilliz
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
SAI KAILASH R
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
Steven Carlson
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
ldtexsolbl
 
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
Zilliz
 
Uncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in LibrariesUncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in Libraries
Brian Pichman
 
Patch Tuesday de julio
Patch Tuesday de julioPatch Tuesday de julio
Patch Tuesday de julio
Ivanti
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
Jimmy Lai
 

Recently uploaded (20)

How UiPath Discovery Suite supports identification of Agentic Process Automat...
How UiPath Discovery Suite supports identification of Agentic Process Automat...How UiPath Discovery Suite supports identification of Agentic Process Automat...
How UiPath Discovery Suite supports identification of Agentic Process Automat...
 
Finetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and DefendingFinetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and Defending
 
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
High Profile Girls call Service Pune 000XX00000 Provide Best And Top Girl Ser...
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
 
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
UX Webinar Series: Essentials for Adopting Passkeys as the Foundation of your...
 
The History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal EmbeddingsThe History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal Embeddings
 
Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3Communications Mining Series - Zero to Hero - Session 3
Communications Mining Series - Zero to Hero - Session 3
 
Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
 
Sonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdfSonkoloniya documentation - ONEprojukti.pdf
Sonkoloniya documentation - ONEprojukti.pdf
 
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdfLeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
 
Camunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptxCamunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptx
 
It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...It's your unstructured data: How to get your GenAI app to production (and spe...
It's your unstructured data: How to get your GenAI app to production (and spe...
 
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and DisadvantagesBLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
BLOCKCHAIN TECHNOLOGY - Advantages and Disadvantages
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
 
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
Garbage In, Garbage Out: Why poor data curation is killing your AI models (an...
 
Uncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in LibrariesUncharted Together- Navigating AI's New Frontiers in Libraries
Uncharted Together- Navigating AI's New Frontiers in Libraries
 
Patch Tuesday de julio
Patch Tuesday de julioPatch Tuesday de julio
Patch Tuesday de julio
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
 

Web

  • 1. Web Security Programming I Building Security in from the Start Except where otherwise noted all portions of this work are Copyright (c) 2007 Google and are licensed under the Creative Commons Attribution 3.0 License http://creativecommons.org/licenses/by/3.0/
  • 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… ( H yper T ext T ransfer P rotocol): 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(); }
  • 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); } }
  • 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;
  • 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"); } /* close the connection to the client */ osw.close();
  • 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";
  • 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"); return; }
  • 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"); while (c != -1) { sb.append((char)c); c = fr.read(); } osw.write (sb.toString());
  • 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 bookstore’s 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();
  • 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”); osw.close(); return; }
  • 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 !
  • 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!
  • 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

Editor's Notes

  1. 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.
  2. 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 client’s request is processed.
  3. 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).
  4. 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.
  5. 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.
  6. Now the method attempts to open the file and read it into the web server’s memory. If the FileReader object is unable to open the file and read a byte from it, it issues an error message.
  7. 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.
  8. 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.
  9. Close the connection to the client, rather than crash the server…
  10. We also need to make sure the function fails in a secure manner.
  11. 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.