Skip to content

Latest commit

 

History

History
430 lines (354 loc) · 44.5 KB

apis.md

File metadata and controls

430 lines (354 loc) · 44.5 KB
description
APIs are essential nowadays, make them secure

APIs

About

A foundational element of innovation in today’s app-driven world is the API. From banks, retail and transportation to IoT, autonomous vehicles and smart cities, APIs are a critical part of modern mobile, SaaS and web applications and can be found in customer-facing, partner-facing and internal applications. By nature, APIs expose application logic and sensitive data such as Personally Identifiable Information (PII) and because of this have increasingly become a target for attackers. Without secure APIs, rapid innovation would be impossible. [1]

Best practices

Extracted from [2], [3] and [4].

Authentication

  • Don't use Basic Auth. Use standard authentication instead (e.g., JWT).
  • Don't reinvent the wheel in Authentication, token generation, password storage. Use the standards.
  • Use Max Retry and jail features in Login.
  • Use encryption on all sensitive data.

JWT (JSON Web Tokens)

  • Use a random complicated key (JWT Secret) to make brute forcing the token very hard.
  • Don't extract the algorithm from the header. Force the algorithm in the backend.
  • Make token expiration (TTL, RTTL) as short as possible.
  • Don't store sensitive data in the JWT payload, it can be decoded easily.
  • Avoid storing too much data. JWT is usually shared in headers and they have a size limit.

Access

  • Limit requests (Throttling) to avoid DDoS / brute-force attacks.
  • Use HTTPS on server side with TLS 1.2+ and secure ciphers to avoid MITM (Man in the Middle Attack).
  • Use HSTS header with SSL to avoid SSL Strip attacks.
  • Turn off directory listings.
  • For private APIs, allow access only from safelisted IPs/hosts.

OAuth

  • Always validate redirect_uri server-side to allow only safelisted URLs.
  • Always try to exchange for code and not tokens (don't allow response_type=token).
  • Use state parameter with a random hash to prevent CSRF on the OAuth authorization process.
  • Define the default scope, and validate scope parameters for each application.

Input

  • Use the proper HTTP method according to the operation: GET, POST, PUT/PATCH, and DELETE, and respond with 405 Method Not Allowed if the requested method isn't appropriate for the requested resource.
  • Validate content-type on request Accept header (Content Negotiation) to allow only your supported format (e.g., application/xml, application/json, etc.) and respond with 406 Not Acceptable response if not matched.
  • Validate content-type of posted data as you accept (e.g., application/x-www-form-urlencoded, multipart/form-data, application/json, etc.).
  • Validate user input to avoid common vulnerabilities (e.g., XSS, SQL-Injection, Remote Code Execution, etc.).
  • Don't use any sensitive data (credentials, Passwords, security tokens, or API keys) in the URL, but use standard Authorization header.
  • Use only server-side encryption.
  • Use an API Gateway service to enable caching, Rate Limit policies (e.g., Quota, Spike Arrest, or Concurrent Rate Limit) and deploy APIs resources dynamically.

Processing

  • Check if all the endpoints are protected behind authentication to avoid broken authentication process.
  • User own resource ID should be avoided. Use /me/orders instead of /user/654321/orders.
  • Don't auto-increment IDs. Use UUID instead.
  • If you are parsing XML data, make sure entity parsing is not enabled to avoid XXE (XML external entity attack).
  • If you are parsing XML, YAML or any other language with anchors and refs, make sure entity expansion is not enabled to avoid Billion Laughs/XML bomb via exponential entity expansion attack.
  • Use a CDN for file uploads.
  • If you are dealing with huge amount of data, use Workers and Queues to process as much as possible in background and return response fast to avoid HTTP Blocking.
  • Do not forget to turn the DEBUG mode OFF.
  • Use non-executable stacks when available.

Output

  • Send X-Content-Type-Options: nosniff header.
  • Send X-Frame-Options: deny header.
  • Send Content-Security-Policy: default-src 'none' header.
  • Remove fingerprinting headers - X-Powered-By, Server, X-AspNet-Version, etc.
  • Force content-type for your response. If you return application/json, then your content-type response is application/json.
  • Don't return sensitive data like credentials, passwords, or security tokens.
  • Return the proper status code according to the operation completed. (e.g., 200 OK, 400 Bad Request, 401 Unauthorized, 405 Method Not Allowed, etc.).

CI/CD

  • Audit your design and implementation with unit/integration tests coverage.
  • Use a code review process and disregard self-approval.
  • Ensure that all components of your services are statically scanned by AV software before pushing to production, including vendor libraries and other dependencies.
  • Continuously run security tests (static/dynamic analysis) on your code.
  • Check your dependencies (both software and OS) for known vulnerabilities.
  • Design a rollback solution for deployments.

Monitoring

  • Use centralized logins for all services and components.
  • Use agents to monitor all traffic, errors, requests, and responses.
  • Use alerts for SMS, Slack, Email, Telegram, Kibana, Cloudwatch, etc.
  • Ensure that you aren't logging any sensitive data like credit cards, passwords, PINs, etc.
  • Use an IDS and/or IPS system to monitor your API requests and instances.

More!

Resources

Find here other resources for APIs security...

Tools

Generic

  • API Development tools: A collection of useful resources for building RESTful HTTP+JSON APIs.
  • API Guesser: Simple website to guess API Key / OAuth Token by Muhammad Daffa.
  • API Key Leaks: Tools and exploits: An API key is a unique identifier that is used to authenticate requests associated with your project. Some developers might hardcode them or leave it on public shares.
  • Key-Checker (⚠️): Go scripts for checking API key / access token validity.
  • Keyhacks: Keyhacks is a repository which shows quick ways in which API keys leaked by a bug bounty program can be checked to see if they’re valid.
  • Private key usage verification: Driftwood is a tool that can enable you to lookup whether a private key is used for things like TLS or as a GitHub SSH key for a user.
  • Burp API enumeration: Using Burp to Enumerate a REST API.
  • ZAP scanning: Scanning APIs with ZAP.
  • ZAP exploring: Exploring APIs with ZAP.
  • ZAP API Scan: A ZAP add-on that automates API security scanning.
  • w3af scanning: Scan REST APIs with w3af.
  • Wallarm Free API Firewall: Fast and light-weight API proxy firewall for request and response validation by OpenAPI specs.
  • dredd: Language-agnostic HTTP API Testing Tool.
  • getallurls (gau): Fetch known URLs from AlienVault’s Open Threat Exchange, the Wayback Machine, and Common Crawl.
  • SoapUI: SoapUI is a free and open-source cross-platform functional testing solution for APIs and web services.
  • Step CI: Open-source framework for API Quality Assurance, which tests REST, GraphQL and gRPC automated and from Open API spec.
  • unfurl: Pull out bits of URLs provided on stdin.
  • ModSecurity: An open-source web application firewall (WAF) that can help protect APIs.

GraphQL

  • BatchQL (⚠️): GraphQL security auditing script with a focus on performing batch GraphQL queries and mutations.
  • clairvoyance: Obtain GraphQL API schema despite disabled introspection!.
  • GraphQLmap: GraphQLmap is a scripting engine to interact with a graphql endpoint for pentesting purposes.
  • graphql-path-enum: Tool that lists the different ways of reaching a given type in a GraphQL schema.
  • graphql-playground: GraphQL IDE for better development workflows (GraphQL Subscriptions, interactive docs & collaboration).
  • graphql-threat-matrix: GraphQL threat framework used by security professionals to research security gaps in GraphQL implementations.
  • graphw00f: graphw00f is GraphQL Server Engine Fingerprinting utility for software security professionals looking to learn more about what technology is behind a given GraphQL endpoint.
  • graphql-shield: A library for securing GraphQL APIs with fine-grained access control.

SOAP

  • Wsdler (⚠️): WSDL Parser extension for Burp.
  • wsdl-wizard (⚠️): WSDL Wizard is a Burp Suite plugin written in Python to detect current and discover new WSDL (Web Service Definition Language) files.

REST APIs

  • Akto: API discovery, automated business logic testing and runtime detection.
  • APICheck: The DevSecOps toolset for REST APIs.
  • APIClarity: Reconstruct Open API Specifications from real-time workload traffic seamlessly.
  • APIFuzzer: Fuzz test your application using your OpenAPI or Swagger API definition without coding.
  • APIKit: Discovery, Scan and Audit APIs Toolkit All In One.
  • Arjun: HTTP parameter discovery suite.
  • Astra: Automated Security Testing For REST API’s.
  • Automatic API Attack Tool (⚠️): Imperva’s customizable API attack tool takes an API specification as an input, generates and runs attacks that are based on it as an output.
  • CATS: CATS is a REST API Fuzzer and negative testing tool for OpenAPI endpoints.
  • Cherrybomb: Stop half-done API specifications with a CLI tool that helps you avoid undefined user behaviour by validating your API specifications.
  • ffuf: Fast web fuzzer written in Go.
  • fuzzapi (⚠️): Fuzzapi is a tool used for REST API pentesting anTnT-Fuzzerd uses API_Fuzzer gem.
  • gotestwaf: An open-source project in Golang to test different web application firewalls (WAF) for detection logic and bypasses.
  • kiterunner (⚠️): Contextual Content Discovery Tool.
  • Metlo | Open-source API security tool: to discover, inventory, test, and protect your APIs.
  • mitmproxy2swagger: Automagically reverse-engineer REST APIs via capturing traffic.
  • Optic: Verify the accuracy of your OpenAPI 3.x spec using real traffic and automatically apply patches that keep it up-to-date.
  • RESTler: RESTler is the first stateful REST API fuzzing tool for automatically testing cloud services through their REST APIs and finding security and reliability bugs in these services.
  • Swagger-EZ: A tool geared towards pentesting APIs using OpenAPI definitions.
  • TnT-Fuzzer (⚠️): OpenAPI 2.0 (Swagger) fuzzer written in python. Basically TnT for your API.
  • wadl-dumper: Dump all available paths and/or endpoints on WADL file.
  • fuzz-lightyear (⚠️): A pytest-inspired, DAST framework, capable of identifying vulnerabilities in a distributed, micro-service ecosystem through chaos engineering testing and stateful, Swagger fuzzing.

Books

Videos & presentations

YouTube Playlists

Other videos & presentations

Specifications

Learning

  • Know your HTTP Headers!: HTTP Headers: a simplified and comprehensive table.
  • Know your HTTP Status codes!: HTTP Status codes: a simplified and comprehensive table.
  • HTTP Status Codes: is an easy to reference database of HTTP Status Codes with their definitions and helpful code references all in one place.
  • Know your HTTP * Well: HTTP headers, media-types, methods, relations and status codes, all summarized and linking to their specification.

Learning Path

Topic Resources
Understanding APIs and their importance What is an API?
RESTful API Design
API Security Basics Why is API Security Important?
API Security: Challenges and Solutions
Authentication and Authorization Introduction to OAuth 2.0
Understanding JSON Web Tokens (JWT)
API Security Best Practices API Security Best Practices
OWASP API Security Top 10
Rate Limiting and Throttling Rate Limiting in APIs
Throttling in APIs
Input Validation and Sanitization Input Validation for APIs
Transport Security Transport Security in APIs
Using HTTPS for API Security
API Security Testing API Security Testing
Top 10 API Security Testing Tools
Project 1 - Building a Secure RESTful API Tutorial: Build a Secure RESTful API
Project 2 - Implementing OAuth 2.0 and JWT Tutorial: Implement OAuth 2.0 and JWT
Project 3 - API Security Audit API Security Audit Checklist

Workshops & labs

  • API security, REST Labs: Pentester Academy - attack & defense.
  • API Security University: APIsec University provides training courses for application security professionals.
  • BankGround API: Banking-like REST and GraphQL API for training/learning purposes.
  • GraphQL challenges: GraphQL Week on The Hacker101 Capture the Flag Challenges.
  • GraphQL Labs: GraphQL Labs on the OWASP Security Knowledge Framework.
  • Hacking APIs: Hacking APIs: workshop.
  • OWASP Top 10 for API: Is a series of free interactive application security training modules that teach developers how to identify and mitigate security vulnerabilities in their web API endpoints.
  • Practical API Security Walkthrough: Learn practical Mobile and API security techniques: API Key, Static and Dynamic HMAC, Dynamic Certificate Pinning, and Mobile App Attestation.

Fuzzing and others

Vulnerable APIs to learn

  • APISandbox: Pre-Built Vulnerable Multiple API Scenarios Environments Based on Docker-Compose.
  • Bookstore: TryHackMe room - A Beginner level box with basic web enumeration and REST API Fuzzing.
  • crAPI: completely ridiculous API (crAPI)
  • Damn-Vulnerable-GraphQL-Application: Damn Vulnerable GraphQL Application is intentionally vulnerable implementation of Facebook’s GraphQL technology to learn and practice GraphQL Security.
  • Damn Vulnerable Micro Services (⚠️): This is a vulnerable microservice written in many languages to demonstrating OWASP API Top Security Risk (under development).
  • Damn Vulnerable Web Services: Damn Vulnerable Web Services is a vulnerable web service/API/application that we can use to learn webservices/API vulnerabilities.
  • Generic-University: Vulnerable API with Laravel App.
  • node-api-goat: A simple Express.JS REST API application that exposes endpoints with code that contains vulnerabilities.
  • Pixi (⚠️): The Pixi module is a MEAN Stack web app with wildly insecure APIs!
  • REST API Goat (⚠️): This is a “Goat” project so you can get familiar with REST API testing.
  • VAmPI: Vulnerable REST API with OWASP top 10 vulnerabilities for APIs.
  • vAPI: vAPI is Vulnerable Adversely Programmed Interface which is Self-Hostable API that mimics OWASP API Top 10 scenarios through Exercises.
  • vulnapi: Intentionaly very vulnerable API with bonus bad coding practices.
  • vulnerable-graphql-api (⚠️): A very vulnerable implementation of a GraphQL API.
  • Websheep: Websheep is an app based on a willingly vulnerable ReSTful APIs.
  • DVNA (⚠️): Damn Vulnerable Node.js Application with insecure APIs.
  • WebGoat: A deliberately insecure web app for security training.
  • Juice Shop: A modern, intentionally insecure web application
  • Gruyere: A web application with security holes used for training.
  • Railsgoat: A vulnerable Ruby on Rails application for learning security.
  • Mutillidae: A deliberately vulnerable set of PHP scripts.
  • NodeGoat: A Node.js/Express app with security vulnerabilities.
  • Hackazon (⚠️): A modern, vulnerable e-commerce web app.
  • GoatDroid (⚠️): A vulnerable Android app with insecure APIs.
  • AltoroJ: A vulnerable Java web app for learning application security.
  • Hackademic (⚠️): A vulnerable web app to learn and practice web application security.

Others

  • The API Specification Toolbox: This Toolbox goal is to try and map out all of the different API specifications in use, as well as the services, tooling, extensions, and other supporting elements.
  • Understanding gRPC, OpenAPI and REST: gRPC vs REST: Understanding gRPC, OpenAPI and REST and when to use them in API design.
  • API security design best practices: API security design best practices for enterprise and public cloud.
  • REST API Design Guide: This design guide or style guide contains best practices suitable for most REST APIs.
  • How to design a REST API: How to design a REST API? - Full guide tackling security, pagination, filtering, versioning, partial answers, CORS, etc.
  • Awesome REST: A collaborative list of great resources about RESTful API architecture, development, test, and performance. Feel free to contribute to this ongoing list.
  • Collect API Requirements: Collecting Requirements for your API with APIOps Cycles.
  • API Audit: API Audit is a method to ensure APIs are matching the API Design guidelines. It also helps check for usability, security and API management platform compatibility

Podcasts

Wikis & Collections

Mind maps:

Books, collections:

Newsletters

  • The Hacker News: A blog and newsletter that covers various API topics, including security.
  • API Evangelist: A blog and newsletter by Kin Lane that covers various API topics, including security.
  • The New Stack: A platform for news and analysis on various technology topics, including API security. Subscribe to their newsletter for regular updates.
  • Secjuice: A cybersecurity publication with a dedicated section for API security articles. Subscribe to their newsletter for updates.
  • Security Weekly: A cybersecurity podcast network and newsletter that occasionally covers API security topics.
  • StatusCode Weekly: A weekly newsletter that covers web operations and occasionally includes API security articles.
  • api security articles: API Security Articles - The Latest API Security News, Vulnerabilities & Best Practices.

Conferences

  • APIsecure: The world’s first conference dedicated to API threat management; bringing together breakers, defenders, and solutions in API security.

Others

Sources

[1]: OWASP API Security Project | OWASP Foundation

[2]: JBAhire/awesome-api-security-essentials: Awesome API Security: A Curated Collection of Resources for Bulletproof API Protection! (github.com)

[3]: arainho/awesome-api-security: A collection of awesome API Security tools and resources. The focus goes to open-source tools and resources that benefit all the community. (github.com)

[4]: shieldfy/API-Security-Checklist: Checklist of the most important security countermeasures when designing, testing, and releasing your API (github.com)