Cyber Security
Backend
Backend
Backend is the part of an application that runs behind the scenes and is responsible for handling business logic, data storage, and communication with external systems.
It contains the core source code of the solution that realize the functionality.
Brute Force: Guessing passwords repeatedly, you should have Strong passwords, login rate limits, and account lockout policies
Fixation: It’s an attack that hacker can steal your session ID and use it to execute HTTP requests
Use HTTPOnly : cookie is not accessible via JavaScript (document.cookie)
Use short session lifetimes
Bind session to IP/User-Agent (optional)
Disable URL-based session tracking
XSS: Cross-Site Scripting — injecting scripts into websites, you should have Input validation, output encoding, Content Security Policy (CSP)
DDoS
Distributed Denial of Service — overwhelms servers
You should have WAF, CDN, rate-limiting, DDoS mitigation tools
Brute-Force: Attacker trying many passwords or passphrases with the hope of eventually guessing correctly. Can be resolved by delaying the repetitive trials and blocking the incoming IPs from IIS
SQLi: SQL Injection — inserting malicious queries into databases, you should have you should have Prepared statements, ORM frameworks, input sanitization
SQL Injection : Injecting malicious SQL queries
Use PreparedStatement or ORM (e.g. Hibernate)
Deserialization Attack:
Running malicious code via deserialized Java objects
Use safe libraries like Jackson with strict type checks
Authentication Bypass
Gaining unauthorized access
Validate JWTs, session tokens, and user roles strictly
Path Traversal:
Accessing files outside allowed directories
Sanitize and validate file paths
RCE (Remote Code Execution)
Executing commands remotely on the server
Avoid Runtime.exec(); validate all inputs
XSS via Server-side Templates
Injecting scripts into server-rendered HTML
Escape output and sanitize user input
CSRF (Cross-Site Request Forgery)
Forging requests on behalf of a logged-in user
Use CSRF tokens and SameSite cookies
Broken Access Control
Unauthorized access to resources or operations
Enforce RBAC (Role-Based Access Control) at every layer
9 Insecure Logging (Info Leak)
Logging sensitive information by mistake
Avoid logging passwords, tokens, or PII
JWT Approach
Payload Encryption
Authentication:
Never use basic authentication.
Strong Authentication (OAuth 2.0, OpenID Connect, JWT)
Encrypted
Better as it has an Expiry
Standard
Has claims and more authorization
MFA: Multi-factor authentication, authentication at first login
Implement Role-Based Access Control (RBAC) to prevent access to improper services
Continuous authentication on sensitive activities
Short-term tokens
RBAC: Role-based access control
Business rate-limiting:
Rate limit functionalities from the system, like 3 failed logins will block the account
CAPTCHA implementation to prevent hacking Bots
Limit login failures to prevent guessing and analyze behavior.
Channel exposure scope: What you described (exposing only specific APIs through the gateway & hiding the rest) is about API exposure control & access policies, which is a security and architecture concern.
Secrets
Use secret keys
Use a secret key for each channel
Auto-Rotate secret keys
Never be exposed to FE
Never log secrets
HMAC
Configuration
Expose configuration to configmaps
Encrypt configurations
Use feature flags to disable/isolate broken functionality
Apply external configuration design pattern
Apply real-time configuration design pattern
Pipeline
Integrate SAST tools at the pipeline, like SonarCloud
Communication
Encrypt payload {_data: EncryptedPayLoad}
Add a filter at the gateway level to decrypt
Configure and implement CSRF tokens
Add HSTS and XSS headers at the backend
API Architecture
Security-based architecture instead of business-based
API Signature Minimization
Uncrawlable parameters
Encrypt payload in Post methods
Use Post methods instead of Get for get methods in order to be able to encrypt the payload, as data exposed in the URL leads risk of leaks
Reduce touch surface
Application of the Aggregator design pattern
API Gateway
Gateway-offloading
CQRS
DDoS considerations:
Service health checkers probes
Circuit breaker
Graceful degradation
API versioning deprecation model for old APIs
Design for failure:
Retry
Circuit breaker
Scheduler agent
Avoid verbose error messages(do not leak stack traces)
Make APIs idempotent → POST returns the same result on retry.
Do not overexpose:
APIs: implement Gateway filters to prevent exposing internal APIs
Parameters in requests
Parameters in response
Channel exposure segregation
Limit access to the integration scope only in the gateway
Limit access per gateway according to the channel scope
Performance and Load Testing:
For example, using JMeter for performance testing that increases the system readiness for accepting more load, and then set the rate limiting upon the stress testing, and enable graceful failure
Resolve the Denial of Services
Caching: Implement caching to prevent DDoS if you are not able to implement rate limiting, or it is not feasible as you have a public service.
Automated Security Testing (OWASP ZAP, Burp Suite )
Payload: Data model
Encrypt payload
Minimize exposure for data models and signatures
Communication:
TLS 1.2 or later
Limit response size to prevent crawling all data
JWT Approach
Payload Encryption
Business Areas Classification
Payment:
Ownership changes
Assets transfer
Data crawling
Sensitive data exposure
Notifications
Financial reports
Security Controls
MFA
CAPTCHA
Encryption
Logging
Process:
Persona Definition: Add hacker as a new persona to your model, and think from a business perspective, using hacker mindsets to secure your solution, including the following:
Hacker values: Penetrate the solution, steal data, steal from others
Hacker characteristics: tech expert
Threat modeling
Classify data sensitivity:
Credentials
Payment records
Medical records
Secret keys
Confidential personal info
Secret and confidential reports
Data collection:
Minimize collected data
Prioritize Data Sensitivity & Privacy
Classify data at the analysis stage: public, confidential, regulated.
Address GDPR, HIPAA, and local privacy laws early.
Evaluate Security Controls Feasibility
During analysis, evaluate how security controls (e.g., MFA, encryption, logging) impact performance, UX, and cost.
Document Assumptions & Residual Risks
Write down assumptions about security context & explicitly note what risks are left for mitigation in later phases.
Embed Security into Acceptance Criteria
Every user story or use case should have clear security acceptance criteria.
What is?
Defensive Programming is a coding practice where developers anticipate and guard against potential errors, misuse, or unexpected conditions during execution. The goal is to make software more reliable, predictable, and maintainable by ensuring it fails safely or recovers gracefully.
Core problem statements:
How can I make my solution more reliable?
How to Secure your solution from abuse and unexpected behavior?
How can we have Consistency Of logic?
Improves software robustness in production.
Prevents small bugs from escalating into critical failures.
Helps maintain security and data integrity.
Supports scalability by making code easier to integrate with other systems.
Issue prediction: Explain what an assertion is, and correctly add precondition and post-condition assertions to functions.
Brainstorming process of what can happen, in the future, understanding your persona, how they can abuse or attack your solution.
Consider a hacker as a core persona within the Defensive programming
Implementation guidelines:
Validate Inputs:
Check data type, range, and format before processing
Double-check approach for FE and BE
Check Preconditions – Ensure assumptions about the environment or state are met.
Fail Fast – Stop execution early when something is wrong rather than letting bad data propagate.
Graceful Error Handling – Provide clear error messages, logs, and fallback behavior.
Use Assertions – Confirm critical assumptions in code during development.
Limit External Dependencies – Reduce reliance on unstable external services or inputs.
Use Immutable Data Structures where possible to prevent accidental changes.
Do not expose yourself and internal behavior
Handle potential integration issues that you can overcome and handle internally:
Like zero and Null values
Like Null text and spaces
Arabic characters
Apply Automation testing: support building concrete defensive programming
Defensive programming and Engineering practices:
Planning phase
Pre Conditions: Use pre-conditions to check that the inputs to a function are safe to use.
Post Conditions: Use post-conditions to check that the output from a function is safe to use.
Coding Standards: Write tests before writing code in order to help determine exactly what that code is supposed to do.
Using defensive programming will support the handling of exceptions before documenting it in the use case.
Phase-based what-if to set proper Handling of any exceptions during the operation, for example:
What if we failed to integrate with other applications during the flow
What if we failed to pay the transaction
Execution phase
Assertions: Put assertions in programs to check their state as they run, and to help readers understand how those programs are supposed to work.
Is the object alive?
Does the object have valid inputs?
Does it come from the authorized channel?
Code Reviews
Unit Testing
TDD
Follow-up phase
Conduct What-if analysis of what can be done
See the crash of the future
Assume that errors are going to arise, and write code to detect them when they do.
Conduct Root cause analysis
Will help preventing the issue arising again
Error Details hiding
What is HMAC?
Security approach used by large tech providers, like CISCO, AWS, Azure, Google, IBM.
HMAC means Hash-based Message Authentication Code, is a security approach that uses Uses secret key + hashing algorithm (e.g., SHA-256) to insure Ensures message integrity and authenticity, so if MITM change the message, it will be verified using the same secret key, and algorithm.
Why It's important?
Prevents request tampering
Fast & lightweight
Stateless – ideal for REST APIs
Does NOT encrypt data
Process:
Input Message:
Shared Secret Key
Hash Function (e.g. HMAC-SHA256)
Combines: message + secret key
Output: Message Signature / HMAC
Receive: Read message Full Message + HMAC
Recalculate HMAC: Uses same message and same secret key
Comparison approach:
If both HMACs match → ✅ Message is authentic and unchanged
If not → ❌ Reject the message
Naming Convention for HMAC header:
Eliminate known names
HMAC
HMAC-HEADER
Go for hardening approach:
X-Auth-Token
X-Custom-Signature
X-Client-Hash
What is Secret key auto-rotation?
Secret key auto-rotation is the automatic, scheduled process of regularly changing secret keys used for encryption or authentication (like HMAC keys) without manual intervention, to enhance security.
CSI (Container Storage Interface) driver is essential in OpenShift (and Kubernetes in general) because it standardizes how storage systems integrate with container orchestration platforms.
Reasons we need CSI in OpenShift:
Standardized Storage Integration
CSI provides a vendor-neutral interface.
Works with any storage backend (Ceph, NetApp, AWS EBS, Azure Disk, etc.).
Dynamic Provisioning
Automates creation of Persistent Volumes (PVs).
Enables StorageClass-based provisioning.
Advanced Storage Features
Snapshots: Take and restore volume snapshots.
Cloning: Create new volumes from existing ones.
Volume Expansion: Resize PVs without downtime.
Portability & Extensibility
Applications can move across environments (on-prem, hybrid, cloud) without changing storage logic.
New drivers can be added without modifying OpenShift core.
Security & Secrets Integration
Works with Vault/KMS for auto-rotation of encryption keys.
Ensures secure mounting/unmounting of volumes.
Future Proofing
In-tree (built-in) volume plugins are deprecated.
CSI is the official Kubernetes standard going forward.
Why It's important?
Instead of using the same secret key for a long time, keys are rotated automatically after a set period (e.g., daily, weekly).
Reduces the key’s lifespan, lowering attack risk.
Improves security management and helps comply with standards like NIST and OWASP.
Minimizes impact if a key is exposed.
The system temporarily supports both old and new keys to ensure smooth operation during rotation.
Process:
Key Generation: Using Vault
Replicate to Infrastructure:
Manage 2 Keys:
Current Key (for signing/verifying new requests)
Previous Key (for verifying requests signed just before rotation)
When a request arrives:
Extract key version from header.
Verify HMAC using corresponding key.
Reject if verification fails.
Auto-rotate keys on a fixed schedule (e.g., every 24h) using a scheduler (Quartz, Spring Scheduled).
After rotation, update key store and notify frontend of new key version if needed.
Infrastructure (OpenShift)
Store secrets securely in OpenShift Secrets or integrate with a vault solution (HashiCorp Vault, AWS KMS, Azure Key Vault).
Mount secrets as environment variables or volumes in microservice pods.
Implement hot-reload or rolling deployment to refresh keys without downtime when secrets rotate.
Use ConfigMaps or API gateway to propagate new key version info to frontend.
Recommended Auto-Rotation Component
Vault can auto-generate & rotate keys via TTL policies.
Microservices fetch the active key using Vault API.
Infra triggers rotation and re-injection into pods.
Alternative: Java Microservice-Based Rotation
If you manage rotation yourself:
Create a dedicated microservice (e.g., key-rotation-service) with:
Secure key generator (SecureRandom, KeyGenerator)
Key versioning logic
Secure persistent storage (e.g., encrypted DB or mounted secrets)
Scheduler (e.g., Spring @Scheduled) to rotate keys every X hours
On rotation:
Promote new key as “current”
Move old current key to “previous”
Update OpenShift secrets
Trigger rolling restart of dependent services
How frontend will know the New Key?
The frontend should never know the actual secret key — only the key version (e.g., v1, v2).
Rotation awareness is handled like this:
Frontend gets the current key version via:
API response header (e.g., X-Key-Version)
Config API (e.g., /auth/config)
Backend knows both current and previous keys, and handles verification.
Frontend signs with current version only.
Only backend handles real key rotation logic.
JWT (JSON Web Token) 🔑
A compact, URL-safe token format used for securely transmitting claims between parties. Often used for authentication/authorization in stateless APIs.
RBAC (Role-Based Access Control) 👥
Access management model where permissions are granted based on user roles. Simplifies administration by grouping privileges into roles.
RBAC Scope 🎯
The boundary that defines where a role’s permissions apply (e.g., project, tenant, system-wide). Prevents privilege overreach.
Excessive Exposure 🚨
When APIs or systems expose more data than necessary. Increases risk of leakage, especially through unfiltered responses.
Sensitive Data Exposure 🔒
Improper handling of critical data (PII, credentials, tokens). Leads to breaches if not encrypted, masked, or minimized.
Encrypt at Transit 🔐
Use of TLS/SSL to secure data as it travels between client, server, and services. Protects against eavesdropping and MITM attacks.
Consolidate 📦
Reducing redundancy by centralizing services, APIs, or controls. Improves maintainability, performance, and security oversight.
Deprecate ⏳
Marking old APIs, features, or methods as outdated. Encourages migration to newer, more secure or efficient alternatives.
Rate Limiting 🚦
Restricts the number of requests a client can make within a timeframe. Protects against brute force, DDoS, and abuse.
Mass Assignment (Auto Map) ⚠️
Automatic mapping of user input to object properties. Dangerous if unvalidated fields allow privilege escalation or data tampering.
Injections 💉
Attacks where malicious input is executed as code (SQLi, NoSQLi, OS commands). Prevented by sanitization, parameterization, and least privilege.
Dr. Ghoniem Lawaty
Tech Evangelist @TechHuB Egypt