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