0% found this document useful (0 votes)
12 views13 pages

Unit 3

Uploaded by

shreekeerthykk
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)
12 views13 pages

Unit 3

Uploaded by

shreekeerthykk
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/ 13

UNIT 3

1. SECURING NATTER APIS: ADDRESSING


THREATS WITH SECURITY CONTROLS
 Rate-limiting:

 Purpose: Prevents users from overwhelming the API with too many
requests.
 Why it's important: Ensures the API remains available and responsive,
protecting against denial-of-service attacks where attackers flood the API
with requests to disrupt service.

 Encryption:

 Purpose: Secures data when it's transmitted over the network or stored
on disk.
 Why it's important: Prevents unauthorized access to sensitive
information by encoding data in a way that only authorized parties can
decrypt, ensuring confidentiality and integrity of data.

 Authentication:

 Purpose: Verifies the identity of users accessing the API.


 Why it's important: Ensures that only legitimate users with proper
credentials can interact with the API, preventing spoofing attacks where
unauthorized users pretend to be legitimate.

 Audit Logging:

 Purpose: Records all activities and events within the API.


 Why it's important: Provides a trail of actions taken by users, helping to
detect and investigate suspicious activities. It also prevents users from
denying their actions (repudiation), ensuring accountability.

 Rate-limiting mitigates Denial of Service (DoS) attacks.


 Encryption prevents Information Disclosure.
 Authentication prevents Spoofing.
 Audit Logging prevents Repudiation.
2. RATE-LIMITING FOR AVAILABILITY:

Denial of Service (DoS) Attacks

 Definition: DoS attacks aim to disrupt access to an API or service, often


by overwhelming it with traffic.
 Methods: Attacks can range from flooding servers with excessive
requests to exploiting vulnerabilities.
 Impact: They hinder legitimate users from accessing services, causing
downtime and potential financial losses.

Distributed DoS (DDoS) Attacks

 Definition: DDoS attacks amplify DoS methods using multiple


computers or networks, making them harder to mitigate.
 Amplification: Attackers use techniques like DNS amplification to
magnify their impact on the target.
 Botnets: Attackers control networks of compromised devices (botnets) to
execute massive DDoS attacks.

Defense Strategies: Rate Limiting

 Purpose: Rate limiting restricts the number of requests a client can make
to prevent API overload.
 Benefits: Ensures that resources are allocated efficiently, reducing the
impact of excessive traffic.
 Implementation: Should be the first defense mechanism applied to
incoming requests to mitigate potential DoS effects.

3. ENCRYPTION

 Definition: Encryption scrambles data (plaintext) into unreadable form


(ciphertext) using a cryptographic key.
 Purpose: Protects data from unauthorized access during transmission
(encryption in transit) and storage (encryption at rest).

Importance of Encryption

 Privacy: Ensures only authorized parties can read sensitive information,


protecting user privacy from attackers, ISPs, and governments.
 Security: Prevents data breaches by securing data on devices and during
communication, even if devices are lost or intercepted.
 Data Integrity: Guarantees that data remains unchanged and unreadable
during transmission, preventing tampering or interception.
 Regulatory Compliance: Required by regulations like HIPAA, PCI-
DSS, and GDPR to safeguard user data and privacy.

Common Encryption Algorithms

 Symmetric Encryption: Uses the same key for encryption and


decryption.
o Examples: AES (Advanced Encryption Standard), 3-DES, SNOW.
 Asymmetric Encryption: Uses a pair of keys (public and private) for
encryption and decryption.
o Examples: RSA, Elliptic Curve Cryptography (ECC).

How Encryption Works

 Process:
o Alice encrypts plaintext ("Hello") using an encryption algorithm
and a key.
o The ciphertext ("Jgnnq") is transmitted or stored securely.
o Bob, possessing the decryption key, decrypts the ciphertext back to
the original plaintext.

4. AUDIT LOGGING

What is an Audit Log?

 An audit log records every operation performed using your API.


 It ensures accountability and aids in forensic investigations post-security
breach.

Purpose of Audit Logs:

 Accountability: Tracks who performed actions, what clients were used,


and when requests were received.
 Security Monitoring: Helps identify ongoing attacks or suspicious
activities in real-time.
 Troubleshooting: Provides details about request types, accessed
resources, success or failure of operations, and related requests made
around the same time.

Key Points:

 Protection and Confidentiality: Audit logs contain sensitive


information and must be protected from tampering.
 Timing: Audit logging occurs after authentication to capture all
attempted operations, not just successful ones.
 Storage: Logs are written to durable storage like file systems or
databases to ensure they survive system crashes.
 Implementation: Typically implemented as a filter after authentication
but before authorization checks to record attempted operations, even if
access is denied.

import java.time.LocalDateTime;

import java.time.format.DateTimeFormatter;

public class AuditController {

public void auditRequestStart(String method, String path, String userId) {

long auditId = generateAuditId(); // Simulating generation of audit ID

logAudit(auditId, method, path, userId);

public void auditRequestEnd(String method, String path, int status, String


userId) {

long auditId = generateAuditId(); // Simulating generation of audit ID

logAudit(auditId, method, path, status, userId);

private void logAudit(long auditId, String method, String path, String userId)
{

LocalDateTime now = LocalDateTime.now();


String logMessage = String.format("[%s] Audit ID: %d - Method: %s,
Path: %s, User: %s",

now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
auditId, method, path, userId);

writeLogToFile(logMessage);

private void logAudit(long auditId, String method, String path, int status,
String userId) {

LocalDateTime now = LocalDateTime.now();

String logMessage = String.format("[%s] Audit ID: %d - Method: %s,


Path: %s, Status: %d, User: %s",

now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
auditId, method, path, status, userId);

writeLogToFile(logMessage);

private void writeLogToFile(String logMessage) {

// Simulate writing to a log file

String logFileName = "audit_log.txt";

System.out.println("Logging: " + logMessage); // Replace with actual


logging mechanism

private long generateAuditId() {

// Simulate generating a unique audit ID

return System.currentTimeMillis(); // Example: Using current time as audit


ID

}
public static void main(String[] args) {

AuditController auditController = new AuditController();

// Simulate logging a request start

auditController.auditRequestStart("GET", "/api/users", "user123");

// Simulate logging a request end

auditController.auditRequestEnd("GET", "/api/users", 200, "user123");

SECURING SERVICE-TO SERVICE APIS: OAUTH2


 OAuth 2.0 is an authorization framework designed to facilitate secure access
to resources on behalf of users without sharing their credentials.
 OAuth 2.0 uses Access Tokens. An Access Token is a piece of data that
represents the authorization to access resources on behalf of the end-user.
OAuth 2.0 doesn’t define a specific format for Access Tokens.

Key Concepts

1. Access Token: A token issued by the Authorization Server that


represents the user's permission to access resources. It is used by the
Client to access protected resources hosted by the Resource Server.
2. Authorization Server: Responsible for authenticating the Resource
Owner and granting Access Tokens to Clients. It exposes endpoints for
authorization (/authorize) and token issuance (/token).
3. Resource Server: Hosts the protected resources that the Client wants to
access. It verifies the Access Token presented by the Client to ensure
access to the requested resources.
4. Resource Owner: The entity that grants access to its protected resources.
Typically, this is the end-user.
5. Scope: Specifies the extent of access requested by the Client. Scopes
define what actions the Client can perform with the Access Token.
6. Client: The application requesting access to resources on behalf of the
Resource Owner. It must be registered with the Authorization Server and
identified using client credentials.
OAuth 2.0 Flow

1. Client Registration: The Client registers with the Authorization Server


and obtains client credentials (client ID and client secret).
2. Authorization Request:
o The Client initiates an authorization request by redirecting the
Resource Owner to the Authorization Server (/authorize
endpoint).
o The request includes client credentials, scopes, and a redirect URI
where the Authorization Server sends the authorization response.
3. User Authorization:
o The Resource Owner authenticates with the Authorization Server
and grants permissions to the Client.
o After successful authentication and authorization, the
Authorization Server redirects back to the Client with an
Authorization Code or Access Token, depending on the grant type.
4. Token Exchange:
o The Client exchanges the Authorization Code for an Access Token
(/token endpoint).
o Alternatively, in implicit grant, the Access Token is returned
directly to the Client after user authorization.
5. Accessing Resources:
o With the Access Token, the Client accesses protected resources by
including the token in API requests to the Resource Server.
o The Resource Server validates the Access Token and allows or
denies access based on the token's scope and validity.
Grant Types

OAuth 2.0 defines several grant types to accommodate different use cases:

 Authorization Code Grant: Suitable for server-side applications


where the Client can securely store client credentials. Involves
exchanging an authorization Code for an Access Token.
 Implicit Grant: Deprecated due to security concerns. Provides the
Access Token directly after user authorization, typically used by browser-
based or mobile apps.
 Client Credentials Grant: Used for machine-to-machine communication
where the Client itself is the resource owner.
 Resource Owner Password Credentials Grant: Allows the Client to
exchange the Resource Owner's credentials for an Access Token.
Generally discouraged due to security implications.
 Authorization Code with PKCE: Enhances security for native and
mobile apps by protecting against interception of the Authorization Code.
 Refresh Token Grant: Enables the Client to obtain a new Access Token
without user interaction by exchanging a Refresh Token.

API KEYS

API keys play a crucial role in securing access to APIs and controlling how
applications interact with sensitive data. Here’s a simplified overview
highlighting their importance, use cases, advantages, types, and best practices:

What are API Keys?

API keys are unique identifiers (usually alphanumeric strings) that authorize
applications to access APIs. They serve as a form of authentication and
authorization mechanism between the Client (application) and the API server.

Uses and Benefits of API Keys

1. Security: Provides an additional layer of security by authenticating and


authorizing requests from clients.
2. Access Control: Ensures only authorized clients can access specific
resources or perform operations.
3. Monitoring and Tracking: Allows tracking and monitoring of API
usage, which can be useful for auditing, billing, and enforcing rate limits.
4. Integration: Facilitates integration between different applications and
services by enabling controlled access to APIs.

Advantages of Using API Keys

 Improved Security: Helps protect sensitive data by restricting access


only to authorized applications.
 Enhanced Performance: Supports caching and load balancing,
optimizing API usage and improving application performance.
 Increased Flexibility: Allows customization of access permissions per
API key, enabling tailored interactions with APIs.

Types of API Keys

1. Public API Keys: Used for read-only access to public data and are
typically embedded in client-side applications.
2. Secret API Keys: Used for accessing sensitive data, including write
operations, and must be kept confidential in server-side applications.
3. JWT-based API Keys: Use JSON Web Tokens for authentication and
authorization, commonly used in modern web applications.
4. Session-based API Keys: Temporary keys issued for short-term access
that expire after a session ends.
5. Scoped API Keys: Used to restrict access to specific features or
resources of an API.

Best Practices for API Keys

 Keep Secret Keys Confidential: Never expose secret keys in public


repositories or client-side code.
 Rotate Keys Regularly: Periodically generate new API keys to mitigate
the risk of unauthorized access.
 Use Environment Variables: Store API keys securely using
environment variables or secret management tools.
 Implement Rate Limiting: Enforce rate limits on API keys to prevent
abuse and protect server resources.

Generating API Keys

 API keys are typically generated through the API provider’s developer
portal or admin dashboard.
 Choose the appropriate type of key based on your application’s needs
(e.g., public vs. secret) and securely manage and store them.

SECURING MICRO SERVICE APIS: SERVICE MESH


What is a Service Mesh?

A service mesh is like a security and management layer for services


(applications) running inside a Kubernetes cluster. It uses small helper programs
(proxies) to control and protect communication between these services.

How Does it Work?

1. Proxy Sidecars: Every service (application) in Kubernetes gets a tiny


"proxy" program that sits alongside it. This proxy manages all incoming
and outgoing communication.
2. Central Control: There's a central control system (control plane) that
manages these proxies. It handles security (like encryption), traffic rules
(like who can talk to whom), and monitoring (keeping an eye on how
things are running).
3. Security and Management: The proxies ensure all communication is
secure using encryption (like a secure tunnel). They also help manage
how much traffic each service gets and can handle errors automatically.
4. Monitoring: The service mesh keeps track of what's happening between
services, collecting data on performance and errors to help with
troubleshooting.

Why Use a Service Mesh?

 Security: Provides strong protection for data traveling between services,


ensuring it can't be intercepted.
 Management: Simplifies how services communicate, making it easier to
control traffic and apply rules.
 Monitoring: Gives detailed insights into how services are performing,
helping to spot and fix issues quickly.

SECURING INCOMING REQUESTS


What is an Ingress Controller?

An ingress controller serves as a gateway that handles incoming requests from


external clients into a Kubernetes cluster.

How Does it Work?

1. Gateway for External Requests: Acts as a reverse proxy or load


balancer that receives all external requests destined for services within the
Kubernetes cluster.
2. Security and Control: Can be configured to perform essential security
functions such as terminating TLS (HTTPS) connections, enforcing rate
limits on incoming requests, and logging all traffic for auditing purposes.
3. Integration with Service Mesh: When integrated with a service mesh
like Linkerd, ensures that incoming requests are automatically secured
using HTTPS (TLS termination).
4. Unified API Gateway: Often functions as an API gateway, providing a
single point of entry and a unified API for multiple services running
within the Kubernetes cluster.

Why Use an Ingress Controller?

 Centralized Control: Manages incoming traffic for the entire Kubernetes


cluster, making it easier to apply security policies consistently.
 Security Enhancements: Enhances security by encrypting external
communications (TLS termination), limiting request rates to prevent
overload (rate limiting), and logging traffic for auditing and monitoring
purposes.
 Simplifies Routing: Provides a simpler way to route incoming requests
to different services based on URL paths or domain names.

You might also like