ios – Getting Error EXC_BAD_ACCESS (code=2, handle=0x2f30650004) in swift


I’m very new to swift, please assist me.
I’m making an attempt to make https request in swift, with id created from certificates and key. My code appear like this
To create the id.

func loadIdentity(certificates: String, privateKey: String)-> SecIdentity? { guard let certData = Information(base64Encoded: certificates, choices:NSData.Base64DecodingOptions.ignoreUnknownCharacters) else { print("Unable to decode certificates PEM") return nil }
 guard let cert = SecCertificateCreateWithData(kCFAllocatorDefault, certData as CFData) else {
        return nil
    }
let addCertQuery: [String: Any] = [kSecClass as String: kSecClassCertificate,
                                   kSecValueRef as String: cert,
                                   kSecAttrLabel as String: "certificateLabel"]


let tag = "fedvfdvdf-tag".knowledge(utilizing: .utf8)!
_ = deleteCertificateAndKey(certLabel: "certificateLabel",keyTag: tag )
let certAddStatus = SecItemAdd(addCertQuery as CFDictionary, nil)
guard let pemKeyData = Information(base64Encoded: privateKey, choices:NSData.Base64DecodingOptions.ignoreUnknownCharacters) else {
     return nil
   }
let sizeInBits = pemKeyData.rely * 8
let keyDict: [CFString: Any] = [
  kSecAttrKeyType: kSecAttrKeyTypeRSA,
  kSecAttrKeyClass: kSecAttrKeyClassPrivate,
  kSecAttrKeySizeInBits: NSNumber(value: sizeInBits),
  kSecReturnPersistentRef: true
]

var error: Unmanaged?
   guard let key = SecKeyCreateWithData(pemKeyData as CFData, keyDict as CFDictionary, &error) else {
     return nil
   }
let addKeyQuery: [String: Any] = [
     kSecClass as String: kSecClassKey,
     kSecAttrIsPermanent as String: true,
     kSecValueRef as String: key,
     kSecAttrApplicationTag as String: tag
   ]
 
   let privKeyAddStatus = SecItemAdd(addKeyQuery as CFDictionary, nil)
let getIdentityQuery = [
    kSecClass : kSecClassIdentity,
    kSecReturnData : true,
    kSecReturnAttributes : true,
    kSecReturnRef : true,
    kSecMatchLimit : kSecMatchLimitAll
    ] as CFDictionary
var identityItem: CFTypeRef?
let standing = SecItemCopyMatching(getIdentityQuery , &identityItem)
print("identityItem completed with standing: (String(describing: identityItem))")
print("standing completed with standing: (standing)")
guard standing == errSecSuccess else {
       print("Unable to create id")
       return nil
   }
return (identityItem as! SecIdentity);
}

to make api request. Code is breaking on this perform, round this strains
let process = session.dataTask(with: request) { (knowledge, response, error) in and let session = URLSession(configuration: .default, delegate: URLSessionPinningDelegate(id: id), delegateQueue: nil)
For testing I eliminated id and simply used default URLSession, and request begin giving response (though it was 401 however it was not crashing), so my guess is error is due to URLSession.

func makeAzureRequest(scopeId:String, registrationId:String, key:String, certificates:String, provisionHost:String, fileNameWithFolder:String, modelId:String, completion: @escaping (Consequence) -> Void ) throws { guard let id = loadIdentity(certificates: certificates, privateKey: key) else { throw NSError(area: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unable to create identity"])
}

 let session = URLSession(configuration: .default, delegate: URLSessionPinningDelegate(id: id), delegateQueue: nil)
print("session: (session)")
 guard let url = URL(string: "https://international.azure-devices-provisioning.internet/(scopeId)/registrations/(registrationId)/register?api-version=2021-06-01") else {
     throw NSError(area: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])
   
 }
   var request = URLRequest(url: url)

 request.httpMethod = "PUT"
 request.setValue("software/json", forHTTPHeaderField: "Content material-Kind")
 request.setValue("utf-8", forHTTPHeaderField: "Content material-Encoding")

 let physique = ["registrationId": registrationId]
 request.httpBody = strive? JSONSerialization.knowledge(withJSONObject: physique, choices: [])
let process = session.dataTask(with: request) { (knowledge, response, error) in
     if let error = error {
         completion(.failure(error))
     } else if let knowledge = knowledge, let responseString = String(knowledge: knowledge, encoding: .utf8) {
         completion(.success(responseString))
     }else {
         completion(.failure(NSError(area: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Unknown error occurred"])))
     }
 }

 process.resume()
}

to name perform the place api perform is triggered.

@objc(AzureProvisionWithCertificate)
class AzureProvisionWithCertificate: NSObject {

  @objc(provisionAndUploadFile:withRegistrationId:withKey:withCertificate:withProvisionHost:withFileNameWithFolder:withModelId:withResolver:withRejecter:)
  func provisionAndUploadFile(scopeId:String, registrationId:String, key:String, certificates:String,  provisionHost:String,  fileNameWithFolder:String,  modelId:String, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void {
      print("beginning swift code right here")
      do {
              strive makeAzureRequest(scopeId: scopeId, registrationId:registrationId, key: key, certificates: certificates, provisionHost: provisionHost, fileNameWithFolder: fileNameWithFolder, modelId: modelId) { end in
                  change consequence {
                  case .success(let responseString):
                      print("Success! Response: (responseString)")
                      // Deal with success, maybe replace the UI or course of the response
                  case .failure(let error):
                      print("Failed with error: (error.localizedDescription)")
                      // Deal with failure, maybe present an error message to the person
                  }
              }
          } catch {
              print("Did not provoke request: (error.localizedDescription)")
//              throw error
          }
      
  }
  
}

And URLSessionPinningDelegate class appear like this to SSL pinning.

import Basis 
import Safety

class URLSessionPinningDelegate: NSObject, URLSessionDelegate { var id: SecIdentity

init(id: SecIdentity) {
    self.id = id
}

 func urlSession(_ session: URLSession,
                 didReceive problem: URLAuthenticationChallenge,
                 completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
   if problem.protectionSpace.authenticationMethod == NSURLAuthenticationMethodClientCertificate {
     let credential = URLCredential(id: self.id,
                                    certificates: nil,
                                    persistence: .forSession)
     completionHandler(.useCredential, credential)
   } else {
     completionHandler(.performDefaultHandling, nil)
   }
 }
}

Stack hint for crash:


  * body #0: 0x000000019e78b038 libobjc.A.dylib`objc_msgSend + 56

    body #1: 0x00000001af0be964 Safety`SecIdentityCopyCertificate + 24

    body #2: 0x00000001d7e3fd2c libboringssl.dylib`boringssl_identity_create_from_identity + 92

    body #3: 0x00000001d7e50488 libboringssl.dylib`boringssl_context_set_identity + 284

    body #4: 0x00000001d7e500dc libboringssl.dylib`__boringssl_context_certificate_request_callback_block_invoke_3 + 1048

    body #5: 0x00000001a6de6230 Community`nw_queue_context_async_if_needed + 88

    body #6: 0x00000001d7e4fc9c libboringssl.dylib`__boringssl_context_certificate_request_callback_block_invoke_2 + 148

    body #7: 0x00000001a7b43668 CFNetwork`___lldb_unnamed_symbol8855 + 576

    body #8: 0x00000001a7bdab08 CFNetwork`___lldb_unnamed_symbol12666 + 204

    body #9: 0x00000001a7b43b08 CFNetwork`___lldb_unnamed_symbol8863 + 700

    body #10: 0x00000001a7b86738 CFNetwork`___lldb_unnamed_symbol10375 + 84

    body #11: 0x00000001a7b869d0 CFNetwork`___lldb_unnamed_symbol10379 + 36

    body #12: 0x00000001079e0b98 libdispatch.dylib`_dispatch_call_block_and_release + 32

    body #13: 0x00000001079e27bc libdispatch.dylib`_dispatch_client_callout + 20

    body #14: 0x00000001079ea66c libdispatch.dylib`_dispatch_lane_serial_drain + 832

    body #15: 0x00000001079eb43c libdispatch.dylib`_dispatch_lane_invoke + 460

    body #16: 0x00000001079ecabc libdispatch.dylib`_dispatch_workloop_invoke + 2336

    body #17: 0x00000001079f8404 libdispatch.dylib`_dispatch_root_queue_drain_deferred_wlh + 328

    body #18: 0x00000001079f7a38 libdispatch.dylib`_dispatch_workloop_worker_thread + 444

    body #19: 0x0000000203763934 libsystem_pthread.dylib`_pthread_wqthread + 288

Thanks in Advance!!!

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles