Securing ASP.NET Web

Dominick Baier hp://leastprivilege.com @leastprivilege think mobile! Dominick Baier

• Security consultant at thinktecture • Focus on – security in distributed applicaons – identy management – access control – Windows/.NET security – mobile app security

• Microso MVP for Developer Security • ASP.NET Web API Advisor • [email protected] • hp://leastprivilege.com think mobile! @leastprivilege 2 Agenda

• HTTP security & SSL • ASP.NET Web API v2 architecture • Applicaon scenarios

• (Token-based) authencaon • Authorizaon • CSRF • CORS • OAuth2

@leastprivilege 3 ASP.NET Web API: the big picture

Host

ASP.NET Web API HTTPS

@leastprivilege 4 Developers & SSL

@leastprivilege 5 Security model for HTTP-based services • Simple model – HTTP + content + SSL • Whenever authencaon is required – Status code of 401 indicates unauthorized – WWW-Authencate response header indicates preferred authencaon method

Status Code: 401 unauthorized

WWW-Authencate: Scheme realm="myapp"

@leastprivilege 6 Authencaon for HTTP-based services • Credenals transmied (typically) via Authorizaon header • e.g. Basic authencaon, access tokens… • somemes other means (query string, cookie…)

GET /service/resource

Authorizaon: scheme credenal

@leastprivilege 7 The Web API v2 Security Pipeline

Host Web API

OWIN/ MessageHandler Authencaon Authorizaon Katana (global/per-route) Filter Filter

Host/Framework Web API cross-cung Web API specific independent concerns, Authorizaon concerns, e.g. CORS authencaon e.g. authencaon

hp://www.asp.net/vnext/overview/owin-and-katana/an-overview-of-project-katana

@leastprivilege 8 Katana Authencaon Middleware

public class Startup { public void Configuration(IAppBuilder app) { app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Cookies", // more options });

app.UseGoogleAuthentication(new GoogleAuthenticationOptions { AuthenticationType = "", // more options });

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { AuthenticationType = "Bearer" // more options }); } }

@leastprivilege 9 Authencaon filter

WebApiConfig.cs

config.Filters.Add(new HostAuthenticationFilter("Bearer"));

[HostAuthentication("Bearer")] public class TestController : ApiController { [HostAuthentication("Google")] public HttpResponseMessage Get() { }

[OverrideAuthentication] [HostAuthentication("Cookies")] public HttpResponseMessage Delete() { } }

@leastprivilege 10 Authorizaon filter

• Determines if a resource needs authencaon – [AllowAnonymous] to skip authorizaon for an acon – emits the 401 status code, if unsuccessful

// minimum requirement is successful authentication [Authorize] public DataController : ApiController { [AllowAnonymous] public Data Get() { … }

[Authorize(Role = "Foo")] public HttpResponseMessage Delete(int id) { … } }

@leastprivilege 11 Custom authorizaon filter

• Derive from AuthorizeAribute

public class PremiumUsersOnlyAttribute : AuthorizeAttribute { protected override bool IsAuthorized(HttpActionContext context) { var principal = actionContext .ControllerContext .RequestContext .Principal as ClaimsPrincipal;

// custom authorization logic }

protected override void HandleUnauthorizedRequest( HttpActionContext actionContext) { // custom response } }

@leastprivilege 12 Resource/Acon-based Authorizaon

• Get rid of the ght coupling between applicaon code and security requirements

[ResourceActionAuthorize("Update", "Customer")] public IHttpActionResult Put(Customer customer) { ... }

hp://thinktecture.github.com/Thinktecture.IdentyModel/

@leastprivilege 13 Applicaon Styles

• Same-Domain & Cross-Domain – classic vs modern

• Same Domain – Browser based applicaons – Web APIs and clients live in the same domain • style callbacks from server-rendered pages • SPA applicaons (like the built-in template in VS2012) – Oen cookie based security • potenal CSRF problems

@leastprivilege 14 Same-Domain Scenario

• Web APIs inherit security sengs of web host – e.g. cookies, Windows authencaon, client certs...

Application

Login Web APIs Pages

$.ajax

@leastprivilege 15 CSRF – The Problem

Login, send authencaon cookie get authencaon cookie

hp://app.com hp://app.com/delete/5

Tab/Process Tab/Process

Browser

@leastprivilege 16 Web API v1 CSRF Protecon

• Part of the SPA template in MVC 4 (Update 2)

Server [ValidateHpAnForgeryToken]

render page & post-back: web call: an-forgery cookie cookie + hidden field cookie + header

Page

@leastprivilege 17 Web API v2 CSRF Protecon

• No cookies allowed anymore…

// Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication();

config.Filters.Add(new HostAuthenticationFilter( OAuthDefaults.AuthenticationType));

WebApiConfig.cs

@leastprivilege 18 Applicaon Styles II

• Cross-Domain – Web APIs and clients live in different domains • nave apps (desktop, mobile) • client side JavaScript code (browser) • Multude of scenarios – shared secret authencaon – CORS restricons for JavaScript-based clients – token-based authencaon • built-in token endpoint • OAuth2 authorizaon server

@leastprivilege 19 Shared Secret Authencaon

• HTTP Basic Authencaon • Shared signature approaches (e.g. hawk)

GET /service/resource

Authorizaon: Basic base64(username:password)

@leastprivilege 20 An-paern!

• The client must store the secret or obtain it from the user (on every request) – storage must be done in clear text (or reversible encrypon) • Server has to validate the secret on every request – high computaonal cost due to brute force protecon

• The probability of accidental exposure of the secret is increased

@leastprivilege 21 Token-based Authencaon

Token Service

request

Web APIs Bob use access token

@leastprivilege 22 OAuth2 (RFC 6749)

• Framework for requesng and using access tokens for – nave clients – web clients – browser-based clients

• OAuth2 introduces the concept of an Authorizaon Server – traffic cop between clients, users and services

@leastprivilege 23 Embedded Authorizaon Server

• e.g. Swap credenal with (long-lived) token

GET /service/token

GET /service/resource

Authorizaon: Bearer

@leastprivilege 24 Embedded Authorizaon Server (Katana View)

OWIN Host

Authorization Server MW User Agent

Bearer MW Application

@leastprivilege 25 Step 1a: Token Request

Resource Server Authorizaon Server

POST /token Authorization: Basic (client_id:secret)

grant_type=password& scope=resource& user_name=owner& password=password&

Resource Owner Client

@leastprivilege 26 Step 1b: Token Response

Resource Server Authorizaon Server

{ "access_token" : "abc", "expires_in" : "3600", "token_type" : "Bearer", "refresh_token" : "xyz" }

Resource Owner Client

@leastprivilege 27 More advanced scenarios

client_id=client1, scope=search read Authorizaon Server

access token

APIs

access token Bob { "iss": "myAuthzServer", "aud": "resources", "exp": 192990121, "sub": "Bob", Scopes: read, write, "client_id": "client1", delete, search… "scope": [ "search", "read" ] }

@leastprivilege 28 JSON Web Token (JWT)

Header { "typ": "JWT", "alg": "HS256" }

Claims { "iss": "http://myIssuer", "exp": "1340819380", "aud": "http://myResource", "sub": "alice",

"client_id": "xyz", "scope": ["read", "search"] }

eyJhbGciOiJub25lIn0.eyJpc3MiOiJqb2UiLA0KICJleHAiOjEzMD.4MTkzODAsDQogImh0dHA6Ly9leGFt

Header Claims Signature

@leastprivilege 29 External Authorizaon Server (Katana View)

Authorizaon Server (1)

User Agent (2) OWIN Host

JWT MW Applicaon

1…n

@leastprivilege 30 AuthorizationServer & IdentityServer v3

hps://github.com/thinktecture/Thinktecture.AuthorizaonServer hps://github.com/thinktecture/Thinktecture.IdentyServer.v3

@leastprivilege 31 Separang user credenals from the client… • Local / mobile / user-agent based clients – Implicit Flow

• Server-based / confidenal clients – Autorizaon Code Flow

@leastprivilege 32 Implicit Flow (Nave / Local Clients)

Resource Owner Client

@leastprivilege 33 Step 1a: Authorizaon Request

Resource Server Authorizaon Server

GET /authorize? client_id=nativeapp& scope=read& redirect_uri=http://localhost/cb& response_type=token& state=123

Resource Owner Client

@leastprivilege 34 Step 1b: Authencaon

@leastprivilege 35 Step 1c: Consent

@leastprivilege 36 Twier Consent

@leastprivilege 37 Evernote Consent

@leastprivilege 38 The Consent Screen is important!

hp://zachholman.com/2011/01/oauth_will_murder_your_children/

@leastprivilege 39 Step 1d: Token Response

Resource Server Authorizaon Server

GET /cb# access_token=abc& expires_in=3600& state=123

Resource Owner Client

@leastprivilege 40 Summary – Implicit Flow

• User enters credenals at the authorizaon server – not at the client • authorizaon server returns (short lived) access token – to reduce exposure of token • Oen combined with OS helper mechanisms – cookie container – nave APIs

@leastprivilege 41 Excursion: CORS (Cross Origin Resource Sharing)

hp://server1/client.htm hp://server2/service

? $.ajax( ... ) Data

@leastprivilege 42 CORS Sample

OPTIONS /service

Access-Control-Request-Method: PUT Origin: hp://server1

$.ajax( ... ) Service Access-Control-Allow-Origin: hp://server1

PUT /service

@leastprivilege 43 CORS in Web API v2

Thinktecture.IdentyModel.Hp.Cors.WebApi

System.Web.Cors

[EnableCors("origin", "headers", "verbs")] public class CustomersController : ApiController { // actions... }

@leastprivilege 44 Authorizaon Code Flow (Server-based Clients)

Web Applicaon Resource Server (Client)

Resource Owner

@leastprivilege 45 Step 1a: Authorizaon Request

Web Applicaon Authorizaon Server (Client)

GET /authorize? client_id=webapp& scope=read& redirect_uri=https://webapp/cb& response_type=code& state=123

Resource Owner

@leastprivilege 46 Step 1d: Authorizaon Response

Web Applicaon Authorizaon Server (Client)

GET /cb? code=xyz& state=123

Resource Owner

@leastprivilege 47 Step 2a: Token Request

Web Applicaon Authorizaon Server (Client)

POST /token Authorization: Basic (client_id:secret)

grant_type=authorization_code& authorization_code=xyz

Resource Owner

@leastprivilege 48 Step 2b: Token Response

Web Applicaon Authorizaon Server (Client)

{ "access_token" : "abc", "expires_in" : "3600", "token_type" : "Bearer", "refresh_token" : "xyz" }

Resource Owner

@leastprivilege 49 Step 3: Resource Access

Web Applicaon Resource Server (Client)

GET /resource

Authorization: Bearer access_token

Resource Owner

@leastprivilege 50 (Step 3: Refreshing the Token)

Client Authorizaon Server

POST /token Authorization: Basic (client_id:secret)

grant_type=refresh_token& refresh_token=xyz

@leastprivilege 51 Refresh Token Management (Flickr)

@leastprivilege 52 Refresh Token Management ()

@leastprivilege 53 Refresh Token Management (Microso Live)

@leastprivilege 54 Summary – Code Flow

• Designed for "confidenal" clients – client can store secret securely – client authencaon and authorizaon based on client identy possible – typically server-based applicaons • Accountability is provided – access token never leaked to the browser • Long-lived access can be implemented

@leastprivilege 55 Summary

• HTTP has a very simple security model • Correct handling of SSL is paramount • Same- vs Cross-Origin applicaons

• Think about CSRF, CORS • Token based (and thus cookie-less) authencaon is the way to go – separate client from API – embedded authorizaon server – full blown authorizaon server (product)

@leastprivilege 56