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

Server.cpp « http « src - github.com/keepassxreboot/keepassxc.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 16423d8cfbebc7eaa4f05c449e851936f2c1184a (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
/**
 ***************************************************************************
 * @file Server.cpp
 *
 * @brief
 *
 * Copyright (C) 2013
 *
 * @author	Francois Ferrand
 * @date	4/2013
 ***************************************************************************
 */

#include "Server.h"
#include <microhttpd.h>
#include "Protocol.h"
#include "HttpSettings.h"
#include "crypto/Crypto.h"
#include <QtCore/QHash>
#include <QtCore/QCryptographicHash>
#include <QtWidgets/QMessageBox>
#include <QEventLoop>
#include <QtNetwork/QHostInfo>
#include <QtNetwork/QHostAddress>

#ifdef Q_OS_WIN
#include <winsock2.h>
#else
#include <netinet/in.h>
#endif

using namespace KeepassHttpProtocol;


////////////////////////////////////////////////////////////////////////////////////////////////////
/// Request
////////////////////////////////////////////////////////////////////////////////////////////////////

Server::Server(QObject *parent) :
    QObject(parent),
    m_started(false)
{
    connect(this, SIGNAL(emitRequest(const QByteArray, QByteArray*)),
            this, SLOT(handleRequest(const QByteArray, QByteArray*)));
    connect(this, SIGNAL(emitOpenDatabase(bool*)),
            this, SLOT(handleOpenDatabase(bool*)));
}


void Server::testAssociate(const Request& r, Response * protocolResp)
{
    if (r.id().isEmpty())
        return;   //ping

    QString key = getKey(r.id());
    if (key.isEmpty() || !r.CheckVerifier(key))
        return;

    protocolResp->setSuccess();
    protocolResp->setId(r.id());
    protocolResp->setVerifier(key);
}

void Server::associate(const Request& r, Response * protocolResp)
{
    if (!r.CheckVerifier(r.key()))
        return;

    QString id = storeKey(r.key());
    if (id.isEmpty())
        return;

    protocolResp->setSuccess();
    protocolResp->setId(id);
    protocolResp->setVerifier(r.key());
}

void Server::getLogins(const Request &r, Response *protocolResp)
{
    QString key = getKey(r.id());
    if (!r.CheckVerifier(key))
        return;

    protocolResp->setSuccess();
    protocolResp->setId(r.id());
    protocolResp->setVerifier(key);
    QList<Entry> entries = findMatchingEntries(r.id(), r.url(), r.submitUrl(), r.realm());  //TODO: filtering, request confirmation [in db adaptation layer?]
    if (r.sortSelection()) {
        //TODO: sorting (in db adaptation layer? here?)
    }
    protocolResp->setEntries(entries);
}

void Server::getLoginsCount(const Request &r, Response *protocolResp)
{
    QString key = getKey(r.id());
    if (!r.CheckVerifier(key))
        return;

    protocolResp->setSuccess();
    protocolResp->setId(r.id());
    protocolResp->setVerifier(key);
    protocolResp->setCount(countMatchingEntries(r.id(), r.url(), r.submitUrl(), r.realm()));
}

void Server::getAllLogins(const Request &r, Response *protocolResp)
{
    QString key = getKey(r.id());
    if (!r.CheckVerifier(key))
        return;

    protocolResp->setSuccess();
    protocolResp->setId(r.id());
    protocolResp->setVerifier(key);
    protocolResp->setEntries(searchAllEntries(r.id()));   //TODO: ensure there is no password --> change API?
}

void Server::setLogin(const Request &r, Response *protocolResp)
{
    QString key = getKey(r.id());
    if (!r.CheckVerifier(key))
        return;

    QString uuid = r.uuid();
    if (uuid.isEmpty())
        addEntry(r.id(), r.login(), r.password(), r.url(), r.submitUrl(), r.realm());
    else
        updateEntry(r.id(), r.uuid(), r.login(), r.password(), r.url());

    protocolResp->setSuccess();
    protocolResp->setId(r.id());
    protocolResp->setVerifier(key);
}


int Server::send_response(struct MHD_Connection *connection, const char *page)
{
    int ret;
    struct MHD_Response *response;

    response = MHD_create_response_from_buffer(
            strlen(page), static_cast<void*>(const_cast<char*>(page)),
            MHD_RESPMEM_PERSISTENT);
    if (!response) return MHD_NO;

    MHD_add_response_header (response, "Content-Type", "application/json");
    ret = MHD_queue_response (connection, MHD_HTTP_OK, response);
    MHD_destroy_response (response);

    return ret;
}


int Server::send_unavailable(struct MHD_Connection *connection)
{
    int ret;
    struct MHD_Response *response;

    response = MHD_create_response_from_buffer(0, NULL, MHD_RESPMEM_PERSISTENT);
    if (!response) return MHD_NO;

    ret = MHD_queue_response (connection, MHD_HTTP_SERVICE_UNAVAILABLE, response);
    MHD_destroy_response (response);

    return ret;
}

void Server::generatePassword(const Request &r, Response *protocolResp)
{
    QString key = getKey(r.id());
    if (!r.CheckVerifier(key))
        return;

    QString password = generatePassword();
    QString bits = QString::number(HttpSettings::getbits());

    protocolResp->setSuccess();
    protocolResp->setId(r.id());
    protocolResp->setVerifier(key);
    protocolResp->setEntries(QList<Entry>() << Entry("generate-password", bits, password, "generate-password"));

    memset(password.data(), 0, password.length());
}


int Server::request_handler_wrapper(void *me, struct MHD_Connection *connection,
        const char *url, const char *method, const char *version,
        const char *upload_data, size_t *upload_data_size, void **con_cls)
{
    Server *myself = static_cast<Server*>(me);

    if (myself)
        return myself->request_handler(connection, url, method, version,
                                       upload_data, upload_data_size, con_cls);
    else
        return MHD_NO;
}


void Server::handleRequest(const QByteArray in, QByteArray *out)
{
    *out = QByteArray();

    Request r;
    if (!r.fromJson(in))
        return;

    QByteArray hash = QCryptographicHash::hash(
        (getDatabaseRootUuid() + getDatabaseRecycleBinUuid()).toUtf8(),
         QCryptographicHash::Sha1).toHex();

    Response protocolResp(r, QString::fromLatin1(hash));
    switch(r.requestType()) {
    case INVALID: break;
    case GET_LOGINS:        getLogins(r, &protocolResp); break;
    case GET_LOGINS_COUNT:  getLoginsCount(r, &protocolResp); break;
    case GET_ALL_LOGINS:    getAllLogins(r, &protocolResp); break;
    case SET_LOGIN:         setLogin(r, &protocolResp); break;
    case ASSOCIATE:         associate(r, &protocolResp); break;
    case TEST_ASSOCIATE:    testAssociate(r, &protocolResp); break;
    case GENERATE_PASSWORD: generatePassword(r, &protocolResp); break;
    }

    *out = protocolResp.toJson().toUtf8();

    // THIS IS A FAKE HACK!!!
    // the real "error" is a misbehavior in the QJSON qobject2qvariant method
    // 1. getLogins returns an empty QList<Entry> into protocolResp->m_entries
    // in toJson() function the following happend:
    // 2. QJson::QObjectHelper::qobject2qvariant marks m_entries as invalid !!!
    // 3. QJson::Serializer write out Entries as null instead of empty list
    //(4. ChromeIPass tries to access Entries.length and fails with null pointer exception)
    // the fake workaround replaces the (wrong) "Entries":null with "Entries:[] to give
    // chromeIPass (and passIFox) en empty list
    QString tmp_out = QString(*out);
    int tmp_pos1 = tmp_out.indexOf("\"Count\":0,");
    int tmp_pos2 = tmp_out.indexOf("\"Entries\":null,");
    if (tmp_pos1 != -1 && tmp_pos2 != -1) {
        tmp_out.replace(tmp_pos2, 15, "\"Entries\":[],");
    }
    *out = tmp_out.toUtf8();

    Q_EMIT donewrk();
}


void Server::handleOpenDatabase(bool *success)
{
    *success = openDatabase();
    Q_EMIT donewrk();
}


int Server::request_handler(struct MHD_Connection *connection,
        const char *, const char *method, const char *,
        const char *upload_data, size_t *upload_data_size, void **con_cls)
{
    struct Server::connection_info_struct *con_info =
        static_cast<struct Server::connection_info_struct*>(*con_cls);

    if (!isDatabaseOpened()) {
        bool success;
        QEventLoop loop1;
        loop1.connect(this, SIGNAL(donewrk()), SLOT(quit()));
        Q_EMIT emitOpenDatabase(&success);
        loop1.exec();

        if (!success)
            return send_unavailable(connection);
    }

    if (con_info == NULL) {
        *con_cls = calloc(1, sizeof(*con_info));
        return MHD_YES;
    }

    if (strcmp (method, MHD_HTTP_METHOD_POST) != 0)
        return MHD_NO;

    if (*upload_data_size == 0) {
        if (con_info && con_info->response)
            return send_response(connection, con_info->response);
        else
            return MHD_NO;
    }

    QString type = MHD_lookup_connection_value(connection,
                                               MHD_HEADER_KIND, "Content-Type");
    if (!type.contains("application/json", Qt::CaseInsensitive))
        return MHD_NO;

    // Now process the POST request

    QByteArray post = QByteArray(upload_data, *upload_data_size);

    QByteArray s;
    QEventLoop loop;
    loop.connect(this, SIGNAL(donewrk()), SLOT(quit()));
    Q_EMIT emitRequest(post, &s);
    loop.exec();

    if (s.size() == 0)
        return MHD_NO;

    con_info->response = static_cast<char*>(calloc(1, s.size()+1));
    memcpy(con_info->response, s.data(), s.size());

    *upload_data_size = 0;

    return MHD_YES;
}


void Server::request_completed(void *, struct MHD_Connection *,
        void **con_cls, enum MHD_RequestTerminationCode)
{
    struct Server::connection_info_struct *con_info =
        static_cast<struct Server::connection_info_struct*>(*con_cls);

    if (con_info == NULL)
        return;

    if (con_info->response) free(con_info->response);
    free(con_info);
    *con_cls = NULL;
}


void Server::start(void)
{
    if (m_started)
        return;

    bool nohost = true;
    int port = HttpSettings::httpPort();

    QHostInfo info = QHostInfo::fromName(HttpSettings::httpHost());
    if (!info.addresses().isEmpty()) {
        void* addrx = NULL;
        unsigned int flags = MHD_USE_SELECT_INTERNALLY;
        QHostAddress address = info.addresses().first();

        if (address.protocol() == QAbstractSocket::IPv4Protocol) {
            struct sockaddr_in *addr = static_cast<struct sockaddr_in*>(calloc(1, sizeof(struct sockaddr_in)));
            addrx = static_cast<void*>(addr);
            addr->sin_family = AF_INET;
            addr->sin_port = htons(HttpSettings::httpPort());
            addr->sin_addr.s_addr = htonl(address.toIPv4Address());
            nohost = false;
        } else {
            struct sockaddr_in6 *addr = static_cast<struct sockaddr_in6*>(calloc(1, sizeof(struct sockaddr_in6)));
            addrx = static_cast<void*>(addr);
            addr->sin6_family = AF_INET6;
            addr->sin6_port = htons(HttpSettings::httpPort());
            memcpy(&addr->sin6_addr, address.toIPv6Address().c, 16);
            nohost = false;
            flags |= MHD_USE_IPv6;
        }

        if (nohost) {
            qWarning("HTTPPlugin: Faled to get configured host!");
        } else {
            if (NULL == (daemon = MHD_start_daemon(flags, port, NULL, NULL,
                                                   &this->request_handler_wrapper, this,
                                                   MHD_OPTION_NOTIFY_COMPLETED,
                                                   this->request_completed, NULL,
                                                   MHD_OPTION_SOCK_ADDR,
                                                   addrx,
                                                   MHD_OPTION_END))) {
                nohost = true;
                qWarning("HTTPPlugin: Failed to bind to configured host!");
            } else {
                nohost = false;
                //qWarning("HTTPPlugin: Binded to configured host.");
            }

        }

        if (addrx != NULL)
            free(addrx);
    }

    if (nohost) {
        if (NULL == (daemon = MHD_start_daemon(MHD_USE_SELECT_INTERNALLY, port, NULL, NULL,
                                 &this->request_handler_wrapper, this,
                                 MHD_OPTION_NOTIFY_COMPLETED,
                                 this->request_completed, NULL,
                                 MHD_OPTION_END))) {
            qWarning("HTTPPlugin: Fatal! Failed to bind to both configured and default hosts!");
        } else {
            qWarning("HTTPPlugin: Bound to fallback address 0.0.0.0/:::!");
        }
    }

    m_started = true;
}


void Server::stop(void)
{
    if (!m_started)
        return;

    MHD_stop_daemon(daemon);
    m_started = false;
}