AJAX and Security

What Is AJAX?

AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to communicate with a server and update content dynamically—without reloading the entire page. Despite the name, modern AJAX primarily uses JSON rather than XML, and it is implemented via the XMLHttpRequest (XHR) object or the newer fetch API.

AJAX became mainstream in the mid-2000s (popularized by Google Maps and Gmail) and is now a fundamental part of virtually every modern web application.

How AJAX Works

  1. An event triggers a JavaScript function (e.g., button click, page scroll).
  2. The JavaScript creates an XMLHttpRequest or fetch object.
  3. A request is sent to the server (GET, POST, PUT, DELETE, etc.).
  4. The server processes the request and returns a response (JSON, XML, HTML, etc.).
  5. JavaScript handles the response and updates the DOM without a full page reload.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Classic XHR example
const xhr = new XMLHttpRequest();
xhr.open('GET', '/api/data', true);
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    const data = JSON.parse(xhr.responseText);
    console.log(data);
  }
};
xhr.send();

// Modern Fetch API
fetch('/api/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

AJAX Security Vulnerabilities

1. Cross-Site Request Forgery (CSRF) via AJAX

AJAX requests are subject to CSRF attacks. An attacker’s page can send AJAX requests to a target site if the browser includes cookies automatically. Mitigations:

  • Use CSRF tokens validated server-side.
  • Use SameSite cookie attribute (Strict or Lax).
  • Check the Origin and Referer headers server-side.

2. Same-Origin Policy (SOP) and CORS Misconfiguration

Browsers enforce SOP, blocking cross-origin AJAX requests by default. However, CORS (Cross-Origin Resource Sharing) headers can relax this restriction. Misconfigured CORS is a critical security risk.

Dangerous CORS configurations:

1
2
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

This combination allows any origin to make authenticated requests—a severe misconfiguration that can lead to credential theft.

Attack scenario: An attacker hosts a malicious page that sends AJAX requests to bank.com. If CORS is misconfigured with * and credentials, the attacker can read sensitive responses.

Testing CORS:

1
2
3
# Test if server reflects arbitrary origin
curl -H "Origin: https://evil.com" -I https://target.com/api/data
# Check for Access-Control-Allow-Origin: https://evil.com in response

3. XSS via AJAX Response Injection

If AJAX response data is rendered directly into the DOM without sanitization, it can lead to XSS:

1
2
3
4
5
// Vulnerable
document.getElementById('output').innerHTML = xhr.responseText;

// Safe
document.getElementById('output').textContent = xhr.responseText;

4. Sensitive Data Exposure in AJAX Responses

APIs consumed by AJAX often return more data than the frontend actually displays. Inspect JSON responses for:

  • Hidden fields (e.g., admin: false, internal_id: 12345)
  • PII not shown in UI
  • Authorization tokens or keys embedded in responses

5. Broken Object-Level Authorization (BOLA/IDOR)

AJAX calls frequently include object identifiers in URLs or request bodies. Changing these identifiers to access other users’ data is a classic IDOR vulnerability:

1
GET /api/orders/1234  → Attacker changes to /api/orders/1235

6. JSON Hijacking (Historical)

Older browsers were vulnerable to JSON array hijacking. A malicious page could override the Array constructor to steal JSON response data. Modern browsers have mitigated this, but it’s still worth understanding.

Penetration Testing AJAX Applications

  1. Intercept all AJAX requests with Burp Suite proxy.
  2. Map the API surface: Identify all endpoints called by JavaScript (use browser DevTools Network tab).
  3. Test each endpoint for IDOR by modifying IDs and user references.
  4. Check CORS configuration using curl or Burp’s CORS scanner.
  5. Test for missing authentication on AJAX endpoints — they sometimes lack proper auth checks.
  6. Review JavaScript source for hardcoded API keys, internal endpoints, or debug parameters.
  7. Check for verbose errors in JSON responses that leak stack traces or database information.

AJAX란?

AJAX(Asynchronous JavaScript and XML)는 웹 페이지가 전체 페이지를 새로고침하지 않고도 서버와 통신하여 콘텐츠를 동적으로 업데이트할 수 있게 하는 기술입니다. 이름과 달리, 현대의 AJAX는 주로 JSON을 사용하며, XMLHttpRequest(XHR) 객체나 최신 fetch API를 통해 구현됩니다.

AJAX는 2000년대 중반(Google Maps와 Gmail로 대중화)에 주류가 되었으며, 현재는 거의 모든 현대 웹 애플리케이션의 핵심 기술입니다.

AJAX 동작 원리

  1. 이벤트가 JavaScript 함수를 트리거합니다 (예: 버튼 클릭, 페이지 스크롤).
  2. JavaScript가 XMLHttpRequest 또는 fetch 객체를 생성합니다.
  3. 서버로 요청을 전송합니다 (GET, POST, PUT, DELETE 등).
  4. 서버가 요청을 처리하고 응답을 반환합니다 (JSON, XML, HTML 등).
  5. JavaScript가 응답을 처리하고 전체 페이지 새로고침 없이 DOM을 업데이트합니다.

AJAX 보안 취약점

1. AJAX를 통한 CSRF(Cross-Site Request Forgery)

AJAX 요청도 CSRF 공격에 노출됩니다. 브라우저가 자동으로 쿠키를 포함시키면, 공격자의 페이지에서 대상 사이트로 AJAX 요청을 보낼 수 있습니다. 완화 방법:

  • 서버 측에서 검증하는 CSRF 토큰 사용
  • SameSite 쿠키 속성 활용 (Strict 또는 Lax)
  • 서버 측에서 OriginReferer 헤더 확인

2. 동일 출처 정책(SOP) 및 CORS 잘못된 구성

브라우저는 기본적으로 교차 출처 AJAX 요청을 차단하는 SOP를 적용합니다. 그러나 CORS(Cross-Origin Resource Sharing) 헤더로 이 제한을 완화할 수 있습니다. 잘못 구성된 CORS는 심각한 보안 위험입니다.

위험한 CORS 구성:

1
2
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

이 조합은 어느 출처에서든 인증된 요청을 보낼 수 있게 허용하여 자격 증명 탈취로 이어질 수 있는 심각한 잘못된 구성입니다.

3. AJAX 응답 주입을 통한 XSS

AJAX 응답 데이터를 정화 없이 DOM에 직접 렌더링하면 XSS로 이어질 수 있습니다. innerHTML 대신 textContent를 사용하는 것이 안전합니다.

4. AJAX 응답의 민감한 데이터 노출

AJAX가 소비하는 API는 종종 프론트엔드에 표시되는 것보다 더 많은 데이터를 반환합니다. JSON 응답에서 숨겨진 필드, UI에 표시되지 않는 PII, 응답에 포함된 인증 토큰 등을 확인해야 합니다.

5. BOLA/IDOR(Broken Object Level Authorization)

AJAX 호출은 URL이나 요청 본문에 객체 식별자를 포함하는 경우가 많습니다. 이 식별자를 변경하여 다른 사용자의 데이터에 접근하는 것이 전형적인 IDOR 취약점입니다.

침투 테스트 시 AJAX 애플리케이션 점검

  1. Burp Suite 프록시로 모든 AJAX 요청 인터셉트
  2. API 표면 매핑: 브라우저 개발자 도구 네트워크 탭을 사용해 JavaScript가 호출하는 모든 엔드포인트 파악
  3. ID 및 사용자 참조를 수정하여 각 엔드포인트에서 IDOR 테스트
  4. curl 또는 Burp의 CORS 스캐너로 CORS 구성 확인
  5. AJAX 엔드포인트에서 누락된 인증 테스트 — 인증 검사가 없는 경우가 종종 있음
  6. 하드코딩된 API 키, 내부 엔드포인트, 디버그 파라미터를 찾아 JavaScript 소스 코드 검토
  7. 스택 추적이나 데이터베이스 정보를 노출하는 JSON 응답의 자세한 오류 확인