1 /* $NetBSD: sign.c,v 1.6 2015/02/10 20:38:15 christos Exp $ */
2
3 /*-
4 * Copyright (c) 2008 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Martin Sch�tte.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38 /*
39 * sign.c
40 * syslog-sign related code for syslogd
41 *
42 * Martin Sch�tte
43 */
44 /*
45 * Issues with the current internet draft:
46 * 1. The draft is a bit unclear on the input format for the signature,
47 * so this might have to be changed later. Cf. sign_string_sign()
48 * 2. The draft only defines DSA signatures. I hope it will be extended
49 * to DSS, thus allowing DSA, RSA (ANSI X9.31) and ECDSA (ANSI X9.62)
50 * 3. The draft does not define the data format for public keys in CBs.
51 * This implementation sends public keys in DER encoding.
52 * 4. This current implementation uses high-level OpenSSL API.
53 * I am not sure if these completely implement the FIPS/ANSI standards.
54 * Update after WG discussion in August:
55 * 1. check; next draft will be clearer and specify the format as implemented.
56 * 2. check; definitely only DSA in this version.
57 * 3. remains a problem, so far no statement from authors or WG.
58 * 4. check; used EVP_dss1 method implements FIPS.
59 */
60 /*
61 * Limitations of this implementation:
62 * - cannot use OpenPGP keys, only PKIX or DSA due to OpenSSL capabilities
63 * - only works for correctly formatted messages, because incorrect messages
64 * are reformatted (e.g. if it receives a message with two spaces between
65 * fields it might even be parsed, but the output will have only one space).
66 */
67
68 #include <sys/cdefs.h>
69 __RCSID("$NetBSD: sign.c,v 1.6 2015/02/10 20:38:15 christos Exp $");
70
71 #ifndef DISABLE_SIGN
72 #include "syslogd.h"
73 #ifndef DISABLE_TLS
74 #include "tls.h"
75 #endif /* !DISABLE_TLS */
76 #include "sign.h"
77 #include "extern.h"
78
79 /*
80 * init all SGs for a given algorithm
81 */
82 bool
sign_global_init(struct filed * Files)83 sign_global_init(struct filed *Files)
84 {
85 DPRINTF((D_CALL|D_SIGN), "sign_global_init()\n");
86 if (!(GlobalSign.sg == 0 || GlobalSign.sg == 1
87 || GlobalSign.sg == 2 || GlobalSign.sg == 3)) {
88 logerror("sign_init(): invalid SG %d", GlobalSign.sg);
89 return false;
90 }
91
92 if (!sign_get_keys())
93 return false;
94
95 /* signature algorithm */
96 /* can probably be merged with the hash algorithm/context but
97 * I leave the optimization for later until the RFC is ready */
98 GlobalSign.sigctx = EVP_MD_CTX_create();
99 EVP_MD_CTX_init(GlobalSign.sigctx);
100
101 /* the signature algorithm depends on the type of key */
102 if (EVP_PKEY_DSA == EVP_PKEY_type(GlobalSign.pubkey->type)) {
103 GlobalSign.sig = EVP_dss1();
104 GlobalSign.sig_len_b64 = SIGN_B64SIGLEN_DSS;
105 /* this is the place to add non-DSA key types and algorithms
106 } else if (EVP_PKEY_RSA == EVP_PKEY_type(GlobalSign.pubkey->type)) {
107 GlobalSign.sig = EVP_sha1();
108 GlobalSign.sig_len_b64 = 28;
109 */
110 } else {
111 logerror("key type not supported for syslog-sign");
112 return false;
113 }
114
115 assert(GlobalSign.keytype == 'C' || GlobalSign.keytype == 'K');
116 assert(GlobalSign.pubkey_b64 && GlobalSign.privkey &&
117 GlobalSign.pubkey);
118 assert(GlobalSign.privkey->pkey.dsa->priv_key);
119
120 GlobalSign.gbc = 0;
121 STAILQ_INIT(&GlobalSign.SigGroups);
122
123 /* hash algorithm */
124 OpenSSL_add_all_digests();
125 GlobalSign.mdctx = EVP_MD_CTX_create();
126 EVP_MD_CTX_init(GlobalSign.mdctx);
127
128 /* values for SHA-1 */
129 GlobalSign.md = EVP_dss1();
130 GlobalSign.md_len_b64 = 28;
131 GlobalSign.ver = "0111";
132
133 if (!sign_sg_init(Files))
134 return false;
135 sign_new_reboot_session();
136
137 DPRINTF(D_SIGN, "length values: SIGN_MAX_SD_LENGTH %d, "
138 "SIGN_MAX_FRAG_LENGTH %d, SIGN_MAX_SB_LENGTH %d, "
139 "SIGN_MAX_HASH_NUM %d\n", SIGN_MAX_SD_LENGTH,
140 SIGN_MAX_FRAG_LENGTH, SIGN_MAX_SB_LENGTH, SIGN_MAX_HASH_NUM);
141
142 /* set just before return, so it indicates initialization */
143 GlobalSign.rsid = now;
144 return true;
145 }
146
147 /*
148 * get keys for syslog-sign
149 * either from the X.509 certificate used for TLS
150 * or by generating a new one
151 *
152 * sets the global variables
153 * GlobalSign.keytype, GlobalSign.pubkey_b64,
154 * GlobalSign.privkey, and GlobalSign.pubkey
155 */
156 bool
sign_get_keys(void)157 sign_get_keys(void)
158 {
159 EVP_PKEY *pubkey = NULL, *privkey = NULL;
160 unsigned char *der_pubkey = NULL, *ptr_der_pubkey = NULL;
161 char *pubkey_b64 = NULL;
162 int der_len;
163
164 /* try PKIX/TLS key first */
165 #ifndef DISABLE_TLS
166 SSL *ssl;
167 if (tls_opt.global_TLS_CTX
168 && (ssl = SSL_new(tls_opt.global_TLS_CTX))) {
169 X509 *cert;
170 DPRINTF(D_SIGN, "Try to get keys from TLS X.509 cert...\n");
171
172 if (!(cert = SSL_get_certificate(ssl))) {
173 logerror("SSL_get_certificate() failed");
174 FREE_SSL(ssl);
175 return false;
176 }
177 if (!(privkey = SSL_get_privatekey(ssl))) {
178 logerror("SSL_get_privatekey() failed");
179 FREE_SSL(ssl);
180 return false;
181 }
182 if (!(pubkey = X509_get_pubkey(cert))) {
183 logerror("X509_get_pubkey() failed");
184 FREE_SSL(ssl);
185 return false;
186 }
187 /* note:
188 * - privkey is just a pointer into SSL_CTX and
189 * must not be changed nor be free()d
190 * - but pubkey has to be freed with EVP_PKEY_free()
191 */
192 FREE_SSL(ssl);
193
194 if (EVP_PKEY_DSA != EVP_PKEY_type(pubkey->type)) {
195 DPRINTF(D_SIGN, "X.509 cert has no DSA key\n");
196 EVP_PKEY_free(pubkey);
197 privkey = NULL;
198 pubkey = NULL;
199 } else {
200 DPRINTF(D_SIGN, "Got public and private key "
201 "from X.509 --> use type PKIX\n");
202 GlobalSign.keytype = 'C';
203 GlobalSign.privkey = privkey;
204 GlobalSign.pubkey = pubkey;
205
206 /* base64 certificate encoding */
207 der_len = i2d_X509(cert, NULL);
208 if (!(ptr_der_pubkey = der_pubkey = malloc(der_len))
209 || !(pubkey_b64 = malloc(der_len*2))) {
210 free(der_pubkey);
211 logerror("malloc() failed");
212 return false;
213 }
214 if (i2d_X509(cert, &ptr_der_pubkey) <= 0) {
215 logerror("i2d_X509() failed");
216 return false;
217 }
218 b64_ntop(der_pubkey, der_len, pubkey_b64, der_len*2);
219 free(der_pubkey);
220 /* try to resize memory object as needed */
221 GlobalSign.pubkey_b64 = realloc(pubkey_b64,
222 strlen(pubkey_b64)+1);
223 if (!GlobalSign.pubkey_b64)
224 GlobalSign.pubkey_b64 = pubkey_b64;
225 }
226 }
227 #endif /* !DISABLE_TLS */
228 if (!(privkey && pubkey)) { /* PKIX not available --> generate key */
229 DSA *dsa;
230
231 DPRINTF(D_SIGN, "Unable to get keys from X.509 "
232 "--> use DSA with type 'K'\n");
233 if (!(privkey = EVP_PKEY_new())) {
234 logerror("EVP_PKEY_new() failed");
235 return false;
236 }
237 dsa = DSA_generate_parameters(SIGN_GENCERT_BITS, NULL, 0,
238 NULL, NULL, NULL, NULL);
239 if (!DSA_generate_key(dsa)) {
240 logerror("DSA_generate_key() failed");
241 return false;
242 }
243 if (!EVP_PKEY_assign_DSA(privkey, dsa)) {
244 logerror("EVP_PKEY_assign_DSA() failed");
245 return false;
246 }
247 GlobalSign.keytype = 'K'; /* public/private keys used */
248 GlobalSign.privkey = privkey;
249 GlobalSign.pubkey = privkey;
250
251 /* pubkey base64 encoding */
252 der_len = i2d_DSA_PUBKEY(dsa, NULL);
253 if (!(ptr_der_pubkey = der_pubkey = malloc(der_len))
254 || !(pubkey_b64 = malloc(der_len*2))) {
255 free(der_pubkey);
256 logerror("malloc() failed");
257 return false;
258 }
259 if (i2d_DSA_PUBKEY(dsa, &ptr_der_pubkey) <= 0) {
260 logerror("i2d_DSA_PUBKEY() failed");
261 free(der_pubkey);
262 free(pubkey_b64);
263 return false;
264 }
265 b64_ntop(der_pubkey, der_len, pubkey_b64, der_len*2);
266 free(der_pubkey);
267 /* try to resize memory object as needed */
268 GlobalSign.pubkey_b64 = realloc(pubkey_b64,
269 strlen(pubkey_b64) + 1);
270 if (!GlobalSign.pubkey_b64)
271 GlobalSign.pubkey_b64 = pubkey_b64;
272 }
273 return true;
274 }
275
276 /*
277 * init SGs
278 */
279 bool
sign_sg_init(struct filed * Files)280 sign_sg_init(struct filed *Files)
281 {
282 struct signature_group_t *sg, *newsg, *last_sg;
283 struct filed_queue *fq;
284 struct string_queue *sqentry, *last_sqentry;
285 struct filed *f;
286 unsigned int i;
287
288 /* note on SG 1 and 2:
289 * it is assumed that redundant signature groups
290 * and especially signature groups without an associated
291 * destination are harmless.
292 * this currently holds true because sign_append_hash()
293 * is called from fprintlog(), so only actually used
294 * signature group get hashes and need memory for them
295 */
296 /* possible optimization for SGs 1 and 2:
297 * use a struct signature_group_t *newsg[IETF_NUM_PRIVALUES]
298 * for direct group lookup
299 */
300
301 #define ALLOC_OR_FALSE(x) do { \
302 if(!((x) = calloc(1, sizeof(*(x))))) { \
303 logerror("Unable to allocate memory"); \
304 return false; \
305 } \
306 } while (/*CONSTCOND*/0)
307
308 #define ALLOC_SG(x) do { \
309 ALLOC_OR_FALSE(x); \
310 (x)->last_msg_num = 1; /* cf. section 4.2.5 */ \
311 STAILQ_INIT(&(x)->hashes); \
312 STAILQ_INIT(&(x)->files); \
313 } while (/*CONSTCOND*/0)
314
315 /* alloc(fq) and add to SGs file queue */
316 #define ASSIGN_FQ() do { \
317 ALLOC_OR_FALSE(fq); \
318 fq->f = f; \
319 f->f_sg = newsg; \
320 DPRINTF(D_SIGN, "SG@%p <--> f@%p\n", newsg, f); \
321 STAILQ_INSERT_TAIL(&newsg->files, fq, entries); \
322 } while (/*CONSTCOND*/0)
323
324 switch (GlobalSign.sg) {
325 case 0:
326 /* one SG, linked to all files */
327 ALLOC_SG(newsg);
328 newsg->spri = 0;
329 for (f = Files; f; f = f->f_next)
330 ASSIGN_FQ();
331 STAILQ_INSERT_TAIL(&GlobalSign.SigGroups,
332 newsg, entries);
333 break;
334 case 1:
335 /* every PRI gets one SG */
336 for (i = 0; i < IETF_NUM_PRIVALUES; i++) {
337 int fac, prilev;
338 fac = LOG_FAC(i);
339 prilev = LOG_PRI(i);
340 ALLOC_SG(newsg);
341 newsg->spri = i;
342
343 /* now find all destinations associated with this SG */
344 for (f = Files; f; f = f->f_next)
345 /* check priorities */
346 if (MATCH_PRI(f, fac, prilev))
347 ASSIGN_FQ();
348 STAILQ_INSERT_TAIL(&GlobalSign.SigGroups,
349 newsg, entries);
350 }
351 break;
352 case 2:
353 /* PRI ranges get one SG, boundaries given by the
354 * SPRI, indicating the largest PRI in the SG
355 *
356 * either GlobalSign.sig2_delims has a list of
357 * user configured delimiters, or we use a default
358 * and set up one SG per facility
359 */
360 if (STAILQ_EMPTY(&GlobalSign.sig2_delims)) {
361 DPRINTF(D_SIGN, "sign_sg_init(): set default "
362 "values for SG 2\n");
363 for (i = 0; i < (IETF_NUM_PRIVALUES>>3); i++) {
364 ALLOC_OR_FALSE(sqentry);
365 sqentry->data = NULL;
366 sqentry->key = (i<<3);
367 STAILQ_INSERT_TAIL(&GlobalSign.sig2_delims,
368 sqentry, entries);
369 }
370 }
371 assert(!STAILQ_EMPTY(&GlobalSign.sig2_delims));
372
373 /* add one more group at the end */
374 last_sqentry = STAILQ_LAST(&GlobalSign.sig2_delims,
375 string_queue, entries);
376 if (last_sqentry->key < IETF_NUM_PRIVALUES) {
377 ALLOC_OR_FALSE(sqentry);
378 sqentry->data = NULL;
379 sqentry->key = IETF_NUM_PRIVALUES-1;
380 STAILQ_INSERT_TAIL(&GlobalSign.sig2_delims,
381 sqentry, entries);
382 }
383
384 STAILQ_FOREACH(sqentry, &GlobalSign.sig2_delims, entries) {
385 unsigned int min_pri = 0;
386 ALLOC_SG(newsg);
387 newsg->spri = sqentry->key;
388
389 /* check _all_ priorities in SG */
390 last_sg = STAILQ_LAST(&GlobalSign.SigGroups,
391 signature_group_t, entries);
392 if (last_sg)
393 min_pri = last_sg->spri + 1;
394
395 DPRINTF(D_SIGN, "sign_sg_init(): add SG@%p: SG=\"2\","
396 " SPRI=\"%d\" -- for msgs with "
397 "%d <= pri <= %d\n",
398 newsg, newsg->spri, min_pri, newsg->spri);
399 /* now find all destinations associated with this SG */
400 for (f = Files; f; f = f->f_next) {
401 bool match = false;
402 for (i = min_pri; i <= newsg->spri; i++) {
403 int fac, prilev;
404 fac = LOG_FAC(i);
405 prilev = LOG_PRI(i);
406 if (MATCH_PRI(f, fac, prilev)) {
407 match = true;
408 break;
409 }
410 }
411 if (match)
412 ASSIGN_FQ();
413 }
414 STAILQ_INSERT_TAIL(&GlobalSign.SigGroups,
415 newsg, entries);
416 }
417 break;
418 case 3:
419 /* every file (with flag) gets one SG */
420 for (f = Files; f; f = f->f_next) {
421 if (!(f->f_flags & FFLAG_SIGN)) {
422 f->f_sg = NULL;
423 continue;
424 }
425 ALLOC_SG(newsg);
426 newsg->spri = f->f_file; /* not needed but shows SGs */
427 ASSIGN_FQ();
428 STAILQ_INSERT_TAIL(&GlobalSign.SigGroups,
429 newsg, entries);
430 }
431 break;
432 }
433 DPRINTF((D_PARSE|D_SIGN), "sign_sg_init() set up these "
434 "Signature Groups:\n");
435 STAILQ_FOREACH(sg, &GlobalSign.SigGroups, entries) {
436 DPRINTF((D_PARSE|D_SIGN), "SG@%p with SG=\"%d\", SPRI=\"%d\","
437 " associated files:\n", sg, GlobalSign.sg, sg->spri);
438 STAILQ_FOREACH(fq, &sg->files, entries) {
439 DPRINTF((D_PARSE|D_SIGN), " f@%p with type %d\n",
440 fq->f, fq->f->f_type);
441 }
442 }
443 return true;
444 }
445
446 /*
447 * free all SGs for a given algorithm
448 */
449 void
sign_global_free(void)450 sign_global_free(void)
451 {
452 struct signature_group_t *sg, *tmp_sg;
453 struct filed_queue *fq, *tmp_fq;
454
455 DPRINTF((D_CALL|D_SIGN), "sign_global_free()\n");
456 STAILQ_FOREACH_SAFE(sg, &GlobalSign.SigGroups, entries, tmp_sg) {
457 if (!STAILQ_EMPTY(&sg->hashes)) {
458 /* send CB and SB twice to get minimal redundancy
459 * for the last few message hashes */
460 sign_send_certificate_block(sg);
461 sign_send_certificate_block(sg);
462 sign_send_signature_block(sg, true);
463 sign_send_signature_block(sg, true);
464 sign_free_hashes(sg);
465 }
466 fq = STAILQ_FIRST(&sg->files);
467 while (fq != NULL) {
468 tmp_fq = STAILQ_NEXT(fq, entries);
469 free(fq);
470 fq = tmp_fq;
471 }
472 STAILQ_REMOVE(&GlobalSign.SigGroups,
473 sg, signature_group_t, entries);
474 free(sg);
475 }
476 sign_free_string_queue(&GlobalSign.sig2_delims);
477
478 if (GlobalSign.privkey) {
479 GlobalSign.privkey = NULL;
480 }
481 if (GlobalSign.pubkey) {
482 EVP_PKEY_free(GlobalSign.pubkey);
483 GlobalSign.pubkey = NULL;
484 }
485 if(GlobalSign.mdctx) {
486 EVP_MD_CTX_destroy(GlobalSign.mdctx);
487 GlobalSign.mdctx = NULL;
488 }
489 if(GlobalSign.sigctx) {
490 EVP_MD_CTX_destroy(GlobalSign.sigctx);
491 GlobalSign.sigctx = NULL;
492 }
493 FREEPTR(GlobalSign.pubkey_b64);
494 }
495
496 /*
497 * create and send certificate block
498 */
499 bool
sign_send_certificate_block(struct signature_group_t * sg)500 sign_send_certificate_block(struct signature_group_t *sg)
501 {
502 struct filed_queue *fq;
503 struct buf_msg *buffer;
504 char *tstamp;
505 char payload[SIGN_MAX_PAYLOAD_LENGTH];
506 char sd[SIGN_MAX_SD_LENGTH];
507 #if !defined(NDEBUG) && defined(__minix)
508 size_t payload_len, sd_len, fragment_len;
509 #else
510 size_t payload_len, fragment_len;
511 #endif /* !defined(NDEBUG) && defined(__minix) */
512 size_t payload_index = 0;
513
514 /* do nothing if CBs already sent or if there was no message in SG */
515 if (!sg->resendcount
516 || ((sg->resendcount == SIGN_RESENDCOUNT_CERTBLOCK)
517 && STAILQ_EMPTY(&sg->hashes)))
518 return false;
519
520 DPRINTF((D_CALL|D_SIGN), "sign_send_certificate_block(%p)\n", sg);
521 tstamp = make_timestamp(NULL, true, (size_t)-1);
522
523 payload_len = snprintf(payload, sizeof(payload), "%s %c %s", tstamp,
524 GlobalSign.keytype, GlobalSign.pubkey_b64);
525 if (payload_len >= sizeof(payload)) {
526 DPRINTF(D_SIGN, "Buffer too small for syslog-sign setup\n");
527 return false;
528 }
529
530 while (payload_index < payload_len) {
531 if (payload_len - payload_index <= SIGN_MAX_FRAG_LENGTH)
532 fragment_len = payload_len - payload_index;
533 else
534 fragment_len = SIGN_MAX_FRAG_LENGTH;
535
536 #if !defined(NDEBUG) && defined(__minix)
537 /* format SD */
538 sd_len =
539 #endif /* !defined(NDEBUG) && defined(__minix) */
540 snprintf(sd, sizeof(sd), "[ssign-cert "
541 "VER=\"%s\" RSID=\"%" PRIuFAST64 "\" SG=\"%d\" "
542 "SPRI=\"%d\" TBPL=\"%zu\" INDEX=\"%zu\" "
543 "FLEN=\"%zu\" FRAG=\"%.*s\" "
544 "SIGN=\"\"]",
545 GlobalSign.ver, GlobalSign.rsid, GlobalSign.sg,
546 sg->spri, payload_len, payload_index+1,
547 fragment_len, (int)fragment_len,
548 &payload[payload_index]);
549 assert(sd_len < sizeof(sd));
550 assert(sd[sd_len] == '\0');
551 assert(sd[sd_len-1] == ']');
552 assert(sd[sd_len-2] == '"');
553
554 if (!sign_msg_sign(&buffer, sd, sizeof(sd)))
555 return 0;
556 DPRINTF((D_CALL|D_SIGN), "sign_send_certificate_block(): "
557 "calling fprintlog()\n");
558
559 STAILQ_FOREACH(fq, &sg->files, entries) {
560 /* we have to preserve the f_prevcount */
561 int tmpcnt;
562 tmpcnt = fq->f->f_prevcount;
563 fprintlog(fq->f, buffer, NULL);
564 fq->f->f_prevcount = tmpcnt;
565 }
566 sign_inc_gbc();
567 DELREF(buffer);
568 payload_index += fragment_len;
569 }
570 sg->resendcount--;
571 return true;
572 }
573
574 /*
575 * determine the SG for a message
576 * returns NULL if -sign not configured or no SG for this priority
577 */
578 struct signature_group_t *
sign_get_sg(int pri,struct filed * f)579 sign_get_sg(int pri, struct filed *f)
580 {
581 struct signature_group_t *sg, *rc = NULL;
582
583 if (GlobalSign.rsid && f)
584 switch (GlobalSign.sg) {
585 case 0:
586 rc = f->f_sg;
587 break;
588 case 1:
589 case 2:
590 STAILQ_FOREACH(sg, &GlobalSign.SigGroups, entries) {
591 if (sg->spri >= (unsigned int)pri) {
592 rc = sg;
593 break;
594 }
595 }
596 break;
597 case 3:
598 if (f->f_flags & FFLAG_SIGN)
599 rc = f->f_sg;
600 else
601 rc = NULL;
602 break;
603 }
604
605 DPRINTF((D_CALL|D_SIGN), "sign_get_sg(%d, %p) --> %p\n", pri, f, rc);
606 return rc;
607 }
608
609 /*
610 * create and send signature block
611 *
612 * uses a sliding window for redundancy
613 * if force==true then simply send all available hashes, e.g. on shutdown
614 *
615 * sliding window checks implicitly assume that new hashes are appended
616 * to the SG between two calls. if that is not the case (e.g. with repeated
617 * messages) the queue size will shrink.
618 * this has no negative consequences except generating more and shorter SBs
619 * than expected and confusing the operator because two consecutive SBs will
620 * have same FMNn
621 */
622 unsigned
sign_send_signature_block(struct signature_group_t * sg,bool force)623 sign_send_signature_block(struct signature_group_t *sg, bool force)
624 {
625 char sd[SIGN_MAX_SD_LENGTH];
626 size_t sd_len;
627 size_t sg_num_hashes = 0; /* hashes in SG queue */
628 size_t hashes_in_sb = 0; /* number of hashes in current SB */
629 size_t hashes_sent = 0; /* count of hashes sent */
630 struct string_queue *qentry, *old_qentry;
631 struct buf_msg *buffer;
632 struct filed_queue *fq;
633 size_t i;
634
635 if (!sg) return 0;
636 DPRINTF((D_CALL|D_SIGN), "sign_send_signature_block(%p, %d)\n",
637 sg, force);
638
639 STAILQ_FOREACH(qentry, &sg->hashes, entries)
640 sg_num_hashes++;
641
642 /* only act if a division is full */
643 if (!sg_num_hashes
644 || (!force && (sg_num_hashes % SIGN_HASH_DIVISION_NUM)))
645 return 0;
646
647 /* if no CB sent so far then do now, just before first SB */
648 if (sg->resendcount == SIGN_RESENDCOUNT_CERTBLOCK)
649 sign_send_certificate_block(sg);
650
651 /* shortly after reboot we have shorter SBs */
652 hashes_in_sb = MIN(sg_num_hashes, SIGN_HASH_NUM);
653
654 DPRINTF(D_SIGN, "sign_send_signature_block(): "
655 "sg_num_hashes = %zu, hashes_in_sb = %zu, SIGN_HASH_NUM = %d\n",
656 sg_num_hashes, hashes_in_sb, SIGN_HASH_NUM);
657 if (sg_num_hashes > SIGN_HASH_NUM) {
658 DPRINTF(D_SIGN, "sign_send_signature_block(): sg_num_hashes"
659 " > SIGN_HASH_NUM -- This should not happen!\n");
660 }
661
662 /* now the SD */
663 qentry = STAILQ_FIRST(&sg->hashes);
664 sd_len = snprintf(sd, sizeof(sd), "[ssign "
665 "VER=\"%s\" RSID=\"%" PRIuFAST64 "\" SG=\"%d\" "
666 "SPRI=\"%d\" GBC=\"%" PRIuFAST64 "\" FMN=\"%" PRIuFAST64 "\" "
667 "CNT=\"%zu\" HB=\"",
668 GlobalSign.ver, GlobalSign.rsid, GlobalSign.sg,
669 sg->spri, GlobalSign.gbc, qentry->key,
670 hashes_in_sb);
671 while (hashes_sent < hashes_in_sb) {
672 assert(qentry);
673 sd_len += snprintf(sd+sd_len, sizeof(sd)-sd_len, "%s ",
674 qentry->data);
675 hashes_sent++;
676 qentry = STAILQ_NEXT(qentry, entries);
677 }
678 /* overwrite last space and close SD */
679 assert(sd_len < sizeof(sd));
680 assert(sd[sd_len] == '\0');
681 assert(sd[sd_len-1] == ' ');
682 sd[sd_len-1] = '\0';
683 sd_len = strlcat(sd, "\" SIGN=\"\"]", sizeof(sd));
684
685 if (sign_msg_sign(&buffer, sd, sizeof(sd))) {
686 DPRINTF((D_CALL|D_SIGN), "sign_send_signature_block(): calling"
687 " fprintlog(), sending %zu out of %zu hashes\n",
688 MIN(SIGN_MAX_HASH_NUM, sg_num_hashes), sg_num_hashes);
689
690 STAILQ_FOREACH(fq, &sg->files, entries) {
691 int tmpcnt;
692 tmpcnt = fq->f->f_prevcount;
693 fprintlog(fq->f, buffer, NULL);
694 fq->f->f_prevcount = tmpcnt;
695 }
696 sign_inc_gbc();
697 DELREF(buffer);
698 }
699 /* always drop the oldest division of hashes */
700 if (sg_num_hashes >= SIGN_HASH_NUM) {
701 qentry = STAILQ_FIRST(&sg->hashes);
702 for (i = 0; i < SIGN_HASH_DIVISION_NUM; i++) {
703 old_qentry = qentry;
704 qentry = STAILQ_NEXT(old_qentry, entries);
705 STAILQ_REMOVE(&sg->hashes, old_qentry,
706 string_queue, entries);
707 FREEPTR(old_qentry->data);
708 FREEPTR(old_qentry);
709 }
710 }
711 return hashes_sent;
712 }
713
714 void
sign_free_hashes(struct signature_group_t * sg)715 sign_free_hashes(struct signature_group_t *sg)
716 {
717 DPRINTF((D_CALL|D_SIGN), "sign_free_hashes(%p)\n", sg);
718 sign_free_string_queue(&sg->hashes);
719 }
720
721 void
sign_free_string_queue(struct string_queue_head * sqhead)722 sign_free_string_queue(struct string_queue_head *sqhead)
723 {
724 struct string_queue *qentry, *tmp_qentry;
725
726 DPRINTF((D_CALL|D_SIGN), "sign_free_string_queue(%p)\n", sqhead);
727 STAILQ_FOREACH_SAFE(qentry, sqhead, entries, tmp_qentry) {
728 STAILQ_REMOVE(sqhead, qentry, string_queue, entries);
729 FREEPTR(qentry->data);
730 free(qentry);
731 }
732 assert(STAILQ_EMPTY(sqhead));
733 }
734
735 /*
736 * hash one syslog message
737 */
738 bool
sign_msg_hash(char * line,char ** hash)739 sign_msg_hash(char *line, char **hash)
740 {
741 unsigned char md_value[EVP_MAX_MD_SIZE];
742 unsigned char md_b64[EVP_MAX_MD_SIZE*2];
743 /* TODO: exact expression for b64 length? */
744 unsigned md_len = 0;
745
746 DPRINTF((D_CALL|D_SIGN), "sign_msg_hash('%s')\n", line);
747
748 SSL_CHECK_ONE(EVP_DigestInit_ex(GlobalSign.mdctx, GlobalSign.md, NULL));
749 SSL_CHECK_ONE(EVP_DigestUpdate(GlobalSign.mdctx, line, strlen(line)));
750 SSL_CHECK_ONE(EVP_DigestFinal_ex(GlobalSign.mdctx, md_value, &md_len));
751
752 b64_ntop(md_value, md_len, (char *)md_b64, EVP_MAX_MD_SIZE*2);
753 *hash = strdup((char *)md_b64);
754
755 DPRINTF((D_CALL|D_SIGN), "sign_msg_hash() --> \"%s\"\n", *hash);
756 return true;
757 }
758
759 /*
760 * append hash to SG queue
761 */
762 bool
sign_append_hash(char * hash,struct signature_group_t * sg)763 sign_append_hash(char *hash, struct signature_group_t *sg)
764 {
765 struct string_queue *qentry;
766
767 /* if one SG is shared by several destinations
768 * prevent duplicate entries */
769 if ((qentry = STAILQ_LAST(&sg->hashes, string_queue, entries))
770 && !strcmp(qentry->data, hash)) {
771 DPRINTF((D_CALL|D_SIGN), "sign_append_hash('%s', %p): "
772 "hash already in queue\n", hash, sg);
773 return false;
774 }
775
776 MALLOC(qentry, sizeof(*qentry));
777 qentry->key = sign_assign_msg_num(sg);
778 qentry->data = hash;
779 STAILQ_INSERT_TAIL(&sg->hashes, qentry, entries);
780 DPRINTF((D_CALL|D_SIGN), "sign_append_hash('%s', %p): "
781 "#%" PRIdFAST64 "\n", hash, sg, qentry->key);
782 return true;
783 }
784
785 /*
786 * sign one syslog-sign message
787 *
788 * requires a ssign or ssigt-cert SD element
789 * ending with ' SIGN=""]' in sd
790 * linesize is available memory (= sizeof(sd))
791 *
792 * function will calculate signature and return a new buffer
793 */
794 bool
sign_msg_sign(struct buf_msg ** bufferptr,char * sd,size_t linesize)795 sign_msg_sign(struct buf_msg **bufferptr, char *sd, size_t linesize)
796 {
797 char *signature, *line;
798 size_t linelen, tlsprefixlen, endptr, newlinelen;
799 struct buf_msg *buffer;
800
801 DPRINTF((D_CALL|D_SIGN), "sign_msg_sign()\n");
802 endptr = strlen(sd);
803
804 assert(endptr < linesize);
805 assert(sd[endptr] == '\0');
806 assert(sd[endptr-1] == ']');
807 assert(sd[endptr-2] == '"');
808
809 /* set up buffer */
810 buffer = buf_msg_new(0);
811 buffer->timestamp = make_timestamp(NULL, !BSDOutputFormat, 0);
812 buffer->prog = appname;
813 buffer->pid = include_pid;
814 buffer->recvhost = buffer->host = LocalFQDN;
815 buffer->pri = 110;
816 buffer->flags = IGN_CONS|SIGN_MSG;
817 buffer->sd = sd;
818
819 /* SD ready, now format and sign */
820 if (!format_buffer(buffer, &line, &linelen, NULL,
821 &tlsprefixlen, NULL)) {
822 DPRINTF((D_CALL|D_SIGN), "sign_send_signature_block():"
823 " format_buffer() failed\n");
824 buffer->sd = NULL;
825 DELREF(buffer);
826 return false;
827 }
828 if (!sign_string_sign(line+tlsprefixlen, &signature)) {
829 DPRINTF((D_CALL|D_SIGN), "sign_send_signature_block():"
830 " sign_string_sign() failed\n");
831 buffer->sd = NULL;
832 DELREF(buffer);
833 FREEPTR(line);
834 return false;
835 }
836 FREEPTR(line);
837 sd[endptr-2] = '\0';
838 newlinelen = strlcat(sd, signature, linesize);
839 newlinelen = strlcat(sd, "\"]", linesize);
840
841 if (newlinelen >= linesize) {
842 DPRINTF(D_SIGN, "sign_send_signature_block(): "
843 "buffer too small\n");
844 buffer->sd = NULL;
845 DELREF(buffer);
846 return false;
847 }
848 assert(newlinelen < linesize);
849 assert(sd[newlinelen] == '\0');
850 assert(sd[newlinelen-1] == ']');
851 assert(sd[newlinelen-2] == '"');
852
853 buffer->sd = strdup(sd);
854 *bufferptr = buffer;
855 return true;
856 }
857
858 /*
859 * sign one string
860 */
861 bool
sign_string_sign(char * line,char ** signature)862 sign_string_sign(char *line, char **signature)
863 {
864 char buf[SIGN_MAX_LENGTH+1];
865 unsigned char sig_value[SIGN_B64SIGLEN_DSS];
866 unsigned char sig_b64[SIGN_B64SIGLEN_DSS];
867 unsigned sig_len = 0;
868 char *p, *q;
869 /*
870 * The signature is calculated over the completely formatted
871 * syslog-message, including all of the PRI, HEADER, and hashes
872 * in the hash block, excluding spaces between fields, and also
873 * excluding the signature field (SD Parameter Name "SIGN", "=",
874 * and corresponding value).
875 *
876 * -- I am not quite sure which spaces are to be removed.
877 * Only the ones inside the "ssign" element or those between
878 * header fields as well?
879 */
880 /* removes the string ' SIGN=""' */
881 for (p = line, q = buf;
882 *p && (q - buf <= SIGN_MAX_LENGTH);) {
883 if (strncmp(p, " SIGN=\"\"", 8) == 0)
884 p += 8;
885 *q++ = *p++;
886 }
887 *q = '\0';
888
889 SSL_CHECK_ONE(EVP_SignInit(GlobalSign.sigctx, GlobalSign.sig));
890 SSL_CHECK_ONE(EVP_SignUpdate(GlobalSign.sigctx, buf, q-buf));
891 assert(GlobalSign.privkey);
892 SSL_CHECK_ONE(EVP_SignFinal(GlobalSign.sigctx, sig_value, &sig_len,
893 GlobalSign.privkey));
894
895 b64_ntop(sig_value, sig_len, (char *)sig_b64, sizeof(sig_b64));
896 *signature = strdup((char *)sig_b64);
897
898 DPRINTF((D_CALL|D_SIGN), "sign_string_sign('%s') --> '%s'\n",
899 buf, *signature);
900 return *signature != NULL;
901 }
902
903 void
sign_new_reboot_session(void)904 sign_new_reboot_session(void)
905 {
906 struct signature_group_t *sg;
907
908 DPRINTF((D_CALL|D_SIGN), "sign_new_reboot_session()\n");
909
910 /* global counters */
911 GlobalSign.gbc = 0;
912 /* might be useful for later analysis:
913 * rebooted session IDs are sequential,
914 * normal IDs are almost always not */
915 GlobalSign.rsid++;
916
917 assert(GlobalSign.sg <= 3);
918 /* reset SGs */
919 STAILQ_FOREACH(sg, &GlobalSign.SigGroups, entries) {
920 sg->resendcount = SIGN_RESENDCOUNT_CERTBLOCK;
921 sg->last_msg_num = 1;
922 }
923 }
924
925 /* get msg_num, increment counter, check overflow */
926 uint_fast64_t
sign_assign_msg_num(struct signature_group_t * sg)927 sign_assign_msg_num(struct signature_group_t *sg)
928 {
929 uint_fast64_t old;
930
931 old = sg->last_msg_num++;
932 if (sg->last_msg_num > SIGN_MAX_COUNT)
933 sign_new_reboot_session();
934 return old;
935 }
936
937
938 /* increment gbc, check overflow */
939 void
sign_inc_gbc(void)940 sign_inc_gbc(void)
941 {
942 if (++GlobalSign.gbc > SIGN_MAX_COUNT)
943 sign_new_reboot_session();
944 }
945 #endif /* !DISABLE_SIGN */
946