Swift - 使用NEVPNManager连接到vpn

时间:2015-11-25 18:24:16

标签: ios swift ios9 vpn nevpnmanager

我从Android获取.ovpn文件,我有用户名和密码,我应该连接到vpn服务器,但我不知道该怎么做。我试过这样的事情:

let manager = NEVPNManager.sharedManager()
manager.loadFromPreferencesWithCompletionHandler { (error) -> Void in
  if manager.`protocol`  == nil {
    let newIPSec = NEVPNProtocolIKEv2()
    newIPSec.serverAddress = "xxx.xxx.xxx.xxx"
    newIPSec.username = "username"
    let keychain = Keychain(service: "com.app.ios")
    let data = keychain[data: "vpnpassword"]
    newIPSec.passwordReference = data
    newIPSec.authenticationMethod = NEVPNIKEAuthenticationMethod.None
    newIPSec.disconnectOnSleep = false

    manager.`protocol` = newIPSec
    manager.enabled = true

    manager.saveToPreferencesWithCompletionHandler({ (error) -> Void in
      print(error)
    })
  }
}

我不知道如何添加证书(在<ca>之间.ovpn)信息以及如何设置它。文件.ovpn看起来像这样(我只删除<ca>标签中的数据并更改服务器地址:

client
dev tun
proto udp
remote xx.xx.xx.xx 443
resolv-retry infinite
nobind
persist-key
persist-tun
verb 3

<auth-user-pass>
#username#
#userpass#
</auth-user-pass>

cipher AES-256-CBC
<ca>
-----BEGIN CERTIFICATE-----
xxx
-----END CERTIFICATE-----
</ca> 

感谢您的帮助

2 个答案:

答案 0 :(得分:0)

您正在使用NEVPNProtocolIKEv2连接到openVPN服务器。 个人VPN仅支持ipsec与ike v1和v2(AEP和证书身份验证)

答案 1 :(得分:0)

这有点晚了,但你必须明白这些是完全不同的两件事。

NetworkExtension API撰写此答案时(我有iOS 9.3.4)支持两种协议: - 使用IKEv1的IPSec - AEP和证书(IKEv2)

您的服务器是OpenVPN服务器。目前没有OpenVVPN的API(如果您遇到任何问题,请告诉我)。那么第一个问题,您的VPN服务器是否支持IKEv1或v2?

有适用于iOS的客户端OpenVPN-connect,但它是支持者和封闭源代码。您仍然可以从应用程序内部调用它,它将弹出给用户,如下所示: ```迅速 func actConnectButtonPressed(sender:AnyObject){         让app:UIApplication = UIApplication.sharedApplication()

    let alert = UIAlertController(title: "Warning", message: "OpenVPN Connect needs to be installed to process .ovpn configuration files on your device. Go to OpenVPN Connect page in AppStore?", preferredStyle: UIAlertControllerStyle.Alert)

    alert.addAction(UIAlertAction(title: "Yes", style: .Default, handler: { (action: UIAlertAction!) in
        app.openURL(NSURL(string: "https://itunes.apple.com/app/id590379981?mt=8")!)
    }))

    alert.addAction(UIAlertAction(title: "No", style: .Default, handler: { (action: UIAlertAction!) in
        let server:Server = self.api.findServerByName(self.settings.loadValue(SettingsController.keyServerName, defValue: "") as! String)!
        let protocolPort:Int = self.settings.loadValue(SettingsController.keyProtocolPort, defValue: 0) as! Int
        app.openURL(NSURL(string: self.api.getOvpnConfigURL(server, proto: self.protocolAndPorts[protocolPort]))!)
    }))
    presentViewController(alert, animated: true, completion: nil)

}

```

此示例来自safejump客户端。看看这里 https://github.com/proxysh/Safejumper-for-iOS

我自己仍在努力让IPSec客户端在iOS上以编程方式运行,这就是我所学到的 - 建议使用共享密钥方法而不是None - 共享密钥也必须保存在密钥链中 - 如果使用共享密钥,则还启用ExtendedAuthentication - 确保在启动连接之前保存配置

希望这有帮助