{"id":13826374,"url":"https://github.com/ss-abramchuk/openvpnadapter","last_synced_at":"2025-10-20T13:55:01.759Z","repository":{"id":41390101,"uuid":"80986171","full_name":"ss-abramchuk/OpenVPNAdapter","owner":"ss-abramchuk","description":"Objective-C wrapper for OpenVPN library. Compatible with iOS and macOS.","archived":true,"fork":false,"pushed_at":"2022-03-19T06:48:18.000Z","size":45759,"stargazers_count":464,"open_issues_count":97,"forks_count":200,"subscribers_count":17,"default_branch":"master","last_synced_at":"2024-04-24T13:20:02.253Z","etag":null,"topics":["framework","ios","macos","network-extension","objective-c","openvpn"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"agpl-3.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ss-abramchuk.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-02-05T10:39:17.000Z","updated_at":"2024-04-11T20:39:42.000Z","dependencies_parsed_at":"2022-08-10T02:07:11.181Z","dependency_job_id":null,"html_url":"https://github.com/ss-abramchuk/OpenVPNAdapter","commit_stats":null,"previous_names":[],"tags_count":9,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ss-abramchuk%2FOpenVPNAdapter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ss-abramchuk%2FOpenVPNAdapter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ss-abramchuk%2FOpenVPNAdapter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ss-abramchuk%2FOpenVPNAdapter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ss-abramchuk","download_url":"https://codeload.github.com/ss-abramchuk/OpenVPNAdapter/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225476384,"owners_count":17480215,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["framework","ios","macos","network-extension","objective-c","openvpn"],"created_at":"2024-08-04T09:01:36.515Z","updated_at":"2025-10-20T13:55:00.129Z","avatar_url":"https://github.com/ss-abramchuk.png","language":"C++","funding_links":[],"categories":["\u003ca id=\"7cf7e8a30b73997985f20698eaf6b0c9\"\u003e\u003c/a\u003eOpenVPN"],"sub_categories":["\u003ca id=\"8ea8f890cf767c3801b5e7951fca3570\"\u003e\u003c/a\u003e公网访问局域网"],"readme":"# OpenVPNAdapter\n\n![Platforms](https://img.shields.io/badge/Platforms-iOS%20%7C%20macOS-lightgrey.svg)\n![iOS Versions](https://img.shields.io/badge/iOS-9.0+-yellow.svg)\n![macOS Versions](https://img.shields.io/badge/macOS-10.11+-yellow.svg)\n![Xcode Version](https://img.shields.io/badge/Xcode-11.0+-yellow.svg)\n![Carthage Compatible](https://img.shields.io/badge/Carthage-Compatible-4BC51D.svg?style=flat)\n![Cocoapods Compatible](https://img.shields.io/badge/Cocoapods-Compatible-4BC51D.svg?style=flat)\n![Swift Package Manager Compatible](https://img.shields.io/badge/Swift%20Package%20Manager-Compatible-4BC51D.svg?style=flat)\n![License](https://img.shields.io/badge/License-AGPLv3-lightgrey.svg)\n\n## !!!ATTENTION!!!\nDue to the lack of time and motivation the support of this project was dropped. If you need a solution for OpenVPN please take a look at alternatives such as [TunnelKit](https://github.com/passepartoutvpn/tunnelkit).\n\n## Overview\nOpenVPNAdapter is an Objective-C framework that allows to easily configure and establish VPN connection using OpenVPN protocol. It is based on the original [openvpn3](https://github.com/OpenVPN/openvpn3) library so it has every feature the library has.\n\nThe framework is designed to use in conjunction with [`NetworkExtension`](https://developer.apple.com/documentation/networkextension) framework and doesn't use any private Apple API. Compatible with iOS and macOS and also Swift friendly.\n\n## Installation\n\n### Requirements\n- iOS 9.0+ or macOS 10.11+\n- Xcode 11.0+\n\n### Carthage\nTo install OpenVPNAdapter with Carthage, add the following line to your `Cartfile`.\n\n```\ngithub \"ss-abramchuk/OpenVPNAdapter\"\n```\n\nThen run `$ carthage update` command. For details of the installation and usage of Carthage, visit [its project page](https://github.com/Carthage/Carthage).\n\n### Cocoapods\nTo install OpenVPNAdapter with Cocoapods, add the following lines to your `Podfile`.\n\n```ruby\ntarget 'Your Target Name' do\n  use_frameworks!\n  pod 'OpenVPNAdapter', :git =\u003e 'https://github.com/ss-abramchuk/OpenVPNAdapter.git', :tag =\u003e '0.8.0'\nend\n```\n\nAnd run `$ pod install`.\n\n### Swift Package Manager\nAdd `OpenVPNAdapter` package to your project using File \u003e Swift Packages \u003e Add Package Dependency menu. Xcode 11 will automatically retrieve all necessary dependencies. In addition to that you need to add `SystemConfiguration` framework to the Frameworks and Libraries. If you work on iOS project add `UIKit` as well.\n\n## Usage\nAt first, you need to add a Packet Tunnel Provider extension to the project and configure provision profiles for both the container app and the extension. There are official documentation and many tutorials describing how to do it so we won't dwell on this in detail.\n\nBefore you can configure and establish VPN connection don't forget to import [`NetworkExtension`](https://developer.apple.com/documentation/networkextension).\n\n```swift\nimport NetworkExtension\n```\n\nThen we need to create or load a VPN profile. [`NETunnelProviderManager`](https://developer.apple.com/documentation/networkextension/netunnelprovidermanager) is used to configure and control  VPN connections provided by a Tunnel Provider extension. Each instance corresponds to a single VPN configuration stored in the Network Extension preferences. ￼Call the following method to load all existing VPN profiles from the system preferences. For the sake of simplicity, we will use only one instance of [`NETunnelProviderManager`](https://developer.apple.com/documentation/networkextension/netunnelprovidermanager) assuming that our object has a property named `providerManager`.\n\n```swift\nNETunnelProviderManager.loadAllFromPreferences { (managers, error) in\n    guard error == nil else {\n        // Handle an occurred error\n        return\n    }\n\n    self.providerManager = managers?.first ?? NETunnelProviderManager()\n}\n```\nThe next step is to provide VPN settings to the instance of [`NETunnelProviderManager`](https://developer.apple.com/documentation/networkextension/netunnelprovidermanager). Setup the [`NETunnelProviderProtocol`](https://developer.apple.com/documentation/networkextension/netunnelproviderprotocol) object with appropriate values and save it in preferences.\n\n```swift\nself.providerManager?.loadFromPreferences(completionHandler: { (error) in\n    guard error == nil else {\n        // Handle an occurred error\n        return\n    }\n\n    // Assuming the app bundle contains a configuration file named 'client.ovpn' lets get its\n    // Data representation\n    guard\n        let configurationFileURL = Bundle.main.url(forResource: \"client\", withExtension: \"ovpn\"),\n        let configurationFileContent = try? Data(contentsOf: configurationFileURL)\n    else {\n        fatalError()\n    }\n\n    let tunnelProtocol = NETunnelProviderProtocol()\n\n    // If the ovpn file doesn't contain server address you can use this property\n    // to provide it. Or just set an empty string value because `serverAddress`\n    // property must be set to a non-nil string in either case.\n    tunnelProtocol.serverAddress = \"\"\n\n    // The most important field which MUST be the bundle ID of our custom network\n    // extension target.\n    tunnelProtocol.providerBundleIdentifier = \"com.example.openvpn-client.tunnel-provider\"\n\n    // Use `providerConfiguration` to save content of the ovpn file.\n    tunnelProtocol.providerConfiguration = [\"ovpn\": configurationFileContent]\n\n    // Provide user credentials if needed. It is highly recommended to use\n    // keychain to store a password.\n    tunnelProtocol.username = \"username\"\n    tunnelProtocol.passwordReference = ... // A persistent keychain reference to an item containing the password\n\n    // Finish configuration by assigning tunnel protocol to `protocolConfiguration`\n    // property of `providerManager` and by setting description.\n    self.providerManager?.protocolConfiguration = tunnelProtocol\n    self.providerManager?.localizedDescription = \"OpenVPN Client\"\n\n    self.providerManager?.isEnabled = true\n\n    // Save configuration in the Network Extension preferences\n    self.providerManager?.saveToPreferences(completionHandler: { (error) in\n        if let error = error  {\n            // Handle an occurred error\n        }\n    })\n}\n```\n\nStart VPN by calling the following code.\n\n```swift\nself.providerManager?.loadFromPreferences(completionHandler: { (error) in\n    guard error == nil else {\n        // Handle an occurred error\n        return\n    }\n\n    do {\n        try self.providerManager?.connection.startVPNTunnel()\n    } catch {\n        // Handle an occurred error\n    }\n}\n```\n\nPacket Tunnel Provider extension uses [`NEPacketTunnelProvider`](https://developer.apple.com/documentation/networkextension/nepackettunnelprovider) subclass to configure and establish VPN connection. Therefore, that class is the right place to configure OpenVPNAdapter. The following example shows how you can setup it:\n\n```swift\nimport NetworkExtension\nimport OpenVPNAdapter\n\n// Extend NEPacketTunnelFlow to adopt OpenVPNAdapterPacketFlow protocol so that\n// `self.packetFlow` could be sent to `completionHandler` callback of OpenVPNAdapterDelegate\n// method openVPNAdapter(openVPNAdapter:configureTunnelWithNetworkSettings:completionHandler).\nextension NEPacketTunnelFlow: OpenVPNAdapterPacketFlow {}\n\nclass PacketTunnelProvider: NEPacketTunnelProvider {\n\n    lazy var vpnAdapter: OpenVPNAdapter = {\n        let adapter = OpenVPNAdapter()\n        adapter.delegate = self\n\n        return adapter\n    }()\n\n    let vpnReachability = OpenVPNReachability()\n\n    var startHandler: ((Error?) -\u003e Void)?\n    var stopHandler: (() -\u003e Void)?\n\n    override func startTunnel(\n        options: [String : NSObject]?, \n        completionHandler: @escaping (Error?) -\u003e Void\n    ) {\n        // There are many ways to provide OpenVPN settings to the tunnel provider. For instance,\n        // you can use `options` argument of `startTunnel(options:completionHandler:)` method or get\n        // settings from `protocolConfiguration.providerConfiguration` property of `NEPacketTunnelProvider`\n        // class. Also you may provide just content of a ovpn file or use key:value pairs\n        // that may be provided exclusively or in addition to file content.\n\n        // In our case we need providerConfiguration dictionary to retrieve content\n        // of the OpenVPN configuration file. Other options related to the tunnel\n        // provider also can be stored there.\n        guard\n            let protocolConfiguration = protocolConfiguration as? NETunnelProviderProtocol,\n            let providerConfiguration = protocolConfiguration.providerConfiguration\n        else {\n            fatalError()\n        }\n\n        guard let ovpnFileContent: Data = providerConfiguration[\"ovpn\"] as? Data else {\n            fatalError()\n        }\n\n        let configuration = OpenVPNConfiguration()\n        configuration.fileContent = ovpnFileContent\n        configuration.settings = [\n            // Additional parameters as key:value pairs may be provided here\n        ]\n\n        // Uncomment this line if you want to keep TUN interface active during pauses or reconnections\n        // configuration.tunPersist = true\n\n        // Apply OpenVPN configuration\n        let evaluation: OpenVPNConfigurationEvaluation\n        do {\n            evaluation = try vpnAdapter.apply(configuration: configuration)\n        } catch {\n            completionHandler(error)\n            return\n        }\n\n        // Provide credentials if needed\n        if !evaluation.autologin {\n            // If your VPN configuration requires user credentials you can provide them by\n            // `protocolConfiguration.username` and `protocolConfiguration.passwordReference`\n            // properties. It is recommended to use persistent keychain reference to a keychain\n            // item containing the password.\n\n            guard let username: String = protocolConfiguration.username else {\n                fatalError()\n            }\n\n            // Retrieve a password from the keychain\n            guard let password: String = ... {\n                fatalError()\n            }\n\n            let credentials = OpenVPNCredentials()\n            credentials.username = username\n            credentials.password = password\n\n            do {\n                try vpnAdapter.provide(credentials: credentials)\n            } catch {\n                completionHandler(error)\n                return\n            }\n        }\n\n        // Checking reachability. In some cases after switching from cellular to\n        // WiFi the adapter still uses cellular data. Changing reachability forces\n        // reconnection so the adapter will use actual connection.\n        vpnReachability.startTracking { [weak self] status in\n            guard status == .reachableViaWiFi else { return }\n            self?.vpnAdapter.reconnect(interval: 5)\n        }\n\n        // Establish connection and wait for .connected event\n        startHandler = completionHandler\n        vpnAdapter.connect(using: packetFlow)\n    }\n\n    override func stopTunnel(\n        with reason: NEProviderStopReason, \n        completionHandler: @escaping () -\u003e Void\n    ) {\n        stopHandler = completionHandler\n\n        if vpnReachability.isTracking {\n            vpnReachability.stopTracking()\n        }\n\n        vpnAdapter.disconnect()\n    }\n\n}\n\nextension PacketTunnelProvider: OpenVPNAdapterDelegate {\n\n    // OpenVPNAdapter calls this delegate method to configure a VPN tunnel.\n    // `completionHandler` callback requires an object conforming to `OpenVPNAdapterPacketFlow`\n    // protocol if the tunnel is configured without errors. Otherwise send nil.\n    // `OpenVPNAdapterPacketFlow` method signatures are similar to `NEPacketTunnelFlow` so\n    // you can just extend that class to adopt `OpenVPNAdapterPacketFlow` protocol and\n    // send `self.packetFlow` to `completionHandler` callback.\n    func openVPNAdapter(\n        _ openVPNAdapter: OpenVPNAdapter, \n        configureTunnelWithNetworkSettings networkSettings: NEPacketTunnelNetworkSettings?, \n        completionHandler: @escaping (Error?) -\u003e Void\n    ) {\n        // In order to direct all DNS queries first to the VPN DNS servers before the primary DNS servers\n        // send empty string to NEDNSSettings.matchDomains  \n        networkSettings?.dnsSettings?.matchDomains = [\"\"]\n\n        // Set the network settings for the current tunneling session.\n        setTunnelNetworkSettings(networkSettings, completionHandler: completionHandler)\n    }\n\n    // Process events returned by the OpenVPN library\n    func openVPNAdapter(\n        _ openVPNAdapter: OpenVPNAdapter, \n        handleEvent event: \n        OpenVPNAdapterEvent, message: String?\n    ) {\n        switch event {\n        case .connected:\n            if reasserting {\n                reasserting = false\n            }\n\n            guard let startHandler = startHandler else { return }\n\n            startHandler(nil)\n            self.startHandler = nil\n\n        case .disconnected:\n            guard let stopHandler = stopHandler else { return }\n\n            if vpnReachability.isTracking {\n                vpnReachability.stopTracking()\n            }\n\n            stopHandler()\n            self.stopHandler = nil\n\n        case .reconnecting:\n            reasserting = true\n\n        default:\n            break\n        }\n    }\n\n    // Handle errors thrown by the OpenVPN library\n    func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, handleError error: Error) {\n        // Handle only fatal errors\n        guard let fatal = (error as NSError).userInfo[OpenVPNAdapterErrorFatalKey] as? Bool, \n              fatal == true else { return }\n\n        if vpnReachability.isTracking {\n            vpnReachability.stopTracking()\n        }\n\n        if let startHandler = startHandler {\n            startHandler(error)\n            self.startHandler = nil\n        } else {\n            cancelTunnelWithError(error)\n        }\n    }\n\n    // Use this method to process any log message returned by OpenVPN library.\n    func openVPNAdapter(_ openVPNAdapter: OpenVPNAdapter, handleLogMessage logMessage: String) {\n        // Handle log messages\n    }\n\n}\n```\n\n## Contributing\nAny contributions and suggestions are welcome! But before creating a PR or an issue please read the [Contribution Guide](CONTRIBUTING.md).\n\n## Acknowledgments\nSpecial thanks goes to [@JonathanDowning](https://github.com/JonathanDowning) for great help in development of this project and bug fixing.\n\n## License\nOpenVPNAdapter is available under the AGPLv3 license. See the [LICENSE](LICENSE) file for more info. Also this project has a few dependencies:\n- [openvpn3](https://github.com/OpenVPN/openvpn3)\n- [asio](https://github.com/chriskohlhoff/asio)\n- [lz4](https://github.com/lz4/lz4)\n- [mbedtls](https://github.com/ARMmbed/mbedtls)\n\nSee the [NOTICE](NOTICE) file for more info about their licenses and copyrights.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fss-abramchuk%2Fopenvpnadapter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fss-abramchuk%2Fopenvpnadapter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fss-abramchuk%2Fopenvpnadapter/lists"}