Ravindra BagaleCourses & study guides Track your progress

AWS Cloud

How to Prevent Hacking of a Web Application: Web Security Interview Questions on SQL Injection, XSS, CSRF and DDoS Defence (20 Questions)

This page has 20 interview questions on how to protect web applications from common attacks. Every answer is defensive: how the risk works at a high level, how to prevent it, and how AWS services help. There are no attack payloads or step-by-step attack instructions here.

1. An everyday example: protecting a house

Why does this topic matter?

Most breaches of web applications come from a short list of mistakes: trusting user input, weak sessions, missing access checks, leaked secrets and old libraries. Interviewers expect cloud engineers to know the fixes, not just the names.

Think of protecting a house. A fence and gate (CloudFront, AWS WAF and Shield) keep most trouble out. Good locks on every door (authentication and access checks) stop those who get past the gate. A safe for valuables (encryption and Secrets Manager) protects what matters most, and cameras and alarms (logs, GuardDuty) tell you quickly when something is wrong. No single layer is enough; together they make the house a hard target.

How to use this page

  • Practise only on applications you own or have written permission to test.
  • Code snippets show a weak pattern next to the safe pattern for learning only.
  • All IDs and names are examples, such as account 111122223333.

2. Fresher level questions

Start here if you are a fresher or have less than two years of experience. Try to answer each question aloud first. Then open it and compare.

Q1. How do you prevent hacking of a web application on AWS? Give a layered checklist from the edge to the database. Fresher
  • Edge: CloudFront with HTTPS only, AWS Shield Standard (automatic), AWS WAF with managed rules and rate-based rules.
  • Load balancer and network: only the ALB is public; app servers and databases in private subnets; security groups allow only the needed ports from the layer in front.
  • Application: validate input, parameterised queries, output encoding, strong session handling, access checks on every request, security headers.
  • Identity: least-privilege IAM roles for the app, no long-term keys, MFA for people.
  • Data: encryption at rest with KMS and in transit with TLS; secrets in Secrets Manager.
  • Operations: patching, dependency scanning (Amazon Inspector), logging (CloudTrail, WAF logs), detection (GuardDuty, Security Hub), backups and an incident plan.
Q2. Why do parameterised queries stop SQL injection when escaping user input by hand is not enough? Fresher

SQL injection happens when user input is joined into the SQL text, so the database may treat part of the input as SQL commands.

Weak pattern (do not use):

query = "SELECT * FROM users WHERE email = '" + email + "'"

Safe pattern:

cursor.execute("SELECT * FROM users WHERE email = %s", (email,))

With parameters, the SQL text and the data travel separately; the database never treats the data as code, whatever characters it contains. Hand-written escaping misses edge cases (encodings, numeric fields, different databases). Also use an ORM correctly, give the app's database user only the permissions it needs, and add AWS WAF's SQL database managed rule group as an extra layer, not as the main fix.

Q3. What are stored, reflected and DOM-based XSS, and how does a defender stop each? Fresher
TypeWhere the script comes fromMain defence
StoredSaved in the database (for example a comment) and shown to other usersEncode output when displaying; sanitise allowed HTML with a trusted library
ReflectedTaken from the request (URL or form) and sent straight back in the pageEncode output; validate input
DOM-basedFront-end JavaScript writes untrusted data into the pageUse safe APIs (textContent instead of innerHTML), framework auto-escaping

For all types: a Content Security Policy limits which scripts can run, and HttpOnly cookies stop scripts from reading session cookies.

Q4. Which HTTP security response headers should a website send, and what does each protect against? Fresher
HeaderProtects against
Content-Security-PolicyXSS and unwanted scripts, frames and data sources
Strict-Transport-SecurityDowngrade to plain HTTP
X-Content-Type-Options: nosniffBrowsers guessing a file type and running it as script
Content-Security-Policy frame-ancestors (or X-Frame-Options)Clickjacking by framing your pages
Referrer-PolicyLeaking full URLs (with tokens or IDs) to other sites
Permissions-PolicyPages using camera, microphone or location without need

On AWS, a CloudFront response headers policy can add these headers to every response without changing the application.

Q5. How do SameSite cookies and anti-CSRF tokens work together to block forged requests? Fresher

CSRF tricks a logged-in user's browser into sending a request to your site that the user did not intend, because the browser attaches the session cookie automatically.

  • SameSite=Lax or Strict on the session cookie tells the browser not to send it on most cross-site requests.
  • An anti-CSRF token: a random value tied to the session, included in forms or headers, and checked by the server on every state-changing request. Another site cannot read it, so it cannot forge it.
  • Never change data with GET requests.

Use both, because older browsers and some flows (for example cross-site logins) weaken SameSite alone. APIs using bearer tokens in headers (not cookies) are not exposed to classic CSRF.

Q6. What do AWS WAF managed rule groups give you, and how do you turn them on safely? Fresher

AWS managed rule groups are ready-made rule sets maintained by AWS, for example:

  • Core rule set: common web attack patterns.
  • Known bad inputs: request patterns linked to known vulnerabilities.
  • SQL database and Linux or Windows operating system rule groups.
  • IP reputation lists and anonymous IP lists.
  • Bot Control and account takeover prevention (paid add-ons).

Safe rollout: add them in count mode, send WAF logs to CloudWatch Logs or S3, check which legitimate requests would be blocked for a week or two, add scoped exclusions, then switch to block.

Q7. Why is client-side validation never enough to protect a web application? Fresher

Client-side validation (JavaScript checks in the browser or app) improves user experience, but the user controls the client. Anyone can turn off scripts, change the app, or send requests directly to the API with a command-line tool.

So the server must check everything again: required fields, types, lengths, allowed values, file types and sizes, and above all whether this user is allowed to perform this action on this record. Treat every request as untrusted, even from your own front end.

3. Mid level questions

These questions check how you use the service in real projects. Interviewers expect the why, the how and one real example.

Q8. How do you add a Content Security Policy to an existing website without breaking it? Mid level
  • Start with Content-Security-Policy-Report-Only, so browsers report violations but do not block anything.

Output:

Content-Security-Policy-Report-Only: default-src 'self'; script-src 'self' https://cdn.example.com; frame-ancestors 'none'; report-to csp-endpoint
  • Collect reports (an endpoint that stores them in CloudWatch Logs) and list the legitimate sources the site needs.
  • Remove inline scripts or use nonces or hashes, instead of allowing 'unsafe-inline'.
  • Tighten the policy, then switch to the enforcing header.
  • Add it through a CloudFront response headers policy or the app, and keep monitoring reports after each release.
Q9. What is clickjacking, and how do frame-ancestors and X-Frame-Options prevent it? Mid level

Clickjacking is when another site loads your page inside an invisible frame and tricks users into clicking buttons on it (for example "confirm transfer").

Prevention: tell browsers who may frame your pages.

Output:

Content-Security-Policy: frame-ancestors 'self'
X-Frame-Options: SAMEORIGIN

frame-ancestors is the modern, more flexible control; X-Frame-Options is the older header kept for old browsers. Use 'none' or DENY if pages should never be framed. For sensitive actions, add re-authentication or confirmation steps as extra protection.

Q10. How do you design a secure "forgot password" flow? Mid level
  • Show the same message whether or not the email exists, so attackers cannot discover accounts.
  • Send a single-use, random, long token that expires quickly (for example 15 to 60 minutes); store only a hash of it.
  • Rate-limit reset requests per account and per IP (AWS WAF rate-based rules and app limits).
  • After the reset: invalidate the token and existing sessions, and notify the user by email.
  • Require MFA again if the account has it.
  • Store the new password with a slow, salted hashing algorithm such as Argon2id or bcrypt.

Managed identity services such as Amazon Cognito provide these flows for you.

Q11. How do you keep secrets out of source code and catch leaks early? Mid level
  • Store secrets in AWS Secrets Manager or SSM Parameter Store (SecureString) and read them at runtime with IAM permissions.
  • Use IAM roles for AWS access instead of access keys.
  • Scan for secrets before commit (pre-commit hooks such as git-secrets or similar tools) and in the repository (for example GitHub secret scanning).
  • Scan build artefacts and container images too.
  • If a secret leaks: revoke and rotate it first, then check logs for misuse, then clean history. Deleting the commit alone does not help because copies may exist.
Q12. How do you reduce the risk from vulnerable open-source libraries in a web application? Mid level
  • Software composition analysis (SCA) in the pipeline to find known vulnerable versions (for example Dependabot or OWASP Dependency-Check).
  • Amazon Inspector scanning for ECR container images, EC2 instances and Lambda functions, with findings in Security Hub.
  • Pin versions with lock files, and use a private package mirror (for example AWS CodeArtifact) so builds pull approved packages.
  • Generate an SBOM (software bill of materials) so you can quickly answer "are we affected?" when a new vulnerability is announced.
  • Remove unused dependencies, and set a patching SLA by severity.
Q13. A feature lets users enter a URL that the server fetches (for example a link preview). How do you make it safe? Mid level

The risk is server-side request forgery: the server could be pushed into calling internal addresses.

Defences:

  • Allow only http and https, and if possible only an allow-list of domains.
  • Resolve the hostname and block private, loopback and link-local ranges (including 169.254.169.254); check again after redirects, or disable redirects.
  • Require IMDSv2 on EC2 instances (and a hop limit of 1 for containers) so metadata credentials are harder to reach.
  • Run the fetcher in an isolated subnet or Lambda function with egress only through a proxy or firewall that blocks internal destinations.
  • Set short timeouts and size limits, and log every fetched URL.
Q14. What are AWS WAF CAPTCHA and Challenge actions, and when do you use them? Mid level
  • CAPTCHA: shows the user a puzzle; real people solve it, and many bots fail. Good for sensitive, low-volume pages such as login, sign-up or ticket booking.
  • Challenge: a silent browser check (no puzzle for the user) that confirms the client is a real browser. Good for broader protection with little user friction.
  • Both set a token cookie with a configurable immunity time, so a verified user is not asked again for a while.

Use them on rules that match suspicious traffic (for example above a rate limit or from anonymous IPs) rather than for everyone. They do not work for API clients that are not browsers, so protect APIs with authentication and rate limits instead.

4. Senior level and scenario questions

These questions check design thinking and troubleshooting. Think aloud. Say what you check first, what you change, and how you prevent it next time.

Q15. What security review would you do before launching a new web application on AWS? Senior
  • Threat model the design: data flows, trust boundaries, sensitive data, likely attackers.
  • Check authentication and access control on every endpoint, especially object-level checks.
  • Run SAST, dependency, image and infrastructure-as-code scans, and a DAST scan against staging.
  • Confirm WAF rules, rate limits, security headers, TLS settings and that only the edge is public.
  • Review IAM roles for least privilege and confirm no long-term keys.
  • Confirm logging (CloudTrail, ALB and WAF logs), GuardDuty, Security Hub, alarms and an incident runbook.
  • Check backups and restore tests, and plan a penetration test by an authorised tester under AWS's policy.
Q16. How do you threat model a new feature using STRIDE? Senior

Draw the data flow (user, CloudFront, API, Lambda, DynamoDB, third parties) and for each element ask:

LetterThreatExample control
SSpoofing identityStrong authentication, MFA, signed requests
TTampering with dataTLS, input validation, integrity checks
RRepudiationAudit logs (CloudTrail, application logs)
IInformation disclosureEncryption, least privilege, no secrets in logs
DDenial of serviceWAF, rate limits, quotas, autoscaling
EElevation of privilegeAccess checks on the server, least-privilege roles

Record threats, rate their risk, assign fixes to owners, and revisit the model when the design changes.

Q17. After enabling AWS WAF, some legitimate customers are blocked. How do you fix it without weakening protection? Senior
  • Find the blocked requests in WAF logs or sampled requests: which rule and which field matched (body, query string, header).
  • Confirm it is a false positive, for example a rich-text editor sending HTML that looks like XSS.
  • Narrow the exception: use a scope-down statement or rule action override for that rule only on that path, or a label-based rule that allows only that case, instead of disabling the whole rule group.
  • If the request body is larger than WAF inspects, decide how to handle oversize content deliberately.
  • Test in count mode, deploy, and keep monitoring; document every exception with an owner and review date.
Q18. How do you detect that a web application on AWS is being attacked right now? Senior
  • AWS WAF metrics and logs: spikes in blocked or counted requests, rate-based rule triggers, unusual countries or user agents.
  • CloudFront and ALB metrics: request surges, 4xx and 5xx error rate changes, latency.
  • Application logs: many failed logins, access-denied errors, unusual parameters.
  • GuardDuty findings for the accounts and workloads (for example unusual API calls or credential misuse), and Security Hub to collect findings.
  • Shield Advanced (if used) for DDoS event detection and help from the Shield Response Team.

Set alarms on these and connect them to an incident runbook with clear first actions.

Q19. Which security checks belong in a CI/CD pipeline, and which should block a release? Senior
CheckWhat it findsUsually blocks on
SASTInsecure code patternsHigh-severity findings in changed code
SCAVulnerable dependenciesCritical vulnerabilities with a fix available
Secret scanningKeys and passwords in codeAny confirmed secret
IaC scanningPublic buckets, open security groups, missing encryptionPolicy violations
Container image scanningVulnerable OS packagesCritical findings
DASTRuntime issues in a deployed test environmentHigh findings, or reported for review

Block on clear, high-confidence issues; report the rest with SLAs, so the pipeline stays trusted and is not bypassed.

Q20. Where should a single-page app keep its login tokens, and how do you handle JWT expiry and logout? Senior
  • Prefer HttpOnly, Secure, SameSite cookies set by a backend (a backend-for-frontend), so page scripts cannot read tokens even if XSS happens; add CSRF protection.
  • localStorage is readable by any script on the page, so XSS can steal tokens stored there.
  • Keep access tokens short-lived (for example minutes) and use refresh tokens with rotation.
  • Logout: delete cookies and revoke the refresh token on the server (Amazon Cognito supports token revocation). A JWT access token stays valid until it expires, so short lifetimes matter.
  • Validate signature, issuer, audience and expiry on every API call.

5. Frequently asked questions

Do cloud engineers need to know application security?

Yes. You configure WAF, headers, secrets, scanning and logging, and you review designs. Knowing why a fix works helps you explain it to developers.

What is the best single defence?

There is none. Secure coding (validated input, parameterised queries, output encoding, access checks) plus layered AWS controls (WAF, least privilege, monitoring) is the answer interviewers want.

What should I practise?

Run a deliberately vulnerable training app in an isolated lab account, put AWS WAF managed rules in count mode in front of it, read the WAF logs, then fix the code and watch the findings go away.

6. Quick revision

  • Parameterised queries stop SQL injection; escaping by hand is not enough.
  • Encode output for its context to stop XSS, and add a Content Security Policy.
  • SameSite cookies plus anti-CSRF tokens stop forged requests.
  • Start AWS WAF managed rules in count mode, then block.
  • Scan code, dependencies, images and infrastructure as code in every pipeline.

This page is one part of the complete AWS interview question set. Open the full list here: All 2052 AWS interview questions.