---
title: Bắt buộc TLS cho mọi kết nối mạng - không tắt App Transport Security
impact: CRITICAL
impactDescription: Tắt ATS hoặc cho phép HTTP cleartext khiến dữ liệu người dùng bị đọc dễ dàng qua man-in-the-middle attack trên mạng WiFi công cộng.
tags: swift, ios, tls, ats, app-transport-security, https, security
---

## Bắt buộc TLS cho mọi kết nối mạng - không tắt App Transport Security

App Transport Security (ATS) bắt buộc HTTPS cho tất cả kết nối theo mặc định. Không được set `NSAllowsArbitraryLoads = YES` trừ trường hợp đặc biệt có lý do. Nếu cần exception, phải hạn chế theo domain cụ thể.

**Incorrect (tắt hoàn toàn ATS):**

```xml
<!-- Info.plist - NGUY HIỂM: tắt hoàn toàn ATS -->
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>  <!-- Cho phép HTTP tất cả domains! -->
</dict>
```

```swift
// !! Kết nối HTTP thuần
let url = URL(string: "http://api.example.com/users")!  // HTTP!
let task = URLSession.shared.dataTask(with: url) { data, _, _ in
    // Dữ liệu truyền cleartext
}
```

**Correct (giữ ATS mặc định, exception theo domain nếu cần):**

```xml
<!-- Info.plist - không cần khai báo nếu chỉ dùng HTTPS -->
<!-- Nếu cần exception cho domain cụ thể (legacy, third-party) -->
<key>NSAppTransportSecurity</key>
<dict>
    <!-- KHÔNG để NSAllowsArbitraryLoads = true -->
    <key>NSExceptionDomains</key>
    <dict>
        <!-- Chỉ exception domain cụ thể với lý do rõ ràng -->
        <key>legacy.thirdparty.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <!-- Và document lý do trong code review -->
        </dict>
    </dict>
</dict>
```

```swift
// Luôn dùng HTTPS
let url = URL(string: "https://api.example.com/users")!

// Kiểm tra scheme trước khi request
func makeSecureRequest(urlString: String) throws -> URLRequest {
    guard let url = URL(string: urlString),
          url.scheme == "https" else {
        throw NetworkError.insecureURL(urlString)
    }
    return URLRequest(url: url)
}
```

**Tools:** Xcode ATS Checker, Apple App Review Guidelines, MASVS-NETWORK

