10

我正在尝试在我的 iOS 应用程序中创建 IPSEC VPN 连接。

我设置配置的代码如下所示:

-(void)setUpConfig
   NEVPNManager *manager = [NEVPNManager sharedManager];

    int status = manager.connection.status;

    if (status == NEVPNStatusConnected) {
        manager.connection stopVPNTunnel];
    } else {
        [manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
            NSError *startError;

        if (error) {
            NSLog(@"Load config failed [%@]", error.localizedDescription);
            return;
        }

        NEVPNProtocolIPSec *p = (NEVPNProtocolIPSec *)self.manager.protocol;
        if (!p) {
            p = [[NEVPNProtocolIPSec alloc] init];
        }

        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"base64_encoded_cert" ofType:@"txt"];
        NSString *certBase64String = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
        NSString *certPassword = @"cert_import_password";

        NSString *vpnUsername = @"myUsername";
        NSString *vpnPassword = @"myPassword";
        NSString *url = @"my.server.address";

        // This saves my credentials to the keychain and returns a persistent keychain reference
        NSData *passRef = [self addVPNCredentialsToKeychain:vpnUsername withPassword:vpnPassword];

        p.username = vpnUsername;
        p.authenticationMethod = NEVPNIKEAuthenticationMethodCertificate;
        p.serverAddress = url;
        p.passwordReference = passRef;
        p.identityData = [NSData dataWithBase64EncodedString:certBase64String];
        p.identityDataPassword = certPassword;
        p.disconnectOnSleep = NO;
        p.useExtendedAuthentication = YES;

        [manager setProtocol:p];
        [manager setOnDemandEnabled:NO];
        [manager setLocalizedDescription:@"My VPN"];

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


-(NSData*)addVPNCredentialsToKeychain:(NSString*)username withPassword:(NSString*)password
{
    NSMutableDictionary *keychainItem = [NSMutableDictionary dictionary];

    NSData *encodedIdentifier = [username dataUsingEncoding:NSUTF8StringEncoding];

    keychainItem[(__bridge id)kSecClass] = (__bridge id)kSecClassGenericPassword;
    keychainItem[(__bridge id)kSecAttrDescription] = @"A password used to authenticate on a VPN server";
    keychainItem[(__bridge id)kSecAttrGeneric] = encodedIdentifier;
    keychainItem[(__bridge id)kSecAttrAccount] = encodedIdentifier;
    keychainItem[(__bridge id)kSecAttrService] = [[NSBundle mainBundle] bundleIdentifier];
    keychainItem[(__bridge id)kSecMatchLimit] = (__bridge id)kSecMatchLimitOne;
    keychainItem[(__bridge id)kSecReturnPersistentRef] = @YES;

    CFTypeRef typeResult = nil;

    OSStatus sts = SecItemCopyMatching((__bridge CFDictionaryRef)keychainItem, &typeResult);

    NSLog(@"Error Code: %d", (int)sts);

    if(sts == noErr) {
        NSData *theReference = (__bridge NSData *)typeResult;
    return theReference;

    } else {
        keychainItem[(__bridge id)kSecValueData] = [password dataUsingEncoding:NSUTF8StringEncoding]; //Our password

        OSStatus sts = SecItemAdd((__bridge CFDictionaryRef)keychainItem, &typeResult);
        NSLog(@"Error Code: %d", (int)sts);

        NSData *theReference = (__bridge NSData *)(typeResult);
        return theReference;
    }
    return nil;
}

然后我尝试像这样打开一个 VPN 连接:

-(void)connect
    NEVPNManager *manager = [NEVPNManager sharedManager];
    [manager loadFromPreferencesWithCompletionHandler:^(NSError *error) {
        NSError *startError;
        [manager.connection startVPNTunnelAndReturnError:&startError];

        if(startError) {
            NSLog(@"Start error: %@", startError.localizedDescription);
        }
    }];
}

这在大多数情况下都有效。我遇到的问题是,在工厂恢复设备(当然是在 iOS 8 上)并尝试通过此设置和连接后,我的配置文件安装得很好,但 VPN 无法连接。事实上,我的解释是它无法尝试连接。

在恢复设备并尝试使用我的方法进行连接后,设备日志中显示以下内容:

<Notice>: NESMLegacySession[MyVPN:BB73C098-B22E-46D3-9491-2A6D9F559F8F]: Received a start command from VPNApp[256], but start was rejected

进入“设置”应用程序并尝试使用“蓝牙”下的开关手动切换 VPN 会导致开关打开片刻,然后立即关闭。在这种情况下,会生成以下日志:

<Warning>: -[VPNBundleController _vpnNetworkingIsDisabled]: Airplane mode: 0, WiFi Enabled: 1

在这两种情况下,当 VPN 无法开始连接时,不会产生错误对话框 - 只有日志。

可以通过导航到“设置”>“常规”>“VPN”来解决这个问题。一旦进入该页面(即不在那里切换 VPN),我就可以很好地控制 VPN。即使在安装 VPN 配置之前访问该页面,我也可以在安装配置后正常连接。

我的目标是能够启动 VPN 连接,而无需先进入“设置”中的那个 VPN 页面。任何人都可以说明情况吗?在我看来,我好像错过了首先启用 VPN 连接的东西。

4

1 回答 1

6

这是因为 VPN 配置disabled默认保留用于初始 VPN 连接。

您必须先启用 VPN saveToPreferencesWithCompletionHandler

[[NEVPNManager sharedManager] setEnabled:YES];

例子:

[[NEVPNManager sharedManager] loadFromPreferencesWithCompletionHandler: ^(NSError *error) {
        if (error) {
            NSLog(@"Load error: %@", error);
        }
        else {
            // No errors! The rest of your codes goes here...
            NEVPNProtocolIPSec *p = [[NEVPNProtocolIPSec alloc] init];
            p.serverAddress = @"VPN SERVER ADDRESS";
            p.authenticationMethod = NEVPNIKEAuthenticationMethodCertificate;
            p.localIdentifier = @"Local identifier";
            p.remoteIdentifier = @"Remote identifier";
            p.useExtendedAuthentication = YES;
            p.identityData = [NSData dataWithBase64EncodedString:certBase64String];;
            p.identityDataPassword = @"identity password";
            p.disconnectOnSleep = NO;
            
            // Set protocol
            [[NEVPNManager sharedManager] setProtocol:p];

            // Set on demand
            NSMutableArray *rules = [[NSMutableArray alloc] init];
            NEOnDemandRuleConnect *connectRule = [NEOnDemandRuleConnect new];
            [rules addObject:connectRule];
            [[NEVPNManager sharedManager] setOnDemandRules:rules];
            
            // Set localized description
            [[NEVPNManager sharedManager] setLocalizedDescription:@"Description"];
            
            // Enable VPN
            [[NEVPNManager sharedManager] setEnabled:YES];
            
            // Save to preference
            [[NEVPNManager sharedManager] saveToPreferencesWithCompletionHandler: ^(NSError *error) {
                NSLog(@"Save VPN to preference complete");
                if (error) {
                    NSLog(@"Save to preference error: %@", error);
                   
                }
            }];
        }
    }];
于 2014-10-27T21:37:56.580 回答