macOS Trust Private CA

ponyo721._.·2025년 2월 8일
post-thumbnail

사설인증서 서버 신뢰

macOS에서는 기본적으로 사설인증서 서버를 신뢰하지 않는다.
하지만 아래 방법을 사용하여 사설인증서버를 신뢰하고 통신할 수 있도록 우회할 수 있다.

Swift

import Cocoa

@main
class AppDelegate: NSObject, NSApplicationDelegate {
    let delegate = URLSessionDelegateHandler()

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
        
        // Set up the delegate and session
        let delegate = URLSessionDelegateHandler()
        let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)

        // Create the URL with query parameters
        let url = URL(string: "https://velog.io/@ponyo721")!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        
        request.addValue("ko", forHTTPHeaderField: "Accept-Language")

        // Create the data task
        let task = session.dataTask(with: request)
        task.resume()
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
        return true
    }


}

class URLSessionDelegateHandler: NSObject, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate {
    
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        if let responseString = String(data: data, encoding: .utf8) {
            print("Response Data: \(responseString)")
        }
    }
    
    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
        if let error = error {
            print("Task Completed with Error: \(error.localizedDescription)")
        } else {
            print("Task Completed Successfully.")
        }
    }
    
    func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
        if let error = error {
            print("Session Invalidated with Error: \(error.localizedDescription)")
        }
    }
    
    //MARK: - 사설인증 서버 신뢰 -
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

        print("urlSession. callback")
        
        let protectionSpace = challenge.protectionSpace
        guard let trust = protectionSpace.serverTrust else { return }
        
        if protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
            if MyBLClass().checkTrue() {
                completionHandler(.useCredential, URLCredential(trust: trust))
            } else {
                completionHandler(.rejectProtectionSpace, nil)
            }
        }
        else {
            completionHandler(.performDefaultHandling, nil)
        }
    }
}

class MyBLClass {
    func checkTrue() -> Bool {
        return true
    }
}

Objc

#import "AppDelegate.h"

@interface URLSessionDelegateHandler : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
@end

@implementation URLSessionDelegateHandler

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
    NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"Response Data: %@", responseString);
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
    if (error) {
        NSLog(@"Task Completed with Error: %@", error.localizedDescription);
    } else {
        NSLog(@"Task Completed Successfully.");
    }
}

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error {
    if (error) {
        NSLog(@"Session Invalidated with Error: %@", error.localizedDescription);
    }
}

- (void)URLSession:(NSURLSession *)session
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
 completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
{
    NSURLProtectionSpace *protectionSpace = challenge.protectionSpace;
    NSString *authenticationMethod = protectionSpace.authenticationMethod;
    
    if ([authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        // If you want to trust
        NSURLCredential* credential = [NSURLCredential credentialForTrust:protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential,
                          credential);
    }
    else {
        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
    }
}

@end


@interface AppDelegate ()


@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    
    // Set up the delegate and session
    URLSessionDelegateHandler *delegate = [[URLSessionDelegateHandler alloc] init];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:delegate delegateQueue:nil];
    
    // Create the URL with query parameters
    NSURL *url = [NSURL URLWithString:@"https://velog.io/@ponyo721"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"GET"];
    [request setValue:@"ko" forHTTPHeaderField:@"Accept-Language"];
    
    // Create the data task
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request];
    [task resume];
    
    // Keep the main run loop alive to wait for responses
    [[NSRunLoop currentRunLoop] run];
}


- (void)applicationWillTerminate:(NSNotification *)aNotification {
    // Insert code here to tear down your application
}


- (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app {
    return YES;
}


@end


profile
macOS Native Application Developer

0개의 댓글