Slide 1

Slide 1 text

Add the security layer to your (RESTfull) API and serve a distributed web application Marco Loche PHPDay 2014

Slide 2

Slide 2 text

PHP is the language Community gives value

Slide 3

Slide 3 text

1. Introduction

Slide 4

Slide 4 text

Who am I ?

Slide 5

Slide 5 text

About  my  company  

Slide 6

Slide 6 text

eLearning •  Learning Management System – Content management system dedicated to learning management  

Slide 7

Slide 7 text

eLearning Sharable Content Object Reference Model – SCORM compliant content must be transferable on LMS server – SCORM compliant content can comunicate with LMS – SCORM compliant conten must be agnostic about server technology  

Slide 8

Slide 8 text

How to serve content remotly and on different domains keeping control of whoever is using it ?

Slide 9

Slide 9 text

2. Context

Slide 10

Slide 10 text

An open system for browsing, sharing and including resources

Slide 11

Slide 11 text

API era is now

Slide 12

Slide 12 text

REST is the best

Slide 13

Slide 13 text

A matter of consuming resources

Slide 14

Slide 14 text

Uniform  interface   Uniform interface

Slide 15

Slide 15 text

Richardson Model Access through HTTP (RMM level 0) Endpoints of the api are resource representations (RMM level 1) Interact with resources with HTTP Verbs and Content negotiation (RMM level 2) … Hypermedia and the glory (RMM level 3)

Slide 16

Slide 16 text

    Be fluent and transitional

Slide 17

Slide 17 text

REST in Symfony jms/serializer-bundle friendsofsymfony/rest-bundle willdurand/hateoas-bundle nelmio/api-doc-bundle

Slide 18

Slide 18 text

Lesson learned

Slide 19

Slide 19 text

3. Managing origin of distributed client

Slide 20

Slide 20 text

Protecting personal data and identity integrity    

Slide 21

Slide 21 text

 Same Origin Policy

Slide 22

Slide 22 text

Pages of the same origin can manipulate each other's DOM

Slide 23

Slide 23 text

Content loaded from one domain can not interact with content coming from another

Slide 24

Slide 24 text

Extended to other aspects : HTTP Cookies, XMLHttpRequest

Slide 25

Slide 25 text

Defining origin http://tools.ietf.org/html/rfc6454 trusted === {scheme, host, port} not trusted !== {scheme, host, port}

Slide 26

Slide 26 text

So what’s trustworthy? http://www.example.com/index.html http://www.example.com/content/page2.html http://user:[email protected]/api/resource

Slide 27

Slide 27 text

And what’s not? http://www.example.com/index.html http://www.example.com:81/content/page2.html https://www.example.com/content/page2.html http://example.com/content/page2.html http://api.example.com/content/page2.html

Slide 28

Slide 28 text

We need to relax

Slide 29

Slide 29 text

Techniques for relaxing   •  document.domain property •  Cross-document messaging •  JSONP •  CORS  

Slide 30

Slide 30 text

document.domain property http://www.example.com/ document.domain = 'example.com'; http://store.example.com/ document.domain = 'example.com';

Slide 31

Slide 31 text

Cross-document messaging http://www.example.com/ http://store.example.net/ http://example.com/ otherWindow.postMessage("hello there!", "http://example.net"); http://example.net/ window.addEventListener("message",receiveMessage,false); function receiveMessage(event) { if (event.origin !== "http://example.com") // DO STUFF HERE WITH event.data }

Slide 32

Slide 32 text

JSONP

Slide 33

Slide 33 text

JSONP

Slide 34

Slide 34 text

Ok, but we want more! Previous solutions are valid only if you want to be in RMM1 No Verbs No Content Negotiation No Headers for security

Slide 35

Slide 35 text

Cross-Origin Resource Sharing •  W3C Recomandation (16 january 2014) •  Enable true cross domain communication for JavaScript application •  Build on top of the XHR

Slide 36

Slide 36 text

Simple Cross-Origin Request JavaScript Code Browser API Server xhr.send() Actual request Actual response onload / onerror

Slide 37

Slide 37 text

Simple Request Method HEAD GET POST  

Slide 38

Slide 38 text

Simple request header Accept Accept-Language Content-Type Content-Language

Slide 39

Slide 39 text

Simple response header Cache-Control Content-Language Content-Type Expires Last-Modified Pragma

Slide 40

Slide 40 text

GET /resource HTTP/1.1 Origin: http://www.example.com Host: api.example.com ... HTTP/1.1 200 OK Access-Control-Allow-Origin: http://www.example.com ...

Slide 41

Slide 41 text

Cross-Origin Request with Prefilght JavaScript Code Browser API Server xhr.send() Actual request Actual response onload / onerror Prefligth request Preflight response

Slide 42

Slide 42 text

•  CORS with preflight request are originated by : –  Other HTTP verbs (PUT PATCH DELETE) –  Other Content-Type (Application/Json) –  Custom Headers (Allow-Header : X-AUTH) –  Non simple header expose (Expose-Header) •  Preflight request + actual request

Slide 43

Slide 43 text

OPTIONS /resource HTTP/1.1 Origin: http://www.example.com Access-Control-Request-Method: PUT Access-Control-Request-Headers: X-Custom-Header Host: api.example.com HTTP/1.1 200 OK Access-Control-Allow-Origin: http://www.example.com Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE Access-Control-Allow-Headers: X-Custom-Header Access-Control-Max-Age: 3600 ...

Slide 44

Slide 44 text

PUT /cors HTTP/1.1 Origin: http://www.example.com Host: api.example.com X-Custom-Header: value   HTTP/1.1 200 OK Access-Control-Allow-Origin: http://www.example.com Content-Type: text/html; charset=utf-8

Slide 45

Slide 45 text

Implementation Client side: •  Nicolas Zakas’s Request Object Wrapper •  jQuery Server side: •  NelmioCorsBundle

Slide 46

Slide 46 text

composer.json "require": { "nelmio/cors-bundle": "~1.0"}, }

Slide 47

Slide 47 text

app/config/config.yml nelmio_cors: defaults: allow_credentials: false allow_origin: [*] allow_methods: ['GET','PUT','POST'] expose_headers: [] max_age: 3600 hosts: []

Slide 48

Slide 48 text

app/config/config.yml nelmio_cors: defaults: allow_credentials: false allow_origin: [*] allow_methods: ['GET','PUT','POST'] expose_headers: [] max_age: 3600 hosts: []

Slide 49

Slide 49 text

app/config/config.yml nelmio_cors: defaults: allow_credentials: false allow_origin: [*] allow_methods: ['GET','PUT','POST'] expose_headers: [] max_age: 3600 hosts: []

Slide 50

Slide 50 text

app/config/config.yml nelmio_cors: defaults: allow_credentials: false allow_origin: [*] allow_methods: ['GET','PUT','POST'] expose_headers: [] max_age: 3600 hosts: []

Slide 51

Slide 51 text

[…] paths: '^/api/': allow_origin: ['*'] allow_methods: ['GET','PUT','POST'] '^/api/sensitiveResource': allow_origin:['https://trusted.io']

Slide 52

Slide 52 text

Lesson learned If you want to be RESTfull you have to go with CORS

Slide 53

Slide 53 text

4. Managing  security  of  your   resources  

Slide 54

Slide 54 text

Authentication •  Basic authentication •  Digest authentication •  Token authentication •  API Key •  WSSE •  OpenID

Slide 55

Slide 55 text

Authorization •  Authorization token •  OAuth 1.0a •  OAuth 2

Slide 56

Slide 56 text

API Security in Symfony hwi/HWIOAuthBundle friendsofsymfony/oauth-server-bundle escapestudios/EscapeWSSEAuthenticationBundle

Slide 57

Slide 57 text

HANDS ON

Slide 58

Slide 58 text

https://www.university.edu 0. authentication Web Application Client LMS SCORM 1. API Key https://auth.example.com 2 request authorization https://content.example.com 3 3 send token 4 access resources

Slide 59

Slide 59 text

Custom Authentication Provider

Slide 60

Slide 60 text

app/configu/security.yml security: providers: [...] capturator: id: capturator.security.tokenAuth in_memory: memory: users: authentication-authority: - password: %auth_authority_pwd% - roles: ROLE_AUTH'

Slide 61

Slide 61 text

app/configu/security.yml security: providers: [...] capturator: id: capturator.security.tokenAuth in_memory: memory: users: authentication-authority: - password: %auth_authority_pwd% - roles: 'ROLE_AUTHENTICATION_AUTHORITY'

Slide 62

Slide 62 text

firewalls: capturator_api_licenser: pattern: ^/api/token(.*) anonymous: ~ http_basic: realm: "Secured Authentication Authority Realm" provider: in_memory capturator_api: pattern: ^/api/(.*) capturator: true stateless: true [...] access_control: [...] - { path: ^/api/token(.*), roles: ROLE_AUTH, ip: 192.168.0.1, requires_channel: https }

Slide 63

Slide 63 text

Capturator/CoreBundle/Resources/config/services.xml Capturator\CoreBundle\Security\User\CapturatorUserProvider Capturator\CoreBundle\Security\Service\TokenRetriever [...] [...]

Slide 64

Slide 64 text

Capturator/CoreBundle/Resources/config/services.xml Capturator\CoreBundle\Security\User\CapturatorUserProvider Capturator\CoreBundle\Security\Service\TokenRetriever [...] [...]

Slide 65

Slide 65 text

class CapturatorListener implements ListenerInterface { protected $securityContext; protected $authenticationManager; protected $tokeRetriever; […] public function handle(GetResponseEvent $event) { $request = $event->getRequest(); $requestTokenString = $this->tokeRetriever->retrieve($request); $token = new CapturatorToken(); $token->setUser($requestTokenString); $authToken = $this->authenticationManager->authenticate($token); $this->securityContext->setToken($authToken); } }

Slide 66

Slide 66 text

class CapturatorListener implements ListenerInterface { protected $securityContext; protected $authenticationManager; protected $tokeRetriever; […] public function handle(GetResponseEvent $event) { $request = $event->getRequest(); $requestTokenString = $this->tokeRetriever->retrieve($request); $token = new CapturatorToken(); $token->setUser($requestTokenString); $authToken = $this->authenticationManager->authenticate($token); $this->securityContext->setToken($authToken); } }

Slide 67

Slide 67 text

namespace Capturator\CoreBundle\Security\Service; use Symfony\Component\HttpFoundation\Request; use Capturator\CoreBundle\Exception\AuthenticationException; class TokenRetriever implements TokenRetrieverInterface { public function retrieve(Request $request) { if (!$request->query->has('token') && !$request->headers->has('x-cassys-auth')) { throw new AuthenticationException( ‘Missing required authentication parameter', __CLASS__); } $requestTokenString = $request->query->has('token') ? $request->query->get('token') : $request->headers->get('x-cassys-auth'); return $requestTokenString; } }

Slide 68

Slide 68 text

class CapturatorListener implements ListenerInterface { protected $securityContext; protected $authenticationManager; protected $tokeRetriever; […] public function handle(GetResponseEvent $event) { $request = $event->getRequest(); $requestTokenString = $this->tokeRetriever->retrieve($request); $token = new CapturatorToken(); $token->setUser($requestTokenString); $authToken = $this->authenticationManager->authenticate($token); $this->securityContext->setToken($authToken); } }

Slide 69

Slide 69 text

Capturator/CoreBundle/Security/User/CapturatorUserProvider.php class CapturatorUserProvider implements UserProviderInterface { protected $em; public function __construct(EntityManager $em) { $this->em = $em; } public function loadUserByUsername( $token) [...] public function refreshUser(UserInterface $user ) [...] public function supportsClass($class) { return ($class == "Capturator\CoreBundle\Security\User\CapturatorUser"); } }

Slide 70

Slide 70 text

The SimplePreAuthenticatorInterface interface was introduced in Symfony 2.4.

Slide 71

Slide 71 text

Extendig NelmioCorsBundle Associating Origin and Authorization

Slide 72

Slide 72 text

/Users/marco/Progetti/Cassys-Server/app/config/config.yml capturator_cors: allow_origin_entity: CapturatorCoreBundle:CustomerDomainName defaults: allow_credentials: false expose_headers: [] max_age: 0 hosts: [] paths: '^/api/3/': allow_headers: ['X-Cassys-Auth', 'X-Requested-With', 'Content-Type'] allow_methods: ['POST', 'PUT', 'GET']

Slide 73

Slide 73 text

/Users/marco/Progetti/Cassys-Server/app/config/config.yml capturator_cors: allow_origin_entity: CapturatorCoreBundle:CustomerDomainName defaults: allow_credentials: false expose_headers: [] max_age: 0 hosts: [] paths: '^/api/3/': allow_headers: ['X-Cassys-Auth', 'X-Requested-With', 'Content-Type'] allow_methods: ['POST', 'PUT', 'GET']

Slide 74

Slide 74 text

Capturator/CoreBundle/Resources/config/services.xml Capturator\CorsBundle\Options\CustomerDomainProvider %capturator_cors.map% %capturator_cors.defaults% %capturator_cors.allow_origin_entity%

Slide 75

Slide 75 text

Capturator/CoreBundle/Resources/config/services.xml Capturator\CorsBundle\Options\CustomerDomainProvider %capturator_cors.map% %capturator_cors.defaults% %capturator_cors.allow_origin_entity%

Slide 76

Slide 76 text

Capturator/CorsBundle/Options/CustomerDomainRepositoryInterface.php namespace Capturator\CorsBundle\Options; interface CustomerDomainRepositoryInterface { /** * @param $origin * @return mixed */ public function findOneByOriginDomain( $origin, $token);}

Slide 77

Slide 77 text

CorsBundle/Options/CustomerDomainProvider.php [...]use Nelmio\CorsBundle\Options\ProviderInterface; class CustomerDomainProvider implements ProviderInterface { [...] public function getOptions(Request $request) { [...] $origin = $request->headers->get('Origin'); $token= $request->headers->get('X-CUSTOM-AUTH'); if (!is_null($this->repository->findOneByOriginDomain($origin, $token))) { $options['allow_origin'] = array($origin); $options= array_merge($this->defaults, $options); return $options; } } }

Slide 78

Slide 78 text

CorsBundle/Options/CustomerDomainProvider.php [...]use Nelmio\CorsBundle\Options\ProviderInterface; class CustomerDomainProvider implements ProviderInterface { [...] public function getOptions(Request $request) { [...] $origin = $request->headers->get('Origin'); $token= $request->headers->get('X-CUSTOM-AUTH'); if (!is_null($this->repository->findOneByOriginDomain($origin, $token))) { $options['allow_origin'] = array($origin); $options= array_merge($this->defaults, $options); return $options; } } }

Slide 79

Slide 79 text

5. Conclusion

Slide 80

Slide 80 text

Work done

Slide 81

Slide 81 text

Prefer open protocol

Slide 82

Slide 82 text

Access control

Slide 83

Slide 83 text

References h7p://www.ics.uci.edu/~fielding/pubs/disserta@on/top.htm   h7ps://www.owasp.org/index.php/REST_Security_Cheat_Sheet#Introduc@on   h7p://www.w3.org/TR/cors/   h7p://www.iana.org/assignments/link-­‐rela@ons/   h7ps://www.oasis-­‐open.org/commi7ees/wss/documents/WSS-­‐Username-­‐02-­‐0223-­‐merged.pdf   h7p://oauth.net/   h7p://www.ieP.org/rfc/rfc2617.txt   h7p://www.ieP.org/rfc/rfc5849.txt  (OAuth  1.0a)   h7p://www.ieP.org/rfc/rfc6749.txt  (OAutn  2.0)   h7p://tools.ieP.org/html/dra[-­‐kelly-­‐json-­‐hal-­‐06   h7p://www.w3.org/TR/json-­‐ld/  

Slide 84

Slide 84 text

Readings h7p://en.wikipedia.org/wiki/Cross-­‐origin_resource_sharing   h7ps://code.google.com/p/browsersec/wiki/Part2#Standard_browser_security_features   h7p://www.html5rocks.com/en/tutorials/cors/   h7p://enable-­‐cors.org/   h7p://williamdurand.fr/2012/08/02/rest-­‐apis-­‐with-­‐symfony2-­‐the-­‐right-­‐way/   h7p://welcometothebundle.com/symfony2-­‐rest-­‐api-­‐the-­‐best-­‐2013-­‐way/   h7p://2012.phpday.it/talk/designing-­‐h7p-­‐interfaces-­‐and-­‐resPul-­‐web-­‐services/   h7p://2013.phpday.it/talk/rest-­‐apis-­‐made-­‐easy-­‐with-­‐symfony2/   h7p://www.slideshare.net/dlondero/rest-­‐in-­‐prac@ce-­‐27335543   h7p://edu.williamdurand.fr/web-­‐security-­‐101-­‐slides/#/   h7p://edu.williamdurand.fr/security-­‐slides/#slide1   h7p://friendsofsymfony.github.io/slides/res@ng-­‐with-­‐symfony2.html#/   h7p://symfony.com/doc/current/cookbook/security/custom_authen@ca@on_provider.html   h7p://symfony.com/doc/current/cookbook/security/api_key_authen@[email protected]  

Slide 85

Slide 85 text

Thanks http://joind.in/11303 @netamorfose www.marcoloche.com [email protected] All pictures are mine

Slide 86

Slide 86 text

Q & A http://joind.in/11303 @netamorfose www.marcoloche.com [email protected] All pictures are mine