iOS - TunnelKit OpenVPNTunnelProvider ProviderConfigurationError - ios

I am trying to create an ios vpn client using Tunnelkit. I am following this tutorial.
https://github.com/passepartoutvpn/tunnelkit
am able to compile and run the application, but when I try to connect, the app crashes and throwing.
Thread 1: Fatal error: 'try!' expression unexpectedly raised an error:
TunnelKit.OpenVPNTunnelProvider.ProviderConfigurationError.credentials(details:
"keychain.set()")
Anyone who had already set up tunnel kit OpenVPN, please help to resolve this issue.
func connect() {
let server = textServer.text!
let domain = textDomain.text!
let hostname = ((domain == "") ? server : [server, domain].joined(separator: "."))
let port = UInt16(textPort.text!)!
let socketType: SocketType = switchTCP.isOn ? .tcp : .udp
let credentials = OpenVPN.Credentials(textUsername.text!, textPassword.text!)
let cfg = Configuration.make(hostname: hostname, port: port, socketType: socketType)
let proto = try! cfg.generatedTunnelProtocol(
withBundleIdentifier: tunnelIdentifier,
appGroup: appGroup,
credentials: credentials
)
let neCfg = NetworkExtensionVPNConfiguration(title: "new title", protocolConfiguration: proto, onDemandRules: [])
vpn.reconnect(configuration: neCfg) { (error) in
if let error = error {
print("configure error: \(error)")
return
}
}
}

You need to follow the integration steps.
https://github.com/passepartoutvpn/tunnelkit#demo
Enable App Groups and Keychain Sharing capabilities

make sure the appGroup value is the same which you set in your target/Signings & Capabilities/App Groups

Related

Unable to connect to remote RabbitMQ server using Swift

I am using RabbitMQ in my app for chat module. It works fine with local server but somehow I am not able to connect to remote RabbitMQ server. I keep getting this error when I try to send a message.
Received connection: <RMQConnection: 0x6000022e2eb0>
disconnectedWithError: Error Domain=GCDAsyncSocketErrorDomain Code=7
"Socket closed by remote peer" UserInfo={NSLocalizedDescription=Socket
closed by remote peer}
My swift code looks like this:
func getRabbitMQUrl() -> String{
var components = URLComponents()
components.scheme = "amqps"
components.host = "[broker-id].mq.[region].amazon.aws.com"
components.user = "[username]"
components.password = "[passowrd]"
components.port = 5671
let url = components.url?.absoluteString ?? "-"
print("RabbitMQ URL", url)
return url
}
let uri = getRabbitMQUrl()
let conn = RMQConnection(uri: uri, delegate: RMQConnectionDelegateLogger())
conn.start()
let ch = conn.createChannel()
let q = ch.queue(UUID().uuidString, options: .durable)
let exc = ch.direct("my-exchange-name-here")
q.bind(exc, routingKey: "my-routing-key")
q.subscribe({(_ message: RMQMessage) -> Void in
print("Message received")
})
While using the local server, I set the uri "amqp://[username]:[password]#localhost:5672" and this works as expected.
PS: when I set this subscriber I do not get any error message regarding connection or anything. so I think it is connecting to the server without any issue.
But, when I send a message from the iOS app, the backend publish it and so the iOS app should receive it back. Exactly at this time, it gives me the above error!
EDIT: Though the C# backend is able to publish and subscribe messages successfully with RabbitMQ remote server. It is just the iOS client who fails!
Any help would be appreciated!
After going through a lots of links, slack channels and Github issues, finally the issue has been resolved! The solution was unexpected.
The problem was, my C# backend has set the vhost to a slash / and in my Swift code I was passing an empty string instead. I got hint from here
I made these 2 changes in my code:
In server uri I added %2f(a slash /) as the vhost at the end.
I set the options of the exchange also to .durable just like the queue
Here is the complete working code:
func getRabbitMQUrl() -> String{
var components = URLComponents()
components.scheme = "amqps"
components.host = "[broker-id].mq.[region].amazon.aws.com"
components.user = "[username]"
components.password = "[passowrd]"
components.port = 5671
components.path = "/%2f" //1st change
let url = components.url?.absoluteString ?? "-"
print("RabbitMQ URL", url)
return url
}
let uri = getRabbitMQUrl()
let conn = RMQConnection(uri: uri, delegate: RMQConnectionDelegateLogger())
conn.start()
let ch = conn.createChannel()
let q = ch.queue(UUID().uuidString, options: .durable)
let exc = ch.direct("my-exchange-name-here", options: .durable) // 2nd change
q.bind(exc, routingKey: "my-routing-key")
q.subscribe({(_ message: RMQMessage) -> Void in
print("Message received")
})
Your URI is AMQP on the local host but AMQP is the example code.
You should connect to port 5671 if you are using AMQPS (And 5672 if you are on AMQP) Try that!

AWS iOT login issue using IAM user credentials iOS

I am trying to login into the AWS iOT using the IAM user credentials.
But I am getting the error continuously "connection error", in the console it is showing as "CP Conn 0x2819e8a80 SSLHandshake failed (-9807)". I checked with different wifi connections but still, I am getting the same errors.
Here I am sharing my code to get the more clarity,
let credentialsProvider = AWSStaticCredentialsProvider(accessKey: myAccessKey, secretKey: mySecretKey)
let configuration = AWSServiceConfiguration(region: AWSRegionType.USEast1, credentialsProvider: credentialsProvider)
AWSIoTDataManager.register(with: configuration!, forKey: "iOTManager")
iotDataManager = AWSIoTDataManager(forKey: "iOTManager")
#if DEMONSTRATE_LAST_WILL_AND_TESTAMENT
let lwtTopic: NSString = Constants.lwtTopic
let lwtMessage: NSString = Constants.lwtMessage
self.iotDataManager.mqttConfiguration.lastWillAndTestament.topic = lwtTopic as String
self.iotDataManager.mqttConfiguration.lastWillAndTestament.message = lwtMessage as String
self.iotDataManager.mqttConfiguration.lastWillAndTestament.qos = .AtMostOnce
#endif
self.iotDataManager.connectUsingWebSocket( withClientId: UUID().uuidString, cleanSession:true, statusCallback: mqttEventCallback)
}
func mqttEventCallback( _ status: AWSIoTMQTTStatus ) {
DispatchQueue.main.async {
print(status.rawValue)
switch(status)
{
case .connecting:
print("Connecting..!")
case .connected:
print("Connected..!")
case .disconnected:
print("Disconnected..!")
case .connectionRefused:
print("connectionRefused..!")
case .connectionError:
print("connectionError..!")
case .protocolError:
print("protocolError..!")
default:
print("unknowState" + String(status.rawValue))
}
}
When I am running the same code in iPad mini, I am able to login into AWS iOT successfully but it is not in iPhone(7, 7Plus, 8Plus). I was wondering, why it is happening. I am not getting what wrong in the code. Please help me to fix this issue.
After some research I found this 2 things
1) SSL handshake fail when using new endpoint with '-ats' or '.ats' here
2) Its gives issue in higher version (IOS 12.1.1) so check your device version.
Please refer this Doc also

Swift - unable to connect to open hotspot

I'm attempting to connect to an open Wi-Fi network using the NEHotspotConfigurationManager without any luck. I've ensured my app has the proper Hotspot Configuration Entitlement and I'm running on a device that is > iOS 11.
Here is the code I'm using to connect to the open network.
// MARK: - Connect to Hotspot
#available(iOS 11.0, *)
func connectToHotspot(completion: #escaping APConnectionStatusHandler) {
let configuration = NEHotspotConfiguration.init(ssid: Constants.hotspotSSID)
configuration.joinOnce = true
NEHotspotConfigurationManager.shared.apply(NEHotspotConfiguration.init()) { connectionError in
if let error = connectionError {
debugPrint("Failed to automatically connect to \(Constants.hotspotSSID)")
debugPrint(error)
completion(false, error.localizedDescription)
}
else {
debugPrint("Automatically connected to \(Constants.hotspotSSID)")
completion(true, nil)
}
}
}
connectionError is populated every time I run this with:
Domain=NEHotspotConfigurationErrorDomain Code=1 "invalid SSID."
I'm unable to find any information on what exactly this error message means. The network shows up in the list of networks for the device I'm using. I'm spelling it correctly and the error message is the same regardless of what SSID string I use.
Any recommendations?
Maybe you shouldn't use Constant.hotspotSSID.
According to the afore-mentioned, I cannot identify what is the 'Constant' or which data type it is.
Here is my thought, try this:
let yourSSID: String = "SSID"
let configuration = NEHotspotConfiguration.init(ssid: yourSSID)
configuration.joinOnce = true
NEHotspotConfigurationManager.shared.apply(configuration) {
(error) in
if error != nil {
print("Connect-> Failure!")
} else {
print("Connect-> Success!")
}
}

NEHotspotConfigurationErrorDomain Code=5 "invalid EAP settings."

I'm using NEHotspotConfigurationManager with on iOS 11 iPhone to connect to specific Wi-Fi spot and then disconnect from it.
Here is the code:
let domainName = ""
let hotspotSettings = NEHotspotHS20Settings.init(domainName: domainName, roamingEnabled: true)
let hotspotEAPSettings = NEHotspotEAPSettings()
hotspotEAPSettings.username = *****
hotspotEAPSettings.password = ******
hotspotEAPSettings.isTLSClientCertificateRequired = true
hotspotEAPSettings.supportedEAPTypes = [21]
hotspotEAPSettings.trustedServerNames = [""]
hotspotEAPSettings.ttlsInnerAuthenticationType = .eapttlsInnerAuthenticationMSCHAPv2
print(hotspotEAPSettings)
let hotspotConfig = NEHotspotConfiguration.init(hs20Settings: hotspotSettings, eapSettings: hotspotEAPSettings)
print( hotspotConfig.ssid)
NEHotspotConfigurationManager.shared.apply(hotspotConfig) {[unowned self] (error) in
print(error?.localizedDescription as Any)// gives Error Domain=NEHotspotConfigurationErrorDomain Code=5 "invalid EAP settings."
print(error as Any)
if let error = error {
self.showError(error: error)
} else {
self.showSuccess()
}
}
Question is: what happened? Why it prompts me error "invalid EAP settings", and also what does this error mean?
For this first we had to save certificate which comes in .mobileconfig file into iPhone keychain in $TeamID.com.apple.networkextensionsharing group, also enable the keychain access group in xCode capability and add $TeamID.com.apple.networkextensionsharing into entitlements.After successfully save the certificate into keychain it works.

Connect to local mac server from device

Im trying to connect to a ruby sinatra server that im running locally on my mac from an app using the following code:
func load(finished: #escaping ()->()) {
// Create destination URL
let destinationFileUrl = documentsUrl.appendingPathComponent("Images.zip")
//Create URL to the source file you want to download
let fileURL = URL(string: "http://waynerumble.local~waynerumble:4567/download")
//Create Session
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
finished()
} else {
print("Error took place while downloading a file. Error description: %#", (error?.localizedDescription)! as String);
finished()
}
}
task.resume()
}
If i test the app from the simulator and set the fileURL to "http://127.0.0.1:4567/download" it works fine but from device i understand this has to be different so far I've tried:
From running ifconig in terminal i get 192.168.1.254 at en1 so i tried "http://192.168.1.255:4567/download" which gave me:
[] nw_socket_connect connectx failed: [13] Permission denied
Error took place while downloading a file. Error description: %# Could not connect to the server.
Ive also tried:
"http://waynerumble.local:4567/download" which gives:
Error took place while downloading a file. Error description: %# Could not connect to the server.
"http://waynerumble.local.~waynerumble:4567/download"(waynerumble is my computer name and username) which gives:
Error took place while downloading a file. Error description: %# A server with the specified hostname could not be found.
I also have wifi internet sharing on from both ethernet and iphone. Im not sure what else to try
192.168.1.255 is a brodcast adress for your network and you should not use it.
Why dont you connect to your real IP 192.168.1.254?
To bind Sinatra app to every interface try:
class MyApp < Sinatra::Base
set :bind, '0.0.0.0'
Then http://192.168.1.254:4567/download should work.
Also remember about opening desired port in the firewall.

Resources