summaryrefslogtreecommitdiff
path: root/app/src/main/java/se/leap/bitmaskclient/providersetup/ProviderApiManagerV5.java
blob: 2680f612f96ea57dd84f6671c454326321a2d994 (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
package se.leap.bitmaskclient.providersetup;

import static android.text.TextUtils.isEmpty;
import static se.leap.bitmaskclient.R.string.malformed_url;
import static se.leap.bitmaskclient.R.string.vpn_certificate_is_invalid;
import static se.leap.bitmaskclient.R.string.warning_corrupted_provider_cert;
import static se.leap.bitmaskclient.R.string.warning_expired_provider_cert;
import static se.leap.bitmaskclient.base.models.Constants.BROADCAST_RESULT_KEY;
import static se.leap.bitmaskclient.base.models.Constants.COUNTRYCODE;
import static se.leap.bitmaskclient.base.models.Constants.PROVIDER_KEY;
import static se.leap.bitmaskclient.providersetup.ProviderAPI.CORRECTLY_DOWNLOADED_EIP_SERVICE;
import static se.leap.bitmaskclient.providersetup.ProviderAPI.CORRECTLY_UPDATED_INVALID_VPN_CERTIFICATE;
import static se.leap.bitmaskclient.providersetup.ProviderAPI.DOWNLOAD_SERVICE_JSON;
import static se.leap.bitmaskclient.providersetup.ProviderAPI.ERRORS;
import static se.leap.bitmaskclient.providersetup.ProviderAPI.INCORRECTLY_DOWNLOADED_EIP_SERVICE;
import static se.leap.bitmaskclient.providersetup.ProviderAPI.INCORRECTLY_UPDATED_INVALID_VPN_CERTIFICATE;
import static se.leap.bitmaskclient.providersetup.ProviderAPI.PROVIDER_NOK;
import static se.leap.bitmaskclient.providersetup.ProviderAPI.PROVIDER_OK;
import static se.leap.bitmaskclient.providersetup.ProviderAPI.QUIETLY_UPDATE_VPN_CERTIFICATE;
import static se.leap.bitmaskclient.providersetup.ProviderAPI.SET_UP_PROVIDER;
import static se.leap.bitmaskclient.providersetup.ProviderAPI.UPDATE_INVALID_VPN_CERTIFICATE;
import static se.leap.bitmaskclient.providersetup.ProviderSetupFailedDialog.DOWNLOAD_ERRORS.ERROR_INVALID_CERTIFICATE;
import static se.leap.bitmaskclient.providersetup.ProviderSetupObservable.DOWNLOADED_V5_BRIDGES;
import static se.leap.bitmaskclient.providersetup.ProviderSetupObservable.DOWNLOADED_V5_GATEWAYS;
import static se.leap.bitmaskclient.providersetup.ProviderSetupObservable.DOWNLOADED_V5_SERVICE_JSON;
import static se.leap.bitmaskclient.providersetup.ProviderSetupObservable.DOWNLOADED_VPN_CERTIFICATE;
import static se.leap.bitmaskclient.tor.TorStatusObservable.TorStatus.OFF;

import android.content.res.Resources;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.util.Log;

import androidx.annotation.Nullable;

import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;

import de.blinkt.openvpn.core.VpnStatus;
import mobile.BitmaskMobile;
import se.leap.bitmaskclient.BuildConfig;
import se.leap.bitmaskclient.R;
import se.leap.bitmaskclient.base.models.Provider;
import se.leap.bitmaskclient.base.models.ProviderObservable;
import se.leap.bitmaskclient.base.utils.ConfigHelper;
import se.leap.bitmaskclient.base.utils.CredentialsParser;
import se.leap.bitmaskclient.base.utils.PreferenceHelper;
import se.leap.bitmaskclient.eip.EipStatus;
import se.leap.bitmaskclient.tor.TorStatusObservable;

public class ProviderApiManagerV5 extends ProviderApiManagerBase implements IProviderApiManager {

    private static final String TAG = ProviderApiManagerV5.class.getSimpleName();

    ProviderApiManagerV5(Resources resources, ProviderApiServiceCallback callback) {
        super(resources, callback);
    }

    @Override
    public void handleAction(String action, Provider provider, Bundle parameters, ResultReceiver receiver) {
        Bundle result = new Bundle();
        switch (action) {
            case SET_UP_PROVIDER:
                result = setupProvider(provider, parameters);
                if (result.getBoolean(BROADCAST_RESULT_KEY)) {
                    serviceCallback.saveProvider(provider);
                    eventSender.sendToReceiverOrBroadcast(receiver, PROVIDER_OK, result, provider);
                } else {
                    eventSender.sendToReceiverOrBroadcast(receiver, PROVIDER_NOK, result, provider);
                }
                break;

            case DOWNLOAD_SERVICE_JSON:
                result = updateServiceInfos(provider, parameters);
                if (result.getBoolean(BROADCAST_RESULT_KEY)) {
                    serviceCallback.saveProvider(provider);
                    eventSender.sendToReceiverOrBroadcast(receiver, CORRECTLY_DOWNLOADED_EIP_SERVICE, result, provider);
                } else {
                    eventSender.sendToReceiverOrBroadcast(receiver, INCORRECTLY_DOWNLOADED_EIP_SERVICE, result, provider);
                }
                break;

            case QUIETLY_UPDATE_VPN_CERTIFICATE:
                result = updateVpnCertificate(provider);
                if (result.getBoolean(BROADCAST_RESULT_KEY)) {
                    Log.d(TAG, "successfully downloaded VPN certificate");
                    provider.setShouldUpdateVpnCertificate(false);
                    PreferenceHelper.storeProviderInPreferences(provider);
                    ProviderObservable.getInstance().updateProvider(provider);
                }
                break;
            case UPDATE_INVALID_VPN_CERTIFICATE:
                result = updateVpnCertificate(provider);
                if (result.getBoolean(BROADCAST_RESULT_KEY)) {
                    eventSender.sendToReceiverOrBroadcast(receiver, CORRECTLY_UPDATED_INVALID_VPN_CERTIFICATE, result, provider);
                } else {
                    eventSender.sendToReceiverOrBroadcast(receiver, INCORRECTLY_UPDATED_INVALID_VPN_CERTIFICATE, result, provider);
                }
                break;
        }

    }

    private Bundle updateServiceInfos(Provider provider, Bundle parameters) {
        Bundle currentDownload = new Bundle();

        BitmaskMobile bm;
        try {
            bm = new BitmaskMobile(provider.getMainUrl(), new PreferenceHelper.SharedPreferenceStore());
            bm.setDebug(BuildConfig.DEBUG);
        } catch (IllegalStateException e) {
            return eventSender.setErrorResult(currentDownload, R.string.config_error_found, null);
        }

        try {
            configureBaseCountryCode(bm, parameters);
        } catch (Exception e) {
            return eventSender.setErrorResult(currentDownload, R.string.config_error_found, null);
        }

        try {
            String serviceJson = bm.getService();
            provider.setService(serviceJson);
        } catch (Exception e) {
            return eventSender.setErrorResult(currentDownload, R.string.config_error_found, null);
        }

        try {
            if (provider.hasIntroducer()) {
                    bm.setIntroducer(provider.getIntroducer().toUrl());
            }
        } catch (Exception e) {
            return eventSender.setErrorResult(currentDownload, R.string.config_error_found, null);
        }

        if (PreferenceHelper.getUseBridges()) {
            try {
                String bridgesJson = bm.getAllBridges("", "", "", "");
                provider.setBridges(bridgesJson);
            } catch (Exception e) {
                // TODO: send failed to fetch bridges event
                return eventSender.setErrorResult(currentDownload, R.string.config_error_found, null);
            }
        } else {
            try {
                String gatewaysJson = bm.getAllGateways("", "", "");
                provider.setGateways(gatewaysJson);
            } catch (Exception e) {
                // TODO: send
                return eventSender.setErrorResult(currentDownload, R.string.config_error_found, null);

            }
        }
        currentDownload.putBoolean(BROADCAST_RESULT_KEY, true);
        return currentDownload;

    }

    protected Bundle setupProvider(Provider provider, Bundle parameters) {
        Bundle currentDownload = new Bundle();

        if (isEmpty(provider.getMainUrl()) || provider.getMainUrl().isEmpty()) {
            currentDownload.putBoolean(BROADCAST_RESULT_KEY, false);
            eventSender.setErrorResult(currentDownload, malformed_url, null);
            VpnStatus.logWarning("[API] MainURL String is not set. Cannot setup provider.");
            return currentDownload;
        }

        //provider certificate invalid
        if (currentDownload.containsKey(ERRORS)) {
            currentDownload.putParcelable(PROVIDER_KEY, provider);
            return currentDownload;
        }

        BitmaskMobile bm;
        try {
            bm = new BitmaskMobile(provider.getMainUrl(), new PreferenceHelper.SharedPreferenceStore());
            bm.setDebug(BuildConfig.DEBUG);
            if (TorStatusObservable.isRunning() && TorStatusObservable.getSocksProxyPort() != -1) {
                bm.setSocksProxy(SOCKS_PROXY_SCHEME + PROXY_HOST + ":" + TorStatusObservable.getSocksProxyPort());
            }
            if (provider.hasIntroducer()) {
                bm.setIntroducer(provider.getIntroducer().toUrl());
            }
        } catch (Exception e) {
            // TODO: improve error message
            return eventSender.setErrorResult(currentDownload, R.string.config_error_found, null);
        }

        try {
            configureBaseCountryCode(bm, parameters);
        } catch (Exception e) {
            return eventSender.setErrorResult(currentDownload, R.string.config_error_found, null);
        }

        try {
            String serviceJson = bm.getService();
            Log.d(TAG, "service Json reponse: " + serviceJson);
            provider.setService(serviceJson);
            ProviderSetupObservable.updateProgress(DOWNLOADED_V5_SERVICE_JSON);
        } catch (Exception e) {
            Log.w(TAG, "failed to fetch service.json: " + e.getMessage());
            e.printStackTrace();
            return eventSender.setErrorResult(currentDownload, R.string.error_json_exception_user_message, null);
        }

        try {
            String gatewaysJson = bm.getAllGateways("", "", "");
            Log.d(TAG, "gateways Json reponse: " + gatewaysJson);
            provider.setGateways(gatewaysJson);
            ProviderSetupObservable.updateProgress(DOWNLOADED_V5_GATEWAYS);
        } catch (Exception e) {
            Log.w(TAG, "failed to fetch gateways: " + e.getMessage());
            e.printStackTrace();
            return eventSender.setErrorResult(currentDownload, R.string.error_json_exception_user_message, null);
        }

        try {
            String bridgesJson = bm.getAllBridges("", "", "", "");
            Log.d(TAG, "bridges Json reponse: " + bridgesJson);
            provider.setBridges(bridgesJson);
            ProviderSetupObservable.updateProgress(DOWNLOADED_V5_BRIDGES);
        } catch (Exception e) {
            Log.w(TAG, "failed to fetch bridges: " + e.getMessage());
            e.printStackTrace();
            return eventSender.setErrorResult(currentDownload, R.string.error_json_exception_user_message, null);
        }

        try {
            String cert = bm.getOpenVPNCert();
            currentDownload = loadCredentials(provider, cert);
            currentDownload = validateCertificateForProvider(currentDownload, provider);
            ProviderSetupObservable.updateProgress(DOWNLOADED_VPN_CERTIFICATE);
        } catch (Exception e) {
            return eventSender.setErrorResult(currentDownload, R.string.error_json_exception_user_message, null);
        }

        return currentDownload;
    }

    private Bundle loadCredentials(Provider provider, String credentials) {
        Bundle result = new Bundle();

        try {
            CredentialsParser.parseXml(credentials, provider);
        } catch (XmlPullParserException | IOException e) {
            e.printStackTrace();
            return eventSender.setErrorResult(result, vpn_certificate_is_invalid, null);
        }

        result.putBoolean(BROADCAST_RESULT_KEY, true);
        return result;
    }

    @Nullable
    private void configureBaseCountryCode(BitmaskMobile bm, Bundle parameters) throws Exception {
        String cc = parameters.getString(COUNTRYCODE, null);
        if (cc == null &&
                EipStatus.getInstance().isDisconnected() &&
                TorStatusObservable.getStatus() == OFF) {
            try {
                cc = bm.getGeolocation();
            } catch (Exception e) {
                // print exception and ignore
                e.printStackTrace();
                cc = "";
            }
        }
        bm.setCountryCode(cc);
    }

    Bundle validateProviderDetails(Provider provider) {
        Bundle result = new Bundle();
        result.putBoolean(BROADCAST_RESULT_KEY, false);

        if (!provider.hasDefinition()) {
            return result;
        }

        result = validateCertificateForProvider(result, provider);

        //invalid certificate or no certificate or unable to connect due other connectivity issues
        if (result.containsKey(ERRORS) || (result.containsKey(BROADCAST_RESULT_KEY) && !result.getBoolean(BROADCAST_RESULT_KEY)) ) {
            return result;
        }

        result.putBoolean(BROADCAST_RESULT_KEY, true);

        return result;
    }

    protected Bundle validateCertificateForProvider(Bundle result, Provider provider) {
        String caCert = provider.getCaCert();

        if (ConfigHelper.checkErroneousDownload(caCert)) {
            VpnStatus.logWarning("[API] No provider cert.");
            return result;
        }

        ArrayList<X509Certificate> certificates = ConfigHelper.parseX509CertificatesFromString(caCert);
        if (certificates == null) {
            return eventSender.setErrorResult(result, warning_corrupted_provider_cert, ERROR_INVALID_CERTIFICATE.toString());
        }

        ArrayList<X509Certificate> validCertificates = new ArrayList<>();
        int invalidCertificates = 0;
        for (X509Certificate certificate : certificates) {
            try {
                certificate.checkValidity();
                validCertificates.add(certificate);
            } catch (CertificateNotYetValidException |
                     CertificateExpiredException e) {
                e.printStackTrace();
                invalidCertificates++;
            }
        }
        if (validCertificates.isEmpty() && invalidCertificates > 0) {
            return eventSender.setErrorResult(result, warning_expired_provider_cert, ERROR_INVALID_CERTIFICATE.toString());
        }

        provider.setCaCert(ConfigHelper.parseX509CertificatesToString(validCertificates));
        result.putParcelable(PROVIDER_KEY, provider);
        result.putBoolean(BROADCAST_RESULT_KEY, true);
        return result;
    }

    protected Bundle updateVpnCertificate(Provider provider) {
        Bundle currentDownload = new Bundle();
        BitmaskMobile bm;
        try {
            bm = new BitmaskMobile(provider.getMainUrl(), new PreferenceHelper.SharedPreferenceStore());
            bm.setDebug(BuildConfig.DEBUG);
        } catch (IllegalStateException e) {
            return eventSender.setErrorResult(currentDownload, R.string.config_error_found, null);
        }

        try {
            String cert = bm.getOpenVPNCert();
            currentDownload = loadCredentials(provider, cert);
            currentDownload = validateCertificateForProvider(currentDownload, provider);
            ProviderSetupObservable.updateProgress(DOWNLOADED_VPN_CERTIFICATE);
        } catch (Exception e) {
            return eventSender.setErrorResult(currentDownload, R.string.error_json_exception_user_message, null);
        }

        return currentDownload;
    }

}