在iOS開發中,保障應用的網路安全是一個非常重要的環節。以下是一些常見的網路安全措施及對應的示例程式碼:
Swift版
1. 使用HTTPS
確保所有的網路請求使用HTTPS協議,以加密資料傳輸,防止中間人攻擊。
示例程式碼:
在Info.plist中配置App Transport Security (ATS):
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
</dict>
2. SSL Pinning
透過SSL Pinning可以確保應用程式只信任指定的伺服器證書,防止被劫持到偽造的伺服器。
示例程式碼:
import Foundation
class URLSessionPinningDelegate: NSObject, URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if let serverTrust = challenge.protectionSpace.serverTrust,
SecTrustEvaluate(serverTrust, nil) == errSecSuccess,
let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
let localCertificateData = try? Data(contentsOf: Bundle.main.url(forResource: "your_cert", withExtension: "cer")!)
let serverCertificateData = SecCertificateCopyData(serverCertificate) as Data
if localCertificateData == serverCertificateData {
let credential = URLCredential(trust: serverTrust)
completionHandler(.useCredential, credential)
return
}
}
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
// Usage
let url = URL(string: "https://yoursecurewebsite.com")!
let session = URLSession(configuration: .default, delegate: URLSessionPinningDelegate(), delegateQueue: nil)
let task = session.dataTask(with: url) { data, response, error in
// Handle response
}
task.resume()
3. 防止SQL隱碼攻擊
在處理使用者輸入時,使用引數化查詢來防止SQL隱碼攻擊。
示例程式碼:
import SQLite3
func queryDatabase(userInput: String) {
var db: OpaquePointer?
// Open database (assuming dbPath is the path to your database)
sqlite3_open(dbPath, &db)
var queryStatement: OpaquePointer?
let query = "SELECT * FROM users WHERE username = ?"
if sqlite3_prepare_v2(db, query, -1, &queryStatement, nil) == SQLITE_OK {
sqlite3_bind_text(queryStatement, 1, userInput, -1, nil)
while sqlite3_step(queryStatement) == SQLITE_ROW {
// Process results
}
}
sqlite3_finalize(queryStatement)
sqlite3_close(db)
}
4. Data Encryption
在儲存敏感資料時,使用iOS的加密庫來加密資料,比如使用Keychain
。
示例程式碼:
import Security
func saveToKeychain(key: String, data: Data) -> OSStatus {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecValueData as String: data
]
SecItemDelete(query as CFDictionary) // Delete any existing item
return SecItemAdd(query as CFDictionary, nil) // Add new item
}
func loadFromKeychain(key: String) -> Data? {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecReturnData as String: kCFBooleanTrue!,
kSecMatchLimit as String: kSecMatchLimitOne
]
var dataTypeRef: AnyObject?
let status: OSStatus = SecItemCopyMatching(query as CFDictionary, &dataTypeRef)
if status == noErr {
return dataTypeRef as? Data
} else {
return nil
}
}
5. 輸入驗證與清理
對使用者輸入進行驗證和清理,防止XSS(跨站指令碼攻擊)和其他注入攻擊。
示例程式碼:
func sanitize(userInput: String) -> String {
// Remove any script tags or other potentially dangerous content
return userInput.replacingOccurrences(of: "<script>", with: "", options: .caseInsensitive)
.replacingOccurrences(of: "</script>", with: "", options: .caseInsensitive)
}
// Usage
let userInput = "<script>alert('xss')</script>"
let sanitizedInput = sanitize(userInput: userInput)
print(sanitizedInput) // Outputs: alert('xss')
OC版
1. 使用HTTPS
確保所有的網路請求都使用HTTPS協議,以加密資料傳輸,防止中間人攻擊。
示例程式碼:
在Info.plist
中配置App Transport Security (ATS):
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<false/>
</dict>
2. SSL Pinning
透過SSL Pinning可以確保應用程式只信任指定的伺服器證書,防止被劫持到偽造的伺服器。
示例程式碼:
#import <Foundation/Foundation.h>
@interface URLSessionPinningDelegate : NSObject <NSURLSessionDelegate>
@end
@implementation URLSessionPinningDelegate
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
NSString *certPath = [[NSBundle mainBundle] pathForResource:@"your_cert" ofType:@"cer"];
NSData *localCertData = [NSData dataWithContentsOfFile:certPath];
NSData *serverCertData = (__bridge NSData *)(SecCertificateCopyData(serverCertificate));
if ([localCertData isEqualToData:serverCertData]) {
NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
return;
}
}
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
}
@end
// Usage
NSURL *url = [NSURL URLWithString:@"https://yoursecurewebsite.com"];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
URLSessionPinningDelegate *pinningDelegate = [[URLSessionPinningDelegate alloc] init];
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:pinningDelegate delegateQueue:nil];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil) {
// Handle response
}
}];
[task resume];
3. 防止SQL隱碼攻擊
在處理使用者輸入時,使用引數化查詢來防止SQL隱碼攻擊。
示例程式碼:
#import <sqlite3.h>
- (void)queryDatabase:(NSString *)userInput {
sqlite3 *db;
// Open database (assuming dbPath is the path to your database)
if (sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK) {
sqlite3_stmt *statement;
const char *query = "SELECT * FROM users WHERE username = ?";
if (sqlite3_prepare_v2(db, query, -1, &statement, NULL) == SQLITE_OK) {
sqlite3_bind_text(statement, 1, [userInput UTF8String], -1, SQLITE_TRANSIENT);
while (sqlite3_step(statement) == SQLITE_ROW) {
// Process results
}
}
sqlite3_finalize(statement);
sqlite3_close(db);
}
}
4. Data Encryption
在儲存敏感資料時,使用iOS的加密庫來加密資料,比如使用Keychain
。
示例程式碼:
#import <Security/Security.h>
- (OSStatus)saveToKeychainWithKey:(NSString *)key data:(NSData *)data {
NSDictionary *query = @{(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrAccount: key,
(__bridge id)kSecValueData: data};
SecItemDelete((__bridge CFDictionaryRef)query); // Delete any existing item
return SecItemAdd((__bridge CFDictionaryRef)query, NULL); // Add new item
}
- (NSData *)loadFromKeychainWithKey:(NSString *)key {
NSDictionary *query = @{(__bridge id)kSecClass: (__bridge id)kSecClassGenericPassword,
(__bridge id)kSecAttrAccount: key,
(__bridge id)kSecReturnData: (__bridge id)kCFBooleanTrue,
(__bridge id)kSecMatchLimit: (__bridge id)kSecMatchLimitOne};
CFTypeRef dataTypeRef = NULL;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &dataTypeRef);
if (status == noErr) {
return (__bridge_transfer NSData *)dataTypeRef;
} else {
return nil;
}
}
5. 輸入驗證與清理
對使用者輸入進行驗證和清理,防止XSS(跨站指令碼攻擊)和其他注入攻擊。
示例程式碼:
- (NSString *)sanitize:(NSString *)userInput {
// Remove any script tags or other potentially dangerous content
NSString *sanitizedInput = [userInput stringByReplacingOccurrencesOfString:@"<script>" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, userInput.length)];
sanitizedInput = [sanitizedInput stringByReplacingOccurrencesOfString:@"</script>" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, sanitizedInput.length)];
return sanitizedInput;
}
// Usage
NSString *userInput = @"<script>alert('xss')</script>";
NSString *sanitizedInput = [self sanitize:userInput];
NSLog(@"%@", sanitizedInput); // Outputs: alert('xss')
透過這些措施,你可以顯著提升iOS應用的網路安全性。根據專案需求,靈活運用這些技術以確保使用者資料的安全。