Advertisement
ginppian

Untitled

Feb 6th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.03 KB | None | 0 0
  1. //
  2. // BSConnectionService.swift
  3. // Nexo
  4. //
  5. // Created by Enrique Gonzalez on 9/6/16.
  6. // Copyright © 2016 capitandurango. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10.  
  11. class BSConnectionService: NSObject, NSURLConnectionDelegate {
  12.  
  13. fileprivate var _connection: NSURLConnection?
  14. fileprivate var _lookServerResponseData:Data!
  15. fileprivate var _uniqueIdentifier: String = String.Empty
  16.  
  17. var delegate: BSConnectionServiceDelegate?
  18.  
  19. override init() {
  20. super.init()
  21.  
  22. _uniqueIdentifier = UUID().uuidString
  23. }
  24.  
  25. func submitRequest(_ request: NSMutableURLRequest) {
  26. _connection = NSURLConnection(request: request as URLRequest, delegate: self, startImmediately: true)
  27. }
  28.  
  29. func cancelRequestWithIdentifier(_ identifier: String) {
  30. println("Metodo no implementado \(#function)")
  31. }
  32.  
  33. func cancelRequest() {
  34. _connection?.cancel()
  35. }
  36.  
  37. func connection(_ connection: NSURLConnection, didReceiveResponse response: URLResponse ) {
  38. _lookServerResponseData = Data()
  39.  
  40. self.delegate?.bsReceiveResponse(didReceiveResponse: response)
  41. }
  42.  
  43. func connection(_ connection: NSURLConnection, didReceiveData data: Data) {
  44. _lookServerResponseData.append(data)
  45. }
  46.  
  47. func connection(_ connection: NSURLConnection, willCacheResponse cachedResponse: CachedURLResponse) -> CachedURLResponse? {
  48. return nil
  49. }
  50.  
  51. func connectionDidFinishLoading(_ connection: NSURLConnection) {
  52. do {
  53. let raw = try JSONSerialization.jsonObject(with: _lookServerResponseData, options: JSONSerialization.ReadingOptions.allowFragments)
  54. self.delegate?.bsReceiveData(receiveRawDictionary: raw as! NSDictionary)
  55. }
  56. catch let error as NSError {
  57. if let responseString = NSString(data: _lookServerResponseData as Data, encoding: String.Encoding.ascii.rawValue) {
  58. println("########## Error: \(#function) => ResponseString: \(responseString)")
  59. }
  60.  
  61. self.delegate?.bsRequestFailWithError(didFailWithError: error)
  62. }
  63. }
  64.  
  65. func connection(_ connection: NSURLConnection, didFailWithError error: Error) {
  66. connection.cancel()
  67.  
  68. println("ERROR DESDE EL MOTOR \(#function): \(error.localizedDescription)")
  69.  
  70. let innerError:NSError!
  71.  
  72. if error._code == NSURLErrorTimedOut {
  73. println(error)
  74. innerError = BSUtils.Error("Se sobrepaso el tiempo de espera, favor de reintentar")
  75. }
  76. else if error._domain == NSURLErrorDomain {
  77. println(error)
  78. innerError = BSUtils.Error("Servicio no disponible, favor de reintentar mas tarde !!!")
  79. }
  80. else {
  81. println(error)
  82. innerError = error as NSError!
  83. }
  84.  
  85. self.delegate?.bsRequestFailWithError(didFailWithError: innerError)
  86. }
  87.  
  88. /////////////////////////////////////////////////////////////////////////////////////////////////////////
  89. //TODO: Pruebas Certificado y Tipo de Autenticación
  90. /////////////////////////////////////////////////////////////////////////////////////////////////////////
  91.  
  92. func connection(_ connection: NSURLConnection, willSendRequestFor challenge: URLAuthenticationChallenge) {
  93. // println("#SSLPinning")
  94. // println("......... \(#function) authenticationMethod: \(challenge.protectionSpace.authenticationMethod)")
  95. //
  96. // switch challenge.protectionSpace.authenticationMethod {
  97. // case NSURLAuthenticationMethodServerTrust:
  98. // println("..........send credential Server Trust")
  99. //
  100. // //let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
  101. // //challenge.sender?.useCredential(credential, forAuthenticationChallenge: challenge)
  102. //
  103. // challenge.sender?.continueWithoutCredential(for: challenge)
  104. //
  105. // break
  106. // case NSURLAuthenticationMethodHTTPBasic:
  107. // println("..........send credential HTTP Basic")
  108. //
  109. // let defaultCredentials: URLCredential = URLCredential(user: "usernameFoo",
  110. // password: "passwordFoo",
  111. // persistence: URLCredential.Persistence.forSession)
  112. //
  113. // challenge.sender?.use(defaultCredentials, for: challenge)
  114. //
  115. // break
  116. // case NSURLAuthenticationMethodNTLM:
  117. // println("..........send credential NTLM")
  118. //
  119. // break
  120. // default:
  121. // println("..........send credential Ninguna de las anteriores")
  122. //
  123. // challenge.sender?.performDefaultHandling?(for: challenge)
  124. // }
  125.  
  126. while true {
  127. let serverTrust = challenge.protectionSpace.serverTrust
  128. print("ServerTrust \(nil != serverTrust ? "YES" : "NO")")
  129. if !(nil != serverTrust) {
  130. print("Error - El servidor no es de confianza")
  131. break
  132. }
  133.  
  134. let status: OSStatus = SecTrustEvaluate(serverTrust!, nil)
  135. print("SecTrustEvaluate: \(errSecSuccess == status ? "YES" : "NO caducado o autofirmado") ")
  136. if !(errSecSuccess == status) {
  137. print("failed: el certificado está caducado o autofirmado")
  138. break
  139. }
  140.  
  141.  
  142. var _serverCertificate: SecCertificate?
  143. if let serverCertificate: SecCertificate = SecTrustGetCertificateAtIndex(serverTrust!, 0) {
  144. println("SecCertificateREF: True")
  145. _serverCertificate = serverCertificate
  146. } else {
  147. println("SecCertificateRef: False")
  148. println("failed: no existe el certificado")
  149. break
  150. }
  151.  
  152. // CFDataRef serverCertificateData = SecCertificateCopyData(serverCertificate);
  153. // SBLogInfo(@"CFDataRef: %@", serverCertificateData?@"YES":@"NO");
  154. //
  155. // if (!(nil != serverCertificateData)) {
  156. // SBLogInfo(@"No se pudieron obtener los datos del certificado");
  157. // break;
  158. // }
  159. //
  160. // const UInt8* const data = CFDataGetBytePtr(serverCertificateData);
  161. // const CFIndex size = CFDataGetLength(serverCertificateData);
  162.  
  163. if let _server_Certificate = _serverCertificate {
  164. if let serverCertificateData: CFData = SecCertificateCopyData(_server_Certificate) {
  165. print("CFData: True")
  166. } else {
  167. print("No se pudieron obtener los datos del certificado")
  168. break
  169. }
  170. } else {
  171. break
  172. }
  173.  
  174. let data = CFDataGetBytePtr(serverCertificateData)
  175. let size: CFIndex = CFDataGetLength(serverCertificateData)
  176. if !(nil != data) || !(size > 0) {
  177. SBLogInfo("ailed: se presentó un error ara UInt8 y CFIndex en los datos del certificado")
  178. break
  179. }
  180.  
  181.  
  182. let serverCertificateNSD = NSData(bytes: data, length: Int(size))
  183. if !(nil != serverCertificateData) {
  184. //SBLogInfo("failed: Certificado recibido no se ha podido obtener")
  185. break
  186. }
  187.  
  188. /* * * Certificado local * * */
  189. let file: String? = Bundle.main.path(forResource: "bancomermovil", ofType: "crt")
  190. if !(nil != file) {
  191. //SBLogInfo("failed: o se pudo obtener la URL del certificado local")
  192. break
  193. }
  194.  
  195. let localCertificateNSD = NSData(contentsOfFile: file!) as Data?
  196. if !(nil != localCertificateNSD) {
  197. //SBLogInfo("failed: no se pudo obtener el certificado local")
  198. break
  199. }
  200.  
  201. let equal: Bool = serverCertificateNSD.isEqual(to: localCertificateNSD!)
  202. if !(false != equal) {
  203. //SBLogInfo("failed: el certificado enviado por el servidor no es igual al certificado local")
  204. break
  205. }
  206.  
  207. //SBLogInfo("el Certificado enviado por el servidor es igual al certficado local")
  208. return challenge.sender!.use(URLCredential(trust: serverTrust!), for: challenge)
  209. }
  210.  
  211. }
  212.  
  213. /*func connection(_ connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: URLProtectionSpace) -> Bool {
  214. println("::::::: authenticationMethod: \(protectionSpace.authenticationMethod)")
  215.  
  216. //return protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
  217.  
  218. return true
  219. }*/
  220.  
  221. func removeReferenceContext(){
  222. _connection?.cancel()
  223. _connection = nil
  224.  
  225. self.delegate = nil
  226. }
  227. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement