summaryrefslogtreecommitdiff
path: root/receiver.cpp
blob: 6be0f8a7cd3aa4df4b1a70d8d505fc0b05e842d9 (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
#include <regex.h>
#include <string.h>
#include <dirent.h>
#include <err.h>
#include <stdio.h>
#include <inttypes.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <limits.h>
#include <netinet/in.h>

#include <mbedtls/pk.h>
#include <mbedtls/entropy.h>
#include "mbedtls/ctr_drbg.h"
#include "mbedtls/gcm.h"

#include <string>
#include <map>
#include <set>
#include <iostream>

const unsigned short PORT = 58132;

static const unsigned char privkey[] =
"-----BEGIN RSA PRIVATE KEY-----\n"
"MII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AbXljvgudL3tmiBWc5j9S7XNLBe\n"
"u9f3WYAYDu7/BVqmQWa/QtD9JquoZ1xgV2D6nAECgYEA29w9t9/VSJvM9xX+nNyi\n"
"AON6GOjrRK3TPWA7WEXjH+S2bshHJi0ANAs+2Xfpw/kunnRdPLmCtuowfMO4LbGf\n"
"VcexpgLEJyAszvBteikeDwpcyCD19wxP9J4kIYCJiggQKpfLoWUfP/P6DydrPnSt\n"
"EUbAlaNqDpl9Mj7YonQVhCMCgYEAv0c9M5+hrDuX7d76zYaZvI4UymUO54E/yZ7e\n"
"UvdOXGPYed+SL/oKeD5aQAeyLzl79bHdgBs3g0QW9kvXzly0cC5eC0oZH5hhs7nI\n"
"TKII1i86bLtM3dD5vQYWnF0sNtWK/+8Bo6L5ZAiNxRE7lP0L4ndaNKbnPaixcoRo\n"
"kNpPhAECgYAg7jmNlw+7VVurzR36LKKE+d6veraF5ltpJiboDb3j38RGe3982LLq\n"
"WaBKm1gkHfXgBjkNzS4r2kyRijw0GQ9JgmWooR7BXFH30HkPNl4gFTSsrOG5zGLi\n"
"0aexkDpXQuKsgBzqU0Wn94GZMM+RhuOYec/56JFT+8U5Tcntb26wwA==\n"
"-----END RSA PRIVATE KEY-----\n";

static const unsigned char pp[] = "IJUHZGFDXTZKHJKHGFDHZLUÖDRTFGHHJGHH";

// Close files after 20 minutes
#define ACCESS_TIMEOUT (20*60)

/*
   1 byte type: 0 allocate session, 1 log to session, rest: discard
   8 bytes session id
   type 0:
      256 bytes rsa 2048 data yielding 32 byte AES session key
   type 1:
      16 bytes iv
      16 bytes tag
      rest cipher text

   File name format: 2020-10-13-23-42-05-SSSSSSSSSSSSSSSS-KKKKKKKKKKKKKKKKKKKKKKKKKKKKKKKK.log

*/

// Time helper
static time_t now() {
    struct timespec tp;
    clock_gettime(CLOCK_MONOTONIC, &tp);
    return tp.tv_sec;
}

// Constants
enum { SESSION_ID_LENGTH = 8, AES_KEY_LENGTH = 16, GCM_IV_LENGTH = 16, GCM_TAG_LENGTH = 16, MIN_PACKET_SIZE = 40 };
enum { DIRNAME_LENGTH = 10, FILENAME_LENGTH = 73, SIDOFFS = 20, KEYOFFS = 37 };

class Session {
public:
    Session(uint64_t session_id, uint8_t key[AES_KEY_LENGTH], const std::string &dirname, const std::string &filename) :
            _session_id(session_id), _dirname(dirname), _filename(filename) {
        memcpy(_key, key, AES_KEY_LENGTH);
        mbedtls_gcm_init(&_ctx);
        mbedtls_gcm_setkey(&_ctx, MBEDTLS_CIPHER_ID_AES, _key, 8 * AES_KEY_LENGTH);
//        std::cerr << "Imported file " << _filename << " in dir " << _dirname << std::endl;
    }

    Session(uint64_t session_id, uint8_t key[AES_KEY_LENGTH]) : _session_id(session_id) {
        memcpy(_key, key, AES_KEY_LENGTH);
        mbedtls_gcm_init(&_ctx);
        mbedtls_gcm_setkey(&_ctx, MBEDTLS_CIPHER_ID_AES, _key, 8 * AES_KEY_LENGTH);

        // Create timestamp
        char tprefix[32];
        time_t t = time(NULL);
        struct tm * jetzt = localtime(&t);
        strftime(tprefix, sizeof(tprefix), "%F-%H-%M-%S", jetzt);

        // Dump key
        char hexkey[2*AES_KEY_LENGTH + 1];
        for (int i=0; i<AES_KEY_LENGTH; ++i)
            sprintf(hexkey + 2 * i, "%02x", _key[i]);

        // Glue together serialisation
        char filename[FILENAME_LENGTH + 1];
        size_t nlen = snprintf(filename, sizeof(filename), "%s-%016" PRIx64 "-%s.log", tprefix, _session_id, hexkey);
        _filename = std::string(filename, filename + nlen);

        _dirname = std::string(filename, DIRNAME_LENGTH);

        // Touch file to save session_id and key
        close(ensure_file());
    }

    ~Session() {
        mbedtls_gcm_free(&_ctx);
    }

    int ensure_file() {
        mkdir(_dirname.c_str(), 0755);
        return open((_dirname + "/" + _filename).c_str(), O_WRONLY | O_APPEND | O_CREAT, 0755);
    }

    void write_log(const uint8_t *packet, size_t len) {
        // First check if the packet holds enough space for session id, iv and at least one gcm block
        if (len < GCM_IV_LENGTH + GCM_TAG_LENGTH) {
            std::cerr << "Error: Short packet, size " << len << std::endl;
            return;
        }

        const uint8_t *iv = packet;
        const uint8_t *tag = packet + GCM_IV_LENGTH;
        const uint8_t *payload = packet + GCM_IV_LENGTH + GCM_TAG_LENGTH;
        len -= GCM_IV_LENGTH + GCM_TAG_LENGTH;

        std::string ivs(packet, packet +GCM_IV_LENGTH);
        if (_used_ivs.find(ivs) != _used_ivs.end()) {
            std::cerr << "Error: Session " << std::hex << _session_id << " reused IV. Dropping packet" << std::endl;
            return;
        }
        _used_ivs.insert(ivs);

        // Create output file if it doesn't exist
        if (_fd < 0)
            _fd = ensure_file();
        if (_fd < 0) {
            std::cerr << "Error: Can't create file " << _filename << " for session " << std::hex << _session_id;
            return;
        }

        // Prepare output scratch space
        uint8_t *output = static_cast<uint8_t*>(alloca(len));

        // This should fail on invalid input sizes
        switch (mbedtls_gcm_auth_decrypt(&_ctx, len, iv, GCM_IV_LENGTH, (uint8_t*)&_session_id, SESSION_ID_LENGTH, tag, GCM_TAG_LENGTH, payload, output))
        {
            case 0:
                write(_fd, output, len);
                _last_access = now();
                break;
            case MBEDTLS_ERR_GCM_BAD_INPUT:
                std::cerr << "Error: Invalid log data" << std::endl;
                break;
            case MBEDTLS_ERR_GCM_AUTH_FAILED :
                std::cerr << "Error: Can't decrypt" << std::endl;
                break;
            default:
                std::cerr << "Error: Unknown gcm error" << std::endl;
        }
    }

    void check_timeout(time_t when) {
        if (_last_access && _last_access < when && _fd != -1) {
            ::close(_fd);
            _fd = -1;
        }
    }

private:
    uint64_t                _session_id;
    uint8_t                 _key[AES_KEY_LENGTH];
    int                     _fd = -1;
    time_t                  _last_access = 0;
    std::string             _dirname;
    std::string             _filename;
    std::set<std::string>   _used_ivs;
    mbedtls_gcm_context     _ctx;
};

std::map<uint64_t, std::unique_ptr<Session>> g_sessions;

static uint8_t hex2nyble(char c)
{
    return (c>='0'&&c<='9') ? (uint8_t)(c-'0')
        : (c>='a'&&c<='f') ? (uint8_t)(c-'a'+10)
        : (c>='A'&&c<='F') ? (uint8_t)(c-'A'+10)
        : 0;
}

static void import_directory(const char *path, std::string dirname) {
    DIR * dirp = opendir(path);
    if (!dirp)
        errx(-1, "Fatal: Can't open dir %s\n", path);

    regex_t regex;
    if (regcomp(&regex, "^[[:digit:]]{4}-[[:digit:]][[:digit:]]-[[:digit:]][[:digit:]]-[[:digit:]][[:digit:]]-[[:digit:]][[:digit:]]-"
                         "[[:digit:]][[:digit:]]-[[:xdigit:]]{16}-[[:xdigit:]]{32}.log$", REG_EXTENDED))
        errx(-1, "Fatal: Can't compile re");

    struct dirent * entry;
    while ((entry = readdir(dirp)) != NULL) {
        // We expect a very specific format
        if (entry->d_type != DT_REG || entry->d_namlen != FILENAME_LENGTH)
            continue;

        std::string filename(entry->d_name, entry->d_name + entry->d_namlen);
        uint64_t session_id;
        uint8_t aeskey[AES_KEY_LENGTH];

        if (regexec(&regex, filename.c_str(), (size_t) 0, NULL, 0) ||
            sscanf(filename.c_str() + SIDOFFS, "%" SCNx64, &session_id) != 1) {
            std::cerr << "Skipping non-re-matching file: " << filename << std::endl;
            continue;
        }

        const char * hexkey = filename.c_str() + KEYOFFS;
        for (int i=0; i<16; ++i)
            aeskey[i] = (hex2nyble(hexkey[2*i]) << 4 ) | hex2nyble(hexkey[2*i+1]);
        g_sessions[session_id] = std::make_unique<Session>(session_id, aeskey, dirname, filename);
    }
    closedir(dirp);
    regfree(&regex);
}

static void import_sessions(const char *root_dir) {
    char dirpath[PATH_MAX];
    DIR * dirp = opendir(root_dir);
    if (!dirp)
        errx(-1, "Fatal: Can't open dir %s\n", root_dir);

    struct dirent * entry;
    while ((entry = readdir(dirp)) != NULL) {
        if (entry->d_type != DT_DIR || entry->d_namlen != DIRNAME_LENGTH)
            continue;
        std::string dirname(entry->d_name, entry->d_name + entry->d_namlen);
        snprintf(dirpath, PATH_MAX, "%s/%*s", root_dir, DIRNAME_LENGTH, entry->d_name);
        import_directory(dirpath, dirname);
    }
    closedir(dirp);
}

int main() {
    mbedtls_ctr_drbg_context ctr_drbg;
    mbedtls_entropy_context entropy;
    mbedtls_pk_context pk;
    int ret = 0;
    unsigned char result[256];
    unsigned char input[256];
    size_t inputlen = 0;

    chdir("sessions");

    mbedtls_pk_init( &pk );
    mbedtls_entropy_init( &entropy );
    mbedtls_ctr_drbg_init( &ctr_drbg );
    mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, pp, sizeof(pp));

    if ((ret = mbedtls_pk_parse_key(&pk, privkey, sizeof(privkey), NULL, 0) ) != 0 )
        errx(-1, "Fatal: mbedtls_pk_parse_key returned -0x%04x\n", -ret );

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
        errx(-1, "Fatal: Can not make socket\n");

    struct sockaddr_in servaddr, peer;
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = INADDR_ANY;
    servaddr.sin_port = htons(PORT);
    if (bind(sock, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
        errx(-1, "Fatal: Can't bind to port %d\n", PORT);

    import_sessions(".");

    time_t last_close_check = now();
    while(1) {
        uint8_t packet[16*1024];
        uint8_t rsa_plain_text[AES_KEY_LENGTH];
        size_t olen;
        socklen_t peer_len = sizeof(peer);

        ssize_t len = recvfrom(sock, packet, sizeof(packet), MSG_WAITALL, (struct sockaddr *) &peer, &peer_len);
        if (len <= 0)
            errx(-1, "Fatal: recvfrom yields %zd\n", len);

        if (len < MIN_PACKET_SIZE) {
            std::cerr << "Skipping short packet" << std::endl;
            continue;
        }

        uint64_t session_id = *(uint64_t*)(packet + 1);
        auto session = g_sessions.find(session_id);

        switch(packet[0]) {
        case 0: // Session setup
            ret = mbedtls_pk_decrypt(&pk, packet + 1 + SESSION_ID_LENGTH, len - 1 - SESSION_ID_LENGTH,
                                     rsa_plain_text, &olen, sizeof(rsa_plain_text), mbedtls_ctr_drbg_random, &ctr_drbg);
            if (ret < 0) {
                std::cerr << "Error: Failed to decrypt key (error " << -ret << ") for session " << std::hex << session_id;
                break;
            }

            if (session == g_sessions.end())
                g_sessions[session_id] = std::make_unique<Session>(session_id, rsa_plain_text);
            break;
        case 1: {
            if (session != g_sessions.end())
                session->second->write_log(packet + 1 + SESSION_ID_LENGTH, len - 1 - SESSION_ID_LENGTH);
            else
                std::cerr << "Error: Can't log to unknown session " << std::hex << session_id << std::endl;
            break;
            }
        default:
            break;
        }

        time_t jetzt = now();
        if (jetzt > last_close_check + 60) {
            for (auto &&session: g_sessions)
                session.second->check_timeout(jetzt - ACCESS_TIMEOUT);
            last_close_check = jetzt;
        }
    }
}