aboutsummaryrefslogtreecommitdiffstats
path: root/OpenKeychain/src/main/java/org/sufficientlysecure/keychain/keyimport/KeybaseKeyServer.java
blob: 953cf3cbb412686b7e644a376f0b04d47afa1598 (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
/*
 * Copyright (C) 2014 Tim Bray <tbray@textuality.com>
 *
 * 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 org.sufficientlysecure.keychain.keyimport;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.sufficientlysecure.keychain.Constants;
import org.sufficientlysecure.keychain.util.JWalk;
import org.sufficientlysecure.keychain.util.Log;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.WeakHashMap;

public class KeybaseKeyServer extends KeyServer {

    private WeakHashMap<String, String> mKeyCache = new WeakHashMap<String, String>();

    @Override
    public ArrayList<ImportKeysListEntry> search(String query) throws QueryException, TooManyResponses,
            InsufficientQuery {
        ArrayList<ImportKeysListEntry> results = new ArrayList<ImportKeysListEntry>();

        if (query.startsWith("0x")) {
            // cut off "0x" if a user is searching for a key id
            query = query.substring(2);
        }

        JSONObject fromQuery = getFromKeybase("_/api/1.0/user/autocomplete.json?q=", query);
        try {

            JSONArray matches = JWalk.getArray(fromQuery, "completions");
            for (int i = 0; i < matches.length(); i++) {
                JSONObject match = matches.getJSONObject(i);

                // only list them if they have a key
                if (JWalk.optObject(match, "components", "key_fingerprint") != null) {
                    String keybaseId = JWalk.getString(match, "components", "username", "val");
                    String fingerprint = JWalk.getString(match, "components", "key_fingerprint", "val");
                    fingerprint = fingerprint.replace(" ", "").toUpperCase();

                    if (keybaseId.equals(query) || fingerprint.startsWith(query.toUpperCase())) {
                        results.add(makeEntry(match));
                    } else {
                        results.add(makeEntry(match));
                    }
                }
            }
        } catch (Exception e) {
            Log.e(Constants.TAG, "keybase result parsing error", e);
            throw new QueryException("Unexpected structure in keybase search result: " + e.getMessage());
        }

        return results;
    }

    private JSONObject getUser(String keybaseId) throws QueryException {
        try {
            return getFromKeybase("_/api/1.0/user/lookup.json?username=", keybaseId);
        } catch (Exception e) {
            String detail = "";
            if (keybaseId != null) {
                detail = ". Query was for user '" + keybaseId + "'";
            }
            throw new QueryException(e.getMessage() + detail);
        }
    }

    private ImportKeysListEntry makeEntry(JSONObject match) throws QueryException, JSONException {

        final ImportKeysListEntry entry = new ImportKeysListEntry();
        String keybaseId = JWalk.getString(match, "components", "username", "val");
        String fullName = JWalk.getString(match, "components", "full_name", "val");
        String fingerprint = JWalk.getString(match, "components", "key_fingerprint", "val");
        fingerprint = fingerprint.replace(" ", "").toUpperCase();

        // in anticipation of a full fingerprint, only use the last 16 chars as 64-bit key id
        entry.setKeyIdHex("0x" + fingerprint.substring(Math.max(0, fingerprint.length() - 16)));
        // store extra info, so we can query for the keybase id directly
        entry.setExtraData(keybaseId);

        // TODO: Fix; have suggested keybase provide this value to avoid search-time crypto calls
        //entry.setBitStrength(4096);
        //entry.setAlgorithm("RSA");

        entry.setFingerprintHex(fingerprint);

        // key data
        // currently there's no need to query the user right away, and it should be avoided, so the
        // user doesn't experience lag and doesn't download many keys unnecessarily, but should we
        // require to do it at soe point:
        // (weakly) remember the key, in case the user tries to import it
        //mKeyCache.put(keybaseId, JWalk.getString(match, "them", "public_keys", "primary", "bundle"));

        ArrayList<String> userIds = new ArrayList<String>();
        String name = fullName + " <keybase.io/" + keybaseId + ">";
        userIds.add(name);
        try {
            userIds.add("github.com/" + JWalk.getString(match, "components", "github", "val"));
        } catch (JSONException e) {
            // ignore
        }
        try {
            userIds.add("twitter.com/" + JWalk.getString(match, "components", "twitter", "val"));
        } catch (JSONException e) {
            // ignore
        }
        try {
            JSONArray array = JWalk.getArray(match, "components", "websites");
            JSONObject website = array.getJSONObject(0);
            userIds.add(JWalk.getString(website, "val"));
        } catch (JSONException e) {
            // ignore
        }
        entry.setUserIds(userIds);
        entry.setPrimaryUserId(name);
        return entry;
    }

    private JSONObject getFromKeybase(String path, String query) throws QueryException {
        try {
            String url = "https://keybase.io/" + path + URLEncoder.encode(query, "utf8");
            Log.d(Constants.TAG, "keybase query: " + url);

            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            conn.setConnectTimeout(5000); // TODO: Reasonable values for keybase
            conn.setReadTimeout(25000);
            conn.connect();
            int response = conn.getResponseCode();
            if (response >= 200 && response < 300) {
                String text = readAll(conn.getInputStream(), conn.getContentEncoding());
                try {
                    JSONObject json = new JSONObject(text);
                    if (JWalk.getInt(json, "status", "code") != 0) {
                        throw new QueryException("Keybase autocomplete search failed");
                    }
                    return json;
                } catch (JSONException e) {
                    throw new QueryException("Keybase.io query returned broken JSON");
                }
            } else {
                String message = readAll(conn.getErrorStream(), conn.getContentEncoding());
                throw new QueryException("Keybase.io query error (status=" + response +
                        "): " + message);
            }
        } catch (Exception e) {
            throw new QueryException("Keybase.io query error");
        }
    }

    @Override
    public String get(String id) throws QueryException {
        String key = mKeyCache.get(id);
        if (key == null) {
            try {
                JSONObject user = getUser(id);
                key = JWalk.getString(user, "them", "public_keys", "primary", "bundle");
            } catch (Exception e) {
                throw new QueryException(e.getMessage());
            }
        }
        return key;
    }

    @Override
    public void add(String armoredKey) throws AddKeyException {
        throw new AddKeyException();
    }
}