Welcome to mirror list, hosted at ThFree Co, Russian Federation.

YubiKey.cpp « drivers « keys « src - github.com/keepassxreboot/keepassxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: d64452f3e05d32697dd0375070fcd8da60d6fd60 (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
/*
 *  Copyright (C) 2014 Kyle Manna <kyle@kylemanna.com>
 *  Copyright (C) 2017 KeePassXC Team <team@keepassxc.org>
 *
 *  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 2 or (at your option)
 *  version 3 of the License.
 *
 *  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/>.
 */

#include <stdio.h>

#include <ykcore.h>
#include <ykdef.h>
#include <ykpers-version.h>
#include <ykstatus.h>
#include <yubikey.h>

#include "core/Global.h"
#include "core/Tools.h"
#include "crypto/Random.h"

#include "YubiKey.h"

#include <QtConcurrent>

namespace
{
    constexpr int MAX_KEYS = 4;

    YK_KEY* openKey(int ykIndex, int okIndex, bool* onlyKey = nullptr)
    {
        YK_KEY* key = nullptr;
        if (onlyKey) {
            *onlyKey = false;
        }
#if YKPERS_VERSION_NUMBER >= 0x011200
        // This function is only available in ykcore >= 1.18.0
        key = yk_open_key(ykIndex);
#else
        // Only allow for the first found key to be used
        if (ykIndex == 0) {
            key = yk_open_first_key();
        }
#endif
#if YKPERS_VERSION_NUMBER >= 0x011400
        // New fuction available in yubikey-personalization version >= 1.20.0 that allows
        // selecting device VID/PID (yk_open_key_vid_pid)
        if (!key) {
            static const int device_pids[] = {0x60fc}; // OnlyKey PID
            key = yk_open_key_vid_pid(0x1d50, device_pids, 1, okIndex);
            if (onlyKey) {
                *onlyKey = true;
            }
        }
#else
        Q_UNUSED(okIndex);
#endif
        return key;
    }

    void closeKey(YK_KEY* key)
    {
        yk_close_key(key);
    }

    unsigned int getSerial(YK_KEY* key)
    {
        unsigned int serial;
        yk_get_serial(key, 1, 0, &serial);
        return serial;
    }

    YK_KEY* openKeySerial(unsigned int serial)
    {
        bool onlykey;
        for (int i = 0, j = 0; i + j < MAX_KEYS;) {
            auto* yk_key = openKey(i, j, &onlykey);
            if (yk_key) {
                onlykey ? ++j : ++i;
                // If the provided serial number is 0, or the key matches the serial, return it
                if (serial == 0 || getSerial(yk_key) == serial) {
                    return yk_key;
                }
                closeKey(yk_key);
            } else {
                // No more connected keys
                break;
            }
        }
        return nullptr;
    }
} // namespace

YubiKey::YubiKey()
    : m_mutex(QMutex::Recursive)
{
    m_interactionTimer.setSingleShot(true);
    m_interactionTimer.setInterval(300);

    if (!yk_init()) {
        qDebug("YubiKey: Failed to initialize USB interface.");
    } else {
        m_initialized = true;
        // clang-format off
        connect(&m_interactionTimer, SIGNAL(timeout()), this, SIGNAL(userInteractionRequest()));
        connect(this, &YubiKey::challengeStarted, this, [this] { m_interactionTimer.start(); }, Qt::QueuedConnection);
        connect(this, &YubiKey::challengeCompleted, this, [this] { m_interactionTimer.stop(); }, Qt::QueuedConnection);
        // clang-format on
    }
}

YubiKey::~YubiKey()
{
    yk_release();
}

YubiKey* YubiKey::m_instance(Q_NULLPTR);

YubiKey* YubiKey::instance()
{
    if (!m_instance) {
        m_instance = new YubiKey();
    }

    return m_instance;
}

bool YubiKey::isInitialized()
{
    return m_initialized;
}

void YubiKey::findValidKeys()
{
    m_error.clear();
    if (!isInitialized()) {
        return;
    }

    QtConcurrent::run([this] {
        if (!m_mutex.tryLock(1000)) {
            emit detectComplete(false);
            return;
        }

        // Remove all known keys
        m_foundKeys.clear();

        // Try to detect up to 4 connected hardware keys
        for (int i = 0, j = 0; i + j < MAX_KEYS;) {
            bool onlyKey = false;
            auto yk_key = openKey(i, j, &onlyKey);
            if (yk_key) {
                onlyKey ? ++j : ++i;
                auto vender = onlyKey ? QStringLiteral("OnlyKey") : QStringLiteral("YubiKey");
                auto serial = getSerial(yk_key);
                if (serial == 0) {
                    closeKey(yk_key);
                    continue;
                }

                auto st = ykds_alloc();
                yk_get_status(yk_key, st);
                int vid, pid;
                yk_get_key_vid_pid(yk_key, &vid, &pid);

                bool wouldBlock;
                QList<QPair<int, QString>> ykSlots;
                for (int slot = 1; slot <= 2; ++slot) {
                    auto config = (i == 1 ? CONFIG1_VALID : CONFIG2_VALID);
                    if (!(ykds_touch_level(st) & config)) {
                        // Slot is not configured
                        continue;
                    }
                    // Don't actually challenge a YubiKey Neo or below, they always require button press
                    // if it is enabled for the slot resulting in failed detection
                    if (pid <= NEO_OTP_U2F_CCID_PID) {
                        auto display = tr("%1 [%2] Configured Slot - %3")
                                           .arg(vender, QString::number(serial), QString::number(slot));
                        ykSlots.append({slot, display});
                    } else if (performTestChallenge(yk_key, slot, &wouldBlock)) {
                        auto display = tr("%1 [%2] Challenge Response - Slot %3 - %4")
                                           .arg(vender,
                                                QString::number(serial),
                                                QString::number(slot),
                                                wouldBlock ? tr("Press") : tr("Passive"));
                        ykSlots.append({slot, display});
                    }
                }

                if (!ykSlots.isEmpty()) {
                    m_foundKeys.insert(serial, ykSlots);
                }

                ykds_free(st);
                closeKey(yk_key);

                Tools::wait(100);
            } else {
                // No more keys are connected
                break;
            }
        }

        m_mutex.unlock();
        emit detectComplete(!m_foundKeys.isEmpty());
    });
}

QList<YubiKeySlot> YubiKey::foundKeys()
{
    QList<YubiKeySlot> keys;
    for (auto serial : m_foundKeys.uniqueKeys()) {
        for (auto key : m_foundKeys.value(serial)) {
            keys.append({serial, key.first});
        }
    }
    return keys;
}

QString YubiKey::getDisplayName(YubiKeySlot slot)
{
    for (auto key : m_foundKeys.value(slot.first)) {
        if (slot.second == key.first) {
            return key.second;
        }
    }
    return tr("%1 Invalid slot specified - %2").arg(QString::number(slot.first), QString::number(slot.second));
}

QString YubiKey::errorMessage()
{
    return m_error;
}

/**
 * Issue a test challenge to the specified slot to determine if challenge
 * response is properly configured.
 *
 * @param slot YubiKey configuration slot
 * @param wouldBlock return if the operation requires user input
 * @return whether the challenge succeeded
 */
bool YubiKey::testChallenge(YubiKeySlot slot, bool* wouldBlock)
{
    bool ret = false;
    auto* yk_key = openKeySerial(slot.first);
    if (yk_key) {
        ret = performTestChallenge(yk_key, slot.second, wouldBlock);
    }
    return ret;
}

bool YubiKey::performTestChallenge(void* key, int slot, bool* wouldBlock)
{
    auto chall = randomGen()->randomArray(1);
    QByteArray resp;
    auto ret = performChallenge(static_cast<YK_KEY*>(key), slot, false, chall, resp);
    if (ret == SUCCESS || ret == WOULDBLOCK) {
        if (wouldBlock) {
            *wouldBlock = ret == WOULDBLOCK;
        }
        return true;
    }
    return false;
}

/**
 * Issue a challenge to the specified slot
 * This operation could block if the YubiKey requires a touch to trigger.
 *
 * @param slot YubiKey configuration slot
 * @param challenge challenge input to YubiKey
 * @param response response output from YubiKey
 * @return challenge result
 */
YubiKey::ChallengeResult YubiKey::challenge(YubiKeySlot slot, const QByteArray& challenge, QByteArray& response)
{
    m_error.clear();
    if (!m_initialized) {
        m_error = tr("The YubiKey interface has not been initialized.");
        return ERROR;
    }

    // Try to grab a lock for 1 second, fail out if not possible
    if (!m_mutex.tryLock(1000)) {
        m_error = tr("Hardware key is currently in use.");
        return ERROR;
    }

    auto* yk_key = openKeySerial(slot.first);
    if (!yk_key) {
        // Key with specified serial number is not connected
        m_error =
            tr("Could not find hardware key with serial number %1. Please plug it in to continue.").arg(slot.first);
        m_mutex.unlock();
        return ERROR;
    }

    emit challengeStarted();
    auto ret = performChallenge(yk_key, slot.second, true, challenge, response);

    closeKey(yk_key);
    emit challengeCompleted();
    m_mutex.unlock();

    return ret;
}

YubiKey::ChallengeResult
YubiKey::performChallenge(void* key, int slot, bool mayBlock, const QByteArray& challenge, QByteArray& response)
{
    m_error.clear();
    int yk_cmd = (slot == 1) ? SLOT_CHAL_HMAC1 : SLOT_CHAL_HMAC2;
    QByteArray paddedChallenge = challenge;

    // yk_challenge_response() insists on 64 bytes response buffer */
    response.clear();
    response.resize(64);

    /* The challenge sent to the yubikey should always be 64 bytes for
     * compatibility with all configurations.  Follow PKCS7 padding.
     *
     * There is some question whether or not 64 bytes fixed length
     * configurations even work, some docs say avoid it.
     */
    const int padLen = 64 - paddedChallenge.size();
    if (padLen > 0) {
        paddedChallenge.append(QByteArray(padLen, padLen));
    }

    const unsigned char* c;
    unsigned char* r;
    c = reinterpret_cast<const unsigned char*>(paddedChallenge.constData());
    r = reinterpret_cast<unsigned char*>(response.data());

    int ret = yk_challenge_response(
        static_cast<YK_KEY*>(key), yk_cmd, mayBlock, paddedChallenge.size(), c, response.size(), r);

    // actual HMAC-SHA1 response is only 20 bytes
    response.resize(20);

    if (!ret) {
        if (yk_errno == YK_EWOULDBLOCK) {
            return WOULDBLOCK;
        } else if (yk_errno) {
            if (yk_errno == YK_ETIMEOUT) {
                m_error = tr("Hardware key timed out waiting for user interaction.");
            } else if (yk_errno == YK_EUSBERR) {
                m_error = tr("A USB error ocurred when accessing the hardware key: %1").arg(yk_usb_strerror());
            } else {
                m_error = tr("Failed to complete a challenge-response, the specific error was: %1")
                              .arg(yk_strerror(yk_errno));
            }

            return ERROR;
        }
    }

    return SUCCESS;
}