summaryrefslogtreecommitdiff
path: root/app/src/main/java/se/leap/bitmaskclient/OkHttpClientGenerator.java
blob: 1bf679f8a5d5ec0d77a5f7e4aece3d0f64c56300 (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
/**
 * Copyright (c) 2018 LEAP Encryption Access Project and contributers
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package se.leap.bitmaskclient;

import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Build;
import android.support.annotation.NonNull;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import okhttp3.CipherSuite;
import okhttp3.ConnectionSpec;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.TlsVersion;

import static android.text.TextUtils.isEmpty;
import static se.leap.bitmaskclient.ProviderAPI.ERRORS;
import static se.leap.bitmaskclient.R.string.certificate_error;
import static se.leap.bitmaskclient.R.string.error_io_exception_user_message;
import static se.leap.bitmaskclient.R.string.error_no_such_algorithm_exception_user_message;
import static se.leap.bitmaskclient.R.string.keyChainAccessError;
import static se.leap.bitmaskclient.R.string.server_unreachable_message;

/**
 * Created by cyberta on 08.01.18.
 */

public class OkHttpClientGenerator {

    SharedPreferences preferences;
    Resources resources;

    public OkHttpClientGenerator(SharedPreferences preferences, Resources resources) {
        this.preferences = preferences;
        this.resources = resources;
    }

    public OkHttpClient initCommercialCAHttpClient(JSONObject initError) {
        return initHttpClient(initError, null);
    }

    public OkHttpClient initSelfSignedCAHttpClient(JSONObject initError) {
        String certificate = preferences.getString(Provider.CA_CERT, "");
        return initHttpClient(initError, certificate);
    }

    public OkHttpClient initSelfSignedCAHttpClient(JSONObject initError, String certificate) {
        return initHttpClient(initError, certificate);
    }


    private OkHttpClient initHttpClient(JSONObject initError, String certificate) {
        try {
            TLSCompatSocketFactory sslCompatFactory;
            ConnectionSpec spec = getConnectionSpec();
            OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder();

            if (!isEmpty(certificate)) {
                sslCompatFactory = new TLSCompatSocketFactory(certificate);
            } else {
                sslCompatFactory = new TLSCompatSocketFactory();
            }
            sslCompatFactory.initSSLSocketFactory(clientBuilder);
            clientBuilder.cookieJar(getCookieJar())
                    .connectionSpecs(Collections.singletonList(spec));
            return clientBuilder.build();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
            addErrorMessageToJson(initError, resources.getString(R.string.certificate_error));
        } catch (IllegalStateException | KeyManagementException | KeyStoreException e) {
            e.printStackTrace();
            addErrorMessageToJson(initError, String.format(resources.getString(keyChainAccessError), e.getLocalizedMessage()));
        } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
            e.printStackTrace();
            addErrorMessageToJson(initError, resources.getString(error_no_such_algorithm_exception_user_message));
        } catch (CertificateException e) {
            e.printStackTrace();
            addErrorMessageToJson(initError, resources.getString(certificate_error));
        } catch (UnknownHostException e) {
            e.printStackTrace();
            addErrorMessageToJson(initError, resources.getString(server_unreachable_message));
        } catch (IOException e) {
            e.printStackTrace();
            addErrorMessageToJson(initError, resources.getString(error_io_exception_user_message));
        }
        return null;
    }



    @NonNull
    private ConnectionSpec getConnectionSpec() {
        ConnectionSpec.Builder connectionSpecbuilder = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_3);
        //FIXME: restrict connection further to the following recommended cipher suites for ALL supported API levels
        //figure out how to use bcjsse for that purpose
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
            connectionSpecbuilder.cipherSuites(
                    CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                    CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                    CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
                    CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
                    CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
                    CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256
            );
        return connectionSpecbuilder.build();
    }

    @NonNull
    private CookieJar getCookieJar() {
        return new CookieJar() {
            private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();

            @Override
            public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                cookieStore.put(url.host(), cookies);
            }

            @Override
            public List<Cookie> loadForRequest(HttpUrl url) {
                List<Cookie> cookies = cookieStore.get(url.host());
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }
        };
    }

    private void addErrorMessageToJson(JSONObject jsonObject, String errorMessage) {
        try {
            jsonObject.put(ERRORS, errorMessage);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}