Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.

API Security

3.804 visualizaciones

Publicado el

Lorsque l’on souhaite mettre en oeuvre une API, on est rapidement confronté aux problématiques de sécurisation. Ce point constitue un enjeu majeur, dans la mesure où le principe Open API consiste à bâtir un « écosystème ouvert » via l’exposition de services utilisables par des tiers, sans avoir d’idée préconçue sur l’usage qui en sera fait. En outre, l’emploi de REST et du Web impacte la manière de sécuriser vos services, y compris pour une utilisation de l’API en interne.

Rendre vos API disponibles du l’internet ne signifie pas qu’elles sont en accès libre, de manière non sécurisée. Il existe des protocoles Web standardisés fiables et sécurisés en profondeur pour gérer l’authentification et l’habilitation des applications appelantes et des utilisateurs connectées à ces applications. La pierre angulaire étant le protocole OAuth2, qui est un framework d’autorisation et qui peut être étendu pour prendre en charge l’authentification via le protocole OpenID Connect. Ces protocoles simples sont bien éloignés des solutions complexes généralement utilisées par les entreprises (WS-Security, SAML2…).

Afin de faciliter et d’accélérer la mise en oeuvre, nous proposons nos convictions, issues de nos expériences autour des principes de sécurisation d’API.

Dans cette carte de référence, nous revenons sur les principes de sécurisation. Nous expliquons quels protocols utiliser et quels protocols ne pas utiliser. Nous revenons sur les “flow” OAuth2 et sur leur contexte d’utilisation. Nous expliquons le principes de “scope” qui est souvent mal utilisé. Nous détaillons les principes du protocol OpenId Connect, de JWT et des claims. Enfin nous revenons sur les erreurs que nous avons souvent constaté sur le terrain concernant la sécurisation d’APIs.

Publicado en: Tecnología
  • Sé el primero en comentar

API Security

  1. 1. WWW.OCTO.COM Securi+y Principles
  2. 2. APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY Security issues arise as soon as work begins on an API, but not necessarily in the way you might think. Commonly held beliefs often turn out to be unfounded when it comes to API security. Poorly designed API security leads to misuse or, worse still, to nonuse by the intended clients — application developers. To facilitate and accelerate the design and development of your APIs, we’re sharing our vision and beliefs with you here, in this Reference Card. Our insights were gained from our direct experience on API projects. API Security Principles  Your API Security strategy must also strike the right balance between safety and usability. In setting up obstacles to deter malicious users, you’re impeding legitimate users as well. Using open standards often helps in finding balance because the obstacles that are known to work well to keep out malicious users are also easily overcome by legitimate users, provided they have the right documentation. Strengthening security is increasingly difficult and decreasingly efficient, so remember to measure your efforts against the actual risks. A sound API security strategy rests upon 3 main pillars: You must authenticate the people and programs accessing your API, thus establishing trust in the identity of that person or program. You should explicitly authorize users and programs to perform certain tasks on your API. API authorization lists which programs are allowed to do what for which user. You should trace calls made to your API in order to ensure the accountability of all parties involved. This is a topic in and of itself and is not the matter of this document. The Right Balance
  3. 3. Why an API strategy ?  “Anytime, Anywhere, Any device” is the plight of digitalization. API is the answer to “Business Agility” as it allows to quickly build new GUIs for upcoming devices. An API layer enables Cross device Omnichannel 360° customer view Open API allows To outsource innovation To create new business models Embrace WOA “Web Oriented Architecture” Build a fast, scalable secured REST API Based on: REST, HATEOAS, Stateless decoupled µ-services, Asynchronous patterns, OpenID Connect OAuth2 protocols Leverage the power of your existing web infrastructure DISCLAMER This Reference Card isn’t intended to be comprehensive but rather to highlight the security concepts that were exposed in the course of our work on APIs. Please check out our blog http://blog.octo.com, and feel free to comment/challenge this API Security cookbook. We’re really looking forward to sharing with you. AUTHORS Powered with by Florent Jaby, Antoine Chantalou, Simon Renoult, WOAPI Tribe Sophie Delronge. APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  4. 4. Which security protocol ? Do not use. No dynamic registration (2-legs only). Browser is mandatory. No standard identity data structure. No notion of privilege delegation to a third party. Only authenticates the application and is notoriously complex to implement for consumers. SOAP-only, XML-only and SAML-only. OAuth2 brought two major improvements: Digital request signatures were replaced by TLS OAuth2 supports many kinds of devices (native, web browser, servers…) Basic auth sends your secret to the network with each request and is primarily intended for end-users. A custom security protocol ultimately ensures that nobody will ever make the effort to learn to use your API. SAML SSL CLIENT CERTIFICATES WS-SECURITY OAUTH 1-A BASIC AUTH CUSTOM PROTOCOLS HTTPS You MUST rely on HTTPS (TLS) for: Confidentiality, thanks to short-lived symmetric cryptography Integrity, thanks to Message Authentication Codes (MAC)preventing data loss Authenticity, thanks to signed public key certificates for the server Cf. RFC 5246 (TLS 1.2), RFC 6101 (SSL 3.0) Always keep your SSL version and cipher suites up to date. R.I.P APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  5. 5. Recommended protocols  You can use only a key for server-to-server communication and it only provides authentication. It is the easiest to put in place but also the least secure of the 3 protocols recommended here. OAuth2 (RFC6749) is a widely used authorization framework, relying on Bearer tokens (RFC6750) for authentication. It allows you to delegate a subset of privileges to applications in order to protect users’ passwords. You SHOULD use this as your default choice for your API as it handles most use cases. Most Web Giants use this. API KEY OAUTH2 OpenID Connect is a standardization of OAuth2. It describes user identity and third-party authentication more specifically. You SHOULD use this if you want to buy a product and handle users in a standard way. Many Web Giants now support it too. OPEN ID CONNECT Protocol decision tree YES YES YES NO NO NO Should I use OAuth2 or OIDC or an API Key? Does API DATA belong to an end-user? Do I want to handle several IDPs? OpenID Connect OAuth2 API KEY API KEY OAuth2 Client Credential My app is public Should I use OAuth2 or OIDC or an API Key? Does API DATA belong to an end-user? Do I want to handle several IDPs? OpenID Connect OAuth2 API KEY API KEY OAuth2 Client Credential My app is public APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  6. 6. GET /servicesapi_key={API_KEY} X-API-Key: {API_KEY} Authorization: Bearer {TOKEN} API Key  Bearer Token  An API key is a randomized string serving as a shared secret between the client and the server. You MUST use a secure channel to exchange the key (email is not a secure channel). A compromised API key must be revoked right away. Bearer Tokens (RFC 6750) are the same as API Keys but are standardized. You may retrieve them from the Authorization header: Bearer tokens are best used in a OAuth2 context, attached to an authorization scope, a user, and when made easily renewable. Query params You may retrieve the API key from the query params: CONS:  No fine-grain authorization  No expiration control  Shared secret unsuitable for web pages and mobile apps  No standard for secure secret exchange Header X-API-KEY You may also retrieve the API key in a custom header: Headers are less likely to get logged and you should prefer this method. APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  7. 7. OAuth2  What OAuth2 flow should I use? With OAuth2, you should recognize 3 different types of clients: Confidential: For applications consuming your API. Usually server- or web-based applications External: Typical third-party web-based clients. Can keep their secrets safe Public: Mobile and Single Page applications. Their credentials cannot be safely stored It offers 4 different flows: YES YES NO NO Which OAuth2 flow should I use? Is an end-user connected? I want to use a common login form Implicit grant Authorization code grant Client Credential grant Is my app trusted? My app is public? Resource owner password credential grant Use an SSO! YESYES NONO THREE-LEGGED FLOWS Consensus between client, authorization server, and user Authorization Code Main flow. It allows external or confidential clients to ask users to delegate some of their privileges without sharing their password. Implicit Best for public clients. Uses HTTPS to have the user agent verify the domain name of the application. Client Credentials No end-user. Uses scopes, thereby following the principle of least privilege. Suited for external and confidential clients. Resource Owner Credentials Intended to ease migrations of legacy codebases. It allows the application to store user passwords. Best avoided. TWO-LEGGED FLOWS Two-party agreement, more likely to be broken APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  8. 8. Scope  In OAuth2 and OpenID Connect, an access token is bound to a set of scopes. A scope describes the limits of the privileges that a user has delegated to an application. It usually looks like: “profile”, “email”, “articles”, “publish”, etc. A user can only delegate privileges he or she has. You should only manage a handful of scopes. If the number of scopes increases with each new feature, your strategy may be inadequate. Scopes are for programs, not people. Naming strategies User privileges can be sliced into many scopes, which in turn can be: Role-based: mapping between system roles and scope: “writers”, “translators”, “proofreaders”, etc. Domain-based: named after business domains (think DDD): “translations” or “articles”. Action-based: best avoided. They’re like Access Control Lists (ACL). Action-based scopes end up with templates such as resource_role_action which leads to an ever-growing list. Consent Choosing when to ask for scopes is a design choice. Three approaches can be considered: Never: the scope is never asked and is granted implicitly (trusted applications only) Once: the scope is asked at the first connection of each client (most common) Always: every request triggers user consent (when security concerns are high). A SCOPE MUST NOT REPLACE HOW USER PRIVILEGES ARE DESCRIBED Service User Application Never Once Always APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  9. 9. OpenID Connect  Objectives OpenID Connect (OIDC) lets app and site developers authenticate users without the additional burden of having to store and manage passwords in the face of an Internet that is well-populated with people trying to compromise users’ accounts for their own gain. OpenID Connect protocol can be used to authenticate both clients (applications) and users on private API resources. Once in place, OpenID Connect allows you to: Manage your own OAuth2 instance to authorize access to API resources Use your own OpenID Connect provider to authenticate users Use any external OpenID Connect provider to authenticate users: Google, Facebook and so on… Web Giants probably handle authentication better than you ever could: two-factor authentication with SMS... Mobile? There is no way to ensure the identity of a mobile application. Any secret stored in a mobile application (like a client id) must be considered public, and therefore untrustworthy. To mitigate this issue, ALWAYS use an Authorization Code flow with PKCE (RFC7636). APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  10. 10. JWT  Claims . JSON Web Tokens (JWT) and more specifically JSON Web Signatures (JWS) are heavily used by OpenID Connect. Composed of 3 Base64 encoded strings separated by dots, they’re both URL-safe. JWTs allow for symmetric and asymmetric cryptography. headers.content.signature Headers explain how to read and check this JWT as a Base64 encoded JSON literal Content is a Base64 encoded JSON literal Signature is a hash (MAC) of the headers and content, allowing to check for integrity and authenticity. Don’t hide secrets in JWTs. OpenID Connect uses a JWT to send the signed identity of the user, but they can also be used as self-explanatory Access Tokens. profile address teamemail Claims are information about the requested end-user and/or the authentication event. You can think of them as “slices” of a user’s identity or flags about the validity of the embedded data. APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  11. 11. OIDC/OAuth2 Flows  AUTHCODE OIDC Oauth2 It’s me, it’s ok Ok! Here’s a codeHere’sacode It’smewithproof andthiscode Iknowthiscode Here’satoken APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  12. 12. OIDC/OAuth2 Flows  IMPLICIT OIDC Oauth2 It’s me, it’s ok Ok! Here’s a tokenHere’satoken APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  13. 13. OIDC/OAuth2 Flows  Implementation While many API Management solutions offer embedded OIDC/OAuth2 options, we advise against them as most of the time they usually only support the “Client Credentials” flow. We prefer dedicated solutions, such as... CLIENT CREDENTIALS Oauth2 Ok! Here’s a token It’s me, with proof Auth0: Cloud - Support all the OIDC/OAuth2 flows Anvil: On premise - Support “Implicit” and “AuthCode” flows APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  14. 14. OIDC/OAuth2 Flows  RESOURCE OWNER Oauth2 Ok! Here’s a token Here’s a password. He said it’s ok What’syourpassword? Verysecret APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  15. 15. Common Pitfalls  Do not confuse scopes with ACLs. ACLs involve only two actors (end-users and data providers). While scopes describe macro-size authorizations for applications, ACLs can grant fine-grained authorization for users. Mobile and Single Page Applications (SPA) are not secured since they can be decompiled. Any secret embedded in application distribution is to be considered public. Claims are information stored in ID tokens. A scope can grant access to a set of claims or limit what an application can access. The “profile” scope, for example, grants access to a handful of claims. In OIDC, claims apply to identity and scopes to privileges. OAuth2 flow “Resource Owner” is a perfectly valid first step when migrating from legacy systems to a state of the art authentication server. However it MUST NOT be considered the end line as it solves none of the issues addressed by the OpenID Connect specification. SCOPE ≠ ACL CLIENT SECRET ON MOBILE SUCKS SCOPE ≠ CLAIMS OAUTH RESOURCE OWNER AIN’T TOP NOTCH APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  16. 16. Who we are ? IT Consulting There is a better way « Nous croyons que l’informatique transformenossociétés.Noussavons que les réalisations marquantes sont le fruit du partage des savoirs et du plaisir à travailler ensemble. Nous recherchons en permanence de meilleures façons de faire. THERE IS A BETTER WAY ! » – Manifeste OCTO Technology Paris Rabat Lausanne Sydney 4 IMPLANTATIONS 448 2 FILIALES PRODUITS 47 M€ de CA 2016 (+23%) COLLABORATEURS CONFÉRENCE ORGANISME DE FORMATION 47 APISECURITYPRINCIPLESTRIBUWOAPIOCTOTECHNOLOGY
  17. 17. WWW.OCTO.COM We believe that API IS THE ENGINE OF DIGI+AL STRATEGY WE KNOW that the Web infiltrates AND transformsCOMPANIES WE WORK +OGETHER, with passion, TO CONNECT BUSINESS IT We help youCREATE OPPORTUNITIES AND EMBRACE THE WEB Inside Out tribu-woapi@octo.com

×