Debian Codegraph @

runtime/lib_ksils12.c

raw
1 /* lib_ksils12.c - rsyslog's KSI-LS12 support library
2 *
3 * Regarding the online algorithm for Merkle tree signing. Expected
4 * calling sequence is:
5 *
6 * sigblkConstruct
7 * for each signature block:
8 * sigblkInitKSI
9 * for each record:
10 * sigblkAddRecordKSI
11 * sigblkFinishKSI
12 * sigblkDestruct
13 *
14 * Obviously, the next call after sigblkFinsh must either be to
15 * sigblkInitKSI or sigblkDestruct (if no more signature blocks are
16 * to be emitted, e.g. on file close). sigblkDestruct saves state
17 * information (most importantly last block hash) and sigblkConstruct
18 * reads (or initilizes if not present) it.
19 *
20 * Copyright 2013-2018 Adiscon GmbH and Guardtime, Inc.
21 *
22 * This file is part of rsyslog.
23 *
24 * Licensed under the Apache License, Version 2.0 (the "License");
25 * you may not use this file except in compliance with the License.
26 * You may obtain a copy of the License at
27 *
28 * http://www.apache.org/licenses/LICENSE-2.0
29 * -or-
30 * see COPYING.ASL20 in the source distribution
31 *
32 * Unless required by applicable law or agreed to in writing, software
33 * distributed under the License is distributed on an "AS IS" BASIS,
34 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
35 * See the License for the specific language governing permissions and
36 * limitations under the License.
37 */
38 #ifdef HAVE_CONFIG_H
39 #include "config.h"
40 #endif
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <errno.h>
44 #include <string.h>
45 #include <stdint.h>
46 #include <assert.h>
47 #include <unistd.h>
48 #include <sys/types.h>
49 #include <sys/stat.h>
50 #include <fcntl.h>
51 #include <stdarg.h>
52 #include <limits.h>
53
54 #include <ksi/ksi.h>
55 #include <ksi/tlv_element.h>
56 #include <ksi/hash.h>
57 #include <ksi/net_async.h>
58 #include <ksi/net_ha.h>
59 #include <ksi/net_uri.h>
60 #include <ksi/signature_builder.h>
61 #include "rsyslog.h"
62 #include "errmsg.h"
63 #include "lib_ksils12.h"
64 #include "lib_ksi_queue.h"
65
66 #ifndef VERSION
67 #define VERSION "no-version"
68 #endif
69
70 #define KSI_BUF_SIZE 4096
71
72 static const char *blockFileSuffix = ".logsig.parts/blocks.dat";
73 static const char *sigFileSuffix = ".logsig.parts/block-signatures.dat";
74 static const char *ls12FileSuffix = ".logsig";
75 static const char *blockCloseReason = "com.guardtime.blockCloseReason";
76
77
78 #define LS12_FILE_HEADER "LOGSIG12"
79 #define LS12_BLOCKFILE_HEADER "LOG12BLK"
80 #define LS12_SIGFILE_HEADER "LOG12SIG"
81 #define LS12_SIGNATURE_TIMEOUT 60
82
83 /* Worker queue item type identifier */
84 typedef enum QITEM_type_en { QITEM_SIGNATURE_REQUEST = 0x00, QITEM_CLOSE_FILE, QITEM_NEW_FILE, QITEM_QUIT } QITEM_type;
85
86 /* Worker queue item status identifier */
87 typedef enum QITEM_status_en {
88 /* State assigned to any item added to queue (initial state). */
89 QITEM_WAITING = 0x00,
90
91 /* State assigned to #QITEM_SIGNATURE_REQUEST item when it is sent out. */
92 QITEM_SENT,
93
94 /* State assigned to #QITEM_SIGNATURE_REQUEST item when request failed or succeeded. */
95 QITEM_DONE
96 } QITEM_status;
97
98
99 /* Worker queue job item */
100 typedef struct QueueItem_st {
101 QITEM_type type;
102 QITEM_status status;
103 KSI_DataHash *root;
104 FILE *file; /* To keep track of the target signature file. */
105 uint64_t intarg1; /* Block time limit or record count or not used. */
106 uint64_t intarg2; /* Level of the sign request or not used. */
107 KSI_AsyncHandle *respHandle;
108 int ksi_status;
109 time_t request_time;
110 } QueueItem;
111
112 static bool queueAddCloseFile(rsksictx ctx, ksifile kf);
113 static bool queueAddNewFile(rsksictx ctx, ksifile kf);
114 static bool queueAddQuit(rsksictx ctx);
115 static bool queueAddSignRequest(rsksictx ctx, ksifile kf, KSI_DataHash *root, unsigned level);
116 static int sigblkFinishKSINoSignature(ksifile ksi, const char *reason);
117
118 void *signer_thread(void *arg);
119
120 static void __attribute__((format(printf, 2, 3))) report(rsksictx ctx, const char *errmsg, ...) {
121 char buf[1024];
122 int r;
123 va_list args;
124 va_start(args, errmsg);
125
126 r = vsnprintf(buf, sizeof(buf), errmsg, args);
127 buf[sizeof(buf) - 1] = '\0';
128 va_end(args);
129
130 if (ctx->logFunc == NULL) return;
131
132 if (r > 0 && r < (int)sizeof(buf))
133 ctx->logFunc(ctx->usrptr, (uchar *)buf);
134 else
135 ctx->logFunc(ctx->usrptr, (uchar *)errmsg);
136 }
137
138 static void reportErr(rsksictx ctx, const char *const errmsg) {
139 if (ctx->errFunc == NULL) goto done;
140 ctx->errFunc(ctx->usrptr, (uchar *)errmsg);
141 done:
142 return;
143 }
144
145 static const char *level2str(int level) {
146 switch (level) {
147 case KSI_LOG_DEBUG:
148 return "DEBUG";
149 case KSI_LOG_INFO:
150 return "INFO";
151 case KSI_LOG_NOTICE:
152 return "NOTICE";
153 case KSI_LOG_WARN:
154 return "WARN";
155 case KSI_LOG_ERROR:
156 return "ERROR";
157 default:
158 return "UNKNOWN LOG LEVEL";
159 }
160 }
161
162 void reportKSIAPIErr(rsksictx ctx, ksifile ksi, const char *apiname, int ecode) {
163 char errbuf[4096];
164 char ksi_errbuf[4096];
165 KSI_ERR_getBaseErrorMessage(ctx->ksi_ctx, ksi_errbuf, sizeof(ksi_errbuf), NULL, NULL);
166 snprintf(errbuf, sizeof(errbuf), "%s[%s:%d]: %s (%s)", (ksi == NULL) ? (uchar *)"" : ksi->blockfilename, apiname,
167 ecode, KSI_getErrorString(ecode), ksi_errbuf);
168
169 errbuf[sizeof(errbuf) - 1] = '\0';
170 reportErr(ctx, errbuf);
171 }
172
173 void rsksisetErrFunc(rsksictx ctx, void (*func)(void *, uchar *), void *usrptr) {
174 ctx->usrptr = usrptr;
175 ctx->errFunc = func;
176 }
177
178 void rsksisetLogFunc(rsksictx ctx, void (*func)(void *, uchar *), void *usrptr) {
179 ctx->usrptr = usrptr;
180 ctx->logFunc = func;
181 }
182
183 static ksifile rsksifileConstruct(rsksictx ctx) {
184 ksifile ksi = NULL;
185 if ((ksi = calloc(1, sizeof(struct ksifile_s))) == NULL) goto done;
186 ksi->ctx = ctx;
187 ksi->hashAlg = ctx->hashAlg;
188 ksi->blockTimeLimit = ctx->blockTimeLimit;
189 ksi->blockSizeLimit = 1 << (ctx->effectiveBlockLevelLimit - 1);
190 ksi->bKeepRecordHashes = ctx->bKeepRecordHashes;
191 ksi->bKeepTreeHashes = ctx->bKeepTreeHashes;
192 ksi->lastLeaf[0] = ctx->hashAlg;
193
194 done:
195 return ksi;
196 }
197
198 /* return the actual length in to-be-written octets of an integer */
199 static uint8_t tlvGetIntSize(uint64_t val) {
200 uint8_t n = 0;
201 while (val != 0) {
202 val >>= 8;
203 n++;
204 }
205 return n;
206 }
207
208 static int tlvWriteOctetString(FILE *f, const uint8_t *data, uint16_t len) {
209 if (fwrite(data, len, 1, f) != 1) return RSGTE_IO;
210 return 0;
211 }
212
213 static int tlvWriteHeader8(FILE *f, int flags, uint8_t tlvtype, int len) {
214 unsigned char buf[2];
215 assert((flags & RSGT_TYPE_MASK) == 0);
216 assert((tlvtype & RSGT_TYPE_MASK) == tlvtype);
217 buf[0] = (flags & ~RSGT_FLAG_TLV16) | tlvtype;
218 buf[1] = len & 0xff;
219
220 return tlvWriteOctetString(f, buf, 2);
221 }
222
223 static int tlvWriteHeader16(FILE *f, int flags, uint16_t tlvtype, uint16_t len) {
224 uint16_t typ;
225 unsigned char buf[4];
226 assert((flags & RSGT_TYPE_MASK) == 0);
227 assert((tlvtype >> 8 & RSGT_TYPE_MASK) == (tlvtype >> 8));
228 typ = ((flags | RSGT_FLAG_TLV16) << 8) | tlvtype;
229
230 buf[0] = typ >> 8;
231 buf[1] = typ & 0xff;
232 buf[2] = (len >> 8) & 0xff;
233 buf[3] = len & 0xff;
234
235 return tlvWriteOctetString(f, buf, 4);
236 }
237
238 static int tlvGetHeaderSize(uint16_t tag, size_t size) {
239 if (tag <= RSGT_TYPE_MASK && size <= 0xff) return 2;
240 if ((tag >> 8) <= RSGT_TYPE_MASK && size <= 0xffff) return 4;
241 return 0;
242 }
243
244 static int tlvWriteHeader(FILE *f, int flags, uint16_t tlvtype, uint16_t len) {
245 int headersize = tlvGetHeaderSize(tlvtype, flags);
246 if (headersize == 2)
247 return tlvWriteHeader8(f, flags, tlvtype, len);
248 else if (headersize == 4)
249 return tlvWriteHeader16(f, flags, tlvtype, len);
250 else
251 return 0;
252 }
253
254 static int tlvWriteOctetStringTLV(FILE *f, int flags, uint16_t tlvtype, const uint8_t *data, uint16_t len) {
255 if (tlvWriteHeader(f, flags, tlvtype, len) != 0) return RSGTE_IO;
256
257 if (fwrite(data, len, 1, f) != 1) return RSGTE_IO;
258
259 return 0;
260 }
261
262 static int tlvWriteInt64TLV(FILE *f, int flags, uint16_t tlvtype, uint64_t val) {
263 unsigned char buf[8];
264 uint8_t count = tlvGetIntSize(val);
265 uint64_t nTmp;
266
267 if (tlvWriteHeader(f, flags, tlvtype, count) != 0) return RSGTE_IO;
268
269 nTmp = val;
270 for (int i = count - 1; i >= 0; i--) {
271 buf[i] = 0xFF & nTmp;
272 nTmp = nTmp >> 8;
273 }
274
275 if (fwrite(buf, count, 1, f) != 1) return RSGTE_IO;
276
277 return 0;
278 }
279
280 static int tlvWriteHashKSI(ksifile ksi, uint16_t tlvtype, KSI_DataHash *rec) {
281 int r;
282 const unsigned char *imprint;
283 size_t imprint_len;
284 r = KSI_DataHash_getImprint(rec, &imprint, &imprint_len);
285 if (r != KSI_OK) {
286 reportKSIAPIErr(ksi->ctx, ksi, "KSI_DataHash_getImprint", r);
287 return r;
288 }
289
290 return tlvWriteOctetStringTLV(ksi->blockFile, 0, tlvtype, imprint, imprint_len);
291 }
292
293 static int tlvWriteBlockHdrKSI(ksifile ksi) {
294 unsigned tlvlen;
295 uint8_t hash_algo = ksi->hashAlg;
296 int r;
297
298 tlvlen = 2 + 1 /* hash algo TLV */ + 2 + KSI_getHashLength(ksi->hashAlg) /* iv */ + 2 +
299 KSI_getHashLength(ksi->lastLeaf[0]) + 1;
300 /* last hash */;
301
302 /* write top-level TLV object block-hdr */
303 CHKr(tlvWriteHeader(ksi->blockFile, 0x00, 0x0901, tlvlen));
304
305 /* hash-algo */
306 CHKr(tlvWriteOctetStringTLV(ksi->blockFile, 0x00, 0x01, &hash_algo, 1));
307
308 /* block-iv */
309 CHKr(tlvWriteOctetStringTLV(ksi->blockFile, 0x00, 0x02, ksi->IV, KSI_getHashLength(ksi->hashAlg)));
310
311 /* last-hash */
312 CHKr(tlvWriteOctetStringTLV(ksi->blockFile, 0x00, 0x03, ksi->lastLeaf, KSI_getHashLength(ksi->lastLeaf[0]) + 1));
313 done:
314 return r;
315 }
316
317 static int tlvWriteKSISigLS12(FILE *outfile, size_t record_count, uchar *der, uint16_t lenDer) {
318 int r = 0;
319 int totalSize = 2 + tlvGetIntSize(record_count) + 4 + lenDer;
320
321 CHKr(tlvWriteHeader(outfile, 0x00, 0x0904, totalSize));
322 CHKr(tlvWriteInt64TLV(outfile, 0x00, 0x01, record_count));
323 CHKr(tlvWriteOctetStringTLV(outfile, 0x00, 0x0905, der, lenDer));
324 done:
325 return r;
326 }
327
328 static int tlvWriteNoSigLS12(FILE *outfile, size_t record_count, const KSI_DataHash *hash, const char *errorText) {
329 int r = 0;
330 int totalSize = 0;
331 int noSigSize = 0;
332 const unsigned char *imprint = NULL;
333 size_t imprintLen = 0;
334
335 KSI_DataHash_getImprint(hash, &imprint, &imprintLen);
336
337 noSigSize = 2 + imprintLen + (errorText ? (2 + strlen(errorText) + 1) : 0);
338 totalSize = 2 + tlvGetIntSize(record_count) + 2 + noSigSize;
339
340 CHKr(tlvWriteHeader(outfile, 0x00, 0x0904, totalSize));
341 CHKr(tlvWriteInt64TLV(outfile, 0x00, 0x01, record_count));
342 CHKr(tlvWriteHeader(outfile, 0x00, 0x02, noSigSize));
343 CHKr(tlvWriteOctetStringTLV(outfile, 0x00, 0x01, imprint, imprintLen));
344 if (errorText) CHKr(tlvWriteOctetStringTLV(outfile, 0x00, 0x02, (uint8_t *)errorText, strlen(errorText) + 1));
345 done:
346 return r;
347 }
348
349 static int tlvCreateMetadata(
350 ksifile ksi, uint64_t record_index, const char *key, const char *value, unsigned char *buffer, size_t *len) {
351 int r = 0;
352 KSI_TlvElement *metadata = NULL, *attrib_tlv = NULL;
353 KSI_Utf8String *key_tlv = NULL, *value_tlv = NULL;
354 KSI_Integer *index_tlv = NULL;
355
356 CHKr(KSI_TlvElement_new(&metadata));
357 metadata->ftlv.tag = 0x0911;
358
359 CHKr(KSI_Integer_new(ksi->ctx->ksi_ctx, record_index, &index_tlv));
360 CHKr(KSI_TlvElement_setInteger(metadata, 0x01, index_tlv));
361
362 CHKr(KSI_TlvElement_new(&attrib_tlv));
363 attrib_tlv->ftlv.tag = 0x02;
364
365 CHKr(KSI_Utf8String_new(ksi->ctx->ksi_ctx, key, strlen(key) + 1, &key_tlv));
366 CHKr(KSI_TlvElement_setUtf8String(attrib_tlv, 0x01, key_tlv));
367
368 CHKr(KSI_Utf8String_new(ksi->ctx->ksi_ctx, value, strlen(value) + 1, &value_tlv));
369 CHKr(KSI_TlvElement_setUtf8String(attrib_tlv, 0x02, value_tlv));
370
371 CHKr(KSI_TlvElement_setElement(metadata, attrib_tlv));
372
373 CHKr(KSI_TlvElement_serialize(metadata, buffer, 0xFFFF, len, 0));
374
375 done:
376 if (metadata) KSI_TlvElement_free(metadata);
377 if (attrib_tlv) KSI_TlvElement_free(attrib_tlv);
378 if (key_tlv) KSI_Utf8String_free(key_tlv);
379 if (value_tlv) KSI_Utf8String_free(value_tlv);
380 if (index_tlv) KSI_Integer_free(index_tlv);
381
382 return r;
383 }
384
385 #define KSI_FILE_AMOUNT_INC 32
386
387 static int rsksiExpandRegisterIfNeeded(rsksictx ctx, size_t inc) {
388 int ret = RSGTE_INTERNAL;
389 ksifile *tmp = NULL;
390
391 if (ctx == NULL || inc == 0) {
392 return RSGTE_INTERNAL;
393 }
394
395 if (ctx->ksiCount < ctx->ksiCapacity) {
396 return RSGTE_SUCCESS;
397 }
398
399 /* If needed allocate memory for the buffer. */
400 tmp = (ksifile *)realloc(ctx->ksi, sizeof(ksifile) * (ctx->ksiCapacity + inc));
401 if (tmp == NULL) {
402 ret = RSGTE_OOM;
403 goto done;
404 }
405
406 /* Make sure that allocated pointers are all set to NULL. */
407 memset(tmp + ctx->ksiCapacity, 0, sizeof(ksifile) * inc);
408
409 /* Update buffer capacity. */
410 ctx->ksiCapacity += inc;
411 ctx->ksi = tmp;
412 tmp = NULL;
413 ret = RSGTE_SUCCESS;
414
415 done:
416 free(tmp);
417 return ret;
418 }
419
420 static int rsksiRegisterKsiFile(rsksictx ctx, ksifile ksi) {
421 int ret = RSGTE_INTERNAL;
422
423 if (ctx == NULL || ksi == NULL) {
424 return RSGTE_INTERNAL;
425 }
426
427 /* To be extra sure that ksifile buffer is initialized correctly, clear variables. */
428 if (ctx->ksi == NULL) {
429 ctx->ksiCount = 0;
430 ctx->ksiCapacity = 0;
431 }
432
433 ret = rsksiExpandRegisterIfNeeded(ctx, KSI_FILE_AMOUNT_INC);
434 if (ret != RSGTE_SUCCESS) goto done;
435
436 ctx->ksi[ctx->ksiCount] = ksi;
437 ctx->ksiCount++;
438 ret = RSGTE_SUCCESS;
439
440 done:
441 return ret;
442 }
443
444 static int rsksiDeregisterKsiFile(rsksictx ctx, ksifile ksi) {
445 int ret = RSGTE_INTERNAL;
446 size_t i = 0;
447
448 if (ctx == NULL || ksi == NULL) {
449 return RSGTE_INTERNAL;
450 }
451
452
453 for (i = 0; i < ctx->ksiCount; i++) {
454 if (ctx->ksi[i] != NULL && ctx->ksi[i] == ksi) {
455 size_t lastElement = ctx->ksiCount - 1;
456
457 if (i != lastElement) {
458 ctx->ksi[i] = ctx->ksi[lastElement];
459 }
460
461 ctx->ksi[lastElement] = NULL;
462
463 ctx->ksiCount--;
464 ret = RSGTE_SUCCESS;
465 goto done;
466 }
467 }
468
469 done:
470 return ret;
471 }
472
473 /* support for old platforms - graceful degrade */
474 #ifndef O_CLOEXEC
475 #define O_CLOEXEC 0
476 #endif
477 /* read rsyslog log state file; if we cannot access it or the
478 * contents looks invalid, we flag it as non-present (and thus
479 * begin a new hash chain).
480 * The context is initialized accordingly.
481 */
482 static bool ksiReadStateFile(ksifile ksi) {
483 int fd = -1;
484 struct rsksistatefile sf;
485 bool ret = false;
486
487 fd = open((char *)ksi->statefilename, O_RDONLY | O_NOCTTY | O_CLOEXEC, 0600);
488 if (fd == -1) goto done;
489
490 if (read(fd, &sf, sizeof(sf)) != sizeof(sf)) goto done;
491 if (strncmp(sf.hdr, "KSISTAT10", 9)) goto done;
492
493 if (KSI_getHashLength(sf.hashID) != sf.lenHash || KSI_getHashLength(sf.hashID) > KSI_MAX_IMPRINT_LEN - 1) goto done;
494
495 if (read(fd, ksi->lastLeaf + 1, sf.lenHash) != sf.lenHash) goto done;
496
497 ksi->lastLeaf[0] = sf.hashID;
498 ret = true;
499
500 done:
501 if (!ret) {
502 memset(ksi->lastLeaf, 0, sizeof(ksi->lastLeaf));
503 ksi->lastLeaf[0] = ksi->hashAlg;
504 }
505
506 if (fd != -1) close(fd);
507 return ret;
508 }
509
510 /* persist all information that we need to re-open and append
511 * to a log signature file.
512 */
513 static void ksiWwriteStateFile(ksifile ksi) {
514 int fd;
515 struct rsksistatefile sf;
516
517 fd = open((char *)ksi->statefilename, O_WRONLY | O_CREAT | O_TRUNC | O_NOCTTY | O_CLOEXEC, ksi->ctx->fCreateMode);
518 if (fd == -1) goto done;
519 if (ksi->ctx->fileUID != (uid_t)-1 || ksi->ctx->fileGID != (gid_t)-1) {
520 /* we need to set owner/group */
521 if (fchown(fd, ksi->ctx->fileUID, ksi->ctx->fileGID) != 0) {
522 report(ksi->ctx, "lmsig_ksi: chown for file '%s' failed: %s", ksi->statefilename, strerror(errno));
523 }
524 }
525
526 memcpy(sf.hdr, "KSISTAT10", 9);
527 sf.hashID = ksi->hashAlg;
528 sf.lenHash = KSI_getHashLength(ksi->lastLeaf[0]);
529 /* if the write fails, we cannot do anything against that. We check
530 * the condition just to keep the compiler happy.
531 */
532 if (write(fd, &sf, sizeof(sf))) {
533 };
534 if (write(fd, ksi->lastLeaf + 1, sf.lenHash)) {
535 };
536 close(fd);
537 done:
538 return;
539 }
540
541
542 static int ksiCloseSigFile(ksifile ksi) {
543 fclose(ksi->blockFile);
544 ksi->blockFile = NULL;
545 if (ksi->ctx->syncMode == LOGSIG_ASYNCHRONOUS) queueAddCloseFile(ksi->ctx, ksi);
546
547 ksiWwriteStateFile(ksi);
548 return 0;
549 }
550
551 static int mkpath(char *path, mode_t mode, uid_t uid, gid_t gid) {
552 if (path == NULL) return 1;
553
554 for (char *p = strchr(path + 1, '/'); p; p = strchr(p + 1, '/')) {
555 *p = '\0';
556 if (mkdir(path, mode) == 0) {
557 if (uid != (uid_t)-1 || gid != (uid_t)-1) {
558 if (chown(path, uid, gid)) {
559 LogError(errno, RS_RET_IO_ERROR,
560 "ksils12 signatures: could not change to "
561 "configured owner - files may be unaccessible");
562 }
563 }
564 } else if (errno != EEXIST) {
565 *p = '/';
566 return -1;
567 }
568
569 *p = '/';
570 }
571 return 0;
572 }
573
574 static FILE *ksiCreateFile(
575 rsksictx ctx, const char *path, uid_t uid, gid_t gid, int mode, bool lockit, const char *header) {
576 int fd = -1;
577 struct stat stat_st;
578 FILE *f = NULL;
579 struct flock lock = {F_WRLCK, SEEK_SET, 0, 0, 0};
580
581 if (path == NULL) return NULL;
582
583 if (mkpath((char *)path, ctx->fDirCreateMode, ctx->dirUID, ctx->dirGID) != 0) {
584 report(ctx, "ksiCreateFile: mkpath failed for %s", path);
585 goto done;
586 }
587
588 fd = open(path, O_RDWR | O_APPEND | O_NOCTTY | O_CLOEXEC, 0600);
589 if (fd == -1) {
590 fd = open(path, O_RDWR | O_CREAT | O_NOCTTY | O_CLOEXEC, mode);
591 if (fd == -1) {
592 report(ctx, "creating file '%s' failed: %s", path, strerror(errno));
593 goto done;
594 }
595
596 if (uid != (uid_t)-1 || gid != (gid_t)-1) {
597 if (fchown(fd, uid, gid) != 0) {
598 report(ctx, "lmsig_ksi: chown for file '%s' failed: %s", path, strerror(errno));
599 }
600 }
601 }
602
603 if (lockit && fcntl(fd, F_SETLK, &lock) != 0) report(ctx, "fcntl error: %s", strerror(errno));
604
605 f = fdopen(fd, "a");
606 if (f == NULL) {
607 report(ctx, "fdopen for '%s' failed: %s", path, strerror(errno));
608 goto done;
609 }
610
611 setvbuf(f, NULL, _IOFBF, KSI_BUF_SIZE);
612
613 if (fstat(fd, &stat_st) == -1) {
614 reportErr(ctx, "ksiOpenSigFile: can not stat file");
615 goto done;
616 }
617
618 if (stat_st.st_size == 0 && header != NULL) {
619 if (fwrite(header, strlen(header), 1, f) != 1) {
620 report(ctx, "ksiOpenSigFile: fwrite for file %s failed: %s", path, strerror(errno));
621 goto done;
622 }
623 }
624 /* Write header immediately as when using dynafile it is possible that the same
625 * file is opened 2x in sequence (caused by small dynafile cache where files are
626 * frequently closed and reopened). If the header already exists double header is
627 * not written. The content of the file is ordered by signer thread.
628 */
629 fflush(f);
630 done:
631 return f;
632 }
633
634 static void handle_ksi_config(rsksictx ctx, KSI_AsyncService *as, KSI_Config *config) {
635 int res = KSI_UNKNOWN_ERROR;
636 KSI_Integer *intValue = NULL;
637
638 if (KSI_Config_getMaxRequests(config, &intValue) == KSI_OK && intValue != NULL) {
639 ctx->max_requests = KSI_Integer_getUInt64(intValue);
640 report(ctx, "KSI gateway has reported a max requests value of %llu", (long long unsigned)ctx->max_requests);
641
642 if (as) {
643 /* libksi expects size_t. */
644 size_t optValue = 0;
645
646 optValue = ctx->max_requests;
647 res = KSI_AsyncService_setOption(as, KSI_ASYNC_OPT_MAX_REQUEST_COUNT, (void *)optValue);
648 if (res != KSI_OK) reportKSIAPIErr(ctx, NULL, "KSI_AsyncService_setOption(max_request)", res);
649
650 optValue = 3 * ctx->max_requests * ctx->blockSigTimeout;
651 KSI_AsyncService_setOption(as, KSI_ASYNC_OPT_REQUEST_CACHE_SIZE, (void *)optValue);
652 }
653 }
654
655 intValue = NULL;
656 if (KSI_Config_getMaxLevel(config, &intValue) == KSI_OK && intValue != NULL) {
657 uint64_t newLevel = 0;
658 newLevel = KSI_Integer_getUInt64(intValue);
659 report(ctx, "KSI gateway has reported a max level value of %llu", (long long unsigned)newLevel);
660 newLevel = MIN(newLevel, ctx->blockLevelLimit);
661 if (ctx->effectiveBlockLevelLimit != newLevel) {
662 report(ctx, "Changing the configured block level limit from %llu to %llu",
663 (long long unsigned)ctx->effectiveBlockLevelLimit, (long long unsigned)newLevel);
664 ctx->effectiveBlockLevelLimit = newLevel;
665 } else if (newLevel < 2) {
666 report(ctx,
667 "KSI gateway has reported an invalid level limit value (%llu), "
668 "plugin disabled",
669 (long long unsigned)newLevel);
670 ctx->disabled = true;
671 }
672 }
673
674 intValue = NULL;
675 if (KSI_Config_getAggrPeriod(config, &intValue) == KSI_OK && intValue != NULL) {
676 uint64_t newThreadSleep = 0;
677 newThreadSleep = KSI_Integer_getUInt64(intValue);
678 report(ctx, "KSI gateway has reported an aggregation period value of %llu", (long long unsigned)newThreadSleep);
679
680 newThreadSleep = MIN(newThreadSleep, ctx->threadSleepms);
681 if (ctx->threadSleepms != newThreadSleep) {
682 report(ctx, "Changing async signer thread sleep from %llu to %llu", (long long unsigned)ctx->threadSleepms,
683 (long long unsigned)newThreadSleep);
684 ctx->threadSleepms = newThreadSleep;
685 }
686 }
687 }
688
689 static int isAggrConfNeeded(rsksictx ctx) {
690 time_t now = 0;
691
692 now = time(NULL);
693
694 if ((uint64_t)ctx->tConfRequested + ctx->confInterval <= (uint64_t)now || ctx->tConfRequested == 0) {
695 ctx->tConfRequested = now;
696 return 1;
697 }
698
699 return 0;
700 }
701
702 /* note: if file exists, the last hash for chaining must
703 * be read from file.
704 */
705 static int ksiOpenSigFile(ksifile ksi) {
706 int r = 0, tmpRes = 0;
707 const char *header;
708 FILE *signatureFile = NULL;
709
710 if (ksi->ctx->syncMode == LOGSIG_ASYNCHRONOUS)
711 header = LS12_BLOCKFILE_HEADER;
712 else
713 header = LS12_FILE_HEADER;
714
715 ksi->blockFile = ksiCreateFile(ksi->ctx, (char *)ksi->blockfilename, ksi->ctx->fileUID, ksi->ctx->fileGID,
716 ksi->ctx->fCreateMode, true, header);
717
718 if (ksi->blockFile == NULL) {
719 r = RSGTE_IO;
720 goto done;
721 }
722
723 /* create the file for ksi signatures if needed */
724 if (ksi->ctx->syncMode == LOGSIG_ASYNCHRONOUS) {
725 signatureFile = ksiCreateFile(ksi->ctx, (char *)ksi->ksifilename, ksi->ctx->fileUID, ksi->ctx->fileGID,
726 ksi->ctx->fCreateMode, true, LS12_SIGFILE_HEADER);
727
728 if (signatureFile == NULL) {
729 r = RSGTE_IO;
730 goto done;
731 }
732
733 ksi->sigFile = signatureFile;
734 queueAddNewFile(ksi->ctx, ksi);
735 }
736
737 /* we now need to obtain the last previous hash, so that
738 * we can continue the hash chain. We do not check for error
739 * as a state file error can be recovered by graceful degredation.
740 */
741 ksiReadStateFile(ksi);
742
743 if (ksi->ctx->syncMode == LOGSIG_SYNCHRONOUS) {
744 if (isAggrConfNeeded(ksi->ctx)) {
745 KSI_Config *config = NULL;
746
747 tmpRes = KSI_receiveAggregatorConfig(ksi->ctx->ksi_ctx, &config);
748 if (tmpRes == KSI_OK) {
749 handle_ksi_config(ksi->ctx, NULL, config);
750 } else {
751 reportKSIAPIErr(ksi->ctx, NULL, "KSI_receiveAggregatorConfig", tmpRes);
752 }
753 KSI_Config_free(config);
754 }
755 }
756
757 done:
758 return r;
759 }
760
761 /*
762 * As of some Linux and security expert I spoke to, /dev/urandom
763 * provides very strong random numbers, even if it runs out of
764 * entropy. As far as he knew, this is save for all applications
765 * (and he had good proof that I currently am not permitted to
766 * reproduce). -- rgerhards, 2013-03-04
767 */
768 static void seedIVKSI(ksifile ksi) {
769 int hashlen;
770 int fd;
771 const char *rnd_device = ksi->ctx->random_source ? ksi->ctx->random_source : "/dev/urandom";
772
773 hashlen = KSI_getHashLength(ksi->hashAlg);
774 ksi->IV = malloc(hashlen); /* do NOT zero-out! */
775 /*
776 * If /dev/urandom is unavailable, the current memory content is used as a
777 * weak fallback for random data. This is a theoretical case, as this
778 * library only supports Linux, where /dev/urandom is expected to be
779 * reliably available.
780 */
781 if ((fd = open(rnd_device, O_RDONLY)) >= 0) {
782 if (read(fd, ksi->IV, hashlen) == hashlen) {
783 }; /* keep compiler happy */
784 close(fd);
785 }
786 }
787
788 static int create_signer_thread(rsksictx ctx) {
789 int r;
790 if (ctx->signer_state != SIGNER_STARTED) {
791 if ((r = pthread_mutex_init(&ctx->module_lock, 0))) report(ctx, "pthread_mutex_init: %s", strerror(r));
792 ctx->signer_queue = ProtectedQueue_new(10);
793
794 ctx->signer_state = SIGNER_INIT;
795 if ((r = pthread_create(&ctx->signer_thread, NULL, signer_thread, ctx))) {
796 report(ctx, "pthread_create: %s", strerror(r));
797 ctx->signer_state = SIGNER_IDLE;
798 return RSGTE_INTERNAL;
799 }
800
801 /* Lock until init. */
802 while (*((volatile int *)&ctx->signer_state) & SIGNER_INIT);
803
804 if (ctx->signer_state != SIGNER_STARTED) {
805 return RSGTE_INTERNAL;
806 }
807 }
808
809 return RSGTE_SUCCESS;
810 }
811
812 rsksictx rsksiCtxNew(void) {
813 rsksictx ctx;
814 ctx = calloc(1, sizeof(struct rsksictx_s));
815 KSI_CTX_new(&ctx->ksi_ctx); // TODO: error check (probably via a generic macro?)
816 ctx->hasher = NULL;
817 ctx->hashAlg = KSI_getHashAlgorithmByName("default");
818 ctx->blockTimeLimit = 0;
819 ctx->bKeepTreeHashes = false;
820 ctx->bKeepRecordHashes = true;
821 ctx->max_requests = (1 << 8);
822 ctx->blockSigTimeout = 10;
823 ctx->confInterval = 3600;
824 ctx->tConfRequested = 0;
825 ctx->threadSleepms = 1000;
826 ctx->errFunc = NULL;
827 ctx->usrptr = NULL;
828 ctx->fileUID = -1;
829 ctx->fileGID = -1;
830 ctx->dirUID = -1;
831 ctx->dirGID = -1;
832 ctx->fCreateMode = 0644;
833 ctx->fDirCreateMode = 0700;
834 #if KSI_SDK_VER_MAJOR == 3 && KSI_SDK_VER_MINOR < 22
835 ctx->roundCount = 0;
836 ctx->bRoundLock = 0;
837 #endif
838 ctx->syncMode = LOGSIG_SYNCHRONOUS;
839 ctx->signer_state = SIGNER_IDLE;
840 ctx->disabled = false;
841 ctx->ksi = NULL;
842
843 /*if (pthread_mutex_init(&ctx->module_lock, 0))
844 report(ctx, "pthread_mutex_init: %s", strerror(errno));
845 ctx->signer_queue = ProtectedQueue_new(10);*/
846
847 /* Creating a thread this way works only in daemon mode but not when being run
848 interactively when not forked */
849 /*ret = pthread_atfork(NULL, NULL, create_signer_thread);
850 if (ret != 0)
851 report(ctx, "pthread_atfork error: %s", strerror(ret));*/
852
853 return ctx;
854 }
855
856 static int rsksiStreamLogger(void *logCtx, int logLevel, const char *message) {
857 char time_buf[32];
858 struct tm *tm_info;
859 time_t timer;
860 FILE *f = (FILE *)logCtx;
861
862 timer = time(NULL);
863
864 tm_info = localtime(&timer);
865 if (tm_info == NULL) {
866 return KSI_UNKNOWN_ERROR;
867 }
868
869 if (f != NULL) {
870 flockfile(f); /* for thread safety */
871 if (strftime(time_buf, sizeof(time_buf), "%d.%m.%Y %H:%M:%S", tm_info)) {
872 if (fprintf(f, "%s [%s] %lu - %s\n", level2str(logLevel), time_buf, pthread_self(), message) > 0) {
873 }
874 }
875 funlockfile(f);
876 }
877
878 return KSI_OK;
879 }
880
881 int rsksiInitModule(rsksictx ctx) {
882 int res = 0;
883
884 if (ctx->debugFileName != NULL) {
885 ctx->debugFile = fopen(ctx->debugFileName, "w");
886 if (ctx->debugFile) {
887 res = KSI_CTX_setLoggerCallback(ctx->ksi_ctx, rsksiStreamLogger, ctx->debugFile);
888 if (res != KSI_OK) reportKSIAPIErr(ctx, NULL, "Unable to set logger callback", res);
889 res = KSI_CTX_setLogLevel(ctx->ksi_ctx, ctx->debugLevel);
890 if (res != KSI_OK) reportKSIAPIErr(ctx, NULL, "Unable to set log level", res);
891 } else {
892 report(ctx, "Could not open logfile %s: %s", ctx->debugFileName, strerror(errno));
893 }
894 }
895
896 KSI_CTX_setOption(ctx->ksi_ctx, KSI_OPT_AGGR_HMAC_ALGORITHM, (void *)((size_t)ctx->hmacAlg));
897
898 return create_signer_thread(ctx);
899 }
900
901 /* either returns ksifile object or NULL if something went wrong */
902 ksifile rsksiCtxOpenFile(rsksictx ctx, unsigned char *logfn) {
903 int ret = RSGTE_INTERNAL;
904 ksifile ksi;
905 char fn[MAXFNAME + 1];
906
907 if (ctx->disabled) return NULL;
908
909 pthread_mutex_lock(&ctx->module_lock);
910
911 /* The thread cannot be be created in rsksiCtxNew because in daemon mode the
912 process forks after rsksiCtxNew and the thread disappears */
913 if (ctx->signer_state != SIGNER_STARTED) {
914 ret = rsksiInitModule(ctx);
915 if (ret != RSGTE_SUCCESS) {
916 report(ctx, "Unable to init. KSI module, signing service disabled");
917 ctx->disabled = true;
918 pthread_mutex_unlock(&ctx->module_lock);
919 return NULL;
920 }
921 }
922
923 if ((ksi = rsksifileConstruct(ctx)) == NULL) goto done;
924
925 snprintf(fn, sizeof(fn), "%s.ksistate", logfn);
926 fn[MAXFNAME] = '\0'; /* be on safe side */
927 ksi->statefilename = (uchar *)strdup(fn);
928
929 if (ctx->syncMode == LOGSIG_ASYNCHRONOUS) {
930 /* filename for blocks of hashes*/
931 snprintf(fn, sizeof(fn), "%s%s", logfn, blockFileSuffix);
932 fn[MAXFNAME] = '\0'; /* be on safe side */
933 ksi->blockfilename = (uchar *)strdup(fn);
934
935 /* filename for KSI signatures*/
936 snprintf(fn, sizeof(fn), "%s%s", logfn, sigFileSuffix);
937 fn[MAXFNAME] = '\0'; /* be on safe side */
938 ksi->ksifilename = (uchar *)strdup(fn);
939 } else if (ctx->syncMode == LOGSIG_SYNCHRONOUS) {
940 snprintf(fn, sizeof(fn), "%s%s", logfn, ls12FileSuffix);
941 fn[MAXFNAME] = '\0'; /* be on safe side */
942 ksi->blockfilename = (uchar *)strdup(fn);
943 }
944
945 if (ksiOpenSigFile(ksi) != 0) {
946 reportErr(ctx, "signature file open failed");
947 /* Free memory */
948 free(ksi);
949 ksi = NULL;
950 }
951
952 done:
953 /* Register ksi file in rsksictx for keeping track of block timeouts. */
954 rsksiRegisterKsiFile(ctx, ksi);
955 pthread_mutex_unlock(&ctx->module_lock);
956 return ksi;
957 }
958
959
960 /* Returns RSGTE_SUCCESS on success, error code otherwise. If algo is unknown or
961 * is not trusted, default hash function is used.
962 */
963 int rsksiSetHashFunction(rsksictx ctx, char *algName) {
964 if (ctx == NULL || algName == NULL) {
965 return RSGTE_INTERNAL;
966 }
967
968 int r, id = KSI_getHashAlgorithmByName(algName);
969 if (!KSI_isHashAlgorithmSupported(id)) {
970 report(ctx, "Hash function '%s' is not supported - using default", algName);
971 ctx->hashAlg = KSI_getHashAlgorithmByName("default");
972 } else {
973 if (!KSI_isHashAlgorithmTrusted(id)) {
974 report(ctx, "Hash function '%s' is not trusted - using default", algName);
975 ctx->hashAlg = KSI_getHashAlgorithmByName("default");
976 } else
977 ctx->hashAlg = id;
978 }
979
980 if ((r = KSI_DataHasher_open(ctx->ksi_ctx, ctx->hashAlg, &ctx->hasher)) != KSI_OK) {
981 reportKSIAPIErr(ctx, NULL, "KSI_DataHasher_open", r);
982 ctx->disabled = true;
983 return r;
984 }
985
986 return RSGTE_SUCCESS;
987 }
988
989 int rsksiSetHmacFunction(rsksictx ctx, char *algName) {
990 int id = KSI_getHashAlgorithmByName(algName);
991 if (!KSI_isHashAlgorithmSupported(id)) {
992 report(ctx, "HMAC function '%s' is not supported - using default", algName);
993 ctx->hmacAlg = KSI_getHashAlgorithmByName("default");
994 } else {
995 if (!KSI_isHashAlgorithmTrusted(id)) {
996 report(ctx, "HMAC function '%s' is not trusted - using default", algName);
997 ctx->hmacAlg = KSI_getHashAlgorithmByName("default");
998 } else
999 ctx->hmacAlg = id;
1000 }
1001 return 0;
1002 }
1003
1004 int rsksifileDestruct(ksifile ksi) {
1005 int r = 0;
1006 rsksictx ctx = NULL;
1007 if (ksi == NULL) return RSGTE_INTERNAL;
1008
1009 pthread_mutex_lock(&ksi->ctx->module_lock);
1010
1011 ctx = ksi->ctx;
1012
1013 /* Deregister ksifile so it is not used by signer thread anymore. Note that files are not closed yet! */
1014 rsksiDeregisterKsiFile(ctx, ksi);
1015
1016 if (!ksi->disabled && ksi->bInBlk) {
1017 sigblkAddMetadata(ksi, blockCloseReason, "Block closed due to file closure.");
1018 r = sigblkFinishKSI(ksi);
1019 }
1020 /* Note that block file is closed immediately but signature file will be closed
1021 * by the signer thread scheduled by signer thread work queue.
1022 */
1023 if (!ksi->disabled) r = ksiCloseSigFile(ksi);
1024 free(ksi->blockfilename);
1025 free(ksi->statefilename);
1026 free(ksi->ksifilename);
1027
1028 free(ksi);
1029
1030 pthread_mutex_unlock(&ctx->module_lock);
1031 return r;
1032 }
1033
1034 /* This can only be used when signer thread has terminated or within the thread. */
1035 static void rsksifileForceFree(ksifile ksi) {
1036 if (ksi == NULL) return;
1037
1038 if (ksi->sigFile != NULL) fclose(ksi->sigFile);
1039 if (ksi->blockFile != NULL) fclose(ksi->blockFile);
1040 free(ksi->blockfilename);
1041 free(ksi->statefilename);
1042 free(ksi->ksifilename);
1043 free(ksi);
1044 return;
1045 }
1046
1047 /* This can only be used when signer thread has terminated or within the thread. */
1048 static void rsksictxForceFreeSignatures(rsksictx ctx) {
1049 size_t i = 0;
1050
1051 if (ctx == NULL || ctx->ksi == NULL) return;
1052
1053 for (i = 0; i < ctx->ksiCount; i++) {
1054 if (ctx->ksi[i] != NULL) {
1055 rsksifileForceFree(ctx->ksi[i]);
1056 ctx->ksi[i] = NULL;
1057 }
1058 }
1059
1060 ctx->ksiCount = 0;
1061 return;
1062 }
1063
1064 /* This can only be used when signer thread has terminated or within the thread. */
1065 static int rsksictxForceCloseWithoutSig(rsksictx ctx, const char *reason) {
1066 size_t i = 0;
1067 if (ctx == NULL || ctx->ksi == NULL) return RSGTE_INTERNAL;
1068 for (i = 0; i < ctx->ksiCount; i++) {
1069 if (ctx->ksi[i] != NULL) {
1070 int ret = RSGTE_INTERNAL;
1071
1072 /* Only if block contains records, create metadata, close the block and add
1073 * no signature marker. Closing block without record will produce redundant
1074 * blocks that needs to be signed afterward.
1075 */
1076 if (ctx->ksi[i]->nRecords > 0) {
1077 ret = sigblkFinishKSINoSignature(ctx->ksi[i], reason);
1078 if (ret != RSGTE_SUCCESS) return ret;
1079 }
1080
1081 /* Free files and remove object from the list. */
1082 rsksifileForceFree(ctx->ksi[i]);
1083 ctx->ksi[i] = NULL;
1084 }
1085 }
1086
1087 ctx->ksiCount = 0;
1088 return RSGTE_SUCCESS;
1089 }
1090
1091 void rsksiCtxDel(rsksictx ctx) {
1092 if (ctx == NULL) return;
1093
1094 /* Note that even in sync. mode signer thread is created and needs to be closed
1095 * correctly.
1096 */
1097 if (ctx->signer_state == SIGNER_STARTED) {
1098 queueAddQuit(ctx);
1099 /* Wait until thread closes to be able to safely free the resources. */
1100 pthread_join(ctx->signer_thread, NULL);
1101 ProtectedQueue_free(ctx->signer_queue);
1102 pthread_mutex_destroy(&ctx->module_lock);
1103 }
1104
1105 free(ctx->aggregatorUri);
1106 free(ctx->aggregatorId);
1107 free(ctx->aggregatorKey);
1108 free(ctx->debugFileName);
1109
1110 if (ctx->random_source) free(ctx->random_source);
1111
1112 KSI_DataHasher_free(ctx->hasher);
1113 KSI_CTX_free(ctx->ksi_ctx);
1114
1115 if (ctx->debugFile != NULL) fclose(ctx->debugFile);
1116
1117 /* After signer thread is terminated there should be no open signature files,
1118 * but to be extra sure that all files are closed, recheck the list of opened
1119 * signature files.
1120 */
1121 rsksictxForceFreeSignatures(ctx);
1122 free(ctx->ksi);
1123
1124 free(ctx);
1125 }
1126
1127 /* new sigblk is initialized, but maybe in existing ctx */
1128 void sigblkInitKSI(ksifile ksi) {
1129 if (ksi == NULL) goto done;
1130 seedIVKSI(ksi);
1131 memset(ksi->roots, 0, sizeof(ksi->roots));
1132 ksi->nRoots = 0;
1133 ksi->nRecords = 0;
1134 ksi->bInBlk = 1;
1135 ksi->blockStarted = time(NULL);
1136 ksi->blockSizeLimit = 1 << (ksi->ctx->effectiveBlockLevelLimit - 1);
1137
1138 /* flush the optional debug file when starting a new block */
1139 if (ksi->ctx->debugFile != NULL) fflush(ksi->ctx->debugFile);
1140
1141 done:
1142 return;
1143 }
1144
1145 int sigblkCreateMask(ksifile ksi, KSI_DataHash **m) {
1146 int r = 0;
1147
1148 CHKr(KSI_DataHasher_reset(ksi->ctx->hasher));
1149 CHKr(KSI_DataHasher_add(ksi->ctx->hasher, ksi->lastLeaf, KSI_getHashLength(ksi->lastLeaf[0]) + 1));
1150 CHKr(KSI_DataHasher_add(ksi->ctx->hasher, ksi->IV, KSI_getHashLength(ksi->hashAlg)));
1151 CHKr(KSI_DataHasher_close(ksi->ctx->hasher, m));
1152
1153 done:
1154 if (r != KSI_OK) {
1155 reportKSIAPIErr(ksi->ctx, ksi, "KSI_DataHasher", r);
1156 r = RSGTE_HASH_CREATE;
1157 }
1158 return r;
1159 }
1160 int sigblkCreateHash(ksifile ksi, KSI_DataHash **out, const uchar *rec, const size_t len) {
1161 int r = 0;
1162
1163 CHKr(KSI_DataHasher_reset(ksi->ctx->hasher));
1164 CHKr(KSI_DataHasher_add(ksi->ctx->hasher, rec, len));
1165 CHKr(KSI_DataHasher_close(ksi->ctx->hasher, out));
1166
1167 done:
1168 if (r != KSI_OK) {
1169 reportKSIAPIErr(ksi->ctx, ksi, "KSI_DataHasher", r);
1170 r = RSGTE_HASH_CREATE;
1171 }
1172
1173 return r;
1174 }
1175
1176
1177 int sigblkHashTwoNodes(ksifile ksi, KSI_DataHash **out, KSI_DataHash *left, KSI_DataHash *right, uint8_t level) {
1178 int r = 0;
1179
1180 CHKr(KSI_DataHasher_reset(ksi->ctx->hasher));
1181 CHKr(KSI_DataHasher_addImprint(ksi->ctx->hasher, left));
1182 CHKr(KSI_DataHasher_addImprint(ksi->ctx->hasher, right));
1183 CHKr(KSI_DataHasher_add(ksi->ctx->hasher, &level, 1));
1184 CHKr(KSI_DataHasher_close(ksi->ctx->hasher, out));
1185
1186 done:
1187 if (r != KSI_OK) {
1188 reportKSIAPIErr(ksi->ctx, ksi, "KSI_DataHash_create", r);
1189 r = RSGTE_HASH_CREATE;
1190 }
1191
1192 return r;
1193 }
1194 int sigblkAddMetadata(ksifile ksi, const char *key, const char *value) {
1195 unsigned char buffer[0xFFFF];
1196 size_t encoded_size = 0;
1197 int ret = 0;
1198
1199 tlvCreateMetadata(ksi, ksi->nRecords, key, value, buffer, &encoded_size);
1200 sigblkAddLeaf(ksi, buffer, encoded_size, true);
1201
1202 return ret;
1203 }
1204
1205 int sigblkAddRecordKSI(ksifile ksi, const uchar *rec, const size_t len) {
1206 int ret = 0;
1207 if (ksi == NULL || ksi->disabled) return 0;
1208
1209 pthread_mutex_lock(&ksi->ctx->module_lock);
1210
1211 if ((ret = sigblkAddLeaf(ksi, rec, len, false)) != 0) goto done;
1212
1213 if (ksi->nRecords == ksi->blockSizeLimit) {
1214 sigblkFinishKSI(ksi);
1215 sigblkInitKSI(ksi);
1216 }
1217
1218 done:
1219 pthread_mutex_unlock(&ksi->ctx->module_lock);
1220 return ret;
1221 }
1222
1223
1224 int sigblkAddLeaf(ksifile ksi, const uchar *leafData, const size_t leafLength, bool metadata) {
1225 KSI_DataHash *mask, *leafHash, *treeNode, *tmpTreeNode;
1226 uint8_t j;
1227 const unsigned char *pTmp;
1228 size_t len;
1229
1230 int r = 0;
1231
1232 if (ksi == NULL || ksi->disabled) goto done;
1233 CHKr(sigblkCreateMask(ksi, &mask));
1234 CHKr(sigblkCreateHash(ksi, &leafHash, leafData, leafLength));
1235
1236 if (ksi->nRecords == 0) tlvWriteBlockHdrKSI(ksi);
1237
1238 /* metadata record has to be written into the block file too*/
1239 if (metadata) tlvWriteOctetString(ksi->blockFile, leafData, leafLength);
1240
1241 if (ksi->bKeepRecordHashes) tlvWriteHashKSI(ksi, 0x0902, leafHash);
1242
1243 /* normal leaf and metadata record are hashed in different order */
1244 if (!metadata) { /* hash leaf */
1245 if ((r = sigblkHashTwoNodes(ksi, &treeNode, mask, leafHash, 1)) != 0) goto done;
1246 } else {
1247 if ((r = sigblkHashTwoNodes(ksi, &treeNode, leafHash, mask, 1)) != 0) goto done;
1248 }
1249
1250 /* persists x here if Merkle tree needs to be persisted! */
1251 if (ksi->bKeepTreeHashes) tlvWriteHashKSI(ksi, 0x0903, treeNode);
1252
1253 KSI_DataHash_getImprint(treeNode, &pTmp, &len);
1254 memcpy(ksi->lastLeaf, pTmp, len);
1255
1256 for (j = 0; j < ksi->nRoots; ++j) {
1257 if (ksi->roots[j] == NULL) {
1258 ksi->roots[j] = treeNode;
1259 treeNode = NULL;
1260 break;
1261 } else if (treeNode != NULL) {
1262 /* hash interim node */
1263 tmpTreeNode = treeNode;
1264 r = sigblkHashTwoNodes(ksi, &treeNode, ksi->roots[j], tmpTreeNode, j + 2);
1265 KSI_DataHash_free(ksi->roots[j]);
1266 ksi->roots[j] = NULL;
1267 KSI_DataHash_free(tmpTreeNode);
1268 if (r != 0) goto done;
1269 if (ksi->bKeepTreeHashes) tlvWriteHashKSI(ksi, 0x0903, treeNode);
1270 }
1271 }
1272 if (treeNode != NULL) {
1273 /* new level, append "at the top" */
1274 ksi->roots[ksi->nRoots] = treeNode;
1275 ++ksi->nRoots;
1276 assert(ksi->nRoots < MAX_ROOTS);
1277 treeNode = NULL;
1278 }
1279 ++ksi->nRecords;
1280
1281 /* cleanup (x is cleared as part of the roots array) */
1282 KSI_DataHash_free(mask);
1283 KSI_DataHash_free(leafHash);
1284
1285 done:
1286 return r;
1287 }
1288
1289 static int sigblkCheckTimeOut(rsksictx ctx) {
1290 int ret = RSGTE_INTERNAL;
1291 time_t now;
1292 char buf[KSI_BUF_SIZE];
1293 size_t i = 0;
1294
1295 if (ctx == NULL) {
1296 return RSGTE_INTERNAL;
1297 }
1298
1299 pthread_mutex_lock(&ctx->module_lock);
1300
1301 if (ctx->ksi == NULL || ctx->disabled || !ctx->blockTimeLimit) {
1302 ret = RSGTE_SUCCESS;
1303 goto done;
1304 }
1305
1306 now = time(NULL);
1307
1308 for (i = 0; i < ctx->ksiCount; i++) {
1309 ksifile ksi = ctx->ksi[i];
1310
1311 if (ksi == NULL) continue; /* To avoide unexpected crash. */
1312 if (!ksi->bInBlk) continue; /* Not inside a block, nothing to close nor sign. */
1313 if ((time_t)(ksi->blockStarted + ctx->blockTimeLimit) > now) continue;
1314
1315 snprintf(buf, KSI_BUF_SIZE, "Block closed due to reaching time limit %d", ctx->blockTimeLimit);
1316 sigblkAddMetadata(ksi, blockCloseReason, buf);
1317 sigblkFinishKSI(ksi);
1318 sigblkInitKSI(ksi);
1319 }
1320
1321 done:
1322 pthread_mutex_unlock(&ctx->module_lock);
1323 return ret;
1324 }
1325
1326
1327 static int sigblkSign(ksifile ksi, KSI_DataHash *hash, int level) {
1328 unsigned char *der = NULL;
1329 size_t lenDer = 0;
1330 int r = KSI_OK;
1331 int ret = 0;
1332 KSI_Signature *sig = NULL;
1333
1334 /* Sign the root hash. */
1335 r = KSI_Signature_signAggregated(ksi->ctx->ksi_ctx, hash, level, &sig);
1336 if (r != KSI_OK) {
1337 reportKSIAPIErr(ksi->ctx, ksi, "KSI_Signature_createAggregated", r);
1338 ret = 1;
1339 goto signing_done;
1340 }
1341
1342 /* Serialize Signature. */
1343 r = KSI_Signature_serialize(sig, &der, &lenDer);
1344 if (r != KSI_OK) {
1345 reportKSIAPIErr(ksi->ctx, ksi, "KSI_Signature_serialize", r);
1346 ret = 1;
1347 lenDer = 0;
1348 goto signing_done;
1349 }
1350
1351 signing_done:
1352 /* if signing failed the signature will be written as zero size */
1353 if (r == KSI_OK) {
1354 r = tlvWriteKSISigLS12(ksi->blockFile, ksi->nRecords, der, lenDer);
1355 if (r != KSI_OK) {
1356 reportKSIAPIErr(ksi->ctx, ksi, "tlvWriteKSISigLS12", r);
1357 ret = 1;
1358 }
1359 } else
1360 r = tlvWriteNoSigLS12(ksi->blockFile, ksi->nRecords, hash, KSI_getErrorString(r));
1361
1362 if (r != KSI_OK) {
1363 reportKSIAPIErr(ksi->ctx, ksi, "tlvWriteBlockSigKSI", r);
1364 ret = 1;
1365 }
1366
1367 if (sig != NULL) KSI_Signature_free(sig);
1368 if (der != NULL) KSI_free(der);
1369 return ret;
1370 }
1371
1372 unsigned sigblkCalcLevel(unsigned leaves) {
1373 unsigned level = 0;
1374 unsigned c = leaves;
1375 while (c > 1) {
1376 level++;
1377 c >>= 1;
1378 }
1379
1380 if (1 << level < (int)leaves) level++;
1381
1382 return level;
1383 }
1384
1385 static int sigblkFinishTree(ksifile ksi, KSI_DataHash **hsh) {
1386 int ret = RSGTE_INTERNAL;
1387 KSI_DataHash *root = NULL;
1388 KSI_DataHash *rootDel = NULL;
1389 int8_t j = 0;
1390
1391 if (ksi == NULL || hsh == NULL) {
1392 goto done;
1393 }
1394
1395 if (ksi->nRecords == 0) {
1396 ret = RSGTE_SUCCESS;
1397 goto done;
1398 }
1399
1400 root = NULL;
1401 for (j = 0; j < ksi->nRoots; ++j) {
1402 if (root == NULL) {
1403 root = ksi->roots[j];
1404 ksi->roots[j] = NULL;
1405 } else if (ksi->roots[j] != NULL) {
1406 rootDel = root;
1407 root = NULL;
1408 ret = sigblkHashTwoNodes(ksi, &root, ksi->roots[j], rootDel, j + 2);
1409 KSI_DataHash_free(ksi->roots[j]);
1410 ksi->roots[j] = NULL;
1411 KSI_DataHash_free(rootDel);
1412 rootDel = NULL;
1413 if (ksi->bKeepTreeHashes) {
1414 tlvWriteHashKSI(ksi, 0x0903, root);
1415 }
1416 if (ret != KSI_OK) goto done; /* checks sigblkHashTwoNodes() result! */
1417 }
1418 }
1419
1420 *hsh = root;
1421 root = NULL;
1422 ret = RSGTE_SUCCESS;
1423
1424 done:
1425 KSI_DataHash_free(root);
1426 KSI_DataHash_free(rootDel);
1427 return ret;
1428 }
1429
1430
1431 int sigblkFinishKSI(ksifile ksi) {
1432 KSI_DataHash *root = NULL;
1433 int ret = RSGTE_INTERNAL;
1434 unsigned level = 0;
1435
1436 if (ksi == NULL) {
1437 goto done;
1438 }
1439
1440 if (ksi->nRecords == 0) {
1441 ret = RSGTE_SUCCESS;
1442 goto done;
1443 }
1444
1445 ret = sigblkFinishTree(ksi, &root);
1446 if (ret != RSGTE_SUCCESS) goto done;
1447
1448 // Multiplying leaves count by 2 to account for blinding masks
1449 level = sigblkCalcLevel(2 * ksi->nRecords);
1450
1451 // in case of async mode we append the root hash to signer queue
1452 if (ksi->ctx->syncMode == LOGSIG_ASYNCHRONOUS) {
1453 ret = tlvWriteNoSigLS12(ksi->blockFile, ksi->nRecords, root, NULL);
1454 if (ret != KSI_OK) {
1455 reportKSIAPIErr(ksi->ctx, ksi, "tlvWriteNoSigLS12", ret);
1456 goto done;
1457 }
1458
1459 queueAddSignRequest(ksi->ctx, ksi, root, level);
1460 root = NULL;
1461 } else {
1462 sigblkSign(ksi, root, level);
1463 }
1464
1465 ret = RSGTE_SUCCESS;
1466
1467 done:
1468 KSI_DataHash_free(root);
1469 free(ksi->IV);
1470 ksi->IV = NULL;
1471 ksi->bInBlk = 0;
1472 return ret;
1473 }
1474
1475 static int sigblkFinishKSINoSignature(ksifile ksi, const char *reason) {
1476 KSI_DataHash *root = NULL;
1477 int ret = RSGTE_INTERNAL;
1478
1479 if (ksi == NULL || ksi->ctx == NULL || (ksi->ctx->syncMode == LOGSIG_ASYNCHRONOUS && ksi->sigFile == NULL) ||
1480 ksi->blockFile == NULL || reason == NULL) {
1481 goto done;
1482 }
1483
1484 ret = sigblkAddMetadata(ksi, blockCloseReason, reason);
1485 if (ret != RSGTE_SUCCESS) goto done;
1486
1487 ret = sigblkFinishTree(ksi, &root);
1488 if (ret != RSGTE_SUCCESS) goto done;
1489
1490 ret = tlvWriteNoSigLS12(ksi->blockFile, ksi->nRecords, root, reason);
1491 if (ret != KSI_OK) {
1492 reportKSIAPIErr(ksi->ctx, ksi, "tlvWriteNoSigLS12", ret);
1493 goto done;
1494 }
1495
1496 if (ksi->ctx->syncMode == LOGSIG_ASYNCHRONOUS) {
1497 ret = tlvWriteNoSigLS12(ksi->sigFile, ksi->nRecords, root, reason);
1498 if (ret != KSI_OK) {
1499 reportKSIAPIErr(ksi->ctx, ksi, "tlvWriteNoSigLS12", ret);
1500 goto done;
1501 }
1502 }
1503
1504 ret = RSGTE_SUCCESS;
1505
1506 done:
1507 KSI_DataHash_free(root);
1508 free(ksi->IV);
1509 ksi->IV = NULL;
1510 ksi->bInBlk = 0;
1511 return ret;
1512 }
1513
1514 int rsksiSetAggregator(rsksictx ctx, char *uri, char *loginid, char *key) {
1515 int r;
1516 char *strTmp, *strTmpUri;
1517
1518 /* only use the strings if they are not empty */
1519 ctx->aggregatorUri = (uri != NULL && strlen(uri) != 0) ? strdup(uri) : NULL;
1520 ctx->aggregatorId = (loginid != NULL && strlen(loginid) != 0) ? strdup(loginid) : NULL;
1521 ctx->aggregatorKey = (key != NULL && strlen(key) != 0) ? strdup(key) : NULL;
1522
1523 /* split the URI string up for possible HA endpoints */
1524 strTmp = ctx->aggregatorUri;
1525 while ((strTmpUri = strsep(&strTmp, "|")) != NULL) {
1526 if (ctx->aggregatorEndpointCount >= KSI_CTX_HA_MAX_SUBSERVICES) {
1527 report(ctx, "Maximum number (%d) of service endoints reached, ignoring endpoint: %s",
1528 KSI_CTX_HA_MAX_SUBSERVICES, strTmpUri);
1529 } else {
1530 ctx->aggregatorEndpoints[ctx->aggregatorEndpointCount] = strTmpUri;
1531 ctx->aggregatorEndpointCount++;
1532 }
1533 }
1534
1535 r = KSI_CTX_setAggregator(ctx->ksi_ctx, ctx->aggregatorUri, ctx->aggregatorId, ctx->aggregatorKey);
1536 if (r != KSI_OK) {
1537 ctx->disabled = true;
1538 reportKSIAPIErr(ctx, NULL, "KSI_CTX_setAggregator", r);
1539 return KSI_INVALID_ARGUMENT;
1540 }
1541
1542 return r;
1543 }
1544
1545
1546 int rsksiSetDebugFile(rsksictx ctx, char *val) {
1547 if (!val) return KSI_INVALID_ARGUMENT;
1548
1549 ctx->debugFileName = strdup(val);
1550 return KSI_OK;
1551 }
1552
1553 static bool add_queue_item(
1554 rsksictx ctx, QITEM_type type, KSI_DataHash *root, FILE *sigFile, uint64_t intarg1, uint64_t intarg2) {
1555 QueueItem *qi = (QueueItem *)malloc(sizeof(QueueItem));
1556 if (!qi) {
1557 ctx->disabled = true;
1558 return false;
1559 }
1560
1561 qi->root = root;
1562 qi->file = sigFile;
1563
1564 qi->type = type;
1565 qi->status = QITEM_WAITING;
1566 qi->intarg1 = intarg1;
1567 qi->intarg2 = intarg2;
1568 qi->respHandle = NULL;
1569 qi->ksi_status = KSI_UNKNOWN_ERROR;
1570 qi->request_time = time(NULL);
1571 if (ProtectedQueue_addItem(ctx->signer_queue, qi) == false) {
1572 ctx->disabled = true;
1573 free(qi);
1574 return false;
1575 }
1576 return true;
1577 }
1578
1579 static bool queueAddCloseFile(rsksictx ctx, ksifile ksi) {
1580 return add_queue_item(ctx, QITEM_CLOSE_FILE, NULL, ksi->sigFile, 0, 0);
1581 }
1582
1583 static bool queueAddNewFile(rsksictx ctx, ksifile ksi) {
1584 return add_queue_item(ctx, QITEM_NEW_FILE, NULL, ksi->sigFile, time(NULL) + ctx->blockTimeLimit, 0);
1585 }
1586
1587 static bool queueAddQuit(rsksictx ctx) {
1588 return add_queue_item(ctx, QITEM_QUIT, NULL, NULL, 0, 0);
1589 }
1590
1591 static bool queueAddSignRequest(rsksictx ctx, ksifile ksi, KSI_DataHash *root, unsigned level) {
1592 return add_queue_item(ctx, QITEM_SIGNATURE_REQUEST, root, ksi->sigFile, ksi->nRecords, level);
1593 }
1594
1595 static bool save_response(rsksictx ctx, FILE *outfile, QueueItem *item) {
1596 bool ret = false;
1597 KSI_Signature *sig = NULL;
1598 unsigned char *raw = NULL;
1599 size_t raw_len;
1600 int res = KSI_OK;
1601
1602 if (item->respHandle != NULL && item->ksi_status == KSI_OK) {
1603 CHECK_KSI_API(KSI_AsyncHandle_getSignature(item->respHandle, &sig), ctx, "KSI_AsyncHandle_getSignature");
1604 CHECK_KSI_API(KSI_Signature_serialize(sig, &raw, &raw_len), ctx, "KSI_Signature_serialize");
1605 tlvWriteKSISigLS12(outfile, item->intarg1, raw, raw_len);
1606 KSI_free(raw);
1607 } else {
1608 tlvWriteNoSigLS12(outfile, item->intarg1, item->root, KSI_getErrorString(item->ksi_status));
1609 }
1610 ret = true;
1611
1612 cleanup:
1613 if (res != KSI_OK) tlvWriteNoSigLS12(outfile, item->intarg1, item->root, KSI_getErrorString(res));
1614
1615 KSI_Signature_free(sig);
1616
1617 return ret;
1618 }
1619
1620 static KSI_DataHash *clone_hash(KSI_CTX *ksi_ctx, const KSI_DataHash *hash) {
1621 int res = KSI_UNKNOWN_ERROR;
1622 const unsigned char *imprint = NULL;
1623 size_t imprint_len = 0;
1624 KSI_DataHash *tmp = NULL;
1625
1626 if (hash == NULL) return NULL;
1627 res = KSI_DataHash_getImprint(hash, &imprint, &imprint_len);
1628 if (res != KSI_OK) return NULL;
1629 res = KSI_DataHash_fromImprint(ksi_ctx, imprint, imprint_len, &tmp);
1630 if (res != KSI_OK) return NULL;
1631
1632 return tmp;
1633 }
1634
1635 static bool process_requests_async(rsksictx ctx, KSI_CTX *ksi_ctx, KSI_AsyncService *as) {
1636 bool ret = false;
1637 QueueItem *item = NULL;
1638 int res = KSI_OK, tmpRes;
1639 KSI_AsyncHandle *reqHandle = NULL;
1640 KSI_AsyncHandle *respHandle = NULL;
1641 KSI_DataHash *clonedHash = NULL;
1642 KSI_AggregationReq *req = NULL;
1643 KSI_Config *config = NULL;
1644 KSI_Integer *level;
1645 long extError;
1646 KSI_Utf8String *errorMsg;
1647 int state, ksi_status;
1648 unsigned i;
1649 size_t p;
1650
1651 KSI_AsyncService_getPendingCount(as, &p);
1652
1653 /* Check if there are pending/available responses and associate them with the request items */
1654 while (true) {
1655 respHandle = NULL;
1656 item = NULL;
1657 tmpRes = KSI_AsyncService_run(as, &respHandle, &p);
1658 if (tmpRes != KSI_OK) reportKSIAPIErr(ctx, NULL, "KSI_AsyncService_run", tmpRes);
1659
1660 if (respHandle == NULL) { /* nothing received */
1661 break;
1662 }
1663
1664 #if KSI_SDK_VER_MAJOR == 3 && KSI_SDK_VER_MINOR < 22
1665 if (p != 0 && ctx->roundCount > 0) {
1666 ctx->roundCount--;
1667 } else {
1668 ctx->bRoundLock = 0;
1669 ctx->roundCount = 0;
1670 }
1671 #endif
1672 state = KSI_ASYNC_STATE_UNDEFINED;
1673
1674 CHECK_KSI_API(KSI_AsyncHandle_getState(respHandle, &state), ctx, "KSI_AsyncHandle_getState");
1675
1676 if (state == KSI_ASYNC_STATE_PUSH_CONFIG_RECEIVED) {
1677 res = KSI_AsyncHandle_getConfig(respHandle, &config);
1678 if (res == KSI_OK) {
1679 handle_ksi_config(ctx, as, config);
1680 KSI_AsyncHandle_free(respHandle);
1681 } else
1682 reportKSIAPIErr(ctx, NULL, "KSI_AsyncHandle_getConfig", res);
1683 } else if (state == KSI_ASYNC_STATE_RESPONSE_RECEIVED) {
1684 CHECK_KSI_API(KSI_AsyncHandle_getRequestCtx(respHandle, (const void **)&item), ctx,
1685 "KSI_AsyncHandle_getRequestCtx");
1686 item->respHandle = respHandle;
1687 item->ksi_status = KSI_OK;
1688 } else if (state == KSI_ASYNC_STATE_ERROR) {
1689 CHECK_KSI_API(KSI_AsyncHandle_getRequestCtx(respHandle, (const void **)&item), ctx,
1690 "KSI_AsyncHandle_getRequestCtx");
1691 errorMsg = NULL;
1692 KSI_AsyncHandle_getError(respHandle, &ksi_status);
1693 KSI_AsyncHandle_getExtError(respHandle, &extError);
1694 KSI_AsyncHandle_getErrorMessage(respHandle, &errorMsg);
1695 report(ctx, "Asynchronous request returned error %s (%d), %lu %s", KSI_getErrorString(ksi_status),
1696 ksi_status, extError, errorMsg ? KSI_Utf8String_cstr(errorMsg) : "");
1697 KSI_AsyncHandle_free(respHandle);
1698
1699 if (item) item->ksi_status = ksi_status;
1700 }
1701
1702 if (item) item->status = QITEM_DONE;
1703 }
1704
1705 KSI_AsyncService_getPendingCount(as, &p);
1706
1707 /* Send all the new requests in the back of the queue to the server */
1708 for (i = 0; i < ProtectedQueue_count(ctx->signer_queue); i++) {
1709 item = NULL;
1710 if (!ProtectedQueue_getItem(ctx->signer_queue, i, (void **)&item) || !item) continue;
1711 /* ingore non request queue items */
1712 if (item->type != QITEM_SIGNATURE_REQUEST) continue;
1713
1714 /* stop at first processed item */
1715 if (item->status != QITEM_WAITING) continue;
1716
1717 /* Due to a bug in libksi it is possible that async signer may send out
1718 * more signing requests than permitted by the gateway. Workaround is to
1719 * keep track of signing requests here.
1720 */
1721 #if KSI_SDK_VER_MAJOR == 3 && KSI_SDK_VER_MINOR < 22
1722 if (ctx->roundCount >= ctx->max_requests) ctx->bRoundLock = 1;
1723 if (ctx->bRoundLock) break;
1724 #endif
1725
1726
1727 /* The data hash is produced in another thread by another KSI_CTX and
1728 * libksi internal uses KSI_DataHash cache to reduce the amount of
1729 * memory allocations by recycling old objects. Lets clone the hash
1730 * value with current KSI_CTX as we can not be sure that this thread is
1731 * not affecting the data hash cache operated by another thread.
1732 */
1733 clonedHash = clone_hash(ksi_ctx, item->root);
1734 CHECK_KSI_API(KSI_AggregationReq_new(ksi_ctx, &req), ctx, "KSI_AggregationReq_new");
1735 CHECK_KSI_API(KSI_AggregationReq_setRequestHash((KSI_AggregationReq *)req, clonedHash), ctx,
1736 "KSI_AggregationReq_setRequestHash");
1737 clonedHash = NULL;
1738 CHECK_KSI_API(KSI_Integer_new(ksi_ctx, item->intarg2, &level), ctx, "KSI_Integer_new");
1739 CHECK_KSI_API(KSI_AggregationReq_setRequestLevel(req, level), ctx, "KSI_AggregationReq_setRequestLevel");
1740 CHECK_KSI_API(KSI_AsyncAggregationHandle_new(ksi_ctx, req, &reqHandle), ctx, "KSI_AsyncAggregationHandle_new");
1741 CHECK_KSI_API(KSI_AsyncHandle_setRequestCtx(reqHandle, (void *)item, NULL), ctx,
1742 "KSI_AsyncRequest_setRequestContext");
1743 res = KSI_AsyncService_addRequest(as, reqHandle); /* this can fail because of throttling */
1744
1745 if (res == KSI_OK) {
1746 item->status = QITEM_SENT;
1747 #if KSI_SDK_VER_MAJOR == 3 && KSI_SDK_VER_MINOR < 22
1748 ctx->roundCount++;
1749 #endif
1750 } else {
1751 reportKSIAPIErr(ctx, NULL, "KSI_AsyncService_addRequest", res);
1752 KSI_AsyncHandle_free(reqHandle);
1753 item->status = QITEM_DONE;
1754 item->ksi_status = res;
1755 break;
1756 }
1757
1758 if (i != 0 && i % ctx->max_requests == 0) {
1759 CHECK_KSI_API(KSI_AsyncService_run(as, NULL, NULL), ctx, "KSI_AsyncService_run");
1760 }
1761 }
1762 CHECK_KSI_API(KSI_AsyncService_run(as, NULL, NULL), ctx, "KSI_AsyncService_run");
1763
1764 /* Save all consequent fulfilled responses in the front of the queue to the signature file */
1765 while (ProtectedQueue_count(ctx->signer_queue)) {
1766 item = NULL;
1767 if (!ProtectedQueue_getItem(ctx->signer_queue, 0, (void **)&item)) break;
1768
1769 if (!item) {
1770 ProtectedQueue_popFront(ctx->signer_queue, (void **)&item);
1771 continue;
1772 }
1773
1774 /* stop at first non request queue item (maybe file close/open, quit) */
1775 if (item->type != QITEM_SIGNATURE_REQUEST) break;
1776
1777 /* stop at first unfinished queue item because the signatures need to be ordered */
1778 if (item->status != QITEM_DONE) break;
1779
1780 ProtectedQueue_popFront(ctx->signer_queue, (void **)&item);
1781 save_response(ctx, item->file, item);
1782 fflush(item->file);
1783 /* the main thread has to be locked when the hash is freed to avoid a race condition */
1784 pthread_mutex_lock(&ctx->module_lock);
1785 KSI_DataHash_free(item->root);
1786 KSI_AsyncHandle_free(item->respHandle);
1787 free(item);
1788 pthread_mutex_unlock(&ctx->module_lock);
1789 }
1790
1791 ret = true;
1792
1793 cleanup:
1794 KSI_DataHash_free(clonedHash);
1795 KSI_AsyncService_getPendingCount(as, &p);
1796 return ret;
1797 }
1798
1799 /* This can only be used when signer thread has terminated or within the thread. */
1800 static bool rsksictxCloseAllPendingBlocksWithoutSignature(rsksictx ctx, const char *reason) {
1801 bool ret = false;
1802 QueueItem *item = NULL;
1803 int res = KSI_OK;
1804
1805 /* Save all consequent fulfilled responses in the front of the queue to the signature file */
1806 while (ProtectedQueue_count(ctx->signer_queue)) {
1807 item = NULL;
1808 ProtectedQueue_popFront(ctx->signer_queue, (void **)&item);
1809
1810 if (item == NULL) {
1811 continue;
1812 }
1813
1814 /* Skip non request queue item. */
1815 if (item->type == QITEM_SIGNATURE_REQUEST) {
1816 res = tlvWriteNoSigLS12(item->file, item->intarg1, item->root, reason);
1817 if (res != KSI_OK) {
1818 reportKSIAPIErr(ctx, NULL, "tlvWriteNoSigLS12", res);
1819 ret = false;
1820 goto cleanup;
1821 }
1822 fflush(item->file);
1823 }
1824
1825 KSI_DataHash_free(item->root);
1826 KSI_AsyncHandle_free(item->respHandle);
1827 free(item);
1828 }
1829
1830 ret = true;
1831
1832 cleanup:
1833 return ret;
1834 }
1835
1836
1837 static void request_async_config(rsksictx ctx, KSI_CTX *ksi_ctx, KSI_AsyncService *as) {
1838 KSI_Config *cfg = NULL;
1839 KSI_AsyncHandle *cfgHandle = NULL;
1840 KSI_AggregationReq *cfgReq = NULL;
1841 int res;
1842 bool bSuccess = false;
1843
1844 CHECK_KSI_API(KSI_AggregationReq_new(ksi_ctx, &cfgReq), ctx, "KSI_AggregationReq_new");
1845 CHECK_KSI_API(KSI_Config_new(ksi_ctx, &cfg), ctx, "KSI_Config_new");
1846 CHECK_KSI_API(KSI_AggregationReq_setConfig(cfgReq, cfg), ctx, "KSI_AggregationReq_setConfig");
1847 CHECK_KSI_API(KSI_AsyncAggregationHandle_new(ksi_ctx, cfgReq, &cfgHandle), ctx, "KSI_AsyncAggregationHandle_new");
1848 CHECK_KSI_API(KSI_AsyncService_addRequest(as, cfgHandle), ctx, "KSI_AsyncService_addRequest");
1849
1850 bSuccess = true;
1851
1852 cleanup:
1853 if (!bSuccess) {
1854 if (cfgHandle)
1855 KSI_AsyncHandle_free(cfgHandle);
1856 else if (cfgReq)
1857 KSI_AggregationReq_free(cfgReq);
1858 else if (cfg)
1859 KSI_Config_free(cfg);
1860 }
1861 }
1862
1863 #pragma GCC diagnostic push
1864 #pragma GCC diagnostic ignored "-Wint-to-pointer-cast"
1865 void *signer_thread(void *arg) {
1866 int res = KSI_UNKNOWN_ERROR;
1867 rsksictx ctx = (rsksictx)arg;
1868 KSI_CTX *ksi_ctx = NULL;
1869 KSI_AsyncService *as = NULL;
1870 size_t size_t_value = 0;
1871 size_t ksiFileCount = 0;
1872 int endpoints = 0;
1873 bool bSleep = true;
1874
1875
1876 CHECK_KSI_API(KSI_CTX_new(&ksi_ctx), ctx, "KSI_CTX_new");
1877 CHECK_KSI_API(KSI_CTX_setAggregator(ksi_ctx, ctx->aggregatorUri, ctx->aggregatorId, ctx->aggregatorKey), ctx,
1878 "KSI_CTX_setAggregator");
1879
1880 if (ctx->debugFile) {
1881 res = KSI_CTX_setLoggerCallback(ksi_ctx, rsksiStreamLogger, ctx->debugFile);
1882 if (res != KSI_OK) reportKSIAPIErr(ctx, NULL, "Unable to set logger callback", res);
1883 res = KSI_CTX_setLogLevel(ksi_ctx, ctx->debugLevel);
1884 if (res != KSI_OK) reportKSIAPIErr(ctx, NULL, "Unable to set log level", res);
1885 }
1886
1887 CHECK_KSI_API(KSI_CTX_setOption(ksi_ctx, KSI_OPT_AGGR_HMAC_ALGORITHM, (void *)((size_t)ctx->hmacAlg)), ctx,
1888 "KSI_CTX_setOption");
1889
1890 res = KSI_SigningHighAvailabilityService_new(ksi_ctx, &as);
1891 if (res != KSI_OK) {
1892 reportKSIAPIErr(ctx, NULL, "KSI_SigningAsyncService_new", res);
1893 } else {
1894 int i = 0;
1895 for (i = 0; i < ctx->aggregatorEndpointCount; i++) {
1896 res = KSI_AsyncService_addEndpoint(as, ctx->aggregatorEndpoints[i], ctx->aggregatorId, ctx->aggregatorKey);
1897 if (res != KSI_OK) {
1898 // This can fail if the protocol is not supported by async api.
1899 reportKSIAPIErr(ctx, NULL, "KSI_AsyncService_addEndpoint", res);
1900 continue;
1901 }
1902
1903 endpoints++;
1904 }
1905 }
1906
1907 if (endpoints == 0) { /* no endpoint accepted, deleting the service */
1908 report(ctx, "No endpoints added, signing service disabled");
1909 ctx->disabled = true;
1910 KSI_AsyncService_free(as);
1911 as = NULL;
1912 goto cleanup;
1913 }
1914
1915 /* Lets use buffer value, as libksi requires size_t. */
1916 size_t_value = ctx->max_requests;
1917 KSI_AsyncService_setOption(as, KSI_ASYNC_OPT_REQUEST_CACHE_SIZE, (void *)size_t_value);
1918 size_t_value = ctx->blockSigTimeout;
1919 KSI_AsyncService_setOption(as, KSI_ASYNC_OPT_SND_TIMEOUT, (void *)size_t_value);
1920
1921
1922 ctx->signer_state = SIGNER_STARTED;
1923 while (true) {
1924 QueueItem *item = NULL;
1925
1926 if (isAggrConfNeeded(ctx)) {
1927 request_async_config(ctx, ksi_ctx, as);
1928 }
1929
1930 /* Wait for a work item or timeout*/
1931 if (bSleep) {
1932 ProtectedQueue_waitForItem(ctx->signer_queue, NULL, ctx->threadSleepms);
1933 }
1934 bSleep = true;
1935
1936 /* Check for block time limit. */
1937 sigblkCheckTimeOut(ctx);
1938
1939 /* in case there are no items go around*/
1940 if (ProtectedQueue_count(ctx->signer_queue) == 0) {
1941 process_requests_async(ctx, ksi_ctx, as);
1942 continue;
1943 }
1944
1945 /* process signing requests only if there is an open signature file */
1946 if (ksiFileCount > 0) {
1947 /* check for pending/unsent requests in asynchronous service */
1948 if (!process_requests_async(ctx, ksi_ctx, as)) {
1949 // probably fatal error, disable signing, error should be already reported
1950 ctx->disabled = true;
1951 goto cleanup;
1952 }
1953 }
1954 /* if there are sig. requests still in the front, then we have to start over*/
1955 if (ProtectedQueue_peekFront(ctx->signer_queue, (void **)&item) && item->type == QITEM_SIGNATURE_REQUEST)
1956 continue;
1957
1958 /* Handle other types of work items */
1959 if (ProtectedQueue_popFront(ctx->signer_queue, (void **)&item) != 0) {
1960 /* There is no point to sleep after processing non request type item
1961 * as there is great possibility that next item can already be
1962 * processed. */
1963 bSleep = false;
1964
1965 if (item->type == QITEM_CLOSE_FILE) {
1966 if (item->file) {
1967 fclose(item->file);
1968 item->file = NULL;
1969 }
1970
1971 if (ksiFileCount > 0) ksiFileCount--;
1972 } else if (item->type == QITEM_NEW_FILE) {
1973 ksiFileCount++;
1974 } else if (item->type == QITEM_QUIT) {
1975 free(item);
1976
1977 /* Will look into work queue for pending KSI signatures and will output
1978 * unsigned block marker instead of actual KSI signature to finalize this
1979 * thread quickly.
1980 */
1981 rsksictxCloseAllPendingBlocksWithoutSignature(
1982 ctx, "Signing not finished due to sudden closure of lmsig_ksi-ls12 module.");
1983 rsksictxForceCloseWithoutSig(ctx, "Block closed due to sudden closure of lmsig_ksi-ls12 module.");
1984
1985 goto cleanup;
1986 }
1987
1988 free(item);
1989 }
1990 }
1991
1992 cleanup:
1993
1994 KSI_AsyncService_free(as);
1995 KSI_CTX_free(ksi_ctx);
1996 ctx->signer_state = SIGNER_STOPPED;
1997
1998 return NULL;
1999 }
2000 #pragma GCC diagnostic push