0% found this document useful (0 votes)
107 views16 pages

REST API Security Cheat Sheet - 1714665717010

The document discusses security best practices for REST APIs, including using HTTPS, implementing access control with JSON Web Tokens (JWT), restricting HTTP methods, validating input and content types, and handling errors and audit logs.

Uploaded by

obydd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
107 views16 pages

REST API Security Cheat Sheet - 1714665717010

The document discusses security best practices for REST APIs, including using HTTPS, implementing access control with JSON Web Tokens (JWT), restricting HTTP methods, validating input and content types, and handling errors and audit logs.

Uploaded by

obydd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

DEFENSE ARCHITECTURE

REST API Security


Cheat Sheet.
REST API security is a critical aspect of ensuring the integrity and confidentiality of data
exchanged between applications. As APIs have become increasingly integral to software
development, the importance of REST API security has grown in tandem.
Table of Contents.
• Defense Architecture
• Introduction
• HTTPS
• Access Control
• JWT
• API Keys
• Restrict HTTP methods
• Input validation
• Validate content types
• Management endpoints
• Error handling
• Audit logs
• Security Headers
• CORS
• Sensitive information in HTTP requests
• HTTP Return Code

DEFENSE ARCHITECTURE
Defense Architecture.
We provide comprehensive security solutions to help organizations of all
sizes protect their information assets from cyber threats. With our
experienced team of cybersecurity professionals and state-of-the-art tools
and techniques, we help our clients stay ahead of evolving threats and
ensure the security of their operations.

At Defense Architecture, we take a proactive approach to cyber security.


We believe that the most effective way to prevent security breaches is to
identify vulnerabilities before they can be exploited. That's why we offer
regular risk assessments and ongoing security monitoring to help our
clients stay ahead of evolving threats. Our team of experts is available to
provide guidance and support, ensuring that our clients are prepared for
any security eventuality.

Our range of services includes CISOaaS, phishing campaigns, penetration


testing, forensics, and more. We understand that each organization has
unique security needs, and we work closely with our clients to develop
customized security strategies that align with their business goals. Our
services are designed to help organizations of all sizes and types, from small
startups to large enterprises.

Our commitment to excellence has earned us a reputation as a trusted


partner in cyber security. We have helped numerous organizations improve
their security posture and protect their information assets from cyber
threats. With our comprehensive range of services and our experienced
team of professionals, you can rest assured that your organization is in
good hands with Defense Architecture.

DEFENSE ARCHITECTURE
Introduction.
In the world of software, ensuring the security of data
exchange is crucial, especially when it comes to REST APIs.
Representational State Transfer (REST) APIs act as the
backbone of modern software development, facilitating seamless
communication between different applications and services. However, with
increased connectivity comes the critical need to address security concerns
effectively. As organizations increasingly rely on REST APIs to power their
applications and share data, ensuring the security of these APIs becomes
paramount to protect sensitive information and maintain the trust of users.

JSON Web Tokens (JWT) play a significant role in enhancing security within
the realm of web applications and APIs. JWTs act as digital passports,
helping verify the identity of users and ensuring that only authorized
individuals can access certain resources. By understanding how JWTs work
and their various use cases, developers can further strengthen the security
of their systems and protect sensitive information from unauthorized
access.

REST (or REpresentational State Transfer) is an architectural style first


described in Roy Fielding's Ph.D. dissertation on Architectural Styles and the
Design of Network-based Software Architectures.

It evolved as Fielding wrote the HTTP/1.1 and URI specs and has been
proven to be well-suited for developing distributed hypermedia
applications. While REST is more widely applicable, it is most commonly
used within the context of communicating with services via HTTP.

The key abstraction of information in REST is a resource. A REST API


resource is identified by a URI, usually a HTTP URL. REST components use
connectors to perform actions on a resource by using a representation to
capture the current or intended state of the resource and transferring that
representation.

DEFENSE ARCHITECTURE
HTTPS.
Secure REST services must only provide HTTPS endpoints. This protects
authentication credentials in transit, for example passwords, API keys or
JSON Web Tokens. It also allows clients to authenticate the service and
guarantees integrity of the transmitted data.

Consider the use of mutually authenticated client-side certificates to


provide additional protection for highly privileged web services.

for secure communication between a client and an API server using HTTPS
with API and Session Token, implementing token-based authentication with
secure token management, utilizing session-based authentication for user
sessions, and ensuring all interactions occur over HTTPS are essential
practices to maintain data security and integrity.

DEFENSE ARCHITECTURE
Access Control.
Non-public REST services must perform access control at each API endpoint.
Web services in monolithic applications implement this by means of user
authentication, authorization logic and session management. This has
several drawbacks for modern architectures which compose multiple
microservices following the RESTful style.

Authentication

Authentication (AuthN) is the process of verifying that an individual, entity,


or website is who or what it claims to be by determining the validity of one
or more authenticators (like passwords, fingerprints, or security tokens)
that are used to back up this claim.

Digital Identity is the unique representation of a subject engaged in an


online transaction. A digital identity is always unique in the context of a
digital service but does not necessarily need to be traceable back to a
specific real-life subject.

Identity Proofing establishes that a subject is actually who they claim to be.
This concept is related to KYC concepts and it aims to bind a digital identity
with a real person.

Session Management is a process by which a server maintains the state of


an entity interacting with it. This is required for a server to remember how
to react to subsequent requests throughout a transaction. Sessions are
maintained on the server by a session identifier which can be passed back
and forth between the client and server when transmitting and receiving
requests. Sessions should be unique per user and computationally very
difficult to predict.

DEFENSE ARCHITECTURE
Authorization

Authorization may be defined as "the process of verifying that a requested


action or service is approved for a specific entity" (NIST). Authorization is
distinct from authentication which is the process of verifying an entity's
identity. When designing and developing a software solution, it is important
to keep these distinctions in mind. A user who has been authenticated
(perhaps by providing a username and password) is often not authorized to
access every resource and perform every action that is technically possible
through a system. For example, a web app may have both regular users and
admins, with the admins being able to perform actions the average user is
not privileged to do so, even though they have been authenticated.
Additionally, authentication is not always required for accessing resources;
an unauthenticated user may be authorized to access certain public
resources, such as an image or login page, or even an entire web app.

JWT.
There seems to be a convergence towards using JSON Web Tokens (JWT) as
the format for security tokens. JWTs are JSON data structures containing a
set of claims that can be used for access control decisions. A cryptographic
signature or message authentication code (MAC) can be used to protect the
integrity of the JWT.

• Ensure JWTs are integrity protected by either a signature or a MAC.


Do not allow the unsecured JWTs: {"alg":"none"}.
• In general, signatures should be preferred over MACs for integrity
protection of JWTs.

If MACs are used for integrity protection, every service that is able to
validate JWTs can also create new JWTs using the same key. This means
that all services using the same key have to mutually trust each other.
Another consequence of this is that a compromise of any service also
compromises all other services sharing the same key. See here for
additional information.

DEFENSE ARCHITECTURE
The relying party or token consumer validates a JWT by verifying its
integrity and claims contained.

• A relying party must verify the integrity of the JWT based on its own
configuration or hard-coded logic. It must not rely on the information
of the JWT header to select the verification algorithm. See here and
here

Some claims have been standardized and should be present in JWT used for
access controls. At least the following of the standard claims should be
verified:

• iss or issuer - is this a trusted issuer? Is it the expected owner of the


signing key?
• aud or audience - is the relying party in the target audience for this
JWT?
• exp or expiration time - is the current time before the end of the
validity period of this token?
• nbf or not before time - is the current time after the start of the
validity period of this token?

DEFENSE ARCHITECTURE
As JWTs contain details of the authenticated entity (user etc.) a disconnect
can occur between the JWT and the current state of the users session, for
example, if the session is terminated earlier than the expiration time due to
an explicit logout or an idle timeout. When an explicit session termination
event occurs, a digest or hash of any associated JWTs should be submitted
to a block list on the API which will invalidate that JWT for any requests
until the expiration of the token.

API Keys.
Public REST services without access control run the risk of being farmed
leading to excessive bills for bandwidth or compute cycles. API keys can be
used to mitigate this risk. They are also often used by organisation to
monetize APIs; instead of blocking high-frequency calls, clients are given
access in accordance to a purchased access plan.

API keys can reduce the impact of denial-of-service attacks. However, when
they are issued to third-party clients, they are relatively easy to
compromise.

• Require API keys for every request to the protected endpoint.


• Return 429 Too Many Requests HTTP response code if requests are
coming in too quickly.
• Revoke the API key if the client violates the usage agreement.
• Do not rely exclusively on API keys to protect sensitive, critical or high-
value resources.

Restrict HTTP methods.


• Apply an allow list of permitted HTTP Methods e.g. GET, POST, PUT.
• Reject all requests not matching the allow list with HTTP response
code 405 Method not allowed.

DEFENSE ARCHITECTURE
• Make sure the caller is authorised to use the incoming HTTP method
on the resource collection, action, and record

Input validation.
• Do not trust input parameters/objects.
• Validate input: length / range / format and type.
• Achieve an implicit input validation by using strong types like
numbers, booleans, dates, times or fixed data ranges in API
parameters.
• Constrain string inputs with regexps.
• Reject unexpected/illegal content.
• Make use of validation/sanitation libraries or frameworks in your
specific language.
• Define an appropriate request size limit and reject requests exceeding
the limit with HTTP response status 413 Request Entity Too Large.
• Consider logging input validation failures. Assume that someone who
is performing hundreds of failed input validations per second is up to
no good.
• Have a look at input validation cheat sheet for comprehensive
explanation.
• Use a secure parser for parsing the incoming messages. If you are
using XML, make sure to use a parser that is not vulnerable to XXE and
similar attacks.

Validate content types.


A REST request or response body should match the intended content type
in the header. Otherwise this could cause misinterpretation at the
consumer/producer side and lead to code injection/execution.

• Document all supported content types in your API.

10

DEFENSE ARCHITECTURE
Validate request content types
• Reject requests containing unexpected or missing content type
headers with HTTP response status 406 Unacceptable or 415
Unsupported Media Type.
• Avoid accidentally exposing unintended content types by explicitly
defining content types e.g. Jersey (Java)
@consumes("application/json"); @produces("application/json"). This
avoids XXE-attack vectors for example.

Send safe response content types


It is common for REST services to allow multiple response types (e.g.
application/xml or application/json, and the client specifies the preferred
order of response types by the Accept header in the request.

• Do NOT simply copy the Accept header to the Content-type header of


the response.
• Reject the request (ideally with a 406 Not Acceptable response) if the
Accept header does not specifically contain one of the allowable
types.

Services including script code (e.g. JavaScript) in their responses must be


especially careful to defend against header injection attack.

• Ensure sending intended content type headers in your response


matching your body content e.g. application/json and not
application/javascript.

Management endpoints.
• Avoid exposing management endpoints via Internet.
• If management endpoints must be accessible via the Internet, make
sure that users must use a strong authentication mechanism, e.g.
multi-factor.
• Expose management endpoints via different HTTP ports or hosts
preferably on a different NIC and restricted subnet.

11

DEFENSE ARCHITECTURE
• Restrict access to these endpoints by firewall rules or use of access
control lists.

Error handling.
• Respond with generic error messages - avoid revealing details of the
failure unnecessarily.
• Do not pass technical details (e.g. call stacks or other internal hints) to
the client.

Audit logs.
• Write audit logs before and after security related events.
• Consider logging token validation errors in order to detect attacks.
• Take care of log injection attacks by sanitizing log data beforehand.

Security Headers.
There are a number of security related headers that can be returned in the HTTP
responses to instruct browsers to act in specific ways. However, some of
these headers are intended to be used with HTML responses, and as such
may provide little or no security benefits on an API that does not return
HTML.
The following headers should be included in all API responses:

12

DEFENSE ARCHITECTURE
The headers below are only intended to provide additional security when responses are
rendered as HTML. As such, if the API will never return HTML in responses, then these
headers may not be necessary. However, if there is any uncertainty about the function of
the headers, or the types of information that the API returns (or may return in future),
then it is recommended to include them as part of a defence-in-depth approach.

CORS.
Cross-Origin Resource Sharing (CORS) is a W3C standard to flexibly specify what cross-
domain requests are permitted. By delivering appropriate CORS Headers your REST API
signals to the browser which domains, AKA origins, are allowed to make JavaScript calls
to the REST service.

• Disable CORS headers if cross-domain calls are not supported/expected.


• Be as specific as possible and as general as necessary when setting the origins of
cross-domain calls.

13

DEFENSE ARCHITECTURE
Sensitive information in HTTP
requests.
RESTful web services should be careful to prevent leaking credentials. Passwords,
security tokens, and API keys should not appear in the URL, as this can be captured in
web server logs, which makes them intrinsically valuable.

• In POST/PUT requests sensitive data should be transferred in the request body or


request headers.
• In GET requests sensitive data should be transferred in an HTTP Header.

OK:

https://example.com/resourceCollection/[ID]/action
https://twitter.com/vanderaj/lists

NOT OK:

https://example.com/controller/123/action?apiKey=a53f435643de32
because API Key is into the URL.

14

DEFENSE ARCHITECTURE
HTTP Return Code.
HTTP defines status code. When designing REST API, don't just use 200 for success or
404 for error. Always use the semantically appropriate status code for the response.
Here is a non-exhaustive selection of security related REST API status codes. Use it to
ensure you return the correct code.

Source: OWASP
CheatSheetSeries

15

DEFENSE ARCHITECTURE
Get in Touch.
Website
www.defarch.com

Email
[email protected]

16

DEFENSE ARCHITECTURE

You might also like