summaryrefslogtreecommitdiff
path: root/main/src/main/java/de/blinkt/openvpn/activities/ConfigConverter.java
blob: 8e11802ceab8f2b0ae43e75a1b4b5552feca9a3e (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

package de.blinkt.openvpn.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.provider.OpenableColumns;
import android.security.KeyChain;
import android.security.KeyChainAliasCallback;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.*;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import de.blinkt.openvpn.R;
import de.blinkt.openvpn.VpnProfile;
import de.blinkt.openvpn.core.ConfigParser;
import de.blinkt.openvpn.core.ConfigParser.ConfigParseError;
import de.blinkt.openvpn.core.ProfileManager;
import de.blinkt.openvpn.fragments.Utils;
import de.blinkt.openvpn.views.FileSelectLayout;
import junit.framework.Assert;

import org.jetbrains.annotations.Nullable;

import java.io.*;
import java.util.*;

import static de.blinkt.openvpn.views.FileSelectLayout.FileSelectCallback;

public class ConfigConverter extends ListActivity implements FileSelectCallback {

    public static final String IMPORT_PROFILE = "de.blinkt.openvpn.IMPORT_PROFILE";
    private static final int RESULT_INSTALLPKCS12 = 7;
    private static final int CHOOSE_FILE_OFFSET = 1000;
    public static final String VPNPROFILE = "vpnProfile";

    private VpnProfile mResult;
    private transient ArrayAdapter<String> mArrayAdapter;

    private transient List<String> mPathsegments;

    private String mAliasName = null;


    private Map<Utils.FileType, FileSelectLayout> fileSelectMap = new HashMap<Utils.FileType, FileSelectLayout>();
    private String mEmbeddedPwFile;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.cancel) {
            setResult(Activity.RESULT_CANCELED);
            finish();
        } else if (item.getItemId() == R.id.ok) {
            if (mResult == null) {
                log("Importing the config had error, cannot save it");
                return true;
            }

            Intent in = installPKCS12();

            if (in != null)
                startActivityForResult(in, RESULT_INSTALLPKCS12);
            else
                saveProfile();

            return true;
        }

        return super.onOptionsItemSelected(item);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mResult != null)
            outState.putSerializable(VPNPROFILE, mResult);
        outState.putString("mAliasName", mAliasName);

        String[] logentries = new String[mArrayAdapter.getCount()];
        for (int i = 0; i < mArrayAdapter.getCount(); i++) {
            logentries[i] = mArrayAdapter.getItem(i);
        }
        outState.putStringArray("logentries", logentries);

        int[] fileselects = new int[fileSelectMap.size()];
        int k = 0;
        for (Utils.FileType key : fileSelectMap.keySet()) {
            fileselects[k] = key.getValue();
            k++;
        }
        outState.putIntArray("fileselects", fileselects);
        outState.putString("pwfile",mEmbeddedPwFile);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent result) {
        if (requestCode == RESULT_INSTALLPKCS12 && resultCode == Activity.RESULT_OK) {
            showCertDialog();
        }

        if (resultCode == Activity.RESULT_OK && requestCode >= CHOOSE_FILE_OFFSET) {
            Utils.FileType type = Utils.FileType.getFileTypeByValue(requestCode - CHOOSE_FILE_OFFSET);


            FileSelectLayout fs = fileSelectMap.get(type);
            fs.parseResponse(result, this);

            String data = fs.getData();

            switch (type) {
                case USERPW_FILE:
                    mEmbeddedPwFile = data;
                    break;
                case PKCS12:
                    mResult.mPKCS12Filename = data;
                    break;
                case TLS_AUTH_FILE:
                    mResult.mTLSAuthFilename = data;
                    break;
                case CA_CERTIFICATE:
                    mResult.mCaFilename = data;
                    break;
                case CLIENT_CERTIFICATE:
                    mResult.mClientCertFilename = data;
                    break;
                case KEYFILE:
                    mResult.mClientKeyFilename = data;
                    break;
                default:
                    Assert.fail();
            }
        }

        super.onActivityResult(requestCode, resultCode, result);
    }

    private void saveProfile() {
        Intent result = new Intent();
        ProfileManager vpl = ProfileManager.getInstance(this);

        if (!TextUtils.isEmpty(mEmbeddedPwFile))
            ConfigParser.useEmbbedUserAuth(mResult, mEmbeddedPwFile);

        vpl.addProfile(mResult);
        vpl.saveProfile(this, mResult);
        vpl.saveProfileList(this);
        result.putExtra(VpnProfile.EXTRA_PROFILEUUID, mResult.getUUID().toString());
        setResult(Activity.RESULT_OK, result);
        finish();
    }

    public void showCertDialog() {
        try {
            KeyChain.choosePrivateKeyAlias(this,
                    new KeyChainAliasCallback() {

                        public void alias(String alias) {
                            // Credential alias selected.  Remember the alias selection for future use.
                            mResult.mAlias = alias;
                            saveProfile();
                        }


                    },
                    new String[]{"RSA"}, // List of acceptable key types. null for any
                    null,                        // issuer, null for any
                    mResult.mServerName,      // host name of server requesting the cert, null if unavailable
                    -1,                         // port of server requesting the cert, -1 if unavailable
                    mAliasName);                       // alias to preselect, null if unavailable
        } catch (ActivityNotFoundException anf) {
            Builder ab = new AlertDialog.Builder(this);
            ab.setTitle(R.string.broken_image_cert_title);
            ab.setMessage(R.string.broken_image_cert);
            ab.setPositiveButton(android.R.string.ok, null);
            ab.show();
        }
    }


    private Intent installPKCS12() {

        if (!((CheckBox) findViewById(R.id.importpkcs12)).isChecked()) {
            setAuthTypeToEmbeddedPKCS12();
            return null;

        }
        String pkcs12datastr = mResult.mPKCS12Filename;
        if (VpnProfile.isEmbedded(pkcs12datastr)) {
            Intent inkeyIntent = KeyChain.createInstallIntent();

            pkcs12datastr = VpnProfile.getEmbeddedContent(pkcs12datastr);


            byte[] pkcs12data = Base64.decode(pkcs12datastr, Base64.DEFAULT);


            inkeyIntent.putExtra(KeyChain.EXTRA_PKCS12, pkcs12data);

            if (mAliasName.equals(""))
                mAliasName = null;

            if (mAliasName != null) {
                inkeyIntent.putExtra(KeyChain.EXTRA_NAME, mAliasName);
            }
            return inkeyIntent;

        }
        return null;
    }


    private void setAuthTypeToEmbeddedPKCS12() {
        if (VpnProfile.isEmbedded(mResult.mPKCS12Filename)) {
            if (mResult.mAuthenticationType == VpnProfile.TYPE_USERPASS_KEYSTORE)
                mResult.mAuthenticationType = VpnProfile.TYPE_USERPASS_PKCS12;

            if (mResult.mAuthenticationType == VpnProfile.TYPE_KEYSTORE)
                mResult.mAuthenticationType = VpnProfile.TYPE_PKCS12;

        }
    }


    private String getUniqueProfileName(String possibleName) {

        int i = 0;

        ProfileManager vpl = ProfileManager.getInstance(this);

        String newname = possibleName;

        // 	Default to
        if (mResult.mName != null && !ConfigParser.CONVERTED_PROFILE.equals(mResult.mName))
            newname = mResult.mName;

        while (newname == null || vpl.getProfileByName(newname) != null) {
            i++;
            if (i == 1)
                newname = getString(R.string.converted_profile);
            else
                newname = getString(R.string.converted_profile_i, i);
        }

        return newname;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.import_menu, menu);
        return true;
    }

    private String embedFile(String filename, Utils.FileType type) {
        if (filename == null)
            return null;

        // Already embedded, nothing to do
        if (VpnProfile.isEmbedded(filename))
            return filename;

        File possibleFile = findFile(filename, type);
        if (possibleFile == null)
            return filename;
        else
            return readFileContent(possibleFile, type == Utils.FileType.PKCS12);

    }

    private File findFile(String filename, Utils.FileType fileType) {
        File foundfile = findFileRaw(filename);

        if (foundfile == null && filename != null && !filename.equals("")) {
            log(R.string.import_could_not_open, filename);
            addFileSelectDialog(fileType);
        }


        return foundfile;
    }

    private void addFileSelectDialog(Utils.FileType type) {
        int titleRes = 0;
        String value = null;
        switch (type) {
            case KEYFILE:
                titleRes = R.string.client_key_title;
                if (mResult != null)
                    value = mResult.mClientKeyFilename;
                break;
            case CLIENT_CERTIFICATE:
                titleRes = R.string.client_certificate_title;
                if (mResult != null)
                    value = mResult.mClientCertFilename;
                break;
            case CA_CERTIFICATE:
                titleRes = R.string.ca_title;
                if (mResult != null)
                    value = mResult.mCaFilename;
                break;
            case TLS_AUTH_FILE:
                titleRes = R.string.tls_auth_file;
                if (mResult != null)
                    value = mResult.mTLSAuthFilename;
                break;
            case PKCS12:
                titleRes = R.string.client_pkcs12_title;
                if (mResult != null)
                    value = mResult.mPKCS12Filename;
                break;

            case USERPW_FILE:
                titleRes = R.string.userpw_file;
                value = mEmbeddedPwFile;
                break;

        }

        boolean isCert = type == Utils.FileType.CA_CERTIFICATE || type == Utils.FileType.CLIENT_CERTIFICATE;
        FileSelectLayout fl = new FileSelectLayout(this, getString(titleRes), isCert);
        fileSelectMap.put(type, fl);
        fl.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        ((LinearLayout) findViewById(R.id.config_convert_root)).addView(fl, 2);
        findViewById(R.id.files_missing_hint).setVisibility(View.VISIBLE);
        fl.setData(value, this);
        int i = getFileLayoutOffset(type);
        fl.setCaller(this, i, type);

    }

    private int getFileLayoutOffset(Utils.FileType type) {
        return CHOOSE_FILE_OFFSET + type.getValue();
    }


    private File findFileRaw(String filename) {
        if (filename == null || filename.equals(""))
            return null;

        // Try diffent path relative to /mnt/sdcard
        File sdcard = Environment.getExternalStorageDirectory();
        File root = new File("/");

        HashSet<File> dirlist = new HashSet<File>();

        for (int i = mPathsegments.size() - 1; i >= 0; i--) {
            String path = "";
            for (int j = 0; j <= i; j++) {
                path += "/" + mPathsegments.get(j);
            }
            // Do a little hackish dance for the Android File Importer
            // /document/primary:ovpn/openvpn-imt.conf


            if (path.indexOf(':') != -1) {
                String possibleDir = path.substring(path.indexOf(':') + 1, path.length());
                possibleDir = possibleDir.substring(0, possibleDir.lastIndexOf('/'));


                dirlist.add(new File(sdcard, possibleDir));

            }
            dirlist.add(new File(path));


        }
        dirlist.add(sdcard);
        dirlist.add(root);


        String[] fileparts = filename.split("/");
        for (File rootdir : dirlist) {
            String suffix = "";
            for (int i = fileparts.length - 1; i >= 0; i--) {
                if (i == fileparts.length - 1)
                    suffix = fileparts[i];
                else
                    suffix = fileparts[i] + "/" + suffix;

                File possibleFile = new File(rootdir, suffix);
                if (!possibleFile.canRead())
                    continue;

                // read the file inline
                return possibleFile;

            }
        }
        return null;
    }

    String readFileContent(File possibleFile, boolean base64encode) {
        byte[] filedata;
        try {
            filedata = readBytesFromFile(possibleFile);
        } catch (IOException e) {
            log(e.getLocalizedMessage());
            return null;
        }

        String data;
        if (base64encode) {
            data = Base64.encodeToString(filedata, Base64.DEFAULT);
        } else {
            data = new String(filedata);

        }

        return VpnProfile.DISPLAYNAME_TAG + possibleFile.getName() + VpnProfile.INLINE_TAG + data;

    }


    private byte[] readBytesFromFile(File file) throws IOException {
        InputStream input = new FileInputStream(file);

        long len = file.length();
        if (len > VpnProfile.MAX_EMBED_FILE_SIZE)
            throw new IOException("File size of file to import too large.");

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int) len];

        // Read in the bytes
        int offset = 0;
        int bytesRead = 0;
        while (offset < bytes.length
                && (bytesRead = input.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += bytesRead;
        }

        input.close();
        return bytes;
    }

    void embedFiles() {
        // This where I would like to have a c++ style
        // void embedFile(std::string & option)

        if (mResult.mPKCS12Filename != null) {
            File pkcs12file = findFileRaw(mResult.mPKCS12Filename);
            if (pkcs12file != null) {
                mAliasName = pkcs12file.getName().replace(".p12", "");
            } else {
                mAliasName = "Imported PKCS12";
            }
        }


        mResult.mCaFilename = embedFile(mResult.mCaFilename, Utils.FileType.CA_CERTIFICATE);
        mResult.mClientCertFilename = embedFile(mResult.mClientCertFilename, Utils.FileType.CLIENT_CERTIFICATE);
        mResult.mClientKeyFilename = embedFile(mResult.mClientKeyFilename, Utils.FileType.KEYFILE);
        mResult.mTLSAuthFilename = embedFile(mResult.mTLSAuthFilename, Utils.FileType.TLS_AUTH_FILE);
        mResult.mPKCS12Filename = embedFile(mResult.mPKCS12Filename, Utils.FileType.PKCS12);
        mEmbeddedPwFile = embedFile(mResult.mPassword, Utils.FileType.USERPW_FILE);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        setContentView(R.layout.config_converter);

        mArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        getListView().setAdapter(mArrayAdapter);

        super.onCreate(savedInstanceState);


        if (savedInstanceState != null && savedInstanceState.containsKey(VPNPROFILE)) {
            mResult = (VpnProfile) savedInstanceState.getSerializable(VPNPROFILE);
            mAliasName = savedInstanceState.getString("mAliasName");
            mEmbeddedPwFile = savedInstanceState.getString("pwfile");
            mArrayAdapter.addAll(savedInstanceState.getStringArray("logentries"));
            for (int k : savedInstanceState.getIntArray("fileselects")) {
                addFileSelectDialog(Utils.FileType.getFileTypeByValue(k));
            }

            return;
        }


        final android.content.Intent intent = getIntent();

        if (intent != null) {
            final android.net.Uri data = intent.getData();
            if (data != null) {
                //log(R.string.import_experimental);
                log(R.string.importing_config, data.toString());
                try {
                    String possibleName = null;
                    if (data.getScheme().equals("file") ||
                            data.getLastPathSegment().endsWith(".ovpn") ||
                            data.getLastPathSegment().endsWith(".conf")) {
                        possibleName = data.getLastPathSegment();
                        if (possibleName.lastIndexOf('/') != -1)
                            possibleName = possibleName.substring(possibleName.lastIndexOf('/') + 1);

                    }
                    InputStream is = getContentResolver().openInputStream(data);
                    mPathsegments = data.getPathSegments();


                    Cursor cursor = getContentResolver().query(data, null, null, null, null);
                    try {


                        if (cursor!=null && cursor.moveToFirst()) {
                            int cidx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);

                            if (cidx != -1) {
                                String displayName = cursor.getString(cidx);
                                if (displayName != null)
                                    possibleName = displayName;
                            }
                            cidx = cursor.getColumnIndex("mime_type");
                            if (cidx != -1) {
                                log("Opening Mime TYPE: " + cursor.getString(cidx));
                            }
                        }
                    } finally {
                        if(cursor!=null)
                            cursor.close();
                    }
                    if (possibleName != null) {
                        possibleName = possibleName.replace(".ovpn", "");
                        possibleName = possibleName.replace(".conf", "");
                    }

                    doImport(is, possibleName);

                } catch (FileNotFoundException e) {
                    log(R.string.import_content_resolve_error);
                }
            }

            // We parsed the intent, relay on saved instance for restoring
            setIntent(null);
        }


    }


    @Override
    protected void onStart() {
        super.onStart();


    }

    private void log(String logmessage) {
        mArrayAdapter.add(logmessage);
    }

    private void doImport(InputStream is, String newName) {
        ConfigParser cp = new ConfigParser();
        try {
            InputStreamReader isr = new InputStreamReader(is);

            cp.parseConfig(isr);
            VpnProfile vp = cp.convertProfile();
            mResult = vp;
            embedFiles();
            displayWarnings();
            mResult.mName = getUniqueProfileName(newName);

            log(R.string.import_done);
            return;

        } catch (IOException e) {
            log(R.string.error_reading_config_file);
            log(e.getLocalizedMessage());
        } catch (ConfigParseError e) {
            log(R.string.error_reading_config_file);
            log(e.getLocalizedMessage());
        }
        mResult = null;

    }

    private void displayWarnings() {
        if (mResult.mUseCustomConfig) {
            log(R.string.import_warning_custom_options);
            String copt = mResult.mCustomConfigOptions;
            if (copt.startsWith("#")) {
                int until = copt.indexOf('\n');
                copt = copt.substring(until + 1);
            }

            log(copt);
        }

        if (mResult.mAuthenticationType == VpnProfile.TYPE_KEYSTORE ||
                mResult.mAuthenticationType == VpnProfile.TYPE_USERPASS_KEYSTORE) {
            findViewById(R.id.importpkcs12).setVisibility(View.VISIBLE);
        }

    }

    private void log(int ressourceId, Object... formatArgs) {
        log(getString(ressourceId, formatArgs));
    }


}