12/08/2018, 12:35

IOS Virtual private networks (VPN)

OVERVIEW Secure access to private corporate networks is available in iOS and OS X using established industry-standard virtual private network (VPN) protocols. Out of the box, iOS and OS X support Cisco IPSec, L2TP over IPSec, and PPTP. iOS also supports IKEv2. If your organization supports one ...

OVERVIEW

  • Secure access to private corporate networks is available in iOS and OS X using established industry-standard virtual private network (VPN) protocols. Out of the box, iOS and OS X support Cisco IPSec, L2TP over IPSec, and PPTP. iOS also supports IKEv2. If your organization supports one of these protocols, no additional network con guration or third-party apps are required in order to connect Apple devices to your VPN.
  • iOS and OS X support SSL VPN from popular VPN providers. Like other VPN protocols supported in iOS and OS X, SSL VPN can be con gured manually on the Apple device, or by con guration pro les or mobile device management.
  • iOS and OS X also support industry-standard technologies such as IPv6, proxy servers, and split- tunneling, providing a rich VPN experience when connecting to corporate networks. And iOS and OS X work with a variety of authentication methods including password, two-factor token, digital certi cates, and for OS X, Kerberos. To streamline the connection in environments where certi cate-based authentication is used, iOS and OS X feature VPN On Demand, which initiates a VPN session when it’s needed in order to connect to speci ed domains.
  • With iOS 7 or later and OS X Yosemite or later, individual apps can be con gured to use a VPN connection independent from other apps. This ensures that corporate data always ows over a VPN connection, and other data, such as an employee’s personal apps from the App Store, does not.
  • iOS also features Always-on VPN, when an iOS device must connect to a known, approved VPN before connecting to any other network services. You can con gure Always-on VPN for both cellular and Wi-Fi con gurations. For example, using Always-on VPN, an iOS device must connect to a known and approved VPN before connecting to any other network services such as mail, web, or messages. This feature depends on your VPN provider supporting this con guration, and is available only for supervised devices

Supported protocols and authentication methods

iOS and OS X support the following protocols and authentication methods:

  • L2TP over IPSec: User authentication by MS-CHAP v2 password, two-factor token, certi cate, machine authentication by shared secret or certi cate.
  • SSL VPN: User authentication by password, two-factor token, certi cates using a third-party VPN client.
  • Cisco IPSec: User authentication by password, two-factor token, machine authentication by shared secret and certi cates.
  • IKEv2: Certi cates (RSA-only), EAP-TLS, EAP-MSCHAPv2. (iOS-only)
  • PPTP: User authentication by MS-CHAP v2 password, certi cate, and two-factor token.

VPN setup guidelines

Proxy setup

For all con gurations, you can specify a VPN proxy:

  • To con gure a single proxy for all connections, use the Manual setting and provide the address, port, and authentication if necessary.
  • To provide the device with an auto-proxy con guration le using PAC or WPAD, use the Auto setting. For PACS, specify the URL of the PACS or JavaScript le. For WPAD, iOS asks DHCP and DNS for the appropriate settings.

The VPN proxy con guration gets used when the VPN is providing the following:

  • The default resolver and the default route
  • A split tunnel

Authentication methods

iOS supports the following authentication methods:

  • Pre-shared key IPSec authentication with user authentication via xauth.
  • Client and server certi cates for IPSec authentication, with optional user authentication via xauth.
  • Hybrid authentication, where the server provides a certi cate and the client provides a pre- shared key for IPSec authentication. User authentication is required via xauth.
  • User authentication is provided via xauth and includes the following authentication methods:
  • Username with password
  • RSA SecurID
  • CRYPTOCard

Certificates

When you set up and install certificates:

  • The server identity certi cate must contain the server’s DNS name or IP address in the SubjectAltName eld.
  • The certi cate of the CA that signed the server’s certi cate needs to be installed on the device.
  • The certi cates and certi cate authorities must be valid (for example, not expired). Sending of certi cate chain by the server isn’t supported.

IPSec settings and descriptions

IPSec has various settings that you can use to de ne how it will be implemented:

  • Mode
  • IKE Exchange Modes
  • Encryption Algorithms: 3DES, AES-128, or AES256.
  • Authentication Algorithms: HMAC-MD5 or HMAC-SHA1.
  • Diffie-Hellman Groups
  • PFS (Perfect Forward Secrecy)
  • Mode Con guration
  • Dead Peer Detection
  • Standard NAT Traversal
  • Load Balancing
  • Rekeying of Phase 1
  • ASA Address Mask
  • Application Version
  • Banner
  • Split Tunnel
  • Split DNS
  • Default Domain

iOS and OS X support IPSec protocols and authentication methods

  • IKEv2: Support for both IPv4 and IPv6 and the following:

    • Authentication methods: Shared secret, certificates, EAP-TLS and EAP-MSCHAPv2

    • Suite B cryptography: ECDSA certificates, ESP encryption with GCM, and ECP Groups for the Diffie-Hellman Group

    • Additional features: MOBIKE, IKE fragmentation, server redirect, split tunnel

  • L2TP over IPSec: User authentication by MS-CHAP v2 password, two-factor token, certificate, machine authentication by shared secret or certificate

  • SSL VPN: User authentication by password, two-factor token, and certificates using a third-party VPN client

  • Cisco IPSec: User authentication by password, two-factor token, and machine authentication by shared secret and certificates

  • PPTP: User authentication by MS-CHAP v2 password, certificate, and two-factor token

OS X can also use Kerberos machine authentication by shared secret or certificate with L2TP over IPSec and with PPTP.

Rules and actions

Rules help de ne the type of networks associated with VPN On Demand. Actions help de ne what happens when matching rules are found to be true.

Example iOS VPN On-Demand Rules

 
<key>OnDemandEnabled</key>
  <integer>1</integer>
 
<key>OnDemandRules</key>
  <array>
     
    <dict>
      <key>InterfaceTypeMatch</key>
        <string>WiFi</string>
      <key>SSIDMatch</key>
        <string>Our-Wireless</string>
      <key>DNSServerAddressMatch</key>
        <array>
          <string>172.24.32.53</string>
        </array>
      <key>Action</key>
        <string>Disconnect</string>
    </dict>
     
    <dict>
      <key>InterfaceTypeMatch</key>
        <string>WiFi</string>
      <key>URLStringProbe</key>
        <string>http://12.34.56.78/canDoVPN?WiFi</string>
      <key>Action</key>
        <string>Connect</string>
    </dict>
     
    <dict>
      <key>InterfaceTypeMatch</key>
        <string>Cellular</string>
      <key>URLStringProbe</key>
        <string>http://12.34.56.78/canDoVPN?Cellular</string>
      <key>Action</key>
        <string>Connect</string>
    </dict>
     
    <dict>
      <key>Action</key>
        <string>Disconnect</string>
    </dict>
  </array>
 
  • the first rule – to disconnect the VPN if you're on our WiFi network – never seems to get triggered so, when coming within our WiFi range and transitioning from cellular to WiFi, the VPN connection remains (which, with OpenVPN, is not really an issue for us)
  • when connected to our WiFi, turning off the WiFi connection then attempting a cellular connection will often "hang" the entire networking stack, requiring that the phone be switched to Airplane mode then back on or will sometimes require a reboot – we've also infrequently seen this behavior when transitioning out of our WiFi range when the phone automatically transitions to cellular
  • rules seem to be triggered when visiting the WiFi settings screen (not when changing the setting) so, if you visit the screen and don't change the setting, "hung" networking can happen
  • the "URLStringProbe" is never issued for the "InterfaceTypeMatch" "WiFi" rule
  • in spite of these issues, we do use this ruleset and enjoy the extra security provided by VPNing our devices' traffic through our network

Action

This required key de nes VPN behavior for when all of the speci ed matching rules evaluate as true. Values for the Action key are:

  • Connect
  • Disconnect
  • Ignore
  • EvaluateConnection
  • Allow

VPN Requirements

  • support multiple concurrent VPN connections from mobile devices with a minimum of administration effort and a maximum amount of transparency to the mobile device User

  • ensure the User can override the VPN capability if required ("smart" services should always have a "lobotomy button")

  • VPN connections are secure/encrypted – this rules out protocols such as "straight" L2TP (i.e., without IPSec) and PPTP (a compromised protocol) ... for us, this leaves IPSec and OpenVPN as two "zero-cost" options

  • a VPN-connected iOS device routes all the device's traffic through our network

    • all the iOS device's traffic goes through our network and is encrypted while doing so – so the cellular data and WiFi parts of the device's traffic can't be "monitored"
    • all unencrypted (and normall SSL browsing, etc.) traffic emanates only from our LAN through our network's (land-based/hard-wired) router
      • this gives our mobile devices the benefit of some "bad site" filters provided by our firewall appliance
    • this differs from the more common VPN strategy wherein only the traffic between the VPN-connected site and the mobile device is encrypted and all the mobile device's traffic to other sites is via direct and possibly unencrypted routes to those sites
  • a VPN-connected device has access to our internal network – i.e., appears to reside on our LAN and is subject to our router/firewall configuration

  • VPN connections are driven by certificates and the User is not required to enter a password to create a VPN connection (even though the devices themselves have reasonably strong access passwords, this "no password entry" requirement does add some risk in the event of a compromised device)

  • VPNs are configured to use self-signed certificates to reduce the security and administrative impact if a device is lost and its certificate information is compromised

  • when the device is connected to our WiFi network, no VPN connection is made and any existing VPN connection is automatically turned OFF

  • when the device is connected to some other WiFi network, the VPN connection to our network is automatically turned ON

  • when the device is connected to the cellular data network, the VPN connection to our network is automatically turned ON

  • when the VPN connection is via OpenVPN (the preferred method), first attempt to connect via one of multiple UDP ports and, failing that, use TCP port 443 (i.e., in an attempt to avoid blockages by firewalls and proxy servers)

  • in any case, a VPN connection should not be attempted if a VPN connection could not be supported (i.e., by our network)

Configuration profiles

  • A configuration profile is an XML file you use to distribute configuration information to Apple devices. Configuration profiles automate the configuration of settings, accounts, restrictions, and credentials.
  • They can be installed on iOS devices via a mail message attachment, downloaded from a webpage, or installed using Apple Configurator 2.
  • If you need to configure a large number of Apple devices, or if you prefer a hands-off wireless deployment, you can deliver configuration profiles using an MDM solution.
  • Configuration profiles can be encrypted and signed, which lets you restrict their use to a specific Apple device and, with the exception of user names and passwords, prevents anyone from changing the settings. You can also mark a profile as being locked to the device, so after the profile is installed, it can be removed only by wiping the device of all data or by entering the password associated with the profile. Accounts that are configured by a profile, such as Microsoft Exchange accounts, can be removed only by deleting the profile.

Configuration Profile Key Reference

A configuration profile is an XML file that allows you to distribute configuration information. If you need to configure a large number of devices or to provide lots of custom email settings, network settings, or certificates to a large number of devices, configuration profiles are an easy way to do it.

A configuration profile contains a number of settings that you can specify, including:

  • Restrictions on device features

  • Wi-Fi settings

  • VPN settings

  • Email server settings

  • Exchange settings

  • LDAP directory service settings

  • CalDAV calendar service settings

  • Web clips

  • Credentials and keys

  • Configuration profiles are written in property list format, with Data values stored in Base64 encoding. The file .plist format can be read/write by xml library

  • There are five ways to deploy configuration profiles.

    • Using Apple Configurator (iOS only)
    • In an email message
    • On a webpage
    • Using over-the air configuration
    • Over the air using a Mobile Device Management Server

APN Payload

  • The APN (Access Point Name) payload is designated by specifying com.apple.apn.managed as the PayloadType value.

  • In iOS 7 and later, the APN payload is deprecated in favor of the Cellular payload.

  • The APN Payload is not supported in OS X.

    • DefaultsData (dictionary): this dictionary contains two key/value pairs.
    • DefaultsDomainName (String): The only allowed value is com.apple.managedCarrier.
    • apns (Array) : This array contains an arbitrary number of dictionaries, each describing an APN configuration, with the key/value pairs below.
    • apn (String): This string specifies the Access Point Name.
    • username (String ): This string specifies the user name for this APN. If it is missing, the device prompts for it during profile installation.
    • password (Data): Optional. This data represents the password for the user for this APN. For obfuscation purposes, the password is encoded. If it is missing from the payload, the device prompts for the password during profile installation.
    • Proxy (String): Optional. The IP address or URL of the APN proxy.
    • ProxyPort (Number): Optional. The port number of the APN proxy.

** Per-App VPN Payload**

  • The Per-App VPN payload is used for configuring add-on VPN software, and it works only on VPN services of type 'VPN'. It should not be confused with the standard VPN payload
  • This payload is supported only in iOS 7.0 and later and OS X v10.9 and later.
  • The VPN payload is designated by specifying com.apple.vpn.managed.applayer as the PayloadType value. The Per-App VPN payload supports all of the keys described in VPN Payload plus the following additional keys
    • VPNUUID (String): A globally-unique identifier for this VPN configuration. This identifier is used to configure apps so that they use the Per-App VPN service for all of their network communication.

    • SafariDomains (Array) : This optional key is a special case of App-to-Per App VPN Mapping. It sets up the app mapping for Safari (Webkit) with a specific identifier and a designated requirement. The array contains strings, each of which is a domain that should trigger this VPN connection in Safari. The rule matching behavior is as follows:

      • Before being matched against a host, all leading and trailing dots are stripped from the domain string. For example, if the domain string is ".com" the domain string used to match is "com"
      • Each label in the domain string must match an entire label in the host string. For example, a domain of "example.com" matches "www.example.com", but not "foo.badexample.com".
      • Domain strings with only one label must match the entire host string. For example, a domain of "com" matches "com", not "www.example.com".
    • OnDemandMatchAppEnabled (Boolean) : This key is placed in the VPN payload sub-dictionary.

      • If true, the Per-App VPN connection starts automatically when apps linked to this Per-App VPN service initiate network communication.
      • If false, the Per-App VPN connection must be started manually by the user before apps linked to this Per-App VPN service can initiate network communication.
      • If this key is not present, the value of the OnDemandEnabled key is used to determine the status of Per-App VPN On Demand.

VPN Dictionary Keys

  • In addition to the VPN Dictionary keys defined in the com.apple.vpn.managed payload, the VPN Dictionary within the com.apple.vpn.managed.applayer payload can also contain the following keys:
    • ProviderType (String): Optional. Either packet-tunnel or app-proxy. The default is app-proxy. If the value of this key is app-proxy, then the VPN service will tunnel traffic at the application layer. If the value of this key is packet-tunnel, then the VPN service will tunnel traffic at the IP layer.

**I - Setting up vpn for iOS **

1. Manual

a. Go to Settings > General > VPN. b. Choose "add VPN configuration"

configure_vpn.png

c. Ask your network administrator which settings to use. In most cases, if you set up a similar VPN on your computer, you can use the same settings on your device.

d. Turn VPN on or Off

After you create a VPN configuration, the option to turn VPN on or off appears in Settings. When you connect using VPN, the VPN icon appears in the status bar.

turn_vpn_on.png

If you use multiple VPN configurations, you can switch configurations using Settings > General > VPN.

**2. Programmatically **

a) NetworkExtension.Framework

  • This framework available from iOS 8. The Network Extension framework allows apps to customize and extend the core networking features of iOS and OS X

  • The Network Extension framework contains APIs that can be used to customize and extend the core networking features of iOS and OS X

  • The NEVPNManager API gives apps the ability to create and manage a Personal VPN configuration on iOS and OS X. Personal VPN configurations are typically used to provide a service to users that protects their Internet browsing activity on insecure networks such as public Wi-Fi networks.

  • You can use the NETunnelProvider family of APIs to connect iOS and OS X devices to a VPN server that uses a non-standard network tunneling protocol, such as an SSL-VPN server.

  • The NETunnelProvider family of APIs gives apps the ability to implement the client side of a custom network tunneling protocol, called a Tunnel Provider. The Tunnel Provider runs as an app extension. The NETunnelProvider family of APIs also contains the following classes, which are used to configure and control the Tunnel Provider:

  • The NEFilterProvider API gives apps the ability to dynamically filter network content on iOS devices. Apps can use the following classes in school environments to protect students as they browse the Internet using school-owned devices:

  • The NEHotspotHelper API gives apps the ability to perform custom authentication for Wi-Fi Hotspots. NEHotspotHelper gives users a way to seamlessly connect to a large aggregated network of Wi-Fi Hotspots.

    This is family api of this framework. The purpose of apis.

Screen Shot 2015-10-26 at 1.24.03 AM.png

**a.1 ) NEHotSpotHelper : Wifi Hotspot Authentication **

  • Previous solutions : Use CNSetSupportedSSIDs and CNMarkPortalOnline. But this solution has some problems
    • Hotspot list has a size limitation
    • Users have a manually run your apps
    • No indication to the user that your app needs to run
  • Current solution
    • Regiser with the system as a HotspotHelper from background
    • Claim Hotspots with a level of confidence
    • Perform the initial authentication
    • Maintai the authetication session

a.2 ) NEVPNManager : Personal VPN

  • Configure and control the built-in IPSec client
  • Create a personal vpn configuration
  • Support IKEv1 and IKEv2
  • Configure connect on demand
  • Configure HTTP proxies
  • Configure with enterprise vpn configuration

Example : Create the configuration

	func createTheConfiguration() {
    //each app get a single configuration
    let manager = NEVPNManager.sharedManager()
    manager.loadFromPreferencesWithCompletionHandler { (error) -> Void in
        //protocol is a keyword, so it needs to be qouted.
        if manager.`protocol` == nil {
            let newIPSec = NEVPNProtocolIKEv2()
            newIPSec.serverAddress = "my.personal.vpn"
            //set all of the properties on newIPSec
            manager.`protocol` = newIPSec

            //Toggles the enabled status of the VPN. Setting this property will disable VPN configurations of other apps. This property will be set to NO  when other VPN configurations are enabled.
            manager.enabled = true

            //save to preference
            manager.saveToPreferencesWithCompletionHandler({ (error) -> Void in

            })
        }
    }
}
func connectDemand() {
    let manager = NEVPNManager.sharedManager()

    // Connect automatically on a matching network
    let connectRule = NEOnDemandRuleConnect()
    connectRule.interfaceTypeMatch = .WiFi
    //set rule in array
    manager.onDemandRules = [connectRule]
    manager.saveToPreferencesWithCompletionHandler { (error) -> Void in

    }
}

`

a.3 ) NETunelProvider : Custom enterprise VPN configuration

  • Create a custom VPN protocol provider

    • Runs as an app extension
    • Packet tunnel provider for IP layer tunnely
    • App proxy provider for app layer tunnely
  • Configure and control your protocol provider from your app.

VPN data path

Screen Shot 2015-10-26 at 2.10.48 AM.png

Example

///VPNManager.h
@interface VPNManager : NSObject
{

}
+ (VPNManager *)instance;
- (void)loadConfig;
- (void)connect;
@end

////////////////////////////////////////////////////

///VPNManager.m
@implementation VPNManager
+ (VPNManager *)instance {
    static VPNManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [VPNManager new];
    });
    return instance;
}

- (void)loadConfig {
    NEVPNManager *manager = [NEVPNManager sharedManager];
    NSLog(@"Hi!");
    [manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
        NSLog(@"Hey!");
        if(error) {
            NSLog(@"Load error: %@", error);
        } else {
            [manager setProtocol:[self getProtocol]];
            [manager setOnDemandEnabled:NO];
            [manager setEnabled:YES];
            [manager setLocalizedDescription:@"Valentin's VPN"];

            [manager saveToPreferencesWithCompletionHandler:^(NSError *error) {
                if(error) {
                    NSLog(@"Save error: %@", error);
                }
                else {
                    NSLog(@"Saved!");
                }
            }];
        }
    }];
}

- (NEVPNProtocolIPSec*)getProtocol {

    NEVPNProtocolIPSec *p = [[NEVPNProtocolIPSec alloc] init];
    p.username = ACCOUNT;
    p.passwordReference = [PASSWORD dataUsingEncoding:NSUTF8StringEncoding];
    p.serverAddress = @"192.168.0.128";
    p.authenticationMethod = NEVPNIKEAuthenticationMethodSharedSecret;
    p.sharedSecretReference = [SECRET dataUsingEncoding:NSUTF8StringEncoding];
    p.localIdentifier = @"[VPN local identifier]";
    p.remoteIdentifier = @"[VPN remote identifier]";
    p.useExtendedAuthentication = YES;
    p.disconnectOnSleep = NO;
    return p;
}

- (void)connect {
    NSError *startError;
    [[NEVPNManager sharedManager].connection startVPNTunnelAndReturnError:&startError];

    if(startError) {
        NSLog(@"Start error: %@", startError.localizedDescription);
    } else {
        NSLog(@"Connection established!");
    }
}

@end

///User VPNManager
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[VPNConnector instance] loadConfig];
}

- (IBAction)connectButtonTapped:(id)sender {
    [[VPNConnector instance] connect];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end
0