Title: Software Security — LearnCoachAssist

Q: What is the OWASP Top 10?
A: The OWASP Top 10 is a regularly updated list of the most critical web application security risks. The 2021 edition includes:
- A01: Broken Access Control
- A02: Cryptographic Failures
- A03: Injection
- A04: Insecure Design
- A05: Security Misconfiguration
- A06: Vulnerable Components
- A07: Authentication Failures
- A08: Data Integrity Failures
- A09: Logging Failures
- A10: SSRF

Q: What is Cross-Site Scripting (XSS)?
A: XSS is a vulnerability where an attacker injects malicious scripts into web pages viewed by other users. Three types:
- Reflected: script in URL is reflected back in the response
- Stored: script is permanently stored on the server (e.g., in a database)
- DOM-based: script manipulates the page's DOM client-side
Prevention: output encoding, CSP, input validation.

Q: What is reflected XSS?
A: Reflected XSS occurs when user input from a request is immediately included in the response without proper encoding. Example: a search page that displays the query parameter without sanitization. Prevention:
- HTML-encode all output
- Use Content-Security-Policy headers
- Validate and sanitize input

Q: What is stored XSS?
A: Stored XSS (persistent XSS) occurs when malicious script is saved on the server (e.g., in a database, forum post, or comment) and served to users who view that content. It's more dangerous than reflected XSS because it affects all users who view the page, not just those who click a crafted link. Prevention: sanitize on input, encode on output.

Q: What is DOM-based XSS?
A: DOM-based XSS occurs entirely on the client side — the vulnerability exists in JavaScript code that processes data from an untrusted source (like location.hash) and writes it to the DOM using unsafe methods like innerHTML or document.write(). The malicious payload never reaches the server. Prevention: use textContent instead of innerHTML, avoid eval().

Q: What is CSRF (Cross-Site Request Forgery)?
A: CSRF tricks a user's browser into making an unwanted request to a site where they're authenticated. Example: a malicious page submitting a hidden form to a banking site. Prevention:
- CSRF tokens — unique tokens per session/request
- SameSite cookie attribute
- Check Origin/Referer headers
- Require re-authentication for sensitive actions

Q: What is SQL injection?
A: SQL injection occurs when untrusted input is included in SQL queries without proper sanitization, allowing attackers to execute arbitrary SQL. Example: SELECT * FROM users WHERE name = '' OR '1'='1'. Prevention:
- Parameterized queries: WHERE name = ?
- Use an ORM
- Input validation and escaping
- Principle of least privilege for DB accounts

Q: What are parameterized queries?
A: Parameterized queries (prepared statements) separate SQL code from data by using placeholders for user input. The database engine treats parameters as data, never as executable code.
Example: db.query("SELECT * FROM users WHERE id = ?", [userId])
This is the primary defense against SQL injection, supported by all major databases and ORMs.

Q: What is the difference between authentication and authorization?
A: - Authentication (AuthN): verifies who you are — login with username/password, biometrics, MFA
- Authorization (AuthZ): determines what you can do — permissions, roles, access control
Authentication always comes first. Example: logging in proves your identity (authentication); your role determines which pages you can access (authorization).

Q: What is OAuth 2.0?
A: OAuth 2.0 is an authorization framework that allows third-party applications to access a user's resources without exposing their credentials. Key grant types:
- Authorization Code: for server-side apps (most secure)
- PKCE: for SPAs and mobile apps
- Client Credentials: for machine-to-machine
- Refresh Token: for obtaining new access tokens

Q: What is the OAuth 2.0 Authorization Code flow?
A: The Authorization Code flow:
1. App redirects user to authorization server
2. User authenticates and grants consent
3. Server redirects back with an authorization code
4. App exchanges the code for an access token (server-to-server)
5. App uses the access token to call APIs
Most secure flow because tokens never pass through the browser.

Q: What is a JWT (JSON Web Token)?
A: A JWT is a compact, URL-safe token format for securely transmitting claims between parties. Structure: header.payload.signature
- Header: algorithm and token type
- Payload: claims (user data, expiry)
- Signature: verifies integrity using HMAC or RSA
JWTs are stateless — the server doesn't need to store session data. Base64Url encoded, not encrypted by default.

Q: What are common JWT security pitfalls?
A: Common JWT security risks:
- Using alg: "none" — always validate the algorithm
- Storing JWTs in localStorage (vulnerable to XSS) — use httpOnly cookies
- Not validating the signature
- No expiration (exp claim)
- Putting sensitive data in the payload (it's only encoded, not encrypted)
- Not implementing token revocation

Q: How does HTTPS/TLS work?
A: HTTPS uses TLS (Transport Layer Security) to encrypt communication. The TLS handshake:
1. Client sends supported cipher suites
2. Server responds with its certificate and chosen cipher
3. Client verifies the certificate against trusted CAs
4. Both parties establish a shared secret using asymmetric encryption
5. All subsequent data is encrypted with symmetric encryption

Q: What is the TLS certificate chain?
A: A TLS certificate chain is a hierarchy of trust:
- Root CA: self-signed, pre-installed in browsers/OS
- Intermediate CA: signed by root CA
- Server certificate: signed by intermediate CA
The browser walks up the chain to verify each certificate is signed by a trusted authority. Certificate pinning restricts which CAs are trusted for a domain.

Q: What is password hashing and why not use encryption?
A: Password hashing is a one-way transformation — you can verify a password but cannot recover the original. Unlike encryption (which is reversible), hashing ensures that even if the database is compromised, passwords cannot be recovered.
Use slow hash functions designed for passwords: bcrypt, argon2, scrypt. Never use MD5 or SHA-256 alone — they're too fast.

Q: What is bcrypt?
A: bcrypt is a password hashing function based on the Blowfish cipher. Key features:
- Built-in salt — prevents rainbow table attacks
- Configurable work factor (cost) — can be increased as hardware improves
- Deliberately slow — resistant to brute force
Usage: bcrypt.hash(password, saltRounds). Output format: $2b$12$salt...hash...

Q: What is Argon2?
A: Argon2 is the winner of the 2015 Password Hashing Competition. Three variants:
- Argon2d: data-dependent, resistant to GPU attacks
- Argon2i: data-independent, resistant to side-channel attacks
- Argon2id: hybrid (recommended)
It's configurable on time, memory, and parallelism, making it resistant to both GPU and ASIC attacks.

Q: What is the difference between symmetric and asymmetric encryption?
A: - Symmetric: same key for encryption and decryption — AES, ChaCha20. Fast, used for bulk data. Challenge: securely sharing the key.
- Asymmetric: public key encrypts, private key decrypts — RSA, ECC. Slower, used for key exchange and digital signatures.
TLS uses asymmetric encryption to exchange a symmetric key, then symmetric encryption for the session.

Q: What is AES encryption?
A: AES (Advanced Encryption Standard) is the most widely used symmetric encryption algorithm. Key features:
- Block cipher with 128-bit blocks
- Key sizes: 128, 192, or 256 bits
- Modes: CBC, GCM (authenticated), CTR
AES-256-GCM is recommended — it provides both confidentiality and integrity (authenticated encryption).

Q: What is CORS (Cross-Origin Resource Sharing)?
A: CORS is a browser mechanism that allows servers to specify which origins can access their resources. Key headers:
- Access-Control-Allow-Origin: allowed origins
- Access-Control-Allow-Methods: allowed HTTP methods
- Access-Control-Allow-Headers: allowed headers
- Access-Control-Allow-Credentials: allow cookies
Preflight requests (OPTIONS) check permissions before the actual request.

Q: What is the Same-Origin Policy?
A: The Same-Origin Policy is a browser security mechanism that restricts scripts from one origin from accessing resources of a different origin. Two URLs have the same origin if they share the same protocol, host, and port.
Example: https://example.com:443 differs from http://example.com:80.
CORS provides controlled exceptions to this policy.

Q: What is Content Security Policy (CSP)?
A: CSP is an HTTP header that tells the browser which sources of content are allowed to load. It mitigates XSS by blocking inline scripts and unauthorized sources.
Example: Content-Security-Policy: default-src 'self'; script-src 'self' cdn.example.com; style-src 'self' 'unsafe-inline'
Key directives: default-src, script-src, style-src, img-src, connect-src.

Q: What is input validation?
A: Input validation is verifying that user-supplied data meets expected format, type, length, and range requirements before processing. Two approaches:
- Allowlist (preferred): accept only known-good patterns
- Denylist: reject known-bad patterns (less secure)
Validate on both client-side (UX) and server-side (security). Never trust client-side validation alone.

Q: What is the difference between input validation and output encoding?
A: - Input validation: verify data meets expected format before processing — reject or sanitize bad input
- Output encoding: transform data for safe display in a specific context — HTML encoding, URL encoding, JS encoding
Both are needed: validation prevents bad data from entering; encoding prevents stored bad data from causing harm when displayed.

Q: What is rate limiting?
A: Rate limiting restricts the number of requests a client can make within a time window. Purposes:
- Prevent brute force attacks
- Protect against DDoS
- Ensure fair usage
Common algorithms:
- Token bucket
- Sliding window
- Fixed window
- Leaky bucket
Typically returns 429 Too Many Requests with Retry-After header.

Q: What is the token bucket algorithm?
A: The token bucket algorithm: a bucket holds tokens up to a maximum capacity. Tokens are added at a fixed rate. Each request consumes one token. If the bucket is empty, the request is rejected. Advantages:
- Allows bursts up to bucket size
- Smooths out request rate over time
- Simple to implement
Used by AWS API Gateway, Stripe, and many rate limiters.

Q: What is secrets management?
A: Secrets management is the practice of securely storing and accessing sensitive data like API keys, passwords, and certificates. Best practices:
- Use a vault (HashiCorp Vault, AWS Secrets Manager)
- Never hardcode secrets in source code
- Use environment variables or secret injection
- Rotate secrets regularly
- Use .gitignore for config files
- Audit access to secrets

Q: What is session management security?
A: Secure session management best practices:
- Generate cryptographically random session IDs
- Set cookies as HttpOnly, Secure, and SameSite
- Implement session timeout (idle and absolute)
- Regenerate session ID after login (prevents session fixation)
- Invalidate sessions on logout
- Store sessions server-side, not in cookies

Q: What is clickjacking?
A: Clickjacking (UI redressing) tricks users into clicking on hidden elements by overlaying a transparent iframe over a legitimate page. The user thinks they're clicking a button but actually interact with the hidden frame.
Prevention:
- X-Frame-Options: DENY header
- Content-Security-Policy: frame-ancestors 'none'
- JavaScript frame-busting (less reliable)

Q: What are important HTTP security headers?
A: Key security headers:
- Strict-Transport-Security (HSTS): force HTTPS
- Content-Security-Policy: control resource loading
- X-Content-Type-Options: nosniff: prevent MIME sniffing
- X-Frame-Options: prevent clickjacking
- X-XSS-Protection: legacy XSS filter
- Referrer-Policy: control referrer information
- Permissions-Policy: control browser features

Q: What is HSTS (HTTP Strict Transport Security)?
A: HSTS tells browsers to only use HTTPS for a domain, even if the user types http://. Header: Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
Benefits:
- Prevents SSL stripping attacks
- Automatic HTTP to HTTPS redirect at browser level
- Preload list: browsers ship with a list of HSTS-enabled domains

Q: What is the principle of least privilege?
A: The principle of least privilege states that every user, program, and process should have only the minimum permissions necessary to perform its function. Examples:
- Database accounts with only required queries
- API keys scoped to specific operations
- Container processes running as non-root
- IAM roles with minimal AWS permissions
Limits the blast radius of a security breach.

Q: What is defense in depth?
A: Defense in depth is a security strategy using multiple layers of protection so that if one layer fails, others still provide security. Layers include:
- Network: firewalls, VPNs, IDS/IPS
- Application: input validation, authentication
- Data: encryption, access controls
- Physical: server room access
- Monitoring: logging, alerting
No single control is considered sufficient.

Q: What is SSRF (Server-Side Request Forgery)?
A: SSRF tricks the server into making HTTP requests to unintended locations, often internal services. Example: an image URL parameter targeting cloud metadata endpoints.
Prevention:
- Allowlist permitted URLs/domains
- Block private IP ranges
- Use network segmentation
- Validate and sanitize URLs
- Disable unnecessary URL schemes

Q: What is Broken Access Control?
A: Broken Access Control (OWASP #1) occurs when users can act outside their intended permissions. Examples:
- IDOR: accessing another user's resources by changing IDs
- Modifying URL parameters to access admin pages
- Missing function-level authorization checks
- CORS misconfiguration
Prevention: deny by default, enforce access control server-side, test authorization on every request.

Q: What are Insecure Direct Object References (IDOR)?
A: IDOR occurs when an application exposes internal object references (like database IDs) and doesn't verify the user has authorization to access them. Example: changing /invoice/1001 to /invoice/1002 to view another user's invoice.
Prevention:
- Check authorization on every request
- Use indirect references (UUIDs)
- Implement proper access control

Q: What is a rainbow table attack?
A: A rainbow table is a precomputed table of hash-to-password mappings used to reverse hash functions. Instead of brute-forcing, attackers look up the hash directly.
Prevention:
- Use a unique salt per password — makes precomputed tables useless
- Use slow hashing algorithms (bcrypt, argon2)
Modern password hashing functions include automatic salting.

Q: What is a salt in password hashing?
A: A salt is a random value added to a password before hashing. Each user gets a unique salt, stored alongside the hash. Benefits:
- Two users with the same password get different hashes
- Defeats rainbow table attacks
- Defeats precomputation attacks
Example: hash(salt + password). bcrypt and argon2 handle salting automatically.

Q: What is multi-factor authentication (MFA)?
A: MFA requires two or more independent authentication factors:
- Knowledge: something you know (password, PIN)
- Possession: something you have (phone, security key)
- Inherence: something you are (fingerprint, face)
Even if one factor is compromised, the attacker cannot authenticate. TOTP and WebAuthn/FIDO2 are common implementations.

Q: What is certificate pinning?
A: Certificate pinning associates a host with its expected public key or certificate, rather than trusting any certificate signed by a CA. The app only accepts connections with the pinned certificate.
Benefits: prevents MITM attacks even if a CA is compromised.
Drawbacks: difficult to rotate certificates, can cause outages if pins expire. HPKP was deprecated in favor of Certificate Transparency.

Q: What is Security Misconfiguration?
A: Security Misconfiguration (OWASP #5) includes:
- Default credentials left unchanged
- Unnecessary features enabled (debug mode, directory listing)
- Missing security headers
- Overly permissive CORS
- Verbose error messages exposing stack traces
- Unpatched software
Prevention: automated configuration scanning, minimal installs, regular audits, infrastructure as code.

Q: What is command injection?
A: Command injection occurs when user input is passed to a system shell without sanitization, allowing execution of arbitrary OS commands. Example: passing unsanitized input to os.system().
Prevention:
- Avoid calling OS commands from application code
- Use language APIs instead of shell commands
- If unavoidable, use parameterized APIs like subprocess.run(["ping", host])

Q: What is a digital signature?
A: A digital signature proves authenticity and integrity of data using asymmetric cryptography:
1. Sender hashes the message
2. Sender encrypts the hash with their private key
3. Recipient decrypts with sender's public key
4. Recipient compares hashes to verify
Used in: code signing, TLS certificates, JWT signing, blockchain transactions.

Q: What is the SameSite cookie attribute?
A: The SameSite cookie attribute controls when cookies are sent with cross-site requests:
- Strict: cookie only sent for same-site requests — strongest CSRF protection
- Lax: sent for top-level navigations but not for forms/AJAX — good balance
- None: always sent (requires Secure flag)
Lax is the browser default since Chrome 80.

Q: What is OpenID Connect (OIDC)?
A: OpenID Connect is an identity layer built on top of OAuth 2.0. While OAuth 2.0 handles authorization, OIDC adds authentication:
- Returns an ID token (JWT) with user identity claims
- Provides a /userinfo endpoint
- Standardized scopes: openid, profile, email
It answers "who is this user?" while OAuth answers "what can they access?"

Q: What is the difference between encoding, encryption, and hashing?
A: - Encoding: transforms data for compatibility (Base64, URL encoding) — not for security, easily reversible
- Encryption: transforms data to protect confidentiality — reversible with key (AES, RSA)
- Hashing: one-way transformation to a fixed-size digest — not reversible (SHA-256, bcrypt)
Each serves a different purpose; using the wrong one creates vulnerabilities.

Q: What is a Man-in-the-Middle (MITM) attack?
A: A MITM attack occurs when an attacker secretly intercepts and relays communication between two parties who believe they're communicating directly. The attacker can eavesdrop, modify, or inject messages.
Prevention:
- Use HTTPS/TLS for all communications
- Implement HSTS
- Certificate pinning
- Verify certificate chains
- Use secure Wi-Fi (WPA3)

Q: What is a CSP nonce?
A: A CSP nonce is a unique random token generated for each page load that allows specific inline scripts to execute. The server adds Content-Security-Policy: script-src 'nonce-abc123' and tags allowed scripts with the matching nonce attribute. This provides fine-grained control over inline scripts without using 'unsafe-inline', strengthening XSS protection.

Q: What is API key security best practice?
A: API key security best practices:
- Never embed keys in client-side code or public repos
- Use environment variables or secret managers
- Scope keys with minimum permissions
- Set expiration dates and rotate regularly
- Use different keys for development and production
- Monitor usage for anomalies
- Revoke compromised keys immediately