Unit 3 Notes
Unit 3 Notes
API Security- Session Cookies, Token Based Authentication, Securing Natter APIs: Addressing threats
with Security Controls, Rate eys , OAuth2, Securing Microservice APIs: Service Mesh, Locking Down
Network Connections, Securing Incoming Requests.
API security
● Definition of API:
● Allows software applications to interact with each other.
● Fundamental for modern software patterns like microservices architectures.
● API Security:
● Process of protecting APIs from attacks.
● APIs enable access to sensitive software functions and data.
● APIs are becoming primary targets for attackers.
API Vulnerabilities
● Common vulnerabilities in APIs:
● Broken authentication and authorization.
● Lack of rate limiting.
● Code injection.
1. Identify Vulnerabilities:
● Understand insecure aspects of the API lifecycle, considering planning, development,
testing, staging, and production stages.
2. Leverage OAuth:
● Use OAuth for authentication and authorization to control API access without
exposing user credentials.
● Encrypt Data
● Encrypt all data managed by the API, especially PII, using encryption at rest and in
transit with TLS. Require signatures for data decryption and modification.
3. Use Rate Limiting and Throttling:
● Set rate limits on API calls to prevent DoS attacks and protect against peak traffic. Rate
limiting helps balance access and availability.
4. Use a Service Mesh:
● Implement service mesh technology to optimize routing requests between services,
ensuring correct authentication and access control.
5. Adopt a Zero-trust Philosophy:
● Shift security focus from network perimeter to specific users, assets, and resources.
Authenticate users and applications, provide least privileges, and monitor for anomalous
behavior.
6. Test Your APIs with DAST:
● Utilize Dynamic Application Security Testing (DAST) tools like Bright to test APIs for
vulnerabilities. Support various API architectures including REST API and GraphQL.
Seamlessly integrate testing into DevOps and CI/CD pipelines for automated vulnerability
detection and mitigation.
Session Cookies
A session is used to temporarily store the information on the server to be used across multiple pages of
the website. It is the total time used for an activity. The user session starts when he logs-in to a particular
network application and ends when the user logs out from the application or shutdowns the system.
Working of Session
The working of a session can be understood with the help of the below diagram:
1. In the first step, the client request to the server via GET or POST method.
2. The sessionID is created on the server, and it saves the sessionID into the database. It returns
the sessionId with a cookie as a response to the client.
3. Cookie with sessionID stored on the browser is sent back to the server. The server matches this id
with the saved sessionID and sends a response HTTP200
What is Cookie?
○ A cookie is a small text file that is stored on the user's computer. The maximum file size of a
cookie is 4KB. It is also known as an HTTP cookie, web cookie, or internet Cookie. Whenever a
user visits a website for the first time, the site sends packets of data in the form of a cookie to the
user's computer.
○ The cookies help the websites to keep track of the user's browsing history or cart information
when they visit their sites.
○ It stores only the "String" data type.
○ The path where the cookies are saved is decided by the browser, as Internet explorer usually stored
them in Temporal Internet File Folder.
What is a Session Cookie?
● Definition: A session cookie is a temporary text file that a website installs on a visitor's device
to track real-time changes in user activity.
● Functionality: It helps in activities like adding items to a shopping cart on e-commerce websites,
ensuring that these actions are remembered as users navigate between different pages.
● Automatic Deletion: Session cookies are designed to be automatically deleted at the end of each
browsing session when the user exits the web browser.
● User Control: Users can manually restrict the use of session cookies during their browsing
sessions, although this can negatively impact the browsing experience and website
performance.
● Default Setting: Most websites have session cookies enabled by default to facilitate faster page
loads and smoother navigation.
How Does a Session Cookie Work?
The session cookie is a server-specific cookie that cannot be passed to any machine other than the one that
generated the cookie. The server creates a “session ID” which is a randomly generated number that
temporarily stores the session cookie. This cookie stores information such as the user’s input and tracks the
movements of the user within the website. There is no other information stored in the session cookie.
● Server-Specific: Session cookies are server-specific, meaning only the server that generated the
session cookie can read or access it.
● Session ID: The server creates a unique, randomly generated session ID that stores session cookies
and tracks user activity.
● User Tracking: Session cookies help track user behavior on the website, allowing the website to
identify users as they navigate through different pages.
● Enhanced User Experience: By tracking user actions, session cookies help create a
personalized and seamless browsing experience.
● Website Memory: Session cookies serve as the memory of a website, retaining user
actions and preferences during the session to ensure continuity.
What are Session Cookies Used For?
● Shopping Carts: They are essential for managing shopping carts on e-commerce sites, enabling
real-time updates as users add or remove items.
● User Navigation: Session cookies keep track of user actions across different web pages, ensuring
smooth navigation without repeated logins or reloading data.
● User Identification: They allow websites to remember users and their actions during a session,
enhancing the user experience and website functionality.
● Session Management: Session cookies help manage user sessions, preventing unauthorized access
and ensuring secure session handling.
● Form Data Storage: They temporarily store data entered into forms, preventing data loss if a user
navigates away from the form and returns later.
● Session Hijacking: Attackers steal session cookies to impersonate users and gain unauthorized
access to API resources.
● Cross-Site Scripting (XSS): Malicious scripts can access session cookies, leading to data
breaches and unauthorized access.
● Session Fixation: Attackers fixate a session ID before a user logs in and then hijack the session
after the user authenticates.
● Replay Attacks: Attackers capture and reuse session cookies to replay valid sessions and
gain unauthorized access.
● Cookie Theft: Through methods like packet sniffing or insecure storage, attackers can steal
session cookies and use them to impersonate users.
Session Cookies
A session stores the variables and their values within Cookies are stored on the user's computer as a text
a file in a temporary directory on the server. file.
The session ends when the user logout from the Cookies end on the lifetime set by the user.
application or closes his web browser.
It can store an unlimited amount of data. It can store only limited data.
We can store as much data as we want within a The maximum size of the browser's cookies is 4
session, but there is a maximum memory limit, which KB.
a script can use at one time, and it is 128 MB.
We need to call the session_start() function to start We don't need to call a function to start a cookie
the session. as it is stored within the local computer.
In PHP, to set a session data, the $_SESSION In PHP, to get the data from cookies, the
global variable is used. $_COOKIE global variable is used.
In PHP, to destroy or remove the data stored within a We can set an expiration date to delete the
session, we can use the session_destroy() function, cookie's data. It will automatically delete the data
and to unset a specific variable, we can use the unset() at that specific time. There is no particular
function. function to remove the data.
Sessions are more secured compared to cookies, as Cookies are not secure, as data is stored in a text
they save data in encrypted form. file, and if any unauthorized user gets access to
our system, he can temper the data.
An authentication token allows internet users to access applications, services, websites, and application
programming interfaces (APIs) without having to enter their login credentials each time they visit. Instead,
the user logs in once, and a unique token is generated and shared with connected applications or websites
to verify their identity.
These tokens are the digital version of a stamped ticket to an event. The user or bearer of the token is
provided with an access token to a website until they log out or close the service.
An authentication token is formed of three key components: the header, payload, and signature.
Header
The header defines the token type being used, as well as the signing algorithm involved.
Payload
The payload is responsible for defining the token issuer and the token’s expiration details. It also provides
information about the user plus other metadata.
Signature
The signature verifies the authenticity of a message and that a message has not changed while in transit.
What Is Token-based Authentication?
Token-based authentication is a protocol that generates encrypted security tokens. It enables users to verify
their identity to websites, which then generates a unique encrypted authentication token. That token provides
users with access to protected pages and resources for a limited period of time without having to re-enter
their username and password.
How does Token-based Authentication work?
Token-based authentication has become a widely used security mechanism used by internet service
providers to offer a quick experience to users while not compromising the security of their data. Let’s
understand how this mechanism works with 4 steps that are easy to grasp.
But software tokens are easy to use, cannot be lost, update automatically, and do not require IT assistance.
They can be integrated with security tools like single sign-on (SSO), and they protect users’ passwords even
if their token is compromised.
JSON Web Token (JWT)
With users increasingly accessing corporate resources and systems via mobile and web applications,
developers need to be able to authenticate them in a way that is appropriate for the platform.
JSON Web Tokens (JWTs) enable secure communication between two parties through an open industry
standard, Request For Comments 7519 (RFC 7519). The data shared is verified by a digital signature using
an algorithm and public and private key pairing, which ensures optimal security. Furthermore, if the data
is sent via Hypertext Transfer Protocol (HTTP), then it is kept secure by encryption.
Why Use Authentication Tokens?
There are many reasons why authentication tokens offer a beneficial alternative to server-based
authentication and relying on traditional password-based logins.
Authentication tokens are meant to enhance your security protocols and keep your server safe. But they
won't work effectively if you don't build your processes with safety in mind.
Your authentication tokens should be:
● Private. Users can't share token authentication devices or pass them around between departments.
Just as they wouldn't share passwords, they shouldn't share any other part of your security system.
● Secure. Communication between the token and your server must be secure via HHTPS
connections. Encryption is a critical part of keeping tokens safe.
● Tested. Run periodic token tests to ensure that your system is secure and functioning properly. If you
spot a problem, fix it quickly.
● Appropriate. Pick the right token type for your individual use case. For example, JWTs aren't
ideal for session tokens. They can be costly, and security risks involved with interception are
impossible to eliminate. Ensure you're always picking the right tool for the job.
Because so many users are accessing systems via mobile phones (apps) and web apps nowadays,
developers need a secure way to authenticate that’s appropriate for those platforms.
To solve that challenge, many developers turn to JSON Web Tokens (JWTs) when working on tokens for
their applications.
A JSON web token (JWT) is an open standard. The finished product allows for safe, secure communication
between two parties. Data is verified with a digital signature, and if it's sent via HTTP, encryption keeps
the data secure.
1. Header: Define token type and the signing algorithm involved in this space.
2. Payload: Define the token issuer, the expiration of the token, and more in this section.
3. Signature: Verify that the message hasn't changed in transit with a secure signature.
Coding ties these pieces together. The finished product looks something like this.
Don't be intimidated by JSON code. This type of notation is common when entities want to pass data back
and forth, and tutorials abound. If you're interested in using JSON tokens but you've never tried the
language before, a resource like this could be helpful.
● Size: Tokens in this code language are tiny, and they can be passed between two entities quite quickly.
● Ease: Tokens can be generated from almost anywhere, and they don't need to be verified on your server.
● Control: You can specify what someone can access, how long that permission lasts, and what the
person can do while logged on.
● Single key: JWTs rely on a single key. If that key is compromised, the entire system is at risk.
● Complexity: These tokens aren’t simple to understand. If a developer doesn’t have a strong
knowledge of cryptographic signature algorithms, they could inadvertently put the system at risk.
● Limitations: You can’t push messages to all clients, and you can’t manage clients from the server side.
● OAuth: Use OAuth for token-based authentication, allowing secure access without
exposing user credentials. It's particularly useful for third-party integrations.
● API Keys: Issue unique keys to users for authenticating API requests. This provides a basic
level of security and helps track usage.
● JWT (JSON Web Tokens): Use JWTs to securely transmit information between parties. JWTs are
compact and ensure data integrity and authenticity.
● Multi-Factor Authentication (MFA): Enhance security by requiring multiple forms of
verification before granting access to the API.
● Role-Based Access Control (RBAC): Define roles and permissions for different users to ensure
they only access necessary parts of the API.
● Scope Limitation: Limit the scope of access tokens to only the resources needed for a specific purpose.
● Least Privilege Principle: Ensure users and systems have the minimum access necessary to perform
their tasks.
● Continuous Verification: Continuously verify the identity and integrity of users and devices,
regardless of their location.
● Micro-Segmentation: Divide the network into smaller segments and enforce strict access controls
for each segment.
● Least Privilege: Ensure users and applications have only the necessary permissions they need to
perform their tasks, reducing the attack surface.
● Traffic Filtering: Use WAFs to filter and monitor HTTP traffic between the web application and the
Internet.
● Attack Detection: WAFs can detect and block common attack patterns, such as SQL injection,
cross-site scripting (XSS), and cross-site request forgery (CSRF).
● Policy Enforcement: Enforce security policies to control what traffic is allowed to reach your APIs.
● Penetration Testing: Regularly perform penetration testing to identify and address security vulnerabilities.
● Security Assessments: Conduct comprehensive security assessments to evaluate the effectiveness
of your security controls.
● Compliance Audits: Ensure your API security measures comply with relevant regulations and standards.
2. Data Interception
Data interception involves attackers capturing data as it is transmitted between clients and servers. This
can result in the exposure of sensitive information, such as personal data or credentials. Man-in-the-middle
(MITM) attacks are a common method used to intercept data.
3. Injection Attacks
Injection attacks, such as SQL injection, occur when attackers inject malicious code into the API's input
fields. This can compromise the API's functionality and lead to data leaks or unauthorized data modification.
These attacks exploit vulnerabilities in the API's input validation processes.
DoS attacks aim to make the API unavailable to legitimate users by overwhelming it with excessive
requests. This can disrupt services and affect the overall performance of the API. Attackers often use botnets
to launch large-scale attacks that can be difficult to mitigate.
XSS attacks involve injecting malicious scripts into web pages viewed by other users. These scripts can
steal session cookies, deface websites, or redirect users to malicious sites. XSS attacks exploit
vulnerabilities in web applications that do not properly sanitize user inputs.
CSRF attacks trick authenticated users into performing actions they did not intend to perform. This
can lead to unauthorized transactions or changes to user data. Attackers exploit the trust that a web
application has in the user's browser.
2. Encrypt
Data in Transit and at
Rest HTTPS and TLS
● Secure Communication: Encrypt data in transit using HTTPS to protect against
eavesdropping and man-in-the-middle attacks.
● Transport Layer Security: Use Transport Layer Security (TLS) to secure communication channels
between clients and servers, ensuring data privacy and integrity.
Data Encryption
● Protect Sensitive Data: Encrypt sensitive data stored on servers to protect it from unauthorized access.
● Strong Encryption Algorithms: Use strong encryption algorithms and key management practices
to ensure data remains secure even if servers are compromised.
Input Sanitization
● Remove Harmful Code: Sanitize inputs to remove any potentially harmful code, reducing the risk
of XSS and other injection attacks.
● Automatic Handling: Use libraries or frameworks that automatically handle input sanitization to
reduce the risk of human error.
4. Implement Rate Limiting and Throttling
Rate Limiting
● Prevent Abuse: Set limits on the number of API requests a user or IP address can make within a
certain timeframe, preventing abuse and ensuring fair usage of the API.
● DDoS Mitigation: Rate limiting helps mitigate the impact of Distributed Denial of Service (DDoS)
attacks by limiting the request rate.
Throttling
● Manage Traffic: Implement throttling to manage and control the number of requests during
peak traffic periods, protecting the API from being overwhelmed.
● Ensure Availability: Throttling helps maintain the availability and performance of the API under
high load conditions.
Real-Time Monitoring
● Detect Threats: Use monitoring tools to track API performance and detect security threats in real-time.
● Set Up Alerts: Set up alerts for unusual or suspicious activity, such as spikes in traffic or repeated
failed authentication attempts, to respond quickly to potential threats.
Session Expiry
● Reduce Hijacking Risk: Set appropriate expiry times for sessions to reduce the risk of session hijacking.
● Automatic Logout: Automatically log out users after a period of inactivity to enhance security.
Policy Enforcement
● Control Access: Enforce security policies to control what traffic is allowed to reach your APIs,
ensuring only legitimate requests are processed.
● Protect Endpoints: Use WAF policies to protect specific API endpoints from targeted attacks.
Micro-Segmentation
● Limit Lateral Movement: Divide the network into smaller segments and enforce strict access
controls for each segment, limiting lateral movement within the network.
● Enhanced Isolation: Micro-segmentation helps contain breaches and reduces the potential
impact of a compromised segment.
Least Privilege
● Minimize Permissions: Ensure users and applications have only the necessary permissions they
need to perform their tasks reducing the risk of abuse.
● Regular Reviews: Regularly review and update permissions to minimize the attack surface and
prevent privilege escalation.
Security Assessments
● Evaluate Posture: Conduct comprehensive security assessments to evaluate the overall security
posture of the API and identify weaknesses.
● Implement Measures: Use assessment findings to implement measures that strengthen
security and address identified vulnerabilities.
Compliance Audits
● Ensure Compliance: Ensure your API security measures comply with relevant regulations and
standards, such as GDPR and HIPAA.
● Regular Updates: Regularly review and update security practices to maintain compliance and
adapt to changing regulatory requirements.
● DoS and DDoS Attacks: Rate limiting helps mitigate denial of service (DoS) and distributed denial
of service (DDoS) attacks by capping the number of requests from a single source. Attackers often
flood APIs with requests to exhaust resources, causing service disruptions. By limiting the request
rate, APIs can resist these attacks and remain operational.
● Brute Force Attacks: Limiting the number of login attempts or sensitive operations can thwart brute
force attacks, where attackers try numerous combinations to gain unauthorized access. This
protection is crucial for endpoints handling authentication and sensitive data operations.
Graceful Degradation:
● Informative Responses: When users hit the rate limit, the API can return informative HTTP 429
(Too Many Requests) responses, guiding users on how to proceed. This transparency helps
maintain user trust and provides clear instructions on retrying requests after a specified period.
● Retry Strategies: Implementing client-side retry strategies can work alongside rate limits to
smooth out traffic bursts, improving the overall experience without overwhelming the server.
● Usage Patterns: Establish appropriate rate limits based on historical usage patterns and server
capacity. Different endpoints might have different limits depending on their sensitivity and
resource requirements.
● Dynamic Limits: Consider implementing dynamic rate limits that adjust based on current server
load and traffic conditions. This approach allows more flexibility and better resource
management.
Throttling Strategies:
● Fixed Window: This simple method resets the count of requests after a fixed time period (e.g., 100
requests per minute). It’s straightforward but can lead to bursts of traffic at the start of each window.
● Sliding Window: This method smooths out request rates by allowing requests based on a
rolling time window, providing more balanced traffic control.
● Token Bucket: This flexible strategy uses tokens to manage request rates, allowing for bursts
while maintaining a steady average rate over time.
● User Education: Provide clear documentation and guidelines on rate limits for developers. This
helps them design applications that comply with rate limits and handle rate-limiting responses
gracefully.
● Policy Enforcement: Develop and enforce rate limiting policies that balance security needs
with user experience considerations. Regularly review and adjust these policies based on
usage trends and feedback.
● Mandatory HTTPS: Enforce HTTPS for all API endpoints, ensuring that all data exchanges
occur over encrypted connections. This prevents attackers from exploiting unsecured
connections to steal or manipulate data.
● Certificate Management: Use valid SSL/TLS certificates from trusted certificate
authorities (CAs). Implement certificate pinning and regularly renew certificates to
maintain secure communications.
● Regular Rotation: Regularly rotate encryption keys to minimize the risk of key compromise.
Automated key rotation policies can help maintain security without disrupting service.
● Revocation Policies: Implement key revocation policies to promptly disable compromised keys and
replace them with new ones, maintaining data protection.
● Hardware Security Modules (HSMs): Store encryption keys securely using HSMs or other secure
key management solutions. HSMs provide physical and logical protection, ensuring keys are
accessible only to authorized entities.
● Complete Lifecycle Protection: Implement end-to-end encryption for highly sensitive data,
ensuring that it remains encrypted throughout its entire lifecycle. This approach provides
maximum security for data transmitted between clients and servers.
● Data Minimization: Minimize the exposure of sensitive data by encrypting it as early as
possible and decrypting it only when absolutely necessary.
● Compliance with Regulations: Protect personally identifiable information (PII) and other sensitive
user data with strong encryption methods. Ensure compliance with data protection regulations such
as GDPR, HIPAA, and others.
● Privacy Enhancements: Enhance user privacy by encrypting data in such a way that even service
providers cannot access it without proper authorization, ensuring users' trust in the service.
Incident Investigation:
● Forensic Analysis: Use audit logs to investigate security incidents, identify the root cause, and
determine the scope of the breach. Detailed logs are invaluable for forensic analysis and
compliance reporting.
● Post-Incident Reviews: Conduct post-incident reviews to learn from security incidents and
improve defenses. Use audit logs to understand the incident timeline and improve future
responses.
Accountability:
● Action Tracking: Ensure accountability by tracking actions performed by users and
administrators. This helps establish a clear chain of responsibility and deters malicious
activities.
● Role-Based Logging: Implement role-based logging to ensure that sensitive actions are
logged with appropriate context, such as the role and permissions of the user performing the
action.
● Retention Periods: Define log retention policies that balance the need for historical data with
storage constraints. Retain logs for an appropriate period based on regulatory and business
requirements.
● Storage Management: Use efficient storage management techniques, such as log
compression and archival, to handle large volumes of log data without excessive storage
costs.
Log Integrity:
● Tamper-Resistance: Ensure the integrity of audit logs by implementing measures such as digital
signatures and secure storage. This prevents tampering and ensures that logs can be trusted during
investigations.
● Audit Log Monitoring: Regularly monitor audit logs for signs of tampering or unauthorized access,
ensuring that any integrity issues are promptly detected and addressed.
Conclusion
Securing Natter APIs requires a comprehensive approach that includes rate limiting, encryption, and audit
logging. Each of these mechanisms plays a critical role in ensuring the security and availability of APIs:
● Rate Limiting: Prevents abuse and overuse, enhances performance and stability, and
improves user experience by controlling the request rate.
● Encryption: Protects sensitive data in transit and at rest, manages encryption keys securely, and
ensures compliance with data protection regulations.
● Audit Logging: Provides detailed records of API activities, detects and responds to security
incidents, ensures compliance and accountability, and maintains log integrity.
By implementing these security controls, organizations can enhance the security and reliability of their
APIs, ensuring a safe and seamless experience for their users. These measures collectively contribute to a
robust security posture, protecting both the API and its users from various threats and ensuring continued
service availability and compliance with regulatory standards.