/*-
* Copyright (c) 2008 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Martin Sch�tte.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/*
* sign.c
* syslog-sign related code for syslogd
*
* Martin Sch�tte
*/
/*
* Issues with the current internet draft:
* 1. The draft is a bit unclear on the input format for the signature,
* so this might have to be changed later. Cf. sign_string_sign()
* 2. The draft only defines DSA signatures. I hope it will be extended
* to DSS, thus allowing DSA, RSA (ANSI X9.31) and ECDSA (ANSI X9.62)
* 3. The draft does not define the data format for public keys in CBs.
* This implementation sends public keys in DER encoding.
* 4. This current implementation uses high-level OpenSSL API.
* I am not sure if these completely implement the FIPS/ANSI standards.
* Update after WG discussion in August:
* 1. check; next draft will be clearer and specify the format as implemented.
* 2. check; definitely only DSA in this version.
* 3. remains a problem, so far no statement from authors or WG.
* 4. check; used EVP_sha1 method implements FIPS.
*/
/*
* Limitations of this implementation:
* - cannot use OpenPGP keys, only PKIX or DSA due to OpenSSL capabilities
* - only works for correctly formatted messages, because incorrect messages
* are reformatted (e.g. if it receives a message with two spaces between
* fields it might even be parsed, but the output will have only one space).
*/
/*
* init all SGs for a given algorithm
*/
bool
sign_global_init(struct filed *Files)
{
DPRINTF((D_CALL|D_SIGN), "sign_global_init()\n");
if (!(GlobalSign.sg == 0 || GlobalSign.sg == 1
|| GlobalSign.sg == 2 || GlobalSign.sg == 3)) {
logerror("sign_init(): invalid SG %d", GlobalSign.sg);
return false;
}
if (!sign_get_keys())
return false;
/* signature algorithm */
/* can probably be merged with the hash algorithm/context but
* I leave the optimization for later until the RFC is ready */
GlobalSign.sigctx = EVP_MD_CTX_create();
EVP_MD_CTX_init(GlobalSign.sigctx);
/* the signature algorithm depends on the type of key */
switch (EVP_PKEY_base_id(GlobalSign.pubkey)) {
case EVP_PKEY_DSA:
GlobalSign.sig = EVP_sha1();
GlobalSign.sig_len_b64 = SIGN_B64SIGLEN_DSS;
break;
#ifdef notyet
/* this is the place to add non-DSA key types and algorithms */
case EVP_PKEY_RSA:
GlobalSign.sig = EVP_sha1();
GlobalSign.sig_len_b64 = 28;
break;
#endif
default:
logerror("key type not supported for syslog-sign");
return false;
}
/* set just before return, so it indicates initialization */
GlobalSign.rsid = now;
return true;
}
/*
* get keys for syslog-sign
* either from the X.509 certificate used for TLS
* or by generating a new one
*
* sets the global variables
* GlobalSign.keytype, GlobalSign.pubkey_b64,
* GlobalSign.privkey, and GlobalSign.pubkey
*/
bool
sign_get_keys(void)
{
EVP_PKEY *pubkey = NULL, *privkey = NULL;
unsigned char *der_pubkey = NULL, *ptr_der_pubkey = NULL;
char *pubkey_b64 = NULL;
int der_len;
/* try PKIX/TLS key first */
#ifndef DISABLE_TLS
SSL *ssl;
if (tls_opt.global_TLS_CTX
&& (ssl = SSL_new(tls_opt.global_TLS_CTX))) {
X509 *cert;
DPRINTF(D_SIGN, "Try to get keys from TLS X.509 cert...\n");
if (!(cert = SSL_get_certificate(ssl))) {
logerror("SSL_get_certificate() failed");
FREE_SSL(ssl);
return false;
}
if (!(privkey = SSL_get_privatekey(ssl))) {
logerror("SSL_get_privatekey() failed");
FREE_SSL(ssl);
return false;
}
if (!(pubkey = X509_get_pubkey(cert))) {
logerror("X509_get_pubkey() failed");
FREE_SSL(ssl);
return false;
}
/* note:
* - privkey is just a pointer into SSL_CTX and
* must not be changed nor be free()d
* - but pubkey has to be freed with EVP_PKEY_free()
*/
FREE_SSL(ssl);
if (EVP_PKEY_DSA != EVP_PKEY_base_id(pubkey)) {
DPRINTF(D_SIGN, "X.509 cert has no DSA key\n");
EVP_PKEY_free(pubkey);
privkey = NULL;
pubkey = NULL;
} else {
DPRINTF(D_SIGN, "Got public and private key "
"from X.509 --> use type PKIX\n");
GlobalSign.keytype = 'C';
GlobalSign.privkey = privkey;
GlobalSign.pubkey = pubkey;
/* note on SG 1 and 2:
* it is assumed that redundant signature groups
* and especially signature groups without an associated
* destination are harmless.
* this currently holds true because sign_append_hash()
* is called from fprintlog(), so only actually used
* signature group get hashes and need memory for them
*/
/* possible optimization for SGs 1 and 2:
* use a struct signature_group_t *newsg[IETF_NUM_PRIVALUES]
* for direct group lookup
*/
#define ALLOC_OR_FALSE(x) do { \
if(!((x) = calloc(1, sizeof(*(x))))) { \
logerror("Unable to allocate memory"); \
return false; \
} \
} while (0)
/* alloc(fq) and add to SGs file queue */
#define ASSIGN_FQ() do { \
ALLOC_OR_FALSE(fq); \
fq->f = f; \
f->f_sg = newsg; \
DPRINTF(D_SIGN, "SG@%p <--> f@%p\n", newsg, f); \
STAILQ_INSERT_TAIL(&newsg->files, fq, entries); \
} while (0)
switch (GlobalSign.sg) {
case 0:
/* one SG, linked to all files */
ALLOC_SG(newsg);
newsg->spri = 0;
for (f = Files; f; f = f->f_next)
ASSIGN_FQ();
STAILQ_INSERT_TAIL(&GlobalSign.SigGroups,
newsg, entries);
break;
case 1:
/* every PRI gets one SG */
for (i = 0; i < IETF_NUM_PRIVALUES; i++) {
int fac, prilev;
fac = LOG_FAC(i);
prilev = LOG_PRI(i);
ALLOC_SG(newsg);
newsg->spri = i;
/* now find all destinations associated with this SG */
for (f = Files; f; f = f->f_next)
/* check priorities */
if (MATCH_PRI(f, fac, prilev))
ASSIGN_FQ();
STAILQ_INSERT_TAIL(&GlobalSign.SigGroups,
newsg, entries);
}
break;
case 2:
/* PRI ranges get one SG, boundaries given by the
* SPRI, indicating the largest PRI in the SG
*
* either GlobalSign.sig2_delims has a list of
* user configured delimiters, or we use a default
* and set up one SG per facility
*/
if (STAILQ_EMPTY(&GlobalSign.sig2_delims)) {
DPRINTF(D_SIGN, "sign_sg_init(): set default "
"values for SG 2\n");
for (i = 0; i < (IETF_NUM_PRIVALUES>>3); i++) {
ALLOC_OR_FALSE(sqentry);
sqentry->data = NULL;
sqentry->key = (i<<3);
STAILQ_INSERT_TAIL(&GlobalSign.sig2_delims,
sqentry, entries);
}
}
assert(!STAILQ_EMPTY(&GlobalSign.sig2_delims));
/* add one more group at the end */
last_sqentry = STAILQ_LAST(&GlobalSign.sig2_delims,
string_queue, entries);
if (last_sqentry->key < IETF_NUM_PRIVALUES) {
ALLOC_OR_FALSE(sqentry);
sqentry->data = NULL;
sqentry->key = IETF_NUM_PRIVALUES-1;
STAILQ_INSERT_TAIL(&GlobalSign.sig2_delims,
sqentry, entries);
}
/* do nothing if CBs already sent or if there was no message in SG */
if (!sg->resendcount
|| ((sg->resendcount == SIGN_RESENDCOUNT_CERTBLOCK)
&& STAILQ_EMPTY(&sg->hashes)))
return false;
STAILQ_FOREACH(fq, &sg->files, entries) {
/* we have to preserve the f_prevcount */
int tmpcnt;
tmpcnt = fq->f->f_prevcount;
fprintlog(fq->f, buffer, NULL);
fq->f->f_prevcount = tmpcnt;
}
sign_inc_gbc();
DELREF(buffer);
payload_index += fragment_len;
}
sg->resendcount--;
return true;
}
/*
* determine the SG for a message
* returns NULL if -sign not configured or no SG for this priority
*/
struct signature_group_t *
sign_get_sg(int pri, struct filed *f)
{
struct signature_group_t *sg, *rc = NULL;
if (GlobalSign.rsid && f)
switch (GlobalSign.sg) {
case 0:
rc = f->f_sg;
break;
case 1:
case 2:
STAILQ_FOREACH(sg, &GlobalSign.SigGroups, entries) {
if (sg->spri >= (unsigned int)pri) {
rc = sg;
break;
}
}
break;
case 3:
if (f->f_flags & FFLAG_SIGN)
rc = f->f_sg;
else
rc = NULL;
break;
}
/*
* create and send signature block
*
* uses a sliding window for redundancy
* if force==true then simply send all available hashes, e.g. on shutdown
*
* sliding window checks implicitly assume that new hashes are appended
* to the SG between two calls. if that is not the case (e.g. with repeated
* messages) the queue size will shrink.
* this has no negative consequences except generating more and shorter SBs
* than expected and confusing the operator because two consecutive SBs will
* have same FMNn
*/
unsigned
sign_send_signature_block(struct signature_group_t *sg, bool force)
{
char sd[SIGN_MAX_SD_LENGTH];
size_t sd_len;
size_t sg_num_hashes = 0; /* hashes in SG queue */
size_t hashes_in_sb = 0; /* number of hashes in current SB */
size_t hashes_sent = 0; /* count of hashes sent */
struct string_queue *qentry, *old_qentry;
struct buf_msg *buffer;
struct filed_queue *fq;
size_t i;
if (!sg) return 0;
DPRINTF((D_CALL|D_SIGN), "sign_send_signature_block(%p, %d)\n",
sg, force);
/*
* sign one syslog-sign message
*
* requires a ssign or ssigt-cert SD element
* ending with ' SIGN=""]' in sd
* linesize is available memory (= sizeof(sd))
*
* function will calculate signature and return a new buffer
*/
bool
sign_msg_sign(struct buf_msg **bufferptr, char *sd, size_t linesize)
{
char *signature, *line;
size_t linelen, tlsprefixlen, endptr, newlinelen;
struct buf_msg *buffer;
/*
* sign one string
*/
bool
sign_string_sign(char *line, char **signature)
{
char buf[SIGN_MAX_LENGTH+1];
unsigned char sig_value[SIGN_B64SIGLEN_DSS];
unsigned char sig_b64[SIGN_B64SIGLEN_DSS];
unsigned sig_len = 0;
char *p, *q;
/*
* The signature is calculated over the completely formatted
* syslog-message, including all of the PRI, HEADER, and hashes
* in the hash block, excluding spaces between fields, and also
* excluding the signature field (SD Parameter Name "SIGN", "=",
* and corresponding value).
*
* -- I am not quite sure which spaces are to be removed.
* Only the ones inside the "ssign" element or those between
* header fields as well?
*/
/* removes the string ' SIGN=""' */
for (p = line, q = buf;
*p && (q - buf <= SIGN_MAX_LENGTH);) {
if (strncmp(p, " SIGN=\"\"", 8) == 0)
p += 8;
*q++ = *p++;
}
*q = '\0';
/* global counters */
GlobalSign.gbc = 0;
/* might be useful for later analysis:
* rebooted session IDs are sequential,
* normal IDs are almost always not */
GlobalSign.rsid++;