簡體   English   中英

"在 Alamofire 中固定證書"

[英]Certificate pinning in Alamofire

我正在創建一個訪問 HTTPS Web 服務的 iPad 應用程序。 我想實施固定,但遇到了問題。

此類創建 Alamofire 管理器(主要取自文檔):

class NetworkManager {

    var manager: Manager?

    init() {
        let serverTrustPolicies: [String: ServerTrustPolicy] = [
            "www.google.co.uk": .PinCertificates(
                certificates: ServerTrustPolicy.certificatesInBundle(),
                validateCertificateChain: true,
                validateHost: true
            ),
            "insecure.expired-apis.com": .DisableEvaluation
        ]

        manager = Alamofire.Manager(
            configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
            serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
        )
    }
}

因此,問題是證書以錯誤的格式保存。

ServerTrustPolicy.certificatesInBundle()根據擴展列表查找包中的所有證書,然后嘗試使用SecCertificateCreateWithData加載它們。 根據其文檔,此功能:

如果data參數中傳遞的數據不是有效的DER編碼的X.509證書,則返回NULL

在Firefox中導出證書時,文件瀏覽器底部會出現“格式”彈出窗口。 選擇“X.509證書(DER)”,您應該為此目的獲得正確格式的證書。

首先,您需要下載證書。 最好的方法是在Firefox瀏覽器上下載證書。

第1步

轉到您的網頁/ API並單擊鎖定圖標以獲取證書。

在此輸入圖像描述

第2步

單擊查看證書

在此輸入圖像描述

第3步

單擊證書字段選項卡的第一部分,然后單擊導出

在此輸入圖像描述

第四步

選擇格式: - DER

在此輸入圖像描述

第5步

將文件拖放到XCode項目中

在此輸入圖像描述

第6步

在“目標>構建階段>復制捆綁資源”下添加證書

在此輸入圖像描述

第7步

添加網絡管理器文件。 用google.com替換您的網址

 import Foundation
 import Alamofire
 import SwiftyJSON

 class MYPNetworkManager {


     var Manager: SessionManager?

     init() {
         let serverTrustPolicies: [String: ServerTrustPolicy] = [
             "https://google.com": .pinCertificates(
                 certificates: ServerTrustPolicy.certificates(),
                 validateCertificateChain: true,
                 validateHost: true
             ),
             "insecure.expired-apis.com": .disableEvaluation
         ]

         Manager = SessionManager(
             serverTrustPolicyManager: ServerTrustPolicyManager(policies: 
 serverTrustPolicies)
         )

     }
 }

第8步

添加文件以獲取會話管理器

import Foundation
import Alamofire
import SwiftyJSON

class APIPinning {

    private static let NetworkManager = MYPNetworkManager()

    public static func getManager() -> SessionManager {
        return NetworkManager.Manager!
    }
 }

第9步

在Alamofire上使用此會話管理器,例如: -

 public static func testPinning() {
NetworkManager.Manager!.request("YourURL", method: .get, encoding: URLEncoding.httpBody, headers: MConnect.headersWithToken)
    .validate()
    .responseJSON { response in

        print(response)
        switch response.result {
        case .success:

            if let value = response.result.value {
                let json = JSON(value)
                print(json)
            } else {

            }

        case .failure:
            print("Error")
        }
}
}

在 Alamofire +5 版之后發生了很大的變化,我將在這里列出我為固定證書所做的工作。 我的目標是 Moya,因為 Moya 作為 Alamofire 之上的一層,適用於 Alamofire 的東西應該適用於 Moya。

首先要獲得服務器證書,您需要在瀏覽器中打開它,然后單擊鎖定圖標 然后您需要單擊證書,如屏幕截圖所示。 在此處輸入圖像描述<\/a> 之后,您需要將此證書拖到您的桌面或下載它的任何地方,請查看下面的屏幕截圖。 然后,您需要使用在 Xcode 檢查屏幕截圖中添加文件將其添加到您的項目中。 這是我的 Alamofire 代碼:

var session: Session!

class ViewController: UIViewController {

func testPinning() {


let evaluators: [String: ServerTrustEvaluating] = [
    "stackoverflow.com": PublicKeysTrustEvaluator()
]

let manager = ServerTrustManager(evaluators: evaluators)

session = Session(serverTrustManager: manager)


session
    .request("https://stackoverflow.com/questions/34611112/certificate-pinning-in-alamofire/55902588#55902588", method: .get)
    .validate()
    .response(completionHandler: { [weak self] response in
        switch response.result {
        case .success:
            print(response.data)
        case .failure(let error):
            switch error {
            case .serverTrustEvaluationFailed(let reason):
                // The reason here is a place where you might fine-tune your
                // error handling and possibly deduce if it's an actualy MITM
                // or just another error, like certificate issue.
                //
                // In this case, this will show `noRequiredEvaluator` if you try
                // testing against a domain not in the evaluators list which is
                // the closest I'm willing to setting up a MITM. In production,
                // it will most likely be one of the other evaluation errors.
                print(reason)
            default:
                print("default")
            }
        }
    })

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM