xref: /minix/usr.sbin/syslogd/sign.c (revision 9f988b79)
1 /*	$NetBSD: sign.c,v 1.5 2012/06/06 00:33:45 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.5 2012/06/06 00:33:45 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
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
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
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
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
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 	size_t payload_len, sd_len, fragment_len;
508 	size_t payload_index = 0;
509 
510 	/* do nothing if CBs already sent or if there was no message in SG */
511 	if (!sg->resendcount
512 	    || ((sg->resendcount == SIGN_RESENDCOUNT_CERTBLOCK)
513 	    && STAILQ_EMPTY(&sg->hashes)))
514 		return false;
515 
516 	DPRINTF((D_CALL|D_SIGN), "sign_send_certificate_block(%p)\n", sg);
517 	tstamp = make_timestamp(NULL, true);
518 
519 	payload_len = snprintf(payload, sizeof(payload), "%s %c %s", tstamp,
520 		GlobalSign.keytype, GlobalSign.pubkey_b64);
521 	if (payload_len >= sizeof(payload)) {
522 		DPRINTF(D_SIGN, "Buffer too small for syslog-sign setup\n");
523 		return false;
524 	}
525 
526 	while (payload_index < payload_len) {
527 		if (payload_len - payload_index <= SIGN_MAX_FRAG_LENGTH)
528 			fragment_len = payload_len - payload_index;
529 		else
530 			fragment_len = SIGN_MAX_FRAG_LENGTH;
531 
532 		/* format SD */
533 		sd_len = snprintf(sd, sizeof(sd), "[ssign-cert "
534 		    "VER=\"%s\" RSID=\"%" PRIuFAST64 "\" SG=\"%d\" "
535 		    "SPRI=\"%d\" TBPL=\"%zu\" INDEX=\"%zu\" "
536 		    "FLEN=\"%zu\" FRAG=\"%.*s\" "
537 		    "SIGN=\"\"]",
538 		    GlobalSign.ver, GlobalSign.rsid, GlobalSign.sg,
539 		    sg->spri, payload_len, payload_index+1,
540 		    fragment_len, (int)fragment_len,
541 		    &payload[payload_index]);
542 		assert(sd_len < sizeof(sd));
543 		assert(sd[sd_len] == '\0');
544 		assert(sd[sd_len-1] == ']');
545 		assert(sd[sd_len-2] == '"');
546 
547 		if (!sign_msg_sign(&buffer, sd, sizeof(sd)))
548 			return 0;
549 		DPRINTF((D_CALL|D_SIGN), "sign_send_certificate_block(): "
550 		    "calling fprintlog()\n");
551 
552 		STAILQ_FOREACH(fq, &sg->files, entries) {
553 			/* we have to preserve the f_prevcount */
554 			int tmpcnt;
555 			tmpcnt = fq->f->f_prevcount;
556 			fprintlog(fq->f, buffer, NULL);
557 			fq->f->f_prevcount = tmpcnt;
558 		}
559 		sign_inc_gbc();
560 		DELREF(buffer);
561 		payload_index += fragment_len;
562 	}
563 	sg->resendcount--;
564 	return true;
565 }
566 
567 /*
568  * determine the SG for a message
569  * returns NULL if -sign not configured or no SG for this priority
570  */
571 struct signature_group_t *
572 sign_get_sg(int pri, struct filed *f)
573 {
574 	struct signature_group_t *sg, *rc = NULL;
575 
576 	if (GlobalSign.rsid && f)
577 		switch (GlobalSign.sg) {
578 		case 0:
579 			rc = f->f_sg;
580 			break;
581 		case 1:
582 		case 2:
583 			STAILQ_FOREACH(sg, &GlobalSign.SigGroups, entries) {
584 				if (sg->spri >= (unsigned int)pri) {
585 					rc = sg;
586 					break;
587 				}
588 			}
589 			break;
590 		case 3:
591 			if (f->f_flags & FFLAG_SIGN)
592 				rc = f->f_sg;
593 			else
594 				rc = NULL;
595 			break;
596 		}
597 
598 	DPRINTF((D_CALL|D_SIGN), "sign_get_sg(%d, %p) --> %p\n", pri, f, rc);
599 	return rc;
600 }
601 
602 /*
603  * create and send signature block
604  *
605  * uses a sliding window for redundancy
606  * if force==true then simply send all available hashes, e.g. on shutdown
607  *
608  * sliding window checks implicitly assume that new hashes are appended
609  * to the SG between two calls. if that is not the case (e.g. with repeated
610  * messages) the queue size will shrink.
611  * this has no negative consequences except generating more and shorter SBs
612  * than expected and confusing the operator because two consecutive SBs will
613  * have same FMNn
614  */
615 unsigned
616 sign_send_signature_block(struct signature_group_t *sg, bool force)
617 {
618 	char sd[SIGN_MAX_SD_LENGTH];
619 	size_t sd_len;
620 	size_t sg_num_hashes = 0;	/* hashes in SG queue */
621 	size_t hashes_in_sb = 0;	/* number of hashes in current SB */
622 	size_t hashes_sent = 0;	/* count of hashes sent */
623 	struct string_queue *qentry, *old_qentry;
624 	struct buf_msg *buffer;
625 	struct filed_queue *fq;
626 	size_t i;
627 
628 	if (!sg) return 0;
629 	DPRINTF((D_CALL|D_SIGN), "sign_send_signature_block(%p, %d)\n",
630 	    sg, force);
631 
632 	STAILQ_FOREACH(qentry, &sg->hashes, entries)
633 		sg_num_hashes++;
634 
635 	/* only act if a division is full */
636 	if (!sg_num_hashes
637 	    || (!force && (sg_num_hashes % SIGN_HASH_DIVISION_NUM)))
638 		return 0;
639 
640 	/* if no CB sent so far then do now, just before first SB */
641 	if (sg->resendcount == SIGN_RESENDCOUNT_CERTBLOCK)
642 		sign_send_certificate_block(sg);
643 
644 	/* shortly after reboot we have shorter SBs */
645 	hashes_in_sb = MIN(sg_num_hashes, SIGN_HASH_NUM);
646 
647 	DPRINTF(D_SIGN, "sign_send_signature_block(): "
648 	    "sg_num_hashes = %zu, hashes_in_sb = %zu, SIGN_HASH_NUM = %d\n",
649 	    sg_num_hashes, hashes_in_sb, SIGN_HASH_NUM);
650 	if (sg_num_hashes > SIGN_HASH_NUM) {
651 		DPRINTF(D_SIGN, "sign_send_signature_block(): sg_num_hashes"
652 		    " > SIGN_HASH_NUM -- This should not happen!\n");
653 	}
654 
655 	/* now the SD */
656 	qentry = STAILQ_FIRST(&sg->hashes);
657 	sd_len = snprintf(sd, sizeof(sd), "[ssign "
658 	    "VER=\"%s\" RSID=\"%" PRIuFAST64 "\" SG=\"%d\" "
659 	    "SPRI=\"%d\" GBC=\"%" PRIuFAST64 "\" FMN=\"%" PRIuFAST64 "\" "
660 	    "CNT=\"%zu\" HB=\"",
661 	    GlobalSign.ver, GlobalSign.rsid, GlobalSign.sg,
662 	    sg->spri, GlobalSign.gbc, qentry->key,
663 	    hashes_in_sb);
664 	while (hashes_sent < hashes_in_sb) {
665 		assert(qentry);
666 		sd_len += snprintf(sd+sd_len, sizeof(sd)-sd_len, "%s ",
667 		    qentry->data);
668 		hashes_sent++;
669 		qentry = STAILQ_NEXT(qentry, entries);
670 	}
671 	/* overwrite last space and close SD */
672 	assert(sd_len < sizeof(sd));
673 	assert(sd[sd_len] == '\0');
674 	assert(sd[sd_len-1] == ' ');
675 	sd[sd_len-1] = '\0';
676 	sd_len = strlcat(sd, "\" SIGN=\"\"]", sizeof(sd));
677 
678 	if (sign_msg_sign(&buffer, sd, sizeof(sd))) {
679 		DPRINTF((D_CALL|D_SIGN), "sign_send_signature_block(): calling"
680 		    " fprintlog(), sending %zu out of %zu hashes\n",
681 		    MIN(SIGN_MAX_HASH_NUM, sg_num_hashes), sg_num_hashes);
682 
683 		STAILQ_FOREACH(fq, &sg->files, entries) {
684 			int tmpcnt;
685 			tmpcnt = fq->f->f_prevcount;
686 			fprintlog(fq->f, buffer, NULL);
687 			fq->f->f_prevcount = tmpcnt;
688 		}
689 		sign_inc_gbc();
690 		DELREF(buffer);
691 	}
692 	/* always drop the oldest division of hashes */
693 	if (sg_num_hashes >= SIGN_HASH_NUM) {
694 		qentry = STAILQ_FIRST(&sg->hashes);
695 		for (i = 0; i < SIGN_HASH_DIVISION_NUM; i++) {
696 			old_qentry = qentry;
697 			qentry = STAILQ_NEXT(old_qentry, entries);
698 			STAILQ_REMOVE(&sg->hashes, old_qentry,
699 			    string_queue, entries);
700 			FREEPTR(old_qentry->data);
701 			FREEPTR(old_qentry);
702 		}
703 	}
704 	return hashes_sent;
705 }
706 
707 void
708 sign_free_hashes(struct signature_group_t *sg)
709 {
710 	DPRINTF((D_CALL|D_SIGN), "sign_free_hashes(%p)\n", sg);
711 	sign_free_string_queue(&sg->hashes);
712 }
713 
714 void
715 sign_free_string_queue(struct string_queue_head *sqhead)
716 {
717 	struct string_queue *qentry, *tmp_qentry;
718 
719 	DPRINTF((D_CALL|D_SIGN), "sign_free_string_queue(%p)\n", sqhead);
720 	STAILQ_FOREACH_SAFE(qentry, sqhead, entries, tmp_qentry) {
721 		STAILQ_REMOVE(sqhead, qentry, string_queue, entries);
722 		FREEPTR(qentry->data);
723 		free(qentry);
724 	}
725 	assert(STAILQ_EMPTY(sqhead));
726 }
727 
728 /*
729  * hash one syslog message
730  */
731 bool
732 sign_msg_hash(char *line, char **hash)
733 {
734 	unsigned char md_value[EVP_MAX_MD_SIZE];
735 	unsigned char md_b64[EVP_MAX_MD_SIZE*2];
736 	/* TODO: exact expression for b64 length? */
737 	unsigned md_len = 0;
738 
739 	DPRINTF((D_CALL|D_SIGN), "sign_msg_hash('%s')\n", line);
740 
741 	SSL_CHECK_ONE(EVP_DigestInit_ex(GlobalSign.mdctx, GlobalSign.md, NULL));
742 	SSL_CHECK_ONE(EVP_DigestUpdate(GlobalSign.mdctx, line, strlen(line)));
743 	SSL_CHECK_ONE(EVP_DigestFinal_ex(GlobalSign.mdctx, md_value, &md_len));
744 
745 	b64_ntop(md_value, md_len, (char *)md_b64, EVP_MAX_MD_SIZE*2);
746 	*hash = strdup((char *)md_b64);
747 
748 	DPRINTF((D_CALL|D_SIGN), "sign_msg_hash() --> \"%s\"\n", *hash);
749 	return true;
750 }
751 
752 /*
753  * append hash to SG queue
754  */
755 bool
756 sign_append_hash(char *hash, struct signature_group_t *sg)
757 {
758 	struct string_queue *qentry;
759 
760 	/* if one SG is shared by several destinations
761 	 * prevent duplicate entries */
762 	if ((qentry = STAILQ_LAST(&sg->hashes, string_queue, entries))
763 	    && !strcmp(qentry->data, hash)) {
764 		DPRINTF((D_CALL|D_SIGN), "sign_append_hash('%s', %p): "
765 		    "hash already in queue\n", hash, sg);
766 		return false;
767 	}
768 
769 	MALLOC(qentry, sizeof(*qentry));
770 	qentry->key = sign_assign_msg_num(sg);
771 	qentry->data = hash;
772 	STAILQ_INSERT_TAIL(&sg->hashes, qentry, entries);
773 	DPRINTF((D_CALL|D_SIGN), "sign_append_hash('%s', %p): "
774 	    "#%" PRIdFAST64 "\n", hash, sg, qentry->key);
775 	return true;
776 }
777 
778 /*
779  * sign one syslog-sign message
780  *
781  * requires a ssign or ssigt-cert SD element
782  * ending with ' SIGN=""]' in sd
783  * linesize is available memory (= sizeof(sd))
784  *
785  * function will calculate signature and return a new buffer
786  */
787 bool
788 sign_msg_sign(struct buf_msg **bufferptr, char *sd, size_t linesize)
789 {
790 	char *signature, *line;
791 	size_t linelen, tlsprefixlen, endptr, newlinelen;
792 	struct buf_msg *buffer;
793 
794 	DPRINTF((D_CALL|D_SIGN), "sign_msg_sign()\n");
795 	endptr = strlen(sd);
796 
797 	assert(endptr < linesize);
798 	assert(sd[endptr] == '\0');
799 	assert(sd[endptr-1] == ']');
800 	assert(sd[endptr-2] == '"');
801 
802 	/* set up buffer */
803 	buffer = buf_msg_new(0);
804 	buffer->timestamp = strdup(make_timestamp(NULL, !BSDOutputFormat));
805 	buffer->prog = appname;
806 	buffer->pid = include_pid;
807 	buffer->recvhost = buffer->host = LocalFQDN;
808 	buffer->pri = 110;
809 	buffer->flags = IGN_CONS|SIGN_MSG;
810 	buffer->sd = sd;
811 
812 	/* SD ready, now format and sign */
813 	if (!format_buffer(buffer, &line, &linelen, NULL,
814 		&tlsprefixlen, NULL)) {
815 		DPRINTF((D_CALL|D_SIGN), "sign_send_signature_block():"
816 		    " format_buffer() failed\n");
817 		buffer->sd = NULL;
818 		DELREF(buffer);
819 		return false;
820 	}
821 	if (!sign_string_sign(line+tlsprefixlen, &signature)) {
822 		DPRINTF((D_CALL|D_SIGN), "sign_send_signature_block():"
823 		    " sign_string_sign() failed\n");
824 		buffer->sd = NULL;
825 		DELREF(buffer);
826 		FREEPTR(line);
827 		return false;
828 	}
829 	FREEPTR(line);
830 	sd[endptr-2] = '\0';
831 	newlinelen = strlcat(sd, signature, linesize);
832 	newlinelen = strlcat(sd, "\"]", linesize);
833 
834 	if (newlinelen >= linesize) {
835 		DPRINTF(D_SIGN, "sign_send_signature_block(): "
836 		    "buffer too small\n");
837 		buffer->sd = NULL;
838 		DELREF(buffer);
839 		return false;
840 	}
841 	assert(newlinelen < linesize);
842 	assert(sd[newlinelen] == '\0');
843 	assert(sd[newlinelen-1] == ']');
844 	assert(sd[newlinelen-2] == '"');
845 
846 	buffer->sd = strdup(sd);
847 	*bufferptr = buffer;
848 	return true;
849 }
850 
851 /*
852  * sign one string
853  */
854 bool
855 sign_string_sign(char *line, char **signature)
856 {
857 	char buf[SIGN_MAX_LENGTH+1];
858 	unsigned char sig_value[SIGN_B64SIGLEN_DSS];
859 	unsigned char sig_b64[SIGN_B64SIGLEN_DSS];
860 	unsigned sig_len = 0;
861 	char *p, *q;
862 	/*
863 	 * The signature is calculated over the completely formatted
864 	 * syslog-message, including all of the PRI, HEADER, and hashes
865 	 * in the hash block, excluding spaces between fields, and also
866 	 * excluding the signature field (SD Parameter Name "SIGN", "=",
867 	 * and corresponding value).
868 	 *
869 	 * -- I am not quite sure which spaces are to be removed.
870 	 * Only the ones inside the "ssign" element or those between
871 	 * header fields as well?
872 	 */
873 	/* removes the string ' SIGN=""' */
874 	for (p = line, q = buf;
875 	     *p && (q - buf <= SIGN_MAX_LENGTH);) {
876 		if (strncmp(p, " SIGN=\"\"", 8) == 0)
877 			p += 8;
878 		*q++ = *p++;
879 	}
880 	*q = '\0';
881 
882 	SSL_CHECK_ONE(EVP_SignInit(GlobalSign.sigctx, GlobalSign.sig));
883 	SSL_CHECK_ONE(EVP_SignUpdate(GlobalSign.sigctx, buf, q-buf));
884 	assert(GlobalSign.privkey);
885 	SSL_CHECK_ONE(EVP_SignFinal(GlobalSign.sigctx, sig_value, &sig_len,
886 	    GlobalSign.privkey));
887 
888 	b64_ntop(sig_value, sig_len, (char *)sig_b64, sizeof(sig_b64));
889 	*signature = strdup((char *)sig_b64);
890 
891 	DPRINTF((D_CALL|D_SIGN), "sign_string_sign('%s') --> '%s'\n",
892 	    buf, *signature);
893 	return *signature != NULL;
894 }
895 
896 void
897 sign_new_reboot_session(void)
898 {
899 	struct signature_group_t *sg;
900 
901 	DPRINTF((D_CALL|D_SIGN), "sign_new_reboot_session()\n");
902 
903 	/* global counters */
904 	GlobalSign.gbc = 0;
905 	/* might be useful for later analysis:
906 	 * rebooted session IDs are sequential,
907 	 * normal IDs are almost always not */
908 	GlobalSign.rsid++;
909 
910 	assert(GlobalSign.sg <= 3);
911 	/* reset SGs */
912 	STAILQ_FOREACH(sg, &GlobalSign.SigGroups, entries) {
913 		sg->resendcount = SIGN_RESENDCOUNT_CERTBLOCK;
914 		sg->last_msg_num = 1;
915 	}
916 }
917 
918 /* get msg_num, increment counter, check overflow */
919 uint_fast64_t
920 sign_assign_msg_num(struct signature_group_t *sg)
921 {
922 	uint_fast64_t old;
923 
924 	old = sg->last_msg_num++;
925 	if (sg->last_msg_num > SIGN_MAX_COUNT)
926 		sign_new_reboot_session();
927 	return old;
928 }
929 
930 
931 /* increment gbc, check overflow */
932 void
933 sign_inc_gbc(void)
934 {
935 	if (++GlobalSign.gbc > SIGN_MAX_COUNT)
936 		sign_new_reboot_session();
937 }
938 #endif /* !DISABLE_SIGN */
939