summaryrefslogtreecommitdiff
path: root/app/src/main/java/de/blinkt/openvpn/VpnProfile.java
blob: 511893d71743b7801ef0d022df67eb216a4a0b6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
/*
 * Copyright (c) 2012-2016 Arne Schwabe
 * Distributed under the GNU GPL v2 with additional terms. For full terms see the file doc/LICENSE.txt
 */

package de.blinkt.openvpn;

import static de.blinkt.openvpn.core.connection.Connection.TransportType.OBFS4;
import static de.blinkt.openvpn.core.connection.Connection.TransportType.OBFS4_HOP;
import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_PROFILE;
import static se.leap.bitmaskclient.base.utils.ConfigHelper.stringEqual;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.security.KeyChain;
import android.security.KeyChainException;
import android.text.TextUtils;
import android.util.Base64;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.spongycastle.util.io.pem.PemObject;
import org.spongycastle.util.io.pem.PemWriter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PSSParameterSpec;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Locale;
import java.util.UUID;
import java.util.Vector;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import de.blinkt.openvpn.core.ExtAuthHelper;
import de.blinkt.openvpn.core.NativeUtils;
import de.blinkt.openvpn.core.OpenVPNManagement;
import de.blinkt.openvpn.core.OpenVPNService;
import de.blinkt.openvpn.core.OrbotHelper;
import de.blinkt.openvpn.core.PasswordCache;
import de.blinkt.openvpn.core.Preferences;
import de.blinkt.openvpn.core.VPNLaunchHelper;
import de.blinkt.openvpn.core.VpnStatus;
import de.blinkt.openvpn.core.X509Utils;
import de.blinkt.openvpn.core.connection.Connection;
import de.blinkt.openvpn.core.connection.ConnectionAdapter;
import de.blinkt.openvpn.core.connection.Obfs4Connection;
import se.leap.bitmaskclient.BuildConfig;
import se.leap.bitmaskclient.R;
import se.leap.bitmaskclient.base.models.ProviderObservable;
import se.leap.bitmaskclient.base.utils.PreferenceHelper;
import se.leap.bitmaskclient.pluggableTransports.models.Obfs4Options;

public class VpnProfile implements Serializable, Cloneable {
    // Note that this class cannot be moved to core where it belongs since
    // the profile loading depends on it being here
    // The Serializable documentation mentions that class name change are possible
    // but the how is unclear
    //
    transient public static final long MAX_EMBED_FILE_SIZE = 2048 * 1024; // 2048kB
    // Don't change this, not all parts of the program use this constant
    public static final String EXTRA_PROFILEUUID = "de.blinkt.openvpn.profileUUID";
    public static final String INLINE_TAG = "[[INLINE]]";
    public static final String DISPLAYNAME_TAG = "[[NAME]]";
    public static final int MAXLOGLEVEL = 4;
    public static final int CURRENT_PROFILE_VERSION = 7;
    public static final int DEFAULT_MSSFIX_SIZE = 1280;
    public static final int TYPE_CERTIFICATES = 0;
    public static final int TYPE_PKCS12 = 1;
    public static final int TYPE_KEYSTORE = 2;
    public static final int TYPE_USERPASS = 3;
    public static final int TYPE_STATICKEYS = 4;
    public static final int TYPE_USERPASS_CERTIFICATES = 5;
    public static final int TYPE_USERPASS_PKCS12 = 6;
    public static final int TYPE_USERPASS_KEYSTORE = 7;
    public static final int TYPE_EXTERNAL_APP = 8;
    public static final int X509_VERIFY_TLSREMOTE = 0;
    public static final int X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING = 1;
    public static final int X509_VERIFY_TLSREMOTE_DN = 2;
    public static final int X509_VERIFY_TLSREMOTE_RDN = 3;
    public static final int X509_VERIFY_TLSREMOTE_RDN_PREFIX = 4;
    public static final int AUTH_RETRY_NONE_FORGET = 0;
    public static final int AUTH_RETRY_NOINTERACT = 2;
    public static final boolean mIsOpenVPN22 = false;
    private static final long serialVersionUID = 7085688938959334563L;
    private static final int AUTH_RETRY_NONE_KEEP = 1;
    private static final int AUTH_RETRY_INTERACT = 3;
    private static final String EXTRA_RSA_PADDING_TYPE = "de.blinkt.openvpn.api.RSA_PADDING_TYPE";
    private static final String EXTRA_SALTLEN = "de.blinkt.openvpn.api.SALTLEN";
    private static final String EXTRA_NEEDS_DIGEST = "de.blinkt.openvpn.api.NEEDS_DIGEST";
    private static final String EXTRA_DIGEST = "de.blinkt.openvpn.api.DIGEST";
    public static String DEFAULT_DNS1 = "8.8.8.8";
    public static String DEFAULT_DNS2 = "8.8.4.4";
    // variable named wrong and should haven beeen transient
    // but needs to keep wrong name to guarante loading of old
    // profiles
    public transient boolean profileDeleted = false;
    public int mAuthenticationType = TYPE_KEYSTORE;
    public String mName;
    public String mAlias;
    public String mClientCertFilename;
    public String mTLSAuthDirection = "";
    public String mTLSAuthFilename;
    public String mClientKeyFilename;
    public String mCaFilename;
    public boolean mUseLzo = false;
    public String mPKCS12Filename;
    public String mPKCS12Password;
    public boolean mUseTLSAuth = false;
    public String mDNS1 = DEFAULT_DNS1;
    public String mDNS2 = DEFAULT_DNS2;
    public String mIPv4Address;
    public String mIPv6Address;
    public boolean mOverrideDNS = false;
    public String mSearchDomain = "blinkt.de";
    public boolean mUseDefaultRoute = true;
    public boolean mUsePull = true;
    public String mCustomRoutes;
    public boolean mCheckRemoteCN = true;
    public boolean mExpectTLSCert = false;
    public String mRemoteCN = "";
    public String mPassword = "";
    public String mUsername = "";
    public boolean mRoutenopull = false;
    public boolean mUseRandomHostname = false;
    public boolean mUseFloat = false;
    public boolean mUseCustomConfig = false;
    public String mCustomConfigOptions = "";
    public String mVerb = "1";  //ignored
    public String mCipher = "";
    public String mDataCiphers = "";
    public boolean mNobind = true;
    public boolean mUseDefaultRoutev6 = true;
    public String mCustomRoutesv6 = "";
    public String mKeyPassword = "";
    public boolean mPersistTun = false;
    public String mConnectRetryMax = "-1";
    public String mConnectRetry = "2";
    public String mConnectRetryMaxTime = "300";
    public boolean mUserEditable = true;
    public String mAuth = "";
    public int mX509AuthType = X509_VERIFY_TLSREMOTE_RDN;
    public String mx509UsernameField = null;
    public boolean mAllowLocalLAN;
    public String mExcludedRoutes;
    public String mExcludedRoutesv6;
    public int mMssFix = 0; // -1 is default,
    public Connection[] mConnections = new Connection[0];
    public boolean mRemoteRandom = false;
    public HashSet<String> mAllowedAppsVpn = new HashSet<>();
    public boolean mAllowedAppsVpnAreDisallowed = true;
    public boolean mAllowAppVpnBypass = false;
    public String mCrlFilename;
    public String mProfileCreator;
    public String mExternalAuthenticator;
    public int mAuthRetry = AUTH_RETRY_NONE_FORGET;
    public int mTunMtu;
    public boolean mPushPeerInfo = false;
    public int mVersion = 0;
    // timestamp when the profile was last used
    public long mLastUsed;
    public String importedProfileHash;
    //TODO: cleanup here
    /* Options no longer used in new profiles */
    public String mServerName = "openvpn.example.com";
    public String mServerPort = "1194";
    @Deprecated
    public boolean mUseUdp = true;
    public boolean mTemporaryProfile = false;
    private transient PrivateKey mPrivateKey;
    // Public attributes, since I got mad with getter/setter
    // set members to default values
    private UUID mUuid;
    private int mProfileVersion;
    public boolean mBlockUnusedAddressFamilies = true;
    public String mGatewayIp;
    private final int mTransportType;

    public VpnProfile(String name, Connection.TransportType transportType) {
        mUuid = UUID.randomUUID();
        mName = name;
        mProfileVersion = CURRENT_PROFILE_VERSION;

        mConnections = new Connection[1];
        mLastUsed = System.currentTimeMillis();
        mTransportType = transportType.toInt();
    }

    public static String openVpnEscape(String unescaped) {
        if (unescaped == null)
            return null;
        String escapedString = unescaped.replace("\\", "\\\\");
        escapedString = escapedString.replace("\"", "\\\"");
        escapedString = escapedString.replace("\n", "\\n");

        if (escapedString.equals(unescaped) && !escapedString.contains(" ") &&
                !escapedString.contains("#") && !escapedString.contains(";")
                && !escapedString.equals(""))
            return unescaped;
        else
            return '"' + escapedString + '"';
    }

    public static boolean doUseOpenVPN3(Context c) {
        SharedPreferences prefs = Preferences.getDefaultSharedPreferences(c);
        boolean useOpenVPN3 = prefs.getBoolean("ovpn3", false);
        if (!BuildConfig.openvpn3)
            useOpenVPN3 = false;
        return useOpenVPN3;
    }

    //! Put inline data inline and other data as normal escaped filename
    public static String insertFileData(String cfgentry, String filedata) {
        if (filedata == null) {
            return String.format("# %s %s\n", cfgentry, "file missing in config profile");
        } else if (isEmbedded(filedata)) {
            String dataWithOutHeader = getEmbeddedContent(filedata);
            return String.format(Locale.ENGLISH, "<%s>\n%s\n</%s>\n", cfgentry, dataWithOutHeader, cfgentry);
        } else {
            return String.format(Locale.ENGLISH, "%s %s\n", cfgentry, openVpnEscape(filedata));
        }
    }

    public static String getDisplayName(String embeddedFile) {
        int start = DISPLAYNAME_TAG.length();
        int end = embeddedFile.indexOf(INLINE_TAG);
        return embeddedFile.substring(start, end);
    }

    public static String getEmbeddedContent(String data) {
        if (!data.contains(INLINE_TAG))
            return data;

        int start = data.indexOf(INLINE_TAG) + INLINE_TAG.length();
        return data.substring(start);
    }

    public static boolean isEmbedded(String data) {
        if (data == null)
            return false;
        if (data.startsWith(INLINE_TAG) || data.startsWith(DISPLAYNAME_TAG))
            return true;
        else
            return false;
    }

    @Override
    public int hashCode() {
        int result =(mGatewayIp != null ? mGatewayIp.hashCode() : 0);
        result = 31 * result + Arrays.hashCode(mConnections);
        result = 31 * result + mTransportType;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof VpnProfile) {
            VpnProfile vp = (VpnProfile) obj;
            return stringEqual(vp.mGatewayIp, mGatewayIp) &&
                    vp.mTransportType == mTransportType &&
                    Arrays.equals(mConnections, vp.mConnections);
        }
        return false;
    }

    public void clearDefaults() {
        mServerName = "unknown";
        mUsePull = false;
        mUseLzo = false;
        mUseDefaultRoute = false;
        mUseDefaultRoutev6 = false;
        mExpectTLSCert = false;
        mCheckRemoteCN = false;
        mPersistTun = false;
        mAllowLocalLAN = true;
        mPushPeerInfo = false;
        mMssFix = 0;
        mNobind = false;
    }

    public UUID getUUID() {
        return mUuid;

    }

    // Only used for the special case of managed profiles
    public void setUUID(UUID uuid) {
        mUuid = uuid;
    }

    public boolean usePluggableTransports() {
        Connection.TransportType type = Connection.TransportType.fromInt(mTransportType);
        return type != null && type.isPluggableTransport();
    }

    public Connection.TransportType getTransportType() {
        return Connection.TransportType.fromInt(mTransportType);
    }

    public @Nullable Obfs4Options getObfs4Options() {
        Connection.TransportType transportType = getTransportType();
        if (!(transportType == OBFS4 || transportType == OBFS4_HOP)) {
            return null;
        }
        return ((Obfs4Connection) mConnections[0]).getObfs4Options();
    }

    public String getObfuscationTransportLayerProtocol() {
        try {
            return getObfs4Options().transport.getProtocols()[0];
        } catch (NullPointerException | ArrayIndexOutOfBoundsException ignore) {
            return null;
        }
    }

    public String getName() {
        if (TextUtils.isEmpty(mName))
            return "No profile name";
        return mName;
    }

    @Deprecated
    public void upgradeProfile() {
        if (mProfileVersion < 6) {
            if (TextUtils.isEmpty(mProfileCreator))
                mUserEditable = true;
        }
        if (mProfileVersion < 7) {
            for (Connection c : mConnections)
                if (c.getProxyType() == null)
                    c.setProxyType(Connection.ProxyType.NONE);
        }

        mProfileVersion = CURRENT_PROFILE_VERSION;

    }

    public String getConfigFile(Context context, boolean configForOvpn3) {

        File cacheDir = context.getCacheDir();
        StringBuilder cfg = new StringBuilder();

        if (!configForOvpn3) {
            // Enable management interface
            cfg.append("# Config for OpenVPN 2.x\n");
            cfg.append("# Enables connection to GUI\n");
            cfg.append("management ");

            cfg.append(cacheDir.getAbsolutePath()).append("/").append("mgmtsocket");
            cfg.append(" unix\n");
            cfg.append("management-client\n");
            // Not needed, see updated man page in 2.3
            //cfg += "management-signal\n";
            cfg.append("management-query-passwords\n");
            cfg.append("management-hold\n\n");

            cfg.append(String.format("setenv IV_GUI_VER %s \n", openVpnEscape(getVersionEnvString(context))));
            String versionString = getPlatformVersionEnvString();
            cfg.append(String.format("setenv IV_PLAT_VER %s\n", openVpnEscape(versionString)));
        } else {
            cfg.append("# Config for OpenVPN 3 C++\n");
        }


        if (!configForOvpn3) {
            cfg.append("machine-readable-output\n");
            if (!mIsOpenVPN22)
                cfg.append("allow-recursive-routing\n");

            // Users are confused by warnings that are misleading...
            cfg.append("ifconfig-nowarn\n");
        }

        boolean useTLSClient = (mAuthenticationType != TYPE_STATICKEYS);

        if (useTLSClient && mUsePull)
            cfg.append("client\n");
        else if (mUsePull)
            cfg.append("pull\n");
        else if (useTLSClient)
            cfg.append("tls-client\n");


        //cfg += "verb " + mVerb + "\n";
        cfg.append("verb " + MAXLOGLEVEL + "\n");

        if (mConnectRetryMax == null) {
            mConnectRetryMax = "-1";
        }

        if (!mConnectRetryMax.equals("-1"))
            cfg.append("connect-retry-max ").append(mConnectRetryMax).append("\n");

        if (TextUtils.isEmpty(mConnectRetry))
            mConnectRetry = "2";

        if (TextUtils.isEmpty(mConnectRetryMaxTime))
            mConnectRetryMaxTime = "300";


        if (!mIsOpenVPN22)
            cfg.append("connect-retry ").append(mConnectRetry).append(" ").append(mConnectRetryMaxTime).append("\n");
        else if (mIsOpenVPN22 && !mUseUdp)
            cfg.append("connect-retry ").append(mConnectRetry).append("\n");


        cfg.append("resolv-retry 60\n");


        // We cannot use anything else than tun
        cfg.append("dev tun\n");


        boolean canUsePlainRemotes = true;

        if (mConnections.length == 1) {
            cfg.append(mConnections[0].getConnectionBlock(configForOvpn3));
        } else {
            for (Connection conn : mConnections) {
                canUsePlainRemotes = canUsePlainRemotes && conn.isOnlyRemote();
            }

            if (mRemoteRandom)
                cfg.append("remote-random\n");

            if (canUsePlainRemotes) {
                for (Connection conn : mConnections) {
                    if (conn.isEnabled()) {
                        cfg.append(conn.getConnectionBlock(configForOvpn3));
                    }
                }
            }
        }


        switch (mAuthenticationType) {
            case VpnProfile.TYPE_USERPASS_CERTIFICATES:
                cfg.append("auth-user-pass\n");
            case VpnProfile.TYPE_CERTIFICATES:
                // Ca
                cfg.append(insertFileData("ca", mCaFilename));

                // Client Cert + Key
                cfg.append(insertFileData("cert", mClientCertFilename));
                mPrivateKey = ProviderObservable.getInstance().getCurrentProvider().getPrivateKey();
                cfg.append("management-external-key nopadding pkcs1 pss digest\n");

                break;
            case VpnProfile.TYPE_USERPASS_PKCS12:
                cfg.append("auth-user-pass\n");
            case VpnProfile.TYPE_PKCS12:
                cfg.append(insertFileData("pkcs12", mPKCS12Filename));

                if (!TextUtils.isEmpty(mCaFilename))
                {
                    cfg.append(insertFileData("ca", mCaFilename));
                }
                break;

            case VpnProfile.TYPE_USERPASS_KEYSTORE:
                cfg.append("auth-user-pass\n");
            case VpnProfile.TYPE_KEYSTORE:
            case VpnProfile.TYPE_EXTERNAL_APP:
                if (!configForOvpn3) {
                    String[] ks = getExternalCertificates(context);
                    cfg.append("### From Keystore/ext auth app ####\n");
                    if (ks != null) {
                        cfg.append("<ca>\n").append(ks[0]).append("\n</ca>\n");
                        if (!TextUtils.isEmpty(ks[1]))
                            cfg.append("<extra-certs>\n").append(ks[1]).append("\n</extra-certs>\n");
                        cfg.append("<cert>\n").append(ks[2]).append("\n</cert>\n");
                        cfg.append("management-external-key nopadding pkcs1 pss digest\n");
                    } else {
                        cfg.append(context.getString(R.string.keychain_access)).append("\n");
                    }
                }
                break;
            case VpnProfile.TYPE_USERPASS:
                cfg.append("auth-user-pass\n");
                cfg.append(insertFileData("ca", mCaFilename));
                if (configForOvpn3) {
                    // OpenVPN 3 needs to be told that a client certificate is not required
                    cfg.append("client-cert-not-required\n");
                }
        }

        if (isUserPWAuth()) {
            if (mAuthRetry == AUTH_RETRY_NOINTERACT)
                cfg.append("auth-retry nointeract\n");
        }

        if (!TextUtils.isEmpty(mCrlFilename))
            cfg.append(insertFileData("crl-verify", mCrlFilename));

        // compression does not work in conjunction with shapeshifter-dispatcher so far
        if (mUseLzo && !usePluggableTransports()) {
            cfg.append("comp-lzo\n");
        }

        if (mUseTLSAuth) {
            boolean useTlsCrypt = mTLSAuthDirection.equals("tls-crypt");
            boolean useTlsCrypt2 = mTLSAuthDirection.equals("tls-crypt-v2");

            if (mAuthenticationType == TYPE_STATICKEYS)
                cfg.append(insertFileData("secret", mTLSAuthFilename));
            else if (useTlsCrypt)
                cfg.append(insertFileData("tls-crypt", mTLSAuthFilename));
            else if (useTlsCrypt2)
                cfg.append(insertFileData("tls-crypt-v2", mTLSAuthFilename));
            else
                cfg.append(insertFileData("tls-auth", mTLSAuthFilename));

            if (!TextUtils.isEmpty(mTLSAuthDirection) && !useTlsCrypt && !useTlsCrypt2) {
                cfg.append("key-direction ");
                cfg.append(mTLSAuthDirection);
                cfg.append("\n");
            }

        }

        if (!mUsePull) {
            if (!TextUtils.isEmpty(mIPv4Address))
                cfg.append("ifconfig ").append(cidrToIPAndNetmask(mIPv4Address)).append("\n");

            if (!TextUtils.isEmpty(mIPv6Address)) {
                // Use our own ip as gateway since we ignore it anyway
                String fakegw = mIPv6Address.split("/", 2)[0];
                cfg.append("ifconfig-ipv6 ").append(mIPv6Address).append(" ").append(fakegw).append("\n");
            }

        }

        if (mUsePull && mRoutenopull)
            cfg.append("route-nopull\n");

        String routes = "";

        if (mUseDefaultRoute)
            routes += "route 0.0.0.0 0.0.0.0 vpn_gateway\n";
        else {
            for (String route : getCustomRoutes(mCustomRoutes)) {
                routes += "route " + route + " vpn_gateway\n";
            }

            for (String route : getCustomRoutes(mExcludedRoutes)) {
                routes += "route " + route + " net_gateway\n";
            }
        }


        if (mUseDefaultRoutev6)
            cfg.append("route-ipv6 ::/0\n");
        else
            for (String route : getCustomRoutesv6(mCustomRoutesv6)) {
                routes += "route-ipv6 " + route + "\n";
            }

        cfg.append(routes);

        if (mOverrideDNS || !mUsePull) {
            if (!TextUtils.isEmpty(mDNS1)) {
                cfg.append("dhcp-option DNS ").append(mDNS1).append("\n");
            }
            if (!TextUtils.isEmpty(mDNS2)) {
                cfg.append("dhcp-option DNS ").append(mDNS2).append("\n");
            }
            if (!TextUtils.isEmpty(mSearchDomain))
                cfg.append("dhcp-option DOMAIN ").append(mSearchDomain).append("\n");

        }

        if (mMssFix != 0) {
            if (mMssFix != 1450) {
                cfg.append(String.format(Locale.US, "mssfix %d\n", mMssFix));
            } else
                cfg.append("mssfix\n");
        }

        if (mTunMtu >= 48 && mTunMtu != 1500) {
            cfg.append(String.format(Locale.US, "tun-mtu %d\n", mTunMtu));
        }

        if (mNobind)
            cfg.append("nobind\n");


        // Authentication
        if (mAuthenticationType != TYPE_STATICKEYS) {
            if (mCheckRemoteCN) {
                if (mRemoteCN == null || mRemoteCN.equals(""))
                    cfg.append("verify-x509-name ").append(openVpnEscape(mConnections[0].getServerName())).append(" name\n");
                else
                    switch (mX509AuthType) {

                        // 2.2 style x509 checks
                        case X509_VERIFY_TLSREMOTE_COMPAT_NOREMAPPING:
                            cfg.append("compat-names no-remapping\n");
                        case X509_VERIFY_TLSREMOTE:
                            cfg.append("tls-remote ").append(openVpnEscape(mRemoteCN)).append("\n");
                            break;

                        case X509_VERIFY_TLSREMOTE_RDN:
                            cfg.append("verify-x509-name ").append(openVpnEscape(mRemoteCN)).append(" name\n");
                            break;

                        case X509_VERIFY_TLSREMOTE_RDN_PREFIX:
                            cfg.append("verify-x509-name ").append(openVpnEscape(mRemoteCN)).append(" name-prefix\n");
                            break;

                        case X509_VERIFY_TLSREMOTE_DN:
                            cfg.append("verify-x509-name ").append(openVpnEscape(mRemoteCN)).append("\n");
                            break;
                    }
                if (!TextUtils.isEmpty(mx509UsernameField))
                    cfg.append("x509-username-field ").append(openVpnEscape(mx509UsernameField)).append("\n");
            }
            if (mExpectTLSCert)
                cfg.append("remote-cert-tls server\n");
        }


        if (!TextUtils.isEmpty(mDataCiphers))
        {
            cfg.append("data-ciphers ").append(mDataCiphers).append("\n");
        }

        if (!TextUtils.isEmpty(mCipher)) {
            cfg.append("cipher ").append(mCipher).append("\n");
        }

        if (!TextUtils.isEmpty(mAuth)) {
            cfg.append("auth ").append(mAuth).append("\n");
        }

        // Obscure Settings dialog
        if (mUseRandomHostname)
            cfg.append("#my favorite options :)\nremote-random-hostname\n");

        if (mUseFloat)
            cfg.append("float\n");

        if (mPersistTun) {
            cfg.append("persist-tun\n");
            cfg.append("# persist-tun also enables pre resolving to avoid DNS resolve problem\n");
            if (!mIsOpenVPN22)
                cfg.append("preresolve\n");
        }

        if (mPushPeerInfo)
            cfg.append("push-peer-info\n");

        boolean usesystemproxy = PreferenceHelper.useSystemProxy();
        if (usesystemproxy && !mIsOpenVPN22 && !configForOvpn3 && !usesExtraProxyOptions()) {
            cfg.append("# Use system proxy setting\n");
            cfg.append("management-query-proxy\n");
        }


        if (mUseCustomConfig) {
            cfg.append("# Custom configuration options\n");
            cfg.append("# You are on your on own here :)\n");
            cfg.append(mCustomConfigOptions);
            cfg.append("\n");

        }

        if (!canUsePlainRemotes) {
            cfg.append("# Connection Options are at the end to allow global options (and global custom options) to influence connection blocks\n");
            for (Connection conn : mConnections) {
                if (conn.isEnabled()) {
                    cfg.append("<connection>\n");
                    cfg.append(conn.getConnectionBlock(configForOvpn3));
                    cfg.append("</connection>\n");
                }
            }
        }


        return cfg.toString();
    }

    public String getPlatformVersionEnvString() {
        return String.format(Locale.US, "%d %s %s %s %s %s", Build.VERSION.SDK_INT, Build.VERSION.RELEASE,
                NativeUtils.getNativeAPI(), Build.BRAND, Build.BOARD, Build.MODEL);
    }

    public String getVersionEnvString(Context c) {
        String version = "unknown";
        try {
            PackageInfo packageinfo = c.getPackageManager().getPackageInfo(c.getPackageName(), 0);
            version = packageinfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            VpnStatus.logException(e);
        }
        return String.format(Locale.US, "%s %s", c.getPackageName(), version);

    }

    @NonNull
    private Collection<String> getCustomRoutes(String routes) {
        Vector<String> cidrRoutes = new Vector<>();
        if (routes == null) {
            // No routes set, return empty vector
            return cidrRoutes;
        }
        for (String route : routes.split("[\n \t]")) {
            if (!route.equals("")) {
                String cidrroute = cidrToIPAndNetmask(route);
                if (cidrroute == null)
                    return cidrRoutes;

                cidrRoutes.add(cidrroute);
            }
        }

        return cidrRoutes;
    }

    private Collection<String> getCustomRoutesv6(String routes) {
        Vector<String> cidrRoutes = new Vector<>();
        if (routes == null) {
            // No routes set, return empty vector
            return cidrRoutes;
        }
        for (String route : routes.split("[\n \t]")) {
            if (!route.equals("")) {
                cidrRoutes.add(route);
            }
        }

        return cidrRoutes;
    }

    private String cidrToIPAndNetmask(String route) {
        String[] parts = route.split("/");

        // No /xx, assume /32 as netmask
        if (parts.length == 1)
            parts = (route + "/32").split("/");

        if (parts.length != 2)
            return null;
        int len;
        try {
            len = Integer.parseInt(parts[1]);
        } catch (NumberFormatException ne) {
            return null;
        }
        if (len < 0 || len > 32)
            return null;


        long nm = 0xffffffffL;
        nm = (nm << (32 - len)) & 0xffffffffL;

        String netmask = String.format(Locale.ENGLISH, "%d.%d.%d.%d", (nm & 0xff000000) >> 24, (nm & 0xff0000) >> 16, (nm & 0xff00) >> 8, nm & 0xff);
        return parts[0] + "  " + netmask;
    }

    public Intent prepareStartService(Context context) {
        Intent intent = getStartServiceIntent(context);

        // This can remain outcommented for now, Bitmask uses VpnProfile.TYPE_CERTIFICATE
//        if (mAuthenticationType == VpnProfile.TYPE_KEYSTORE || mAuthenticationType == VpnProfile.TYPE_USERPASS_KEYSTORE) {
//            if (getKeyStoreCertificates(context) == null)
//                return null;
//        }

        return intent;
    }

    public void writeConfigFile(Context context) throws IOException {
        FileWriter cfg = new FileWriter(VPNLaunchHelper.getConfigFilePath(context));
        cfg.write(getConfigFile(context, false));
        cfg.flush();
        cfg.close();

    }

    public Intent getStartServiceIntent(Context context) {
        Intent intent = new Intent(context, OpenVPNService.class);
        intent.putExtra(PROVIDER_PROFILE, this);
        return intent;
    }

    public void checkForRestart(final Context context) {
        /* This method is called when OpenVPNService is restarted */

        if ((mAuthenticationType == VpnProfile.TYPE_KEYSTORE || mAuthenticationType == VpnProfile.TYPE_USERPASS_KEYSTORE)
                && mPrivateKey == null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    getExternalCertificates(context);

                }
            }).start();
        }
    }

    @Override
    protected VpnProfile clone() throws CloneNotSupportedException {
        VpnProfile copy = (VpnProfile) super.clone();
        copy.mUuid = UUID.randomUUID();
        copy.mConnections = new Connection[mConnections.length];
        int i = 0;
        for (Connection conn : mConnections) {
            copy.mConnections[i++] = conn.clone();
        }
        copy.mAllowedAppsVpn = (HashSet<String>) mAllowedAppsVpn.clone();
        return copy;
    }

    public VpnProfile copy(String name) {
        try {
            VpnProfile copy = clone();
            copy.mName = name;
            return copy;

        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
            return null;
        }
    }

    public void pwDidFail(Context c) {

    }

    private X509Certificate[] getKeyStoreCertificates(Context context) throws KeyChainException, InterruptedException {
        PrivateKey privateKey = KeyChain.getPrivateKey(context, mAlias);
        mPrivateKey = privateKey;


        X509Certificate[] caChain = KeyChain.getCertificateChain(context, mAlias);
        return caChain;
    }

    private X509Certificate[] getExtAppCertificates(Context context) throws KeyChainException {
        if (mExternalAuthenticator == null || mAlias == null)
            throw new KeyChainException("Alias or external auth provider name not set");
        return ExtAuthHelper.getCertificateChain(context, mExternalAuthenticator, mAlias);
    }

    /**
     * returns an array certificates, depending on the profile type either from the keychain or an external cert provider
     * @param context
     * @return pem encoded certificates, where:
     *  [0] is the ca cert
     *  [1] is an optional extra cert
     *  [2] is the vpn certificate
     */
    public String[] getExternalCertificates(Context context) {
        return getExternalCertificates(context, 5);
    }


    synchronized String[] getExternalCertificates(Context context, int tries) {
        // Force application context- KeyChain methods will block long enough that by the time they
        // are finished and try to unbind, the original activity context might have been destroyed.
        context = context.getApplicationContext();

        try {
            String keystoreChain = null;

            X509Certificate caChain[];
            if (mAuthenticationType == TYPE_EXTERNAL_APP) {
                caChain = getExtAppCertificates(context);
            } else {
                caChain = getKeyStoreCertificates(context);
            }
            if (caChain == null)
                throw new NoCertReturnedException("No certificate returned from Keystore");

            if (caChain.length <= 1 && TextUtils.isEmpty(mCaFilename)) {
                VpnStatus.logMessage(VpnStatus.LogLevel.ERROR, "", context.getString(R.string.keychain_nocacert));
            } else {
                StringWriter ksStringWriter = new StringWriter();

                PemWriter pw = new PemWriter(ksStringWriter);
                for (int i = 1; i < caChain.length; i++) {
                    X509Certificate cert = caChain[i];
                    pw.writeObject(new PemObject("CERTIFICATE", cert.getEncoded()));
                }
                pw.close();
                keystoreChain = ksStringWriter.toString();
            }


            String caout = null;
            if (!TextUtils.isEmpty(mCaFilename)) {
                try {
                    Certificate[] cacerts = X509Utils.getCertificatesFromFile(mCaFilename);
                    StringWriter caoutWriter = new StringWriter();
                    PemWriter pw = new PemWriter(caoutWriter);

                    for (Certificate cert : cacerts)
                        pw.writeObject(new PemObject("CERTIFICATE", cert.getEncoded()));
                    pw.close();
                    caout = caoutWriter.toString();

                } catch (Exception e) {
                    VpnStatus.logError("Could not read CA certificate" + e.getLocalizedMessage());
                }
            }


            StringWriter certout = new StringWriter();


            if (caChain.length >= 1) {
                X509Certificate usercert = caChain[0];

                PemWriter upw = new PemWriter(certout);
                upw.writeObject(new PemObject("CERTIFICATE", usercert.getEncoded()));
                upw.close();

            }
            String user = certout.toString();


            String ca, extra;
            if (caout == null) {
                ca = keystoreChain;
                extra = null;
            } else {
                ca = caout;
                extra = keystoreChain;
            }

            return new String[]{ca, extra, user};
        } catch (InterruptedException | IOException | KeyChainException | NoCertReturnedException | IllegalArgumentException
                | CertificateException e) {
            e.printStackTrace();
            VpnStatus.logError(R.string.keyChainAccessError, e.getLocalizedMessage());

            VpnStatus.logError(R.string.keychain_access);
            return null;

        } catch (AssertionError e) {
            if (tries == 0)
                return null;
            VpnStatus.logError(String.format("Failure getting Keystore Keys (%s), retrying", e.getLocalizedMessage()));
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e1) {
                VpnStatus.logException(e1);
            }
            return getExternalCertificates(context, tries - 1);
        }

    }

    public int checkProfile(Context c) {
        return checkProfile(c, doUseOpenVPN3(c));
    }

    //! Return an error if something is wrong
    public int checkProfile(Context context, boolean useOpenVPN3) {
        if (mAuthenticationType == TYPE_KEYSTORE || mAuthenticationType == TYPE_USERPASS_KEYSTORE || mAuthenticationType == TYPE_EXTERNAL_APP) {
            if (mAlias == null)
                return R.string.no_keystore_cert_selected;
        } else if (mAuthenticationType == TYPE_CERTIFICATES || mAuthenticationType == TYPE_USERPASS_CERTIFICATES) {
            if (TextUtils.isEmpty(mCaFilename))
                return R.string.no_ca_cert_selected;
        }

        if (mCheckRemoteCN && mX509AuthType == X509_VERIFY_TLSREMOTE)
            return R.string.deprecated_tls_remote;

        if (!mUsePull || mAuthenticationType == TYPE_STATICKEYS) {
            if (mIPv4Address == null || cidrToIPAndNetmask(mIPv4Address) == null)
                return R.string.ipv4_format_error;
        }
        if (!mUseDefaultRoute) {
            if (!TextUtils.isEmpty(mCustomRoutes) && getCustomRoutes(mCustomRoutes).size() == 0)
                return R.string.custom_route_format_error;

            if (!TextUtils.isEmpty(mExcludedRoutes) && getCustomRoutes(mExcludedRoutes).size() == 0)
                return R.string.custom_route_format_error;

        }

        if (mUseTLSAuth && TextUtils.isEmpty(mTLSAuthFilename))
            return R.string.missing_tlsauth;

        if ((mAuthenticationType == TYPE_USERPASS_CERTIFICATES &&
                (TextUtils.isEmpty(mClientCertFilename) || (TextUtils.isEmpty(mClientKeyFilename)))) ||
                mAuthenticationType == TYPE_CERTIFICATES && TextUtils.isEmpty(mClientCertFilename))
            return R.string.missing_certificates;

        if ((mAuthenticationType == TYPE_CERTIFICATES || mAuthenticationType == TYPE_USERPASS_CERTIFICATES)
                && TextUtils.isEmpty(mCaFilename))
            return R.string.missing_ca_certificate;


        boolean noRemoteEnabled = true;
        for (Connection c : mConnections) {
            if (c.isEnabled())
                noRemoteEnabled = false;

        }
        if (noRemoteEnabled)
            return R.string.remote_no_server_selected;

        if (useOpenVPN3) {
            if (mAuthenticationType == TYPE_STATICKEYS) {
                return R.string.openvpn3_nostatickeys;
            }
            if (mAuthenticationType == TYPE_PKCS12 || mAuthenticationType == TYPE_USERPASS_PKCS12) {
                return R.string.openvpn3_pkcs12;
            }
            for (Connection conn : mConnections) {
                if (conn.getProxyType() == Connection.ProxyType.ORBOT || conn.getProxyType() == Connection.ProxyType.SOCKS5)
                    return R.string.openvpn3_socksproxy;
            }
        }
        for (Connection c : mConnections) {
            if (c.getProxyType() == Connection.ProxyType.ORBOT) {
                if (usesExtraProxyOptions())
                    return R.string.error_orbot_and_proxy_options;
                if (!OrbotHelper.checkTorReceier(context))
                    return R.string.no_orbotfound;
            }
        }


        // Everything okay
        return R.string.no_error_found;

    }

    //! Openvpn asks for a "Private Key", this should be pkcs12 key
    //
    public String getPasswordPrivateKey() {
        String cachedPw = PasswordCache.getPKCS12orCertificatePassword(mUuid, true);
        if (cachedPw != null) {
            return cachedPw;
        }
        switch (mAuthenticationType) {
            case TYPE_PKCS12:
            case TYPE_USERPASS_PKCS12:
                return mPKCS12Password;

            case TYPE_CERTIFICATES:
            case TYPE_USERPASS_CERTIFICATES:
                return mKeyPassword;

            case TYPE_USERPASS:
            case TYPE_STATICKEYS:
            default:
                return null;
        }
    }

    public boolean isUserPWAuth() {
        switch (mAuthenticationType) {
            case TYPE_USERPASS:
            case TYPE_USERPASS_CERTIFICATES:
            case TYPE_USERPASS_KEYSTORE:
            case TYPE_USERPASS_PKCS12:
                return true;
            default:
                return false;

        }
    }

    public boolean requireTLSKeyPassword() {
        if (TextUtils.isEmpty(mClientKeyFilename))
            return false;

        String data = "";
        if (isEmbedded(mClientKeyFilename))
            data = mClientKeyFilename;
        else {
            char[] buf = new char[2048];
            FileReader fr;
            try {
                fr = new FileReader(mClientKeyFilename);
                int len = fr.read(buf);
                while (len > 0) {
                    data += new String(buf, 0, len);
                    len = fr.read(buf);
                }
                fr.close();
            } catch (FileNotFoundException e) {
                return false;
            } catch (IOException e) {
                return false;
            }

        }

        if (data.contains("Proc-Type: 4,ENCRYPTED"))
            return true;
        else if (data.contains("-----BEGIN ENCRYPTED PRIVATE KEY-----"))
            return true;
        else
            return false;
    }

    public int needUserPWInput(String transientCertOrPkcs12PW, String mTransientAuthPW) {
        if ((mAuthenticationType == TYPE_PKCS12 || mAuthenticationType == TYPE_USERPASS_PKCS12) &&
                (mPKCS12Password == null || mPKCS12Password.equals(""))) {
            if (transientCertOrPkcs12PW == null)
                return R.string.pkcs12_file_encryption_key;
        }

        if (mAuthenticationType == TYPE_CERTIFICATES || mAuthenticationType == TYPE_USERPASS_CERTIFICATES) {
            if (requireTLSKeyPassword() && TextUtils.isEmpty(mKeyPassword))
                if (transientCertOrPkcs12PW == null) {
                    return R.string.private_key_password;
                }
        }

        if (isUserPWAuth() &&
                (TextUtils.isEmpty(mUsername) ||
                        (TextUtils.isEmpty(mPassword) && mTransientAuthPW == null))) {
            return R.string.password;
        }
        return 0;
    }

    public String getPasswordAuth() {
        String cachedPw = PasswordCache.getAuthPassword(mUuid, true);
        if (cachedPw != null) {
            return cachedPw;
        } else {
            return mPassword;
        }
    }

    // Used by the Array Adapter
    @Override
    public String toString() {
        return mName;
    }

    public String toJson() {
        Gson gson = new Gson();
        try {
            return gson.toJson(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static VpnProfile fromJson(String json) {
        try {
            GsonBuilder builder = new GsonBuilder();
            builder.registerTypeAdapter(Connection.class, new ConnectionAdapter());
            return builder.create().fromJson(json, VpnProfile.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getUUIDString() {
        return mUuid.toString().toLowerCase(Locale.ENGLISH);
    }

    public PrivateKey getKeystoreKey() {
        return mPrivateKey;
    }

    @Nullable
    public String getSignedData(Context c, String b64data, OpenVPNManagement.SignaturePadding padding, String saltlen, String hashalg, boolean needDigest) {
        byte[] data = Base64.decode(b64data, Base64.DEFAULT);
        byte[] signed_bytes;
        if (mAuthenticationType == TYPE_EXTERNAL_APP) {
            signed_bytes = getExtAppSignedData(c, data, padding, saltlen, hashalg, needDigest);
        } else {
            signed_bytes = getKeyChainSignedData(data, padding, saltlen, hashalg, needDigest);
        }

        if (signed_bytes != null)
            return Base64.encodeToString(signed_bytes, Base64.NO_WRAP);
        else
            return null;
    }

    private byte[] getExtAppSignedData(Context c, byte[] data, OpenVPNManagement.SignaturePadding padding, String saltlen, String hashalg, boolean needDigest)
    {

        Bundle extra = new Bundle();
        RsaPaddingType paddingType;
        switch (padding) {
            case RSA_PKCS1_PADDING:
                paddingType = RsaPaddingType.PKCS1_PADDING;
                break;
            case NO_PADDING:
                paddingType = RsaPaddingType.NO_PADDING;
                break;
            case RSA_PKCS1_PSS_PADDING:
                paddingType = RsaPaddingType.RSAPSS_PADDING;
                break;
            default:
                paddingType = RsaPaddingType.NO_PADDING;
        }

        extra.putInt(EXTRA_RSA_PADDING_TYPE, paddingType.ordinal());
        extra.putString(EXTRA_SALTLEN, saltlen);
        extra.putString(EXTRA_DIGEST, hashalg);
        extra.putBoolean(EXTRA_NEEDS_DIGEST, needDigest);

        if (TextUtils.isEmpty(mExternalAuthenticator))
            return null;
        try {
            return ExtAuthHelper.signData(c, mExternalAuthenticator, mAlias, data, extra);
        } catch (KeyChainException | InterruptedException e) {
            VpnStatus.logError(R.string.error_extapp_sign, mExternalAuthenticator, e.getClass().toString(), e.getLocalizedMessage());
            return null;
        }
    }

    private byte[] getKeyChainSignedData(byte[] data, OpenVPNManagement.SignaturePadding padding, String saltlen, String hashalg, boolean needDigest) {
        PrivateKey privkey = getKeystoreKey();

        try {
            @SuppressLint("GetInstance")
            String keyalgorithm = privkey.getAlgorithm();

            byte[] signed_bytes;
            if (needDigest || keyalgorithm.equals("EC")) {
                return doDigestSign(privkey, data, padding, hashalg, saltlen);
            } else {
             /* ECB is perfectly fine in this special case, since we are using it for
                the public/private part in the TLS exchange */
                Cipher signer = null;
                switch (padding) {
                    case RSA_PKCS1_PADDING:
                        signer = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
                        break;
                    case NO_PADDING:
                        signer = Cipher.getInstance("RSA/ECB/NoPadding");
                        break;
                    case RSA_PKCS1_PSS_PADDING:
                        throw new NoSuchPaddingException("Cannot do PKCS1 PSS padding without also doing the digest");
                }

                signer.init(Cipher.ENCRYPT_MODE, privkey);

                signed_bytes = signer.doFinal(data);

                return signed_bytes;
            }
        } catch
        (NoSuchAlgorithmException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchPaddingException | SignatureException | InvalidAlgorithmParameterException
                        e) {
            VpnStatus.logError(R.string.error_rsa_sign, e.getClass().toString(), e.getLocalizedMessage());
            return null;
        }
    }

    private byte[] addPSSPadding(PrivateKey privkey, String digest, byte[] data) throws NoSuchAlgorithmException {
        /* For < API 23, add padding ourselves */
        int hashtype = getHashtype(digest);

        MessageDigest msgDigest = MessageDigest.getInstance(digest);
        byte[] hash = msgDigest.digest(data);

        /*  MSBits = (BN_num_bits(rsa->n) - 1) & 0x7; */
        int numbits = ((RSAPrivateKey) privkey).getModulus().bitLength();

        int MSBits = (numbits - 1) & 0x7;

        return NativeUtils.addRssPssPadding(hashtype, MSBits, numbits/8, hash);
    }

    private int getHashtype(String digest) throws NoSuchAlgorithmException {
        int hashtype = 0;
        switch (digest) {
            case "SHA1":
                hashtype = 1;
                break;
            case "SHA224":
                hashtype = 2;
                break;
            case "SHA256":
                hashtype = 3;
                break;
            case "SHA384":
                hashtype = 4;
                break;
            case "SHA512":
                hashtype = 5;
                break;
            default:
                throw new NoSuchAlgorithmException("Unknown digest algorithm: " + digest);
        }
        return hashtype;
    }

    private byte[] doDigestSign(PrivateKey privkey, byte[] data, OpenVPNManagement.SignaturePadding padding, String hashalg, String saltlen) throws SignatureException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException {
        /* RSA */
        Signature sig = null;

        if (privkey.getAlgorithm().equals("EC")) {
            if (hashalg.equals(""))
                hashalg = "NONE";
            /* e.g. SHA512withECDSA */
            hashalg = hashalg + "withECDSA";
            sig = Signature.getInstance(hashalg.toUpperCase(Locale.ROOT));
        } else if (padding == OpenVPNManagement.SignaturePadding.RSA_PKCS1_PSS_PADDING) {
            /* https://developer.android.com/training/articles/keystore#SupportedSignatures */
            if (!"digest".equals(saltlen))
                throw new SignatureException("PSS signing requires saltlen=digest");

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                data = addPSSPadding(privkey, hashalg, data);
                return getKeyChainSignedData(data, OpenVPNManagement.SignaturePadding.NO_PADDING, "none", "none", false);
            }

            sig = Signature.getInstance(hashalg + "withRSA/PSS");

            PSSParameterSpec pssspec = null;
            switch (hashalg) {
                case "SHA256":
                    pssspec = new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1);
                    break;
                case "SHA512":
                    pssspec = new PSSParameterSpec("SHA-512", "MGF1", MGF1ParameterSpec.SHA512, 64, 1);
                    break;
                case "SHA384":
                    pssspec = new PSSParameterSpec("SHA-384", "MGF1", MGF1ParameterSpec.SHA384, 48, 1);
                    break;
            }
            sig.setParameter(pssspec);
        } else if (padding == OpenVPNManagement.SignaturePadding.RSA_PKCS1_PADDING) {
            sig = Signature.getInstance(hashalg + "withRSA");
        }

        sig.initSign(privkey);
        sig.update(data);
        return sig.sign();
    }


    private boolean usesExtraProxyOptions() {
        if (mUseCustomConfig && mCustomConfigOptions != null && mCustomConfigOptions.contains("http-proxy-option "))
            return true;
        for (Connection c : mConnections)
            if (c.usesExtraProxyOptions())
                return true;

        return false;
    }

    /**
     * The order of elements is important!
     */
    private enum RsaPaddingType {
        NO_PADDING,
        PKCS1_PADDING,
        RSAPSS_PADDING
    }


    class NoCertReturnedException extends Exception {
        public NoCertReturnedException(String msg) {
            super(msg);
        }
    }


}