0% found this document useful (0 votes)
9 views38 pages

API Security and Best Practices v1.0-10

The document outlines best practices for API security, focusing on common vulnerabilities, risks, and secure coding techniques. It emphasizes the importance of authentication, authorization, encryption, and secure software development lifecycle to protect APIs from threats. Key recommendations include implementing proper access controls, input validation, and regular security assessments to ensure API integrity and confidentiality.

Uploaded by

Najib Kun
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)
9 views38 pages

API Security and Best Practices v1.0-10

The document outlines best practices for API security, focusing on common vulnerabilities, risks, and secure coding techniques. It emphasizes the importance of authentication, authorization, encryption, and secure software development lifecycle to protect APIs from threats. Key recommendations include implementing proper access controls, input validation, and regular security assessments to ensure API integrity and confidentiality.

Uploaded by

Najib Kun
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/ 38

ST RENGT HENING API SE CURI T Y: E XPLORING

VUL NERABILI T IES, RISKS, AND BE ST


PRACT ICE S

WRITING CODE SECURELY 1


WHOAMI

Dr. Semi Yulianto


BSc. (Accounting), M.IT (IT Security & Governance), Ph.D. (DIT & DCS)
MCT, MCDBA, MCTS, MCITP, MCSA, MCSE (Security & Messaging), MCT, CNA, CNE, CNI, CCNP, CWNA, CND, CEH, ECSA, CHFI,
ECSP, EDRP, CEI, SSCP, CISSP, CSSLP, CISA, CISM, Security+, CySA+, PenTest+, CASP+, CNSP, CNVP, CSAP, OSSA, CASE
Java, ISO 27001 LA, BSSN ISO 27001 Implementer

[email protected] // +62-858-1325-6600 .and. +62-813-8135-4988


YouTube.com/c/SemiYulianto

API SECURITY & BEST PRACTICES 2


Course Objectives
 Learn about common API vulnerabilities, including those in the
OWASP Top 10.
 Understand how to scan and fix API security issues using specialized
tools.
 Implement coding techniques like input validation and strong
authentication to secure APIs.
 Identify potential threats and weaknesses in API designs.
 Enhance communication between developers and security teams to
build secure APIs.

API SECURITY & BEST PRACTICES 3


AGENDA
 Introduction to API Security
 Secure Software Development Lifecycle
 OWASP Top 10 API Risks
 Secure Coding Best Practices
 API Security Best Practices
 Questions & Answers

API SECURITY & BEST PRACTICES 4


Introduction to API Security (1)
 API security refers to the practice of protecting application
programming interfaces (APIs) from unauthorized access, attacks,
and misuse.
 APIs allow applications to communicate and share data, making them
critical components in modern software architectures, including web
applications, mobile apps, and cloud services.
 Ensuring API security is essential to prevent data breaches,
unauthorized access, and service disruptions.

API SECURITY & BEST PRACTICES 5


Introduction to API Security (2)
Key aspects of API security include:
 Authentication: Ensuring only authorized users or systems can
access the API using methods like OAuth, API keys, or JWT (JSON
Web Tokens).
 Authorization: Defining what authenticated users or systems are
allowed to do by implementing role-based or attribute-based access
controls (RBAC/ABAC).

API SECURITY & BEST PRACTICES 6


Introduction to API Security (3)
Key aspects of API security include:
 Encryption: Protecting data in transit and at rest using encryption
protocols such as TLS/SSL to prevent eavesdropping and data
interception.
 Rate Limiting and Throttling: Preventing abuse by limiting the
number of API requests a user or system can make within a certain
timeframe to avoid denial-of-service (DoS) attacks.

API SECURITY & BEST PRACTICES 7


Introduction to API Security (4)
Key aspects of API security include:
 Input Validation and Sanitization: Ensuring that incoming data is
properly validated and sanitized to prevent injection attacks such as
SQL injection and cross-site scripting (XSS).
 Logging and Monitoring: Tracking API activity to detect and
respond to suspicious behavior, ensuring compliance and quick
identification of security incidents.

API SECURITY & BEST PRACTICES 8


Introduction to API Security (5)
Key aspects of API security include:
 API Gateway Security: Using an API gateway to enforce security
policies, manage traffic, and provide centralized control over API
access.
 Security Testing: Regularly conducting security assessments,
including penetration testing and vulnerability scanning, to identify
and fix potential weaknesses.

API SECURITY & BEST PRACTICES 9


Introduction to API Security (6)
Key aspects of API security include:
 Secure Coding Practices: Following secure development principles
such as avoiding hardcoded credentials, using strong authentication
mechanisms, and implementing least privilege access.
 Compliance and Governance: Ensuring API security measures
align with industry regulations and standards such as GDPR, HIPAA,
and ISO 27001.

API SECURITY & BEST PRACTICES 10


Introduction to API Security (7)
 By implementing these security measures, organizations can protect
their APIs from threats such as unauthorized access, data breaches,
injection attacks, and denial-of-service attacks, ensuring the
confidentiality, integrity, and availability of their systems.

API SECURITY & BEST PRACTICES 11


Introduction to API Security (8)
 The most common attacks on APIs exploit vulnerabilities in authentication,
authorization, and data handling processes.
 Some of the most prevalent API attacks include:
o Broken Object Level Authorization (BOLA)
o Broken User Authentication
o Excessive Data Exposure
o Rate Limiting Bypass (Denial of Service)
o Injection Attacks (SQL, XML, NoSQL, etc.)
o Security Misconfiguration
o Insecure Direct Object References (IDOR)
o Cross-Site Scripting (XSS) via API

API SECURITY & BEST PRACTICES 12


API Gateway Architecture Example

API SECURITY & BEST PRACTICES 13


Secure Software Development Lifecycle (1)
 The Secure Development Lifecycle (SDL) is a structured process
that integrates security practices into each phase of the software
development lifecycle. Its primary goal is to minimize vulnerabilities in
applications and ensure they are secure from design through
deployment and beyond.
 Key Phases of SDL are Planning and Requirements, Design,
Implementation, Testing, Deployment, Operations and Maintenance,
End-of-Life.

API SECURITY & BEST PRACTICES 14


Secure Software Development Lifecycle (2)

API SECURITY & BEST PRACTICES 15


Secure Software Development Lifecycle (3)
Phase Activities
Planning and Requirements • Define security requirements alongside functional requirements.
• Identify potential threats and compliance obligations (e.g., GDPR, PCI-DSS).
• Conduct a risk assessment to determine the application's security needs.
Design • Perform threat modeling to identify and address potential risks early.
• Incorporate secure architecture and design principles (e.g., least privilege, defense in depth).
• Specify security controls and countermeasures.
Implementation • Use secure coding practices to minimize vulnerabilities (e.g., OWASP Secure Coding Guidelines).
• Adopt static code analysis tools to identify vulnerabilities during development.
• Conduct peer code reviews with a focus on security.
Testing • Perform security testing such as penetration testing, fuzz testing, and vulnerability scanning.
• Validate inputs, authentication, and access control mechanisms.
• Ensure secure error handling and proper logging practices.
Deployment • Harden servers and configurations to prevent exploitation.
• Implement secure deployment pipelines to ensure that security controls are enforced.
• Use containerization and virtualization to isolate applications.
Operations and Maintenance • Monitor for new vulnerabilities and apply patches promptly.
• Conduct regular security assessments and audits.
• Use logging and monitoring tools to detect and respond to incidents.
End-of-Life • Ensure secure decommissioning of applications.
• Safely archive or delete sensitive data associated with the application.

API SECURITY & BEST PRACTICES 16


Secure Software Development Lifecycle (4)
Benefits of SDL
 Reduces the cost of fixing vulnerabilities by identifying them early.
 Helps ensure compliance with regulatory and industry standards.
 Improves user trust and reduces the risk of breaches.
 Builds a culture of security awareness among developers.

API SECURITY & BEST PRACTICES 17


Secure Software Development Lifecycle (5)
 Addressing security in each phase of the SDLC ensures robust
applications that resist attacks, reducing ownership costs for both
users and vendors through secure design, coding, testing, and
deployment.
 SDL can be tailored to Agile or DevOps methodologies by embedding
security as a continuous process, often referred to as DevSecOps,
promoting ongoing resilience.

API SECURITY & BEST PRACTICES 18


OWASP Top 10 API Security Risks (1)
 The OWASP Top 10 API Security Risks is a list of the most critical
security risks to APIs, published by the Open Web Application
Security Project (OWASP).
 It provides guidance to help organizations secure their APIs by
addressing common vulnerabilities.

API SECURITY & BEST PRACTICES 19


OWASP Top 10 API Security Risks (2)
 API1:2023 - Broken Object Level  API6:2023 - Unrestricted Access to
Authorization Sensitive Business Flows
 API2:2023 - Broken Authentication  API7:2023 - Server-Side Request
Forgery (SSRF)
 API3:2023 - Broken Object
 API8:2023 - Security
Property Level Authorization Misconfiguration
 API4:2023 - Unrestricted Resource  API9:2023 - Improper Inventory
Consumption Management
 API5:2023 - Broken Function Level  API10:2023 - Unsafe Consumption
Authorization of APIs

API SECURITY & BEST PRACTICES 20


Secure Coding Best Practices
 Broken Object Level Authorization
 Broken User Authentication
 Excessive Data Exposure
 Lack of Resources & Rate Limiting
 Broken Function Level Authorization

API SECURITY & BEST PRACTICES 21


Broken Object Level Authorization (1)
 Description: APIs often expose endpoints that allow access to
objects without proper authorization checks, leading to data exposure
or manipulation.
 Recommendations:
• Implement proper authorization checks.
• Use access tokens to validate user permissions.
• Apply role-based access controls (RBAC).

API SECURITY & BEST PRACTICES 22


Broken Object Level Authorization (2)
 Vulnerable Code:

@app.route('/api/user/<user_id>', methods=['GET'])
def get_user(user_id):
user = db.get_user_by_id(user_id)
return jsonify(user)

An attacker can manipulate the user_id parameter to access other users'


data without authorization.

API SECURITY & BEST PRACTICES 23


Broken Object Level Authorization (3)
 Safe Code:
@app.route('/api/user/<user_id>', methods=['GET'])
def get_user(user_id):
if session['user_id'] != user_id:
return jsonify({"error": "Unauthorized access"}), 403
user = db.get_user_by_id(user_id)
return jsonify(user)

Ensure the logged-in user's session ID matches the requested user_id


before returning data.

API SECURITY & BEST PRACTICES 24


Broken User Authentication (1)
 Description: Weak authentication mechanisms can allow attackers
to bypass authentication and gain unauthorized access.
 Recommendations:
• Always hash passwords using strong algorithms.
• Implement multi-factor authentication (MFA).
• Use secure session management practices.

API SECURITY & BEST PRACTICES 25


Broken User Authentication (2)
 Vulnerable Code:
@app.route('/api/login', methods=['POST'])
def login():
user = db.get_user_by_username(request.json['username'])
if user and user['password'] == request.json['password']:
return jsonify({"token": "dummy-token"})
return jsonify({"error": "Invalid credentials"}), 401

The password is being compared in plain text without hashing, making it


susceptible to attacks if data is leaked.

API SECURITY & BEST PRACTICES 26


Broken User Authentication (3)
 Safe Code:
import bcrypt

@app.route('/api/login', methods=['POST'])
def login():
user = db.get_user_by_username(request.json['username'])
if user and bcrypt.checkpw(request.json['password'].encode('utf-8'),
user['password'].encode('utf-8')):
return jsonify({"token": generate_jwt_token(user['id'])})
return jsonify({"error": "Invalid credentials"}), 401

Use bcrypt to hash passwords and implement token-based authentication.

API SECURITY & BEST PRACTICES 27


Excessive Data Exposure (1)
 Description: APIs may expose more data than necessary, leading to
potential information leakage.
 Recommendations:
• Avoid exposing sensitive information.
• Use response filtering mechanisms.

API SECURITY & BEST PRACTICES 28


Excessive Data Exposure (2)
 Vulnerable Code:
@app.route('/api/user/profile', methods=['GET'])
def get_profile():
user = db.get_user_by_id(session['user_id'])
return jsonify(user)

All user data, including sensitive fields like passwords and tokens, may be
exposed in the response.

API SECURITY & BEST PRACTICES 29


Excessive Data Exposure (3)
 Safe Code:
@app.route('/api/user/profile', methods=['GET'])
def get_profile():
user = db.get_user_by_id(session['user_id'])
return jsonify({"name": user['name'], "email": user['email']})

Limit the data returned to only what is necessary.

API SECURITY & BEST PRACTICES 30


Lack of Resources & Rate Limiting (1)
 Description: APIs without rate limits are vulnerable to denial-of-
service (DoS) attacks.
 Recommendations:
• Use rate-limiting mechanisms.
• Monitor and log API usage.

API SECURITY & BEST PRACTICES 31


Lack of Resources & Rate Limiting (2)
 Vulnerable Code:

@app.route('/api/search', methods=['GET'])
def search():
query = request.args.get('query')
return jsonify(db.search(query))

An attacker can flood the API with requests, overwhelming the server.

API SECURITY & BEST PRACTICES 32


Lack of Resources & Rate Limiting (3)
 Safe Code:
from flask_limiter import Limiter

limiter = Limiter(app, key_func=lambda: request.remote_addr)

@app.route('/api/search', methods=['GET'])
@limiter.limit("10 per minute")
def search():
query = request.args.get('query')
return jsonify(db.search(query))

Implement rate limiting to restrict the number of API requests.

API SECURITY & BEST PRACTICES 33


Broken Function Level Authorization (1)
 Description: Incorrect access control at the function level can allow
unauthorized users to access admin functions.
 Recommendations:
• Use role-based access control.
• Enforce the principle of least privilege.

API SECURITY & BEST PRACTICES 34


Broken Function Level Authorization (2)
 Vulnerable Code:
@app.route('/api/admin/delete_user', methods=['POST'])
def delete_user():
user_id = request.json['user_id']
db.delete_user(user_id)
return jsonify({"message": "User deleted"})

Any authenticated user can access the delete function without admin
verification.

API SECURITY & BEST PRACTICES 35


Broken Function Level Authorization (3)
 Safe Code:
@app.route('/api/admin/delete_user', methods=['POST'])
def delete_user():
if session['role'] != 'admin':
return jsonify({"error": "Access denied"}), 403
user_id = request.json['user_id']
db.delete_user(user_id)
return jsonify({"message": "User deleted"})

Implement role-based authorization checks.

API SECURITY & BEST PRACTICES 36


API Security Best Practices
 API security best practices help organizations protect their APIs from
potential threats and ensure the confidentiality, integrity, and
availability of data.
 Here are some key best practices:
• Implement Authentication and Authorization
• Use HTTPS/TLS Encryption
• Implement Rate Limiting and Throttling
• Validate and Sanitize Inputs
• Minimize Data Exposure
• Use Secure API Gateways

API SECURITY & BEST PRACTICES 37


Questions & Answers

API SECURITY & BEST PRACTICES 38

You might also like