00:00:00

Security

Notes

Who Is Speaking?

Notes

William DURAND

PhD / CTO TailorDev

Graduated from IUT, ISIMA, Blaise Pascal University. Worked at:

Open-Source evangelist:

twitter.com/couac  |  github.com/willdurand  |  williamdurand.fr

Notes

Notes

What Is Security?

Computer security is information security as applied to computers and networks.

Information security is the practice of defending information from unauthorized access, use, disclosure, disruption, modification, perusal, inspection, recording or destruction.

Agenda

  • Securing The Web
  • Authentication
  • Authentication Mechanisms
  • Authorization
  • Web Security 101
  • IP tracking

Notes

Securing The Web

Notes

Agenda

  • Secure Sockets Layer (SSL)
  • Transport Layer Security (TLS)
  • HTTPS

Notes

What Is Encryption?

Notes

Asymmetric Encryption

Asymmetric encryption or public-key cryptography uses a separate key for encryption and decryption.

Anyone can use the encryption key (public key) to encrypt a message.

However, decryption keys (private keys) are secret.

The most common asymmetric encryption algorithm is RSA.

Notes

Symmetric Encryption

Symmetric encryption or pre-shared key encryption uses a single key to both encrypt and decrypt data.

Both the sender and the receiver need the same key to communicate.

The larger the key size, the harder the key is to crack.

Popular symmetric algorithms: Blowfish, AES, Twofish.

Notes

SSL

Notes

Secure Socket Layer (SSL)

Protocol developed by Netscape Communications Corporation.

Provide security and privacy over the Internet.

Maintains the security and integrity of the transmission channel by using encryption, authentication and message authentication codes.

Use asymmetric encryption techniques to generate a shared secret key, which avoids the key distribution problem.

It's all about authentication, privacy, and integrity.

Versions

  • 1.0 developed by Netscape, never publicly released;
  • 2.0 released in February 1995, but contained some security flaws;
  • 3.0 released in 1996, RFC 6101.

Notes

Authentication

During both client and server authentication there is a step that requires data to be encrypted with one of the keys in an asymmetric key pair and decrypted with the other key of the pair.

In a nutshell

  1. Generate a key pair (public and private key)
  2. Use a X.509 certificate to wrap public key
  3. Exchange CA-signed public keys

Notes

Certificate Authority (CA)

An entity that issues digital certificates.

It's a trusted third party that is trusted by both the subject (owner) of the certificate and the party relying upon the certificate.

When server presents certificate to client during SSL handshake, client will attempt to verify signature against a list of known good signers.

Web browsers normally come with lists of CAs that they will implicitly trust to identify hosts.

If the authority is not in the list, as with some sites that sign their own certificates, the browser will alert the user that the certificate is not signed by a recognized authority and ask the user if they wish to continue communications with unverified site.

Well-known Certificate Authorities: Comodo, GeoTrust, or VeriSign.

Notes

Privacy

The SSL client and SSL server agree an encryption algorithm and a shared secret key to be used for one session only.

All messages transmitted between the SSL client and SSL server are encrypted using that algorithm and key, ensuring that the message remains private even if it is intercepted.

Symmetric algorithms supported in SSL are: DES, 3DES, ARCFOUR, AES, Camellia, RC2, IDEA, SEED, NULL (no encryption).

Notes

Integrity

SSL provides data integrity by calculating a message digest (fingerprinting).

Message integrity refers to maintaining and assuring the accuracy and consistency of the message.

Notes

SSL Handshake

Source: An overview of the SSL handshake

Notes

TLS

Notes

Transport Layer Security (TLS)

Cryptographic protocol that provides communication security over the Internet.

Internet Engineering Task Force (IETF) standard, described in RFC 5246, and based on SSL.

Implemented on top of the Transport Layer.

Composed of two layers:

  • the TLS Record Protocol;
  • the TLS Handshake Protocol.

Versions

Notes

Transport Layer Security (TLS)

TLS Record Protocol

Negotiate a private, reliable connection between the client and the server.

Use symmetric cryptography keys to ensure a private connection. This connection is secured through the use of hash functions generated by Message Authentication Code.

TLS Handshake Protocol

Allow the server and the client to speak the same language, with a determined encryption algorithm and determined encryption keys.

Use the same handshake protocol procedure as SSL.

SSL vs TLS

TLS is the new name for SSL. Namely, SSL protocol got to version 3.0.

TLS 1.0 is "SSL 3.1".

Notes

Notes

The Heartbleed Bug

The Heartbleed Bug is a serious vulnerability in the popular OpenSSL cryptographic software library.

This weakness allows stealing the information protected, under normal conditions, by the SSL/TLS encryption used to secure the Internet. SSL/TLS provides communication security and privacy over the Internet for applications such as web, email, instant messaging (IM) and some virtual private networks (VPNs).

More information at: http://heartbleed.com/

Notes

HTTPS

Notes

HTTP + SSL/TLS = HTTPS

Notes

Hypertext Transfer Protocol Secure

The main idea of HTTPS is to create a secure channel over an insecure network.

HTTPS URLs begin with https:// and use port 443 by default, whereas HTTP URLs begin with http:// and use port 80 by default.

HTTPS encrypts and decrypts user page requests as well as the pages that are returned by the web server. The use of HTTPS protects against eavesdropping and man-in-the-middle attacks:

Notes

HTTPS: The Big Picture

Notes

No Excuse Not To Use HTTPS!





Notes

Authentication

Notes

Agenda

  • Authentication Factors
  • Two-Factor Authentication
  • Weak Authentication
  • Strong Authentication

Notes

Authentication

Authentication is the mechanism whereby systems may securely identify their users.

Authentication systems provide an answers to the questions:

  • Who is the user?
  • Is the user really who he/she represents himself to be?

Authentication systems depend on some unique bit of information known only to the individual being authenticated and the authentication system: a shared secret.

In order to verify the identity of a user, the authenticating system typically challenges the user to provide his unique information.

If the authenticating system can verify that the shared secret was presented correctly, the user is considered authenticated.

Notes

Authentication Factors

The ways in which someone may be authenticated fall into three categories, based on what are known as the factors of authentication: something the user knows, something the user has, and something the user is.

Each authentication factor covers a range of elements used to authenticate or verify a person's identity.

The three classes are:

  • the ownership/possession factors: something the user has;
  • the knowledge factors: something the user knows;
  • the inherence factors: something the user is or does.

Notes

Possession Factors

Something the user has.

Security Tokens

Dallas iButton

Notes

More Possession Factors

Non exhaustive list:

  • Cell Phones
  • Connected tokens
  • Magnetic stripe cards
  • Software tokens
  • USB tokens
  • Wireless

Notes

Knowledge Factors

Something the user knows.

Knowledge factors is the most common form of authentication used. In this form user is required to prove the knowledge of a secret in order to authenticate.

  • Challenge Question
  • Password
  • Pass Phrase
  • Pattern (on Android devices for instance)
  • Personal Identification Number (PIN)

Notes

Inherence Factors

Something the user is.

  • Fingerprint
  • Retinal Pattern
  • DNA sequence
  • Signature
  • Face
  • Voice

Notes

Two-Factor Authentication

Notes

Two-Factor Authentication

Definition

Multi-factor authentication is an approach to authentication which requires the presentation of two or more of the three authentication factors: a knowledge factor ("something the user knows"), a possession factor ("something the user has"), and an inherence factor ("something the user is"). (Wikipedia)


Two-factor authentication is not a new concept, having been used throughout history. When a bank customer visits a local automated teller machine (ATM), one authentication factor is the physical ATM card the customer slides into the machine ("something the user has"). The second factor is the PIN the customer enters through the keypad ("something the user knows").

Notes

Two-Factor Authentication Process


Notes

Examples

Amazon Web Services: AWS Multi-Factor Authentication

Dropbox: Two-Factor Verification

Facebook: Login approvals

Google Accounts: 2-step verification/Google Authenticator

Microsoft/Hotmail: Microsoft account Security Code

Paypal/eBay: Security Key

Notes

Weak Authentication

Notes

Weak Authentication

Weak authentication offers authentication without relying on trusted third parties.

Authentication with passwords is weak.

Examples

  • Passwords
  • Challenge Questions
  • PIN

And generally speaking, everything that uses one authentication factor.

Notes

On Passwords


Notes

I Have Been Pwned?


>> haveibeenpwned.com <<

Notes

Strong Authentication

Notes

Strong Authentication

Techniques that permit entities to provide evidence that they know a particular secret without revealing the secret.

It is a system of verifying user and network server identities on an unprotected network in which the parties must demonstrate knowledge of a "secret" rather than transmit a password.

Typically the verification is done via a trusted third-party authentication service using conventional cryptography.

Strong authentication is not necessarily multifactor authentication. For instance, soliciting multiple answers to challenge questions may be considered strong authentication but, unless the process also retrieves something you have or something you are, it would not be considered multi-factor authentication.

Notes

Authentication Mechanisms

Notes

Authentication answers the following question:

Are They Really Who They Say They Are?

Notes

Agenda

  • HTTP Basic
  • HTTP Token
  • HTTP Digest
  • Form Based
  • Web Services Security
  • OpenID
  • OpenID Connect
  • Other Authentication Mechanisms

Notes

HTTP Basic Authentication

Notes

HTTP Basic Authentication

The oldest and most common format for web authentication.

Requests are authenticated in the form of the user’s username and password:

https://username:password@www.example.org/

Low security, but can be reinforced through the use of SSL/TLS.

Users can disable API access from third-party apps at any time by changing their username or password.

HTTP Basic has a big disadvantage in that it's implemented entirely by the browser, and can't be customized for each site.

Notes

HTTP Basic - Server

When the server wants the user agent to authenticate itself towards the server, it can send a request for authentication.

This request should be sent using the HTTP 401 Unauthorized response code containing a WWW-Authenticate HTTP header:

WWW-Authenticate: Basic realm="insert realm"


Q: What does "realm" standfor?

A: http://en.wikipedia.org/wiki/Realm_(disambiguation)

Notes

HTTP Basic - Client

When the client wants to send the server authentication credentials it may use the Authorization header:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=

The Authorization header is constructed as follows:

  • username and password are combined into a string username:password;
  • the resulting string literal is then encoded using Base64;
  • the authorization method and a space i.e. "Basic " is then put before the encoded string.

Notes

Apache And The .htaccess File

Apache can be configured through a .htaccess file that allows to:

  • restrict access to a directory or a file;
  • rewrite URLs;
  • display custom error pages.

Example

AuthUserFile /path/to/.htpasswd
AuthName "Restricted Area"
AuthType Basic
require valid-user

Add username/password using the following command:

$ htpasswd -c .htpasswd username

Notes

HTTP Token Authentication

Notes

HTTP Token Authentication

Requests are authenticated through a token.

Each user possesses a unique token, retrievable on that user’s settings page. Rather than entering username/password information, users just key in their token. Most of the time, this token will be passed in the query string of an URL:

http://example.org/?token=3dZR23REFERGfe

But you can also use the Authorization header:

Authorization: Token token="3dZR23REFERGfe"

Low security, but requires a more active role from the user. Security can also be reinforced through SSL/TLS. It can be useful when you need to secure a private API, because it is really easy to implement such a mechanism.

Notes

HTTP Digest Authentication

Notes

HTTP Digest Authentication

HTTP Digest authentication (RFC 2069, and RFC 2617) encrypts the password using a one-way hash so it's impossible to reverse-engineer even if SSL is not used.

It is an application of MD5 cryptographic hashing with usage of nonce values to prevent replay attacks.

However, it still must be implemented by the browser and can't be designed into a nice UI.

Notes

The HTTP Digest Dance (1/2)

A client requests a page:

GET /skynet.html HTTP/1.0
Host: localhost

The server responds with the 401 Unauthorized response code, providing the authentication realm and a randomly-generated, single-use value called a nonce:

HTTP/1.0 401 Unauthorized
Server: HTTPd/0.9
Date: Sat, 19 Apr 2011 20:11:00 GMT
WWW-Authenticate: Digest realm="a realm",
                         qop="auth,auth-int",
                         nonce="dcd90f0e8b11d0f600bfb0c093",
                         opaque="5cccebaf9f0171e9517f40e41"
...

At this point, the browser will present the authentication realm to the user and prompt for a username and password.

Notes

The HTTP Digest Dance (2/2)

Once a username and password have been supplied, the client re-sends the same request but adds an authentication header that includes the response code:

GET /skynet.html HTTP/1.0
Host: localhost
Authorization: Digest username="sarah",
                      realm="a realm",
                      nonce="dcd90f0e8b11d0f600bfb0c093",
                      uri="/skynet.html",
                      qop=auth,
                      nc=00000001,
                      cnonce="0a4f113b",
                      response="6629ae49393a05397450974ef1",
                      opaque="5cccebaf9f0171e9517f40e41"

The server accepts the authentication and the page is returned:

HTTP/1.0 200 OK
...

Notes

The "response" Value

The response value is calculated in three steps:

  • The MD5 hash of the combined username, realm and password is calculated. The result is referred to as HA1;
  • The MD5 hash of the combined method and URI is calculated, e.g. of GET and /skynet.html. The result is referred to as HA2;
  • The MD5 hash of the combined HA1 result, server nonce (nonce), request counter (nc), client nonce (cnonce), quality of protection code (qop) and HA2 result is calculated. The result is the response value provided by the client.

Since the server has the same information as the client, the response can be checked by performing the same calculation.

Notes

HTTP Digest Authentication In Picture


Notes

Form Based Authentication

Notes

Form Based Authentication

It refers to the notion of a user being presented with an editable form to fill in and submit in order to log in to some system or service.

As a user, you visit a web page that prompts you for a username and password. If authentication is successful, then under the covers you are granted a unique cookie, which your web browser sends with each subsequent request.

It just looks like you logged in and now the site works, but under the covers it is quite different from Basic.

Credentials are sent in plaintext if you don't rely on SSL to create an encrypted tunnel between the client and server.

Notes

The Form Authentication Flow


Source: Single Sign On (SSO) for cross-domain ASP.NET applications.

Notes

Web Services Security

Notes

Web Services Security

Web Services SEcurity (WSSE) also known as WSS or WS-Security is a family of open security specifications for web services, specifically SOAP web services.

Authentication can be done using security tokens.

WS-Security allows you to use any security token you like to use. There are two different options:

  • username/password authentication also known as WSSE Username Token;
  • binary authentication tokens, also know as WSSE Binary Token in the form of Kerberos tickets or X.509 certificates;

In addition, custom binary security tokens can be applied.

Notes

WSSE Username Token

The Username Token algorithm is not SOAP-specific.

The benefits of WSSE Username Token are:

  • Username / Password encryption;
  • Safe guarding against replay attacks;
  • No web server configuration required.

Notes

WSSE Username Token

The client requests a page:

GET /somewhere HTTP/1.1

The server returns a 401 Unauthorized status code:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: WSSE realm="foo", profile="UsernameToken"

The client sends the same request with his authentication credentials:

Authorization: WSSE profile="UsernameToken"
X-WSSE: UsernameToken Username="bob",
        PasswordDigest="quR/EWLAV4xLf9Zqyw4pDmfV9OY=",
        Nonce="d36e316282959a9ed4c89851497a717f",
        Created="2003-12-15T14:43:07Z"

The application looks in the X-WSSE: header for the actual authentication credentials, and recreates the steps the client took in order to verify that the client knows his password.

Notes

Notes

OpenID

OpenID is a safe, faster, and easier way to log in to web sites.

It is an open standard that allows users to be authenticated by certain co-operating sites (known as Relying Parties or RP) using a third party service.

OpenID was created in the summer of 2005 by an open source community trying to solve a problem that was not easily solved by other existing identity technologies.

Users may create accounts with their preferred OpenID identity providers, and then use those accounts as the basis for signing on to any website which accepts OpenID authentication.

The OpenID protocol does not rely on a central authority to authenticate a user's identity. OpenID authentication is now used and provided by several large websites.

Providers include Google, Yahoo!, PayPal, BBC, MySpace, Steam, etc.

Notes

In-Depth With OpenID

An end-user is the entity that wants to assert a particular identity.

A Relying Party (RP) is a web site or application that wants to verify the end-user's identifier.

An identity provider, or OpenID Provider (OP) is a service that specializes in registering OpenID URLs or eXtensible Resource Identifiers (XRIs).

OpenID enables an end-user to communicate with a relying party. This communication is done through the exchange of an identifier or OpenID, which is the URL or XRI chosen by the end-user to name the end-user's identity.

An Identity provider provides the OpenID authentication.

eXtensible Identifier Resources are a new form of Internet identifier designed specifically for cross-domain digital identity.

Notes

OpenID Overview



Source: OpenID and Rails: Authentication 2.0.

Notes

The OpenID Flow

Assuming a user wants to access his account on example.com.

The application example.com (the Relying Party) asks the user for his OpenID.

User enters his OpenID.

Then, example.com redirects the user to his OpenID provider.

User authenticates himself to the OpenID provider.

OpenID provider redirects the user back to example.com.

Finally, example.com allows the user to access his account.

Notes

The OpenID Flow

Source: OpenID and Rails: Authentication 2.0.

Notes

Why Should You Use OpenID?

Faster And Easier To Sign Up

An OpenID is a way of identifying yourself no matter which web site you visit. It's like a driver's license for the Internet.

Faster And Easier To Sign In

You only have to remember one username and one password. You might already use one username and one password online, but OpenID lets you do this in a secure way. That's because you only give your password to your OpenID provider, and then your provider tells the websites you're visiting that you are who you say you are.

Closer To A Unified Web Identity

Once you establish yourself as the person who uses a particular OpenID, whenever someone sees your OpenID in use, anywhere on the Internet, they will know that it's you.

Notes

Unfortunately,
Not Used Enough :-(

Notes

OpenID Connect

Built on-top of OAuth 2.0 protocol (April 2015).

More on this later!

https://openid.net/connect/

Notes

Other Authentication Mechanisms

Notes

Kerberos

Kerberos is a secure method for authenticating a request for a service in a computer network.

Kerberos protocol messages are protected against eavesdropping and replay attacks. It builds on symmetric key cryptography and requires a trusted third party.

Kerberos lets a user request an encrypted ticket from an authentication process that can then be used to request a particular service from a server. The user's password does not have to pass through the network.

When the Kerberos server is down, no one can log in.

Notes

How Does Kerberos Work? (1/2)

Suppose you want to access a server on another computer. You know that this server requires a Kerberos "ticket" before it will honor your request.

Notes

How Does Kerberos Work? (2/2)

To get your ticket, you first request authentication from the Authentication Server (AS).

The Authentication Server creates a session key basing it on your password and a random value that represents the requested service. The session key is a ticket-granting ticket.

You next send your ticket-granting ticket to a Ticket Granting Server (TGS). The TGS returns the ticket that can be sent to the server for the requested service.

The service either rejects the ticket or accepts it and performs the service.

Because the ticket you received from the TGS is time-stamped, it allows you to make additional requests using the same ticket within a certain time period without having to be reauthenticated.

Notes

Remote Authentication Dial-In User Service (RADIUS)

A networking protocol that provides centralized Authentication, Authorization, and Accounting (AAA) management for computers to connect and use a network service. RADIUS is a client/server protocol that runs in the application layer, using UDP as transport. It is described in RFC 2865.

In RADIUS, authentication and authorization are coupled together. If the username is found and the password is correct, the RADIUS server returns an Access-Accept response, including a list of attribute-value pairs that describe the parameters to be used for this session.

Notes

API Security Recommendations

Notes

Use API Keys For Non-Sensitive Data

If you have an open API, one that exposes data you’d make public on the Internet anyway, consider issuing non-sensitive API keys.

These are easy to manipulate and still give you a way to identify users.

Armed with an API key, you have the option of establishing a quota for your API, or at least monitoring usage by user.

Example

The Yahoo Maps Geocoding API issues API keys so it can track its users and establish a quota, but the data that it returns is not sensitive so it’s not critical to keep the key secret.

Notes

Use Username/Password Auth. For APIs Based On Web Sites

If your API is based on a web site, support username/password authentication. That way, users can access your site using the API the same way that they access it using their web browser.

However, if you do this, you may want to avoid session-based authentication, especially if you want people to be able to write API clients in lots of environments.

Example

It is very simple to use curl for instance, to grab some data from the Twitter API because it uses HTTP Basic authentication.

It is a lot more complex if I instead have to call login and extract a session ID from some cookie or header, and then pass that to the real API call I want to make.

Notes

Use SSL For Everything Sensitive

Unless your API has only open and non-sensitive data, support SSL, and consider even enforcing it (that is, redirect any API traffic on the non-SSL port to the SSL port).

It makes other authentication schemes more secure, and keeps your user’s private API data from prying eyes.

Notes

And ...

  1. Use nonce tokens (randomly-generated, single-use values) to avoid replay attacks;

  2. Rely on request signing to ensure data integrity;

  3. Use strong methods to generate random values.

Notes

Authorization

Notes

What Is Authorization?

Authorization is the process of giving someone permission to do or have something.

In multi-user computer systems, a system administrator defines for the system which users are allowed to access to the system and what privileges of use.

It is the function of specifying access rights to resources. It is related to access control in information security, and computer security.

Authorization is preceded by Authentication.

Notes

Authentication vs Authorization

Authentication is the mechanism whereby systems may securely identify their users.

Authentication systems provide answers to the following questions:

  • Who is the user?
  • Is the user really who he/she represents himself to be?

Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system.

Authorization systems provide answers to the following questions:

  • Is user X authorized to access resource R?
  • Is user X authorized to perform operation O?
  • Is user X authorized to perform operation O on resource R?

Notes

Authentication vs Authorization

Source: http://people.duke.edu/~rob/kerberos/authvauth.html

Notes

Notes

OAuth

OAuth is an open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications. It is an authorization framework that enables a third-party application to obtain limited access to an HTTP service.

For Consumer Developers

OAuth is a simple way to publish and interact with protected data. It is also a safer and more secure way for people to give you access. We've kept it simple to save you time.

For Service Provider Developers

If you are storing protected data on your users' behalf, they should not be spreading their passwords around the web to get access to it. Use OAuth to give your users access to their data while protecting their account credentials.

Notes

History

The idea came from Twitter in November 2006.

A discussion group was created in April 2007, including some Google folks. The OAuth Core 1.0 specification was declared final in December 2007.

Version 1.0 revision A of the OAuth Core protocol was issued to address a session fixation security flaw in June 2009. In the meantime, Twitter released a delegated user authentication solution, called Sign-In With Twitter.

In April 2010, the OAuth 1.0 Protocol was published as an informational RFC 5849. It replaces the OAuth Core 1.0 Revision A specification.

Since August 31, 2010, all third party Twitter applications have been required to use OAuth.

OAuth 2.0, the next evolution of the OAuth protocol, which is not backward compatible with OAuth 1.0, was expected by the end of 2010. However, it was published as RFC 6749 in October 2012.

Notes

The OAuth 2.0 Controversy

In comparing OAuth 2.0 with 1.0, Eran Hammer (lead author for the OAuth 2.0 project) points out that it has become "more complex, less interoperable, less useful, more incomplete, and most importantly, less secure".

In July 2012, he resigned his role of lead author, and removed his name from the specification. Some people did the same, and Dick Hardt took over the editor role to publish the RFC.

OAuth 2.0 doesn't support signature, encryption, channel binding, or client verification. It relies completely on SSL for some degree of confidentiality and server authentication. OAuth 2.0 has had numerous security flaws exposed in implementations. The protocol itself has been described as inherently insecure by security experts and a primary contributor to the specification stated that implementation mistakes are almost inevitable.

Must Read: OAuth 2.0 and the Road to Hell.

Notes

OpenID vs OAuth

OAuth lets you authorize one web application, the consumer, to access your data from another web application, the provider.

With OAuth, you still need to log into the provider. It could be a standard username/password login, or it could well be via OpenID.

OpenID gives you one login for multiple web applications. There is no suggestion of two web applications sharing your data.

But...

OpenID Connect has been released last year (April 2015)!
And it is a game-changer.

Notes

OpenID Connect

Server Flow

  1. Create an anti-forgery state token
  2. Send an authentication request to provider (e.g., Google)
  3. Confirm the anti-forgery state token
  4. Exchange code for access token and ID token (JSON Web Token)
  5. Obtain user information from the ID token
  6. Authenticate the user

Notes

JWT & ID Token - Google


{
    "at_hash": "HK6E_P6Dh8Y93mRNtsDB1Q",
    "aud": "1234987819200.apps.googleusercontent.com",
    "azp": "1234987819200.apps.googleusercontent.com",
    "email": "jsmith@example.com",
    "email_verified": "true",
    "exp": 1353604926,
    "hd": "example.com",
    "iat": 1353601026,
    "iss": "accounts.google.com",
    "sub": "10769150350006150715113082367"
}

Source: https://developers.google.com/identity/protocols/OpenIDConnect

Notes

OAuth 1.0a

Notes

OAuth 1.0a - Terminology

User — a user who has an account on the Service Provider,and tries to use the Consumer.

Service Provider — service that provides an API that uses OAuth (api.example.org).

Consumer — an application or web service that wants to use functions of the Service Provider through OAuth (your.application.org). This application must be known by the Service Provider, and owns two keys: a Consumer Key and a Consumer Secret Key.

Request Token — a value that a Consumer uses to be authorized by the Service Provider. After completing authorization, it is exchanged for an Access Token.

Access Token — a value that contains a key for the Consumer to access the resource of the Service Provider.

Notes

OAuth 1.0a - Authentication Process

In A Nutshell

  1. You ask for a Request Token and specify your callback;
  2. You direct the user to the Authorization Screen;
  3. You receive a token at the URL you have specified;
  4. You ask for an Access Token;
  5. You make API calls!




Easy, isn't it?

Notes

OAuth 1.0a - Authentication Process

Notes

Getting A Request Token (1/2)




GET https://api.example.org/oauth/v1/request_token?
    oauth_callback=http://your.application.org/oauth&
    oauth_consumer_key=WEhGuJZWUasHg&
    oauth_nonce=zSs4RFI7lakpADpSsv&
    oauth_signature=wz9+ZO5OLUnTors7HlyaKat1Mo0=&
    oauth_signature_method=HMAC-SHA1&
    oauth_timestamp=1330442419&
    oauth_version=1.0

Notes

Getting A Request Token (2/2)

oauth_callback is the URL of the Consumer that will be redirected after the Service Provider has completed authentication. If the Consumer is not a web application and has no redirection URL, the lower-case Out Of Band (oob) is used as value.

oauth_consumer_key is the Consumer Key provided to you by the Service Provider when you registered your application with it.

oauth_nonce is a random string (Number Once).

oauth_signature is the signature value for the request.

oauth_signature_method is the signature method that you use to sign the request, such as PLAINTEXT, HMAC-SHA1 or RSA-SHA1.

oauth_timestamp is the current timestamp of the request.

oauth_version is always 1.0.

Notes

Generating oauth_signature (1/2)

1. Collect all request parameters

All parameters related to OAuth which start with oauth_ except for oauth_signature should be collected.

If parameters are used in the POST body, they should also be collected.

2. Normalize the parameters

Sort all parameters in alphabetical order and apply URL encoding to each key and value (RFC 3986).

List the results of URL encoding as <key>=<value> format and insert & between each pair.

Apply URL encoding to the entire result again.

Notes

Generating oauth_signature (2/2)

3. Create a Signature Base String

Combine the HTTP method name (GET or POST), the HTTP URL address called by the Consumer (except for parameters), and the normalized parameters by using &. The combination becomes:

[GET|POST] + & + [URL string without params] + & + [Normalized Parameters]"

4. Generating a Key

Encrypt the string generated at stage 3 using the Consumer Secret Key.

This Consumer Secret Key is obtained when the Consumer has registered with the Service Provider. Using the encryption method, such as HMAC-SHA1, generates the final oauth_signature.

Notes

Request Token Response



oauth_token=z4ezdgj&
oauth_token_secret=47ba47e0048b7f2105db67df18ffd24bd072688a&
oauth_expires_in=3600&
oauth_callback_confirmed=true


The oauth_token value is now your Request Token.

The oauth_token_secret will be used for signing your request in order to get an Access Token.

The oauth_callback_confirmed value just gives you confirmation that the oauth_callback parameter you provided has been recognized.

Notes

The Authorization Step

Now that you have a Request Token, you can build the URL to authorize the user:

https://api.example.org/oauth/v1/authorize?oauth_token=z4ezdgj

It is your job to send the user to this page. It asks the user whether he wants to authorize your application to access his private data:

When the user authorizes your application, he will be either sent back to the oauth_callback specified in the previous step, or presented with a PIN code (Out Of Band).

At this time, the Service Provider passes new oauth_token and oauth_verifier to the Consumer. These values are used to request the Access Token.

Notes

Requesting An Access Token

GET https://api.example.org/oauth/v1/access_token?
    oauth_consumer_key=WEhGuJZWUasHg&
    oauth_nonce=8B9SpFé&
    oauth_signature=5f78507cf0acc38890cf5aa69721&
    oauth_signature_method=HMAC-SHA1&
    oauth_timestamp=1440442419&
    oauth_token=z4ezdgj&
    oauth_version=1.0&
    oauth_verifier=svmhhd

oauth_signature is now signed with the signing key obtained by concatenating the Consumer Secret Key and oauth_token_secret value separated by an & character:

url_escape(consumer_secret_key)&url_escape(oauth_token_secret)

Generating the oauth_signature value follows the same steps described before, except that the signing key is different !

The oauth_verifier value has been passed through oauth_callback when requesting the Request Token.

Notes

Access Token Response



oauth_token=A%3DqVDHXBE8bRwPoXV9eq4vAtNX_8KVca9&
oauth_token_secret=c5a9684d3a3aa22aa051308987219efb8d6982fc&
oauth_expires_in=3600



The oauth_token value is now your Access Token.

The oauth_token_secret will be used for signing all requests on behalf of the user.

Notes

Notes

Not Yet!
(Yeah, it hurts my eyes too...)

Notes

Using An Access Token

Create an HTTP Authorization header with all parameters + the oauth_signature generated as usual:

GET http://api.example.org/users/me
Authorization: OAuth
    realm="example.org",
    oauth_consumer_key="WEhGuJZWUasHg",
    oauth_nonce="248292331",
    oauth_signature_method="HMAC-SHA1",
    oauth_timestamp="1559450170",
    oauth_token="A%3DqVDHXBE8bRwPoXV9eq4vAtNX_8KVca9",
    oauth_version="1.0",
    oauth_signature="O2AQipLITO0aYHKZc9266RzC94%3D"


You will either get the result you expected or a 401.

Notes

Notes

xAuth

Notes

xAuth

xAuth is still OAuth.

xAuth provides a way for desktop and mobile applications to exchange a username and password for an OAuth access token. Once the Access Token has been retrieved, xAuth-enabled developers should dispose of the login and password corresponding to the user.

xAuth access should be restricted to approved applications only.

It is all about requesting an Access Token directly, without using a Request Token. You have to submit x_auth_* parameters in addition to the conventional oauth_* parameters:

  • x_auth_username the login credential of the user the client is obtaining a token on behalf of;
  • x_auth_password the password credential of the user the client is obtaining a token on behalf of.

Notes

OAuth 2.0

Notes

Roles

OAuth 2.0 defines the following roles of users and applications:

  • Resource Owner: the user;
  • Resource Server: the API;
  • Client Application: the third-party application;
  • Authorization Server: often the same as the API server;

Notes

Prerequisites (1/2)

Before you can begin the OAuth process, you must first register a new application. You usually register basic information such as application name, website, a logo, etc. In addition, you must register a redirect URI to be used for redirecting users to for web server, browser-based, or mobile applications.

Redirect URIs

The authorization server will only redirect users to a registered URI, which helps prevent some attacks (in theory...). Any HTTP redirect URIs must be protected with TLS security, so the service will only redirect to URIs beginning with https://. This prevents tokens from being intercepted during the authorization process.

Notes

Prerequisites (2/2)

Client ID and Secret

After registering your app, you will receive a client ID and a client secret. The client ID is considered public information, and is used to build login URLs, or included in JavaScript source code on a page. The client secret must be kept confidential. If a deployed application cannot keep the secret confidential, such as JavaScript or native apps, then the secret is not used.

Notes

Authorization

The first step of OAuth 2 is to get authorization from the user. For browser-based or mobile apps, this is usually accomplished by displaying an interface provided by the service to the user.

The authorization grant is given to a client application by the resource owner, in cooperation with the authorization server associated with the resource server.

The OAuth 2.0 specification lists different types of authorization grants. Each type has different security characteristics. The most used authorization Grant Types are:

  • Authorization Code
  • Implicit
  • Password
  • Client Credentials

Notes

Authorization Code (1/3)

In your application, the user will perform the following request, by clicking on a button to connect his GitHub account for instance:

GET https://github.com/login/oauth/authorize?
    response_type=code&
    client_id=YOUR_CLIENT_ID&
    redirect_uri=https://example.com/auth&
    scopes=profile

User visits the Authorization Page:

Notes

Scopes

Scopes let you specify exactly which level of access you need.

Scopes limit access for OAuth tokens. They do not grant any additional permission beyond that which the user already has.

The OAuth 2.0 specification does not define any value, it is left up to the implementor.

Scopes should be expressed as a list of space-delimited strings:

scopes=s1 s2 s3

In practice, many people use comma-separators instead:

scopes=s1,s2,s3

Notes

Example: Facebook Permissions



Notes

Authorization Code (2/3)

On success, user is redirected back to your site with auth code:

https://example.com/auth?code=AUTH_CODE_HERE

On error, user is redirected back to your site with error code:

https://example.com/auth?error=access_denied

Notes

Authorization Code (3/3)

Server exchanges auth code for an Access Token:

POST https://github.com/login/oauth/access_token

POST body:

grant_type=authorization_code&
code=CODE_FROM_QUERY_STRING&
redirect_uri=REDIRECT_URI&
client_id=YOUR_CLIENT_ID&
client_secret=YOUR_CLIENT_SECRET

Response:

{
    "access_token":"e72e16c7e42f292c6912e7710c838347ae178b4a",
    "token_type":"bearer"
}

// Or if an error has occured:
{ "error": "invalid_request" }

Notes

Example: Facebook's OAuth Flow


Notes

Potential Security Issues (1/2)

Client account hijacking by connecting attacker's provider account (CSRF attack)

In step 2/3, provider returns code by redirecting the user-agent to:

https://example.com/auth?code=AUTH_CODE_HERE

In step 3/3, the client must send code along with client credentials and redirect_uri to obtain access_token. If the client implementation doesn't use state parameter to mitigate CSRF, we can easily connect our provider account to the victim's client account.

Notes

Potential Security Issues (1/2)

Client account hijacking by connecting attacker's provider account (CSRF attack)

Remediation

Before sending user to the provider generate a random nonce and save it in cookies or session. When user is back make sure state you received is equal one from cookies.

The Most Common OAuth2 Vulnerability

Notes

Potential Security Issues (2/2)

Account hijacking by leaking authorization code

OAuth documentation makes it clear that providers must check the first redirect_uri is equal redirect_uri the client uses to obtain an access_token.

Find a leaking page on the client's domain, insert cross domain image or a link to your website, then use this page as redirect_uri. When your victim will load crafted URL it will send him to leaking_page?code=CODE and victim's user-agent will expose the code in the Referrer header.

Remediation

Flexible redirect_uri is a bad practice. But if you need it, store redirect_uri for every code you issue and verify it on access_token creation.

How I hacked Github again.

Notes

More OAuth issues in this
OAuth Security Cheatsheet

Notes

Implicit Grant (1/2)

In your application, the user will perform the following request, by clicking on a button to connect his GitHub account for instance:

GET https://github.com/login/oauth/authorize?
    response_type=token&
    client_id=YOUR_CLIENT_ID&
    redirect_uri=https://example.com/auth&
    scopes=profile

Look at the response_type, it is token now.

User visits the Authorization Page:

Notes

Implicit Grant (2/2)

On success, user is redirected back to your site with the access token in the fragment:

https://example.com/auth#token=ACCESS_TOKEN

Token is only available to the browser since it is in the fragment.

On error, user is redirected back to your site with error code:

https://example.com/auth#error=access_denied

Usage

It is useful for Browser-Based applications. No server side code needed, the client secret is not used, and browser makes API requests directly.

Notes

Password Grant

Password grant is only appropriate for trusted clients, most likely first-party applications only. It should be used for your services only.

POST https://github.com/oauth/token

POST body:

grant_type=password&
username=USERNAME&
password=PASSWORD&
client_id=YOUR_CLIENT_SECRET&
client_secret=YOUR_CLIENT_SECRET

Response:

{
    "access_token": "e72e16c7e42f292c6912e7710c838347ae178b4a",
    "token_type": "bearer",
    "expires_in": 3600,
    "refresh_token": "el2132eEdzFEfrfdc"
}

Notes

Client Credentials Grant

POST https://github.com/oauth/token

POST body:

grant_type=client_credentials&
client_id=YOUR_CLIENT_ID&
client_secret=YOUR_CLIENT_SECRET

Response:

{
    "access_token": "e72e16c7e42f292c6912e7710c838347ae178b4a",
    "token_type": "bearer",
    "expires_in": 3600,
    "refresh_token": "el2132eEdzFEfrfdc"
}

Usage

Application access.

Notes

So You Have An Access Token, Now What?

Notes

Using The Access Token

The access token allows you to make requests to the API on a behalf of a user:

GET https://api.github.com/users?access_token=...

The access token can be in the query string as well as in an HTTP header:

GET https://api.github.com/users
Authorization: Bearer ...

Notes

Refresh Token

It is all about getting a new Access Token using a Refresh Token.

POST https://github.com/oauth/token

POST body:

grant_type=refresh_token&
refresh_token=el2132eEdzFEfrfdc&
client_id=YOUR_CLIENT_ID&
client_secret=YOUR_CLIENT_SECRET

Response:

{
    "access_token": "ERfegrfEZGrbosfef2E3Rfezfoefezf",
    "expires_in": 3600,
    "refresh_token": "el2132eEdzFEfrfdc"
}

Notes

Differences From OAuth 1.0 (1/2)

Security

OAuth 2.0 replaces signatures with requiring HTTPS for all communications between browsers, clients and the API. It is easier for developers, but it is less secure in its essence. OAuth 1.0 is more secure than OAuth 2.0 as all requests are signed.

User Experience

OAuth 2.0 supports a better user experience for native applications, and supports extending the protocol to provide compatibility with future device requirements. OAuth 1.0 is not good at offering a nice user experience for mobile applications, that is why xAuth has been created.

Notes

Differences From OAuth 1.0 (2/2)

Scalability

OAuth 2 supports the separation of the roles of obtaining user authorization and handling API calls. Larger providers needing this scalability are free to implement it as such, and smaller providers can use the same server for both roles if they wish.

Notes

Final Thoughts




Notes

Notes

Fork me on GitHub