diff --git a/g10/build-packet.c b/g10/build-packet.c
index 7eceda0e7..abe018115 100644
--- a/g10/build-packet.c
+++ b/g10/build-packet.c
@@ -1,1311 +1,1315 @@
/* build-packet.c - assemble packets and write them
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
* 2006 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include "packet.h"
#include "errors.h"
#include "iobuf.h"
#include "mpi.h"
#include "util.h"
#include "cipher.h"
#include "memory.h"
#include "i18n.h"
#include "options.h"
static int do_user_id( IOBUF out, int ctb, PKT_user_id *uid );
static int do_public_key( IOBUF out, int ctb, PKT_public_key *pk );
static int do_secret_key( IOBUF out, int ctb, PKT_secret_key *pk );
static int do_symkey_enc( IOBUF out, int ctb, PKT_symkey_enc *enc );
static int do_pubkey_enc( IOBUF out, int ctb, PKT_pubkey_enc *enc );
static u32 calc_plaintext( PKT_plaintext *pt );
static int do_plaintext( IOBUF out, int ctb, PKT_plaintext *pt );
static int do_encrypted( IOBUF out, int ctb, PKT_encrypted *ed );
static int do_encrypted_mdc( IOBUF out, int ctb, PKT_encrypted *ed );
static int do_compressed( IOBUF out, int ctb, PKT_compressed *cd );
static int do_signature( IOBUF out, int ctb, PKT_signature *sig );
static int do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops );
static int calc_header_length( u32 len, int new_ctb );
static int write_16(IOBUF inp, u16 a);
static int write_32(IOBUF inp, u32 a);
static int write_header( IOBUF out, int ctb, u32 len );
static int write_sign_packet_header( IOBUF out, int ctb, u32 len );
static int write_header2( IOBUF out, int ctb, u32 len, int hdrlen );
static int write_new_header( IOBUF out, int ctb, u32 len, int hdrlen );
static int write_version( IOBUF out, int ctb );
/****************
* Build a packet and write it to INP
* Returns: 0 := okay
* >0 := error
* Note: Caller must free the packet
*/
int
build_packet( IOBUF out, PACKET *pkt )
{
int new_ctb=0, rc=0, ctb;
int pkttype;
if( DBG_PACKET )
log_debug("build_packet() type=%d\n", pkt->pkttype );
assert( pkt->pkt.generic );
switch( (pkttype = pkt->pkttype) )
{
case PKT_PLAINTEXT: new_ctb = pkt->pkt.plaintext->new_ctb; break;
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC: new_ctb = pkt->pkt.encrypted->new_ctb; break;
case PKT_COMPRESSED:new_ctb = pkt->pkt.compressed->new_ctb; break;
case PKT_USER_ID:
if( pkt->pkt.user_id->attrib_data )
pkttype = PKT_ATTRIBUTE;
break;
default: break;
}
if( new_ctb || pkttype > 15 ) /* new format */
ctb = 0xc0 | (pkttype & 0x3f);
else
ctb = 0x80 | ((pkttype & 15)<<2);
switch( pkttype )
{
case PKT_ATTRIBUTE:
case PKT_USER_ID:
rc = do_user_id( out, ctb, pkt->pkt.user_id );
break;
case PKT_OLD_COMMENT:
case PKT_COMMENT:
/*
Ignore these. Theoretically, this will never be called as
we have no way to output comment packets any longer, but
just in case there is some code path that would end up
outputting a comment that was written before comments were
dropped (in the public key?) this is a no-op.
*/
break;
case PKT_PUBLIC_SUBKEY:
case PKT_PUBLIC_KEY:
rc = do_public_key( out, ctb, pkt->pkt.public_key );
break;
case PKT_SECRET_SUBKEY:
case PKT_SECRET_KEY:
rc = do_secret_key( out, ctb, pkt->pkt.secret_key );
break;
case PKT_SYMKEY_ENC:
rc = do_symkey_enc( out, ctb, pkt->pkt.symkey_enc );
break;
case PKT_PUBKEY_ENC:
rc = do_pubkey_enc( out, ctb, pkt->pkt.pubkey_enc );
break;
case PKT_PLAINTEXT:
rc = do_plaintext( out, ctb, pkt->pkt.plaintext );
break;
case PKT_ENCRYPTED:
rc = do_encrypted( out, ctb, pkt->pkt.encrypted );
break;
case PKT_ENCRYPTED_MDC:
rc = do_encrypted_mdc( out, ctb, pkt->pkt.encrypted );
break;
case PKT_COMPRESSED:
rc = do_compressed( out, ctb, pkt->pkt.compressed );
break;
case PKT_SIGNATURE:
rc = do_signature( out, ctb, pkt->pkt.signature );
break;
case PKT_ONEPASS_SIG:
rc = do_onepass_sig( out, ctb, pkt->pkt.onepass_sig );
break;
case PKT_RING_TRUST:
break; /* ignore it (keyring.c does write it directly)*/
case PKT_MDC: /* we write it directly, so we should never see it here. */
default:
log_bug("invalid packet type in build_packet()\n");
break;
}
return rc;
}
/****************
* calculate the length of a packet described by PKT
*/
u32
calc_packet_length( PACKET *pkt )
{
u32 n=0;
int new_ctb = 0;
assert( pkt->pkt.generic );
switch( pkt->pkttype ) {
case PKT_PLAINTEXT:
n = calc_plaintext( pkt->pkt.plaintext );
new_ctb = pkt->pkt.plaintext->new_ctb;
break;
case PKT_ATTRIBUTE:
case PKT_USER_ID:
case PKT_COMMENT:
case PKT_PUBLIC_KEY:
case PKT_SECRET_KEY:
case PKT_SYMKEY_ENC:
case PKT_PUBKEY_ENC:
case PKT_ENCRYPTED:
case PKT_SIGNATURE:
case PKT_ONEPASS_SIG:
case PKT_RING_TRUST:
case PKT_COMPRESSED:
default:
log_bug("invalid packet type in calc_packet_length()");
break;
}
n += calc_header_length(n, new_ctb);
return n;
}
static void
write_fake_data( IOBUF out, MPI a )
{
if( a ) {
unsigned int i;
void *p;
p = mpi_get_opaque( a, &i );
iobuf_write( out, p, i );
}
}
static int
do_user_id( IOBUF out, int ctb, PKT_user_id *uid )
{
if( uid->attrib_data )
{
write_header(out, ctb, uid->attrib_len);
if( iobuf_write( out, uid->attrib_data, uid->attrib_len ) )
return G10ERR_WRITE_FILE;
}
else
{
write_header2( out, ctb, uid->len, 2 );
if( iobuf_write( out, uid->name, uid->len ) )
return G10ERR_WRITE_FILE;
}
return 0;
}
static int
do_public_key( IOBUF out, int ctb, PKT_public_key *pk )
{
int rc = 0;
int n, i;
IOBUF a = iobuf_temp();
if( !pk->version )
iobuf_put( a, 3 );
else
iobuf_put( a, pk->version );
write_32(a, pk->timestamp );
if( pk->version < 4 ) {
u16 ndays;
if( pk->expiredate )
ndays = (u16)((pk->expiredate - pk->timestamp) / 86400L);
else
ndays = 0;
write_16(a, ndays );
}
iobuf_put(a, pk->pubkey_algo );
n = pubkey_get_npkey( pk->pubkey_algo );
if( !n )
write_fake_data( a, pk->pkey[0] );
for(i=0; i < n; i++ )
mpi_write(a, pk->pkey[i] );
write_header2(out, ctb, iobuf_get_temp_length(a), pk->hdrbytes);
if( iobuf_write_temp( out, a ) )
rc = G10ERR_WRITE_FILE;
iobuf_close(a);
return rc;
}
static int
do_secret_key( IOBUF out, int ctb, PKT_secret_key *sk )
{
int rc = 0;
int i, nskey, npkey;
IOBUF a = iobuf_temp(); /* build in a self-enlarging buffer */
/* Write the version number - if none is specified, use 3 */
if( !sk->version )
iobuf_put( a, 3 );
else
iobuf_put( a, sk->version );
write_32(a, sk->timestamp );
/* v3 needs the expiration time */
if( sk->version < 4 ) {
u16 ndays;
if( sk->expiredate )
ndays = (u16)((sk->expiredate - sk->timestamp) / 86400L);
else
ndays = 0;
write_16(a, ndays);
}
iobuf_put(a, sk->pubkey_algo );
/* get number of secret and public parameters. They are held in
one array first the public ones, then the secret ones */
nskey = pubkey_get_nskey( sk->pubkey_algo );
npkey = pubkey_get_npkey( sk->pubkey_algo );
/* If we don't have any public parameters - which is the case if
we don't know the algorithm used - the parameters are stored as
one blob in a faked (opaque) MPI */
if( !npkey ) {
write_fake_data( a, sk->skey[0] );
goto leave;
}
assert( npkey < nskey );
/* Writing the public parameters is easy */
for(i=0; i < npkey; i++ )
mpi_write(a, sk->skey[i] );
/* build the header for protected (encrypted) secret parameters */
if( sk->is_protected ) {
if( is_RSA(sk->pubkey_algo) && sk->version < 4
&& !sk->protect.s2k.mode ) {
/* the simple rfc1991 (v3) way */
iobuf_put(a, sk->protect.algo );
iobuf_write(a, sk->protect.iv, sk->protect.ivlen );
}
else {
/* OpenPGP protection according to rfc2440 */
iobuf_put(a, sk->protect.sha1chk? 0xfe : 0xff );
iobuf_put(a, sk->protect.algo );
if( sk->protect.s2k.mode >= 1000 ) {
/* These modes are not possible in OpenPGP, we use them
to implement our extensions, 101 can be seen as a
private/experimental extension (this is not
specified in rfc2440 but the same scheme is used
for all other algorithm identifiers) */
- iobuf_put(a, 101 );
+ iobuf_put(a, 101 );
iobuf_put(a, sk->protect.s2k.hash_algo );
iobuf_write(a, "GNU", 3 );
iobuf_put(a, sk->protect.s2k.mode - 1000 );
}
else {
iobuf_put(a, sk->protect.s2k.mode );
iobuf_put(a, sk->protect.s2k.hash_algo );
}
if( sk->protect.s2k.mode == 1
|| sk->protect.s2k.mode == 3 )
iobuf_write(a, sk->protect.s2k.salt, 8 );
if( sk->protect.s2k.mode == 3 )
- iobuf_put(a, sk->protect.s2k.count );
+ iobuf_put(a, sk->protect.s2k.count );
/* For out special modes 1001, 1002 we do not need an IV */
- if( sk->protect.s2k.mode != 1001
+ if( sk->protect.s2k.mode != 1001
&& sk->protect.s2k.mode != 1002 )
iobuf_write(a, sk->protect.iv, sk->protect.ivlen );
}
}
else
iobuf_put(a, 0 );
if( sk->protect.s2k.mode == 1001 )
- ; /* GnuPG extension - don't write a secret key at all */
+ ; /* GnuPG extension - don't write a secret key at all */
else if( sk->protect.s2k.mode == 1002 )
- { /* GnuPG extension - divert to OpenPGP smartcard. */
+ { /* GnuPG extension - divert to OpenPGP smartcard. */
iobuf_put(a, sk->protect.ivlen ); /* length of the serial
number or 0 for no serial
number. */
/* The serial number gets stored in the IV field. */
iobuf_write(a, sk->protect.iv, sk->protect.ivlen);
}
else if( sk->is_protected && sk->version >= 4 ) {
/* The secret key is protected - write it out as it is */
byte *p;
unsigned int ndata;
assert( mpi_is_opaque( sk->skey[npkey] ) );
p = mpi_get_opaque( sk->skey[npkey], &ndata );
iobuf_write(a, p, ndata );
}
else if( sk->is_protected ) {
/* The secret key is protected te old v4 way. */
for( ; i < nskey; i++ ) {
byte *p;
unsigned int ndata;
assert (mpi_is_opaque (sk->skey[i]));
p = mpi_get_opaque (sk->skey[i], &ndata);
iobuf_write (a, p, ndata);
}
write_16(a, sk->csum );
}
else {
/* non-protected key */
for( ; i < nskey; i++ )
mpi_write(a, sk->skey[i] );
write_16(a, sk->csum );
}
leave:
/* Build the header of the packet - which we must do after writing all
the other stuff, so that we know the length of the packet */
write_header2(out, ctb, iobuf_get_temp_length(a), sk->hdrbytes);
/* And finally write it out the real stream */
if( iobuf_write_temp( out, a ) )
rc = G10ERR_WRITE_FILE;
iobuf_close(a); /* close the remporary buffer */
return rc;
}
static int
do_symkey_enc( IOBUF out, int ctb, PKT_symkey_enc *enc )
{
int rc = 0;
IOBUF a = iobuf_temp();
assert( enc->version == 4 );
switch( enc->s2k.mode ) {
case 0: case 1: case 3: break;
default: log_bug("do_symkey_enc: s2k=%d\n", enc->s2k.mode );
}
iobuf_put( a, enc->version );
iobuf_put( a, enc->cipher_algo );
iobuf_put( a, enc->s2k.mode );
iobuf_put( a, enc->s2k.hash_algo );
if( enc->s2k.mode == 1 || enc->s2k.mode == 3 ) {
iobuf_write(a, enc->s2k.salt, 8 );
if( enc->s2k.mode == 3 )
iobuf_put(a, enc->s2k.count);
}
if( enc->seskeylen )
iobuf_write(a, enc->seskey, enc->seskeylen );
write_header(out, ctb, iobuf_get_temp_length(a) );
if( iobuf_write_temp( out, a ) )
rc = G10ERR_WRITE_FILE;
iobuf_close(a);
return rc;
}
static int
do_pubkey_enc( IOBUF out, int ctb, PKT_pubkey_enc *enc )
{
int rc = 0;
int n, i;
IOBUF a = iobuf_temp();
write_version( a, ctb );
if( enc->throw_keyid ) {
write_32(a, 0 ); /* don't tell Eve who can decrypt the message */
write_32(a, 0 );
}
else {
write_32(a, enc->keyid[0] );
write_32(a, enc->keyid[1] );
}
iobuf_put(a,enc->pubkey_algo );
n = pubkey_get_nenc( enc->pubkey_algo );
if( !n )
write_fake_data( a, enc->data[0] );
for(i=0; i < n; i++ )
mpi_write(a, enc->data[i] );
write_header(out, ctb, iobuf_get_temp_length(a) );
if( iobuf_write_temp( out, a ) )
rc = G10ERR_WRITE_FILE;
iobuf_close(a);
return rc;
}
static u32
calc_plaintext( PKT_plaintext *pt )
{
/* Truncate namelen to the maximum 255 characters. Note this means
that a function that calls build_packet with an illegal literal
packet will get it back legalized. */
if(pt->namelen>255)
pt->namelen=255;
return pt->len? (1 + 1 + pt->namelen + 4 + pt->len) : 0;
}
static int
do_plaintext( IOBUF out, int ctb, PKT_plaintext *pt )
{
int i, rc = 0;
u32 n;
byte buf[1000]; /* this buffer has the plaintext! */
int nbytes;
write_header(out, ctb, calc_plaintext( pt ) );
iobuf_put(out, pt->mode );
iobuf_put(out, pt->namelen );
for(i=0; i < pt->namelen; i++ )
iobuf_put(out, pt->name[i] );
if( write_32(out, pt->timestamp ) )
rc = G10ERR_WRITE_FILE;
n = 0;
while( (nbytes=iobuf_read(pt->buf, buf, 1000)) != -1 ) {
if( iobuf_write(out, buf, nbytes) == -1 ) {
rc = G10ERR_WRITE_FILE;
break;
}
n += nbytes;
}
wipememory(buf,1000); /* burn the buffer */
if( (ctb&0x40) && !pt->len )
iobuf_set_partial_block_mode(out, 0 ); /* turn off partial */
/* On VMS, byte counts will not match for some file record
* formats, so it's best to disable the following error. */
#ifndef __VMS
if( pt->len && n != pt->len )
log_error("do_plaintext(): wrote %lu bytes but expected %lu bytes\n",
(ulong)n, (ulong)pt->len );
#endif
return rc;
}
static int
do_encrypted( IOBUF out, int ctb, PKT_encrypted *ed )
{
int rc = 0;
u32 n;
n = ed->len ? (ed->len + ed->extralen) : 0;
write_header(out, ctb, n );
/* This is all. The caller has to write the real data */
return rc;
}
static int
do_encrypted_mdc( IOBUF out, int ctb, PKT_encrypted *ed )
{
int rc = 0;
u32 n;
assert( ed->mdc_method );
/* Take version number and the following MDC packet in account. */
n = ed->len ? (ed->len + ed->extralen + 1 + 22) : 0;
write_header(out, ctb, n );
iobuf_put(out, 1 ); /* version */
/* This is all. The caller has to write the real data */
return rc;
}
static int
do_compressed( IOBUF out, int ctb, PKT_compressed *cd )
{
int rc = 0;
/* We must use the old convention and don't use blockmode for tyhe
sake of PGP 2 compatibility. However if the new_ctb flag was
set, CTB is already formatted as new style and write_header2
does create a partial length encoding using new the new
style. */
write_header2(out, ctb, 0, 0);
iobuf_put(out, cd->algorithm );
/* This is all. The caller has to write the real data */
return rc;
}
/****************
* Delete all subpackets of type REQTYPE and return a bool whether a packet
* was deleted.
*/
int
delete_sig_subpkt (subpktarea_t *area, sigsubpkttype_t reqtype )
{
int buflen;
sigsubpkttype_t type;
byte *buffer, *bufstart;
size_t n;
size_t unused = 0;
int okay = 0;
if( !area )
return 0;
buflen = area->len;
buffer = area->data;
for(;;) {
if( !buflen ) {
okay = 1;
break;
}
bufstart = buffer;
n = *buffer++; buflen--;
if( n == 255 ) {
if( buflen < 4 )
break;
n = (buffer[0] << 24) | (buffer[1] << 16)
| (buffer[2] << 8) | buffer[3];
buffer += 4;
buflen -= 4;
}
else if( n >= 192 ) {
if( buflen < 2 )
break;
n = (( n - 192 ) << 8) + *buffer + 192;
buffer++;
buflen--;
}
if( buflen < n )
break;
-
+
type = *buffer & 0x7f;
if( type == reqtype ) {
buffer++;
buflen--;
n--;
if( n > buflen )
break;
buffer += n; /* point to next subpkt */
buflen -= n;
memmove (bufstart, buffer, buflen); /* shift */
unused += buffer - bufstart;
buffer = bufstart;
}
else {
buffer += n; buflen -=n;
}
}
if (!okay)
log_error ("delete_subpkt: buffer shorter than subpacket\n");
assert (unused <= area->len);
area->len -= unused;
return !!unused;
}
/****************
* Create or update a signature subpacket for SIG of TYPE. This
* functions knows where to put the data (hashed or unhashed). The
* function may move data from the unhashed part to the hashed one.
* Note: All pointers into sig->[un]hashed (e.g. returned by
* parse_sig_subpkt) are not valid after a call to this function. The
* data to put into the subpaket should be in a buffer with a length
- * of buflen.
+ * of buflen.
*/
void
build_sig_subpkt (PKT_signature *sig, sigsubpkttype_t type,
const byte *buffer, size_t buflen )
{
byte *p;
int critical, hashed;
subpktarea_t *oldarea, *newarea;
size_t nlen, n, n0;
critical = (type & SIGSUBPKT_FLAG_CRITICAL);
type &= ~SIGSUBPKT_FLAG_CRITICAL;
/* Sanity check buffer sizes */
if(parse_one_sig_subpkt(buffer,buflen,type)<0)
BUG();
switch(type)
{
case SIGSUBPKT_NOTATION:
case SIGSUBPKT_POLICY:
case SIGSUBPKT_REV_KEY:
case SIGSUBPKT_SIGNATURE:
/* we do allow multiple subpackets */
break;
default:
/* we don't allow multiple subpackets */
delete_sig_subpkt(sig->hashed,type);
delete_sig_subpkt(sig->unhashed,type);
break;
}
/* Any special magic that needs to be done for this type so the
packet doesn't need to be reparsed? */
switch(type)
{
case SIGSUBPKT_NOTATION:
sig->flags.notation=1;
break;
case SIGSUBPKT_POLICY:
sig->flags.policy_url=1;
break;
case SIGSUBPKT_PREF_KS:
sig->flags.pref_ks=1;
break;
case SIGSUBPKT_EXPORTABLE:
if(buffer[0])
sig->flags.exportable=1;
else
sig->flags.exportable=0;
break;
case SIGSUBPKT_REVOCABLE:
if(buffer[0])
sig->flags.revocable=1;
else
sig->flags.revocable=0;
break;
case SIGSUBPKT_TRUST:
sig->trust_depth=buffer[0];
sig->trust_value=buffer[1];
break;
case SIGSUBPKT_REGEXP:
sig->trust_regexp=buffer;
break;
/* This should never happen since we don't currently allow
creating such a subpacket, but just in case... */
case SIGSUBPKT_SIG_EXPIRE:
if(buffer_to_u32(buffer)+sig->timestamp<=make_timestamp())
sig->flags.expired=1;
else
sig->flags.expired=0;
break;
default:
break;
}
if( (buflen+1) >= 8384 )
nlen = 5; /* write 5 byte length header */
else if( (buflen+1) >= 192 )
nlen = 2; /* write 2 byte length header */
else
nlen = 1; /* just a 1 byte length header */
switch( type )
{
/* The issuer being unhashed is a historical oddity. It
should work equally as well hashed. Of course, if even an
unhashed issuer is tampered with, it makes it awfully hard
to verify the sig... */
case SIGSUBPKT_ISSUER:
case SIGSUBPKT_SIGNATURE:
hashed = 0;
break;
- default:
+ default:
hashed = 1;
break;
}
if( critical )
type |= SIGSUBPKT_FLAG_CRITICAL;
oldarea = hashed? sig->hashed : sig->unhashed;
/* Calculate new size of the area and allocate */
n0 = oldarea? oldarea->len : 0;
n = n0 + nlen + 1 + buflen; /* length, type, buffer */
if (oldarea && n <= oldarea->size) { /* fits into the unused space */
newarea = oldarea;
/*log_debug ("updating area for type %d\n", type );*/
}
else if (oldarea) {
newarea = xrealloc (oldarea, sizeof (*newarea) + n - 1);
newarea->size = n;
/*log_debug ("reallocating area for type %d\n", type );*/
}
else {
newarea = xmalloc (sizeof (*newarea) + n - 1);
newarea->size = n;
/*log_debug ("allocating area for type %d\n", type );*/
}
newarea->len = n;
p = newarea->data + n0;
if (nlen == 5) {
*p++ = 255;
*p++ = (buflen+1) >> 24;
*p++ = (buflen+1) >> 16;
*p++ = (buflen+1) >> 8;
*p++ = (buflen+1);
*p++ = type;
memcpy (p, buffer, buflen);
}
else if (nlen == 2) {
*p++ = (buflen+1-192) / 256 + 192;
*p++ = (buflen+1-192) % 256;
*p++ = type;
memcpy (p, buffer, buflen);
}
else {
*p++ = buflen+1;
*p++ = type;
memcpy (p, buffer, buflen);
}
- if (hashed)
+ if (hashed)
sig->hashed = newarea;
else
sig->unhashed = newarea;
}
/****************
* Put all the required stuff from SIG into subpackets of sig.
* Hmmm, should we delete those subpackets which are in a wrong area?
*/
void
build_sig_subpkt_from_sig( PKT_signature *sig )
{
u32 u;
byte buf[8];
u = sig->keyid[0];
buf[0] = (u >> 24) & 0xff;
buf[1] = (u >> 16) & 0xff;
buf[2] = (u >> 8) & 0xff;
buf[3] = u & 0xff;
u = sig->keyid[1];
buf[4] = (u >> 24) & 0xff;
buf[5] = (u >> 16) & 0xff;
buf[6] = (u >> 8) & 0xff;
buf[7] = u & 0xff;
build_sig_subpkt( sig, SIGSUBPKT_ISSUER, buf, 8 );
u = sig->timestamp;
buf[0] = (u >> 24) & 0xff;
buf[1] = (u >> 16) & 0xff;
buf[2] = (u >> 8) & 0xff;
buf[3] = u & 0xff;
build_sig_subpkt( sig, SIGSUBPKT_SIG_CREATED, buf, 4 );
if(sig->expiredate)
{
if(sig->expiredate>sig->timestamp)
u=sig->expiredate-sig->timestamp;
else
u=1; /* A 1-second expiration time is the shortest one
OpenPGP has */
buf[0] = (u >> 24) & 0xff;
buf[1] = (u >> 16) & 0xff;
buf[2] = (u >> 8) & 0xff;
buf[3] = u & 0xff;
/* Mark this CRITICAL, so if any implementation doesn't
understand sigs that can expire, it'll just disregard this
sig altogether. */
build_sig_subpkt( sig, SIGSUBPKT_SIG_EXPIRE | SIGSUBPKT_FLAG_CRITICAL,
buf, 4 );
}
}
void
build_attribute_subpkt(PKT_user_id *uid,byte type,
const void *buf,u32 buflen,
const void *header,u32 headerlen)
{
byte *attrib;
int idx;
if(1+headerlen+buflen>8383)
idx=5;
else if(1+headerlen+buflen>191)
idx=2;
else
idx=1;
/* realloc uid->attrib_data to the right size */
uid->attrib_data=xrealloc(uid->attrib_data,
uid->attrib_len+idx+1+headerlen+buflen);
attrib=&uid->attrib_data[uid->attrib_len];
if(idx==5)
{
attrib[0]=255;
attrib[1]=(1+headerlen+buflen) >> 24;
attrib[2]=(1+headerlen+buflen) >> 16;
attrib[3]=(1+headerlen+buflen) >> 8;
attrib[4]=1+headerlen+buflen;
}
else if(idx==2)
{
attrib[0]=(1+headerlen+buflen-192) / 256 + 192;
attrib[1]=(1+headerlen+buflen-192) % 256;
}
else
attrib[0]=1+headerlen+buflen; /* Good luck finding a JPEG this small! */
attrib[idx++]=type;
/* Tack on our data at the end */
if(headerlen>0)
memcpy(&attrib[idx],header,headerlen);
memcpy(&attrib[idx+headerlen],buf,buflen);
uid->attrib_len+=idx+headerlen+buflen;
}
struct notation *
string_to_notation(const char *string,int is_utf8)
{
const char *s;
int saw_at=0;
struct notation *notation;
notation=xmalloc_clear(sizeof(*notation));
if(*string=='-')
{
notation->flags.ignore=1;
string++;
}
if(*string=='!')
{
notation->flags.critical=1;
string++;
}
/* If and when the IETF assigns some official name tags, we'll have
to add them here. */
for( s=string ; *s != '='; s++ )
{
if( *s=='@')
saw_at++;
/* -notationname is legal without an = sign */
if(!*s && notation->flags.ignore)
break;
if( !*s || !isascii (*s) || (!isgraph(*s) && !isspace(*s)) )
{
log_error(_("a notation name must have only printable characters"
" or spaces, and end with an '='\n") );
goto fail;
}
}
notation->name=xmalloc((s-string)+1);
strncpy(notation->name,string,s-string);
notation->name[s-string]='\0';
if(!saw_at && !opt.expert)
{
log_error(_("a user notation name must contain the '@' character\n"));
goto fail;
}
if (saw_at > 1)
{
log_error(_("a notation name must not contain more than"
" one '@' character\n"));
goto fail;
}
if(*s)
{
const char *i=s+1;
int highbit=0;
/* we only support printable text - therefore we enforce the use
of only printable characters (an empty value is valid) */
for(s++; *s ; s++ )
{
if ( !isascii (*s) )
highbit=1;
else if (iscntrl(*s))
{
log_error(_("a notation value must not use any"
" control characters\n"));
goto fail;
}
}
if(!highbit || is_utf8)
notation->value=xstrdup(i);
else
notation->value=native_to_utf8(i);
}
return notation;
fail:
free_notation(notation);
return NULL;
}
struct notation *
sig_to_notation(PKT_signature *sig)
{
const byte *p;
size_t len;
int seq=0,crit;
struct notation *list=NULL;
while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_NOTATION,&len,&seq,&crit)))
{
int n1,n2;
struct notation *n=NULL;
if(len<8)
{
log_info(_("WARNING: invalid notation data found\n"));
continue;
}
n1=(p[4]<<8)|p[5];
n2=(p[6]<<8)|p[7];
if(8+n1+n2!=len)
{
log_info(_("WARNING: invalid notation data found\n"));
continue;
}
n=xmalloc_clear(sizeof(*n));
n->name=xmalloc(n1+1);
memcpy(n->name,&p[8],n1);
n->name[n1]='\0';
if(p[0]&0x80)
{
n->value=xmalloc(n2+1);
memcpy(n->value,&p[8+n1],n2);
n->value[n2]='\0';
}
else
{
n->bdat=xmalloc(n2);
n->blen=n2;
memcpy(n->bdat,&p[8+n1],n2);
n->value=xmalloc(2+strlen(_("not human readable"))+2+1);
strcpy(n->value,"[ ");
strcat(n->value,_("not human readable"));
strcat(n->value," ]");
}
n->flags.critical=crit;
n->next=list;
list=n;
}
return list;
}
void
free_notation(struct notation *notation)
{
while(notation)
{
struct notation *n=notation;
xfree(n->name);
xfree(n->value);
xfree(n->altvalue);
xfree(n->bdat);
notation=n->next;
xfree(n);
}
}
static int
do_signature( IOBUF out, int ctb, PKT_signature *sig )
{
int rc = 0;
int n, i;
IOBUF a = iobuf_temp();
if( !sig->version )
iobuf_put( a, 3 );
else
iobuf_put( a, sig->version );
if( sig->version < 4 )
iobuf_put(a, 5 ); /* constant */
iobuf_put(a, sig->sig_class );
if( sig->version < 4 ) {
write_32(a, sig->timestamp );
write_32(a, sig->keyid[0] );
write_32(a, sig->keyid[1] );
}
iobuf_put(a, sig->pubkey_algo );
iobuf_put(a, sig->digest_algo );
if( sig->version >= 4 ) {
size_t nn;
/* timestamp and keyid must have been packed into the
* subpackets prior to the call of this function, because
* these subpackets are hashed */
nn = sig->hashed? sig->hashed->len : 0;
write_16(a, nn);
if( nn )
iobuf_write( a, sig->hashed->data, nn );
nn = sig->unhashed? sig->unhashed->len : 0;
write_16(a, nn);
if( nn )
iobuf_write( a, sig->unhashed->data, nn );
}
iobuf_put(a, sig->digest_start[0] );
iobuf_put(a, sig->digest_start[1] );
n = pubkey_get_nsig( sig->pubkey_algo );
if( !n )
write_fake_data( a, sig->data[0] );
for(i=0; i < n; i++ )
mpi_write(a, sig->data[i] );
if( is_RSA(sig->pubkey_algo) && sig->version < 4 )
write_sign_packet_header(out, ctb, iobuf_get_temp_length(a) );
else
write_header(out, ctb, iobuf_get_temp_length(a) );
if( iobuf_write_temp( out, a ) )
rc = G10ERR_WRITE_FILE;
iobuf_close(a);
return rc;
}
static int
do_onepass_sig( IOBUF out, int ctb, PKT_onepass_sig *ops )
{
int rc = 0;
IOBUF a = iobuf_temp();
write_version( a, ctb );
iobuf_put(a, ops->sig_class );
iobuf_put(a, ops->digest_algo );
iobuf_put(a, ops->pubkey_algo );
write_32(a, ops->keyid[0] );
write_32(a, ops->keyid[1] );
iobuf_put(a, ops->last );
write_header(out, ctb, iobuf_get_temp_length(a) );
if( iobuf_write_temp( out, a ) )
rc = G10ERR_WRITE_FILE;
iobuf_close(a);
return rc;
}
static int
write_16(IOBUF out, u16 a)
{
iobuf_put(out, a>>8);
if( iobuf_put(out,a) )
return -1;
return 0;
}
static int
write_32(IOBUF out, u32 a)
{
iobuf_put(out, a>> 24);
iobuf_put(out, a>> 16);
iobuf_put(out, a>> 8);
if( iobuf_put(out, a) )
return -1;
return 0;
}
/****************
* calculate the length of a header
*/
static int
calc_header_length( u32 len, int new_ctb )
{
if( !len )
return 1; /* only the ctb */
if( new_ctb ) {
if( len < 192 )
return 2;
if( len < 8384 )
return 3;
else
return 6;
}
if( len < 256 )
return 2;
if( len < 65536 )
return 3;
return 5;
}
/****************
* Write the CTB and the packet length
*/
static int
write_header( IOBUF out, int ctb, u32 len )
{
return write_header2( out, ctb, len, 0 );
}
static int
write_sign_packet_header( IOBUF out, int ctb, u32 len )
{
+ (void)ctb;
+
/* work around a bug in the pgp read function for signature packets,
* which are not correctly coded and silently assume at some
* point 2 byte length headers.*/
iobuf_put(out, 0x89 );
iobuf_put(out, len >> 8 );
return iobuf_put(out, len ) == -1 ? -1:0;
}
/****************
* If HDRLEN is > 0, try to build a header of this length. We need
* this so that we can hash packets without reading them again. If
* len is 0, write a partial or indeterminate length header, unless
* hdrlen is specified in which case write an actual zero length
* (using the specified hdrlen).
*/
static int
write_header2( IOBUF out, int ctb, u32 len, int hdrlen )
{
if( ctb & 0x40 )
return write_new_header( out, ctb, len, hdrlen );
if( hdrlen )
{
if( hdrlen == 2 && len < 256 )
;
else if( hdrlen == 3 && len < 65536 )
ctb |= 1;
else
ctb |= 2;
}
else
{
if( !len )
ctb |= 3;
else if( len < 256 )
;
else if( len < 65536 )
ctb |= 1;
else
ctb |= 2;
}
if( iobuf_put(out, ctb ) )
return -1;
if( len || hdrlen )
{
if( ctb & 2 )
{
if(iobuf_put(out, len >> 24 ))
return -1;
if(iobuf_put(out, len >> 16 ))
return -1;
}
if( ctb & 3 )
if(iobuf_put(out, len >> 8 ))
return -1;
if( iobuf_put(out, len ) )
return -1;
}
return 0;
}
static int
write_new_header( IOBUF out, int ctb, u32 len, int hdrlen )
{
if( hdrlen )
log_bug("can't cope with hdrlen yet\n");
if( iobuf_put(out, ctb ) )
return -1;
if( !len ) {
iobuf_set_partial_block_mode(out, 512 );
}
else {
if( len < 192 ) {
if( iobuf_put(out, len ) )
return -1;
}
else if( len < 8384 ) {
len -= 192;
if( iobuf_put( out, (len / 256) + 192) )
return -1;
if( iobuf_put( out, (len % 256) ) )
return -1;
}
else {
if( iobuf_put( out, 0xff ) )
return -1;
if( iobuf_put( out, (len >> 24)&0xff ) )
return -1;
if( iobuf_put( out, (len >> 16)&0xff ) )
return -1;
if( iobuf_put( out, (len >> 8)&0xff ) )
return -1;
if( iobuf_put( out, len & 0xff ) )
return -1;
}
}
return 0;
}
static int
write_version( IOBUF out, int ctb )
{
+ (void)ctb;
+
if( iobuf_put( out, 3 ) )
return -1;
return 0;
}
diff --git a/g10/getkey.c b/g10/getkey.c
index 4506c7c92..9cb5b9504 100644
--- a/g10/getkey.c
+++ b/g10/getkey.c
@@ -1,3054 +1,3056 @@
/* getkey.c - Get a key from the database
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
* 2006 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include "util.h"
#include "packet.h"
#include "memory.h"
#include "iobuf.h"
#include "keydb.h"
#include "options.h"
#include "main.h"
#include "trustdb.h"
#include "i18n.h"
#include "keyserver-internal.h"
#define MAX_PK_CACHE_ENTRIES PK_UID_CACHE_SIZE
#define MAX_UID_CACHE_ENTRIES PK_UID_CACHE_SIZE
#if MAX_PK_CACHE_ENTRIES < 2
#error We need the cache for key creation
#endif
struct getkey_ctx_s {
int exact;
KBNODE keyblock;
KBPOS kbpos;
KBNODE found_key; /* pointer into some keyblock */
int last_rc;
int req_usage;
int req_algo;
KEYDB_HANDLE kr_handle;
int not_allocated;
int nitems;
KEYDB_SEARCH_DESC items[1];
};
#if 0
static struct {
int any;
int okay_count;
int nokey_count;
int error_count;
} lkup_stats[21];
#endif
typedef struct keyid_list {
struct keyid_list *next;
u32 keyid[2];
} *keyid_list_t;
#if MAX_PK_CACHE_ENTRIES
typedef struct pk_cache_entry {
struct pk_cache_entry *next;
u32 keyid[2];
PKT_public_key *pk;
} *pk_cache_entry_t;
static pk_cache_entry_t pk_cache;
static int pk_cache_entries; /* number of entries in pk cache */
static int pk_cache_disabled;
#endif
#if MAX_UID_CACHE_ENTRIES < 5
#error we really need the userid cache
#endif
typedef struct user_id_db {
struct user_id_db *next;
keyid_list_t keyids;
int len;
char name[1];
} *user_id_db_t;
static user_id_db_t user_id_db;
static int uid_cache_entries; /* number of entries in uid cache */
static void merge_selfsigs( KBNODE keyblock );
static int lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode );
#if 0
static void
print_stats()
{
int i;
for(i=0; i < DIM(lkup_stats); i++ ) {
if( lkup_stats[i].any )
fprintf(stderr,
"lookup stats: mode=%-2d ok=%-6d nokey=%-6d err=%-6d\n",
i,
lkup_stats[i].okay_count,
lkup_stats[i].nokey_count,
lkup_stats[i].error_count );
}
}
#endif
void
cache_public_key( PKT_public_key *pk )
{
#if MAX_PK_CACHE_ENTRIES
pk_cache_entry_t ce;
u32 keyid[2];
if( pk_cache_disabled )
return;
if( pk->dont_cache )
return;
if( is_ELGAMAL(pk->pubkey_algo)
|| pk->pubkey_algo == PUBKEY_ALGO_DSA
|| is_RSA(pk->pubkey_algo) ) {
keyid_from_pk( pk, keyid );
}
else
return; /* don't know how to get the keyid */
for( ce = pk_cache; ce; ce = ce->next )
if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] ) {
if( DBG_CACHE )
log_debug("cache_public_key: already in cache\n");
return;
}
if( pk_cache_entries >= MAX_PK_CACHE_ENTRIES ) {
/* fixme: use another algorithm to free some cache slots */
pk_cache_disabled=1;
if( opt.verbose > 1 )
log_info(_("too many entries in pk cache - disabled\n"));
return;
}
pk_cache_entries++;
ce = xmalloc( sizeof *ce );
ce->next = pk_cache;
pk_cache = ce;
ce->pk = copy_public_key( NULL, pk );
ce->keyid[0] = keyid[0];
ce->keyid[1] = keyid[1];
#endif
}
/* Return a const utf-8 string with the text "[User ID not found]".
This fucntion is required so that we don't need to switch gettext's
encoding temporary. */
static const char *
user_id_not_found_utf8 (void)
{
static char *text;
if (!text)
text = native_to_utf8 (_("[User ID not found]"));
return text;
}
/*
* Return the user ID from the given keyblock.
* We use the primary uid flag which has been set by the merge_selfsigs
* function. The returned value is only valid as long as then given
* keyblock is not changed
*/
static const char *
get_primary_uid ( KBNODE keyblock, size_t *uidlen )
{
KBNODE k;
const char *s;
for (k=keyblock; k; k=k->next ) {
if ( k->pkt->pkttype == PKT_USER_ID
&& !k->pkt->pkt.user_id->attrib_data
&& k->pkt->pkt.user_id->is_primary ) {
*uidlen = k->pkt->pkt.user_id->len;
return k->pkt->pkt.user_id->name;
}
- }
+ }
s = user_id_not_found_utf8 ();
*uidlen = strlen (s);
return s;
}
static void
release_keyid_list ( keyid_list_t k )
{
while ( k ) {
keyid_list_t k2 = k->next;
xfree (k);
k = k2;
}
}
/****************
* Store the association of keyid and userid
* Feed only public keys to this function.
*/
static void
cache_user_id( KBNODE keyblock )
{
user_id_db_t r;
const char *uid;
size_t uidlen;
keyid_list_t keyids = NULL;
KBNODE k;
for (k=keyblock; k; k = k->next ) {
if ( k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
keyid_list_t a = xmalloc_clear ( sizeof *a );
/* Hmmm: For a long list of keyids it might be an advantage
* to append the keys */
keyid_from_pk( k->pkt->pkt.public_key, a->keyid );
/* first check for duplicates */
for(r=user_id_db; r; r = r->next ) {
keyid_list_t b = r->keyids;
for ( b = r->keyids; b; b = b->next ) {
if( b->keyid[0] == a->keyid[0]
&& b->keyid[1] == a->keyid[1] ) {
if( DBG_CACHE )
log_debug("cache_user_id: already in cache\n");
release_keyid_list ( keyids );
xfree ( a );
return;
}
}
}
/* now put it into the cache */
a->next = keyids;
keyids = a;
}
}
if ( !keyids )
BUG (); /* No key no fun */
uid = get_primary_uid ( keyblock, &uidlen );
if( uid_cache_entries >= MAX_UID_CACHE_ENTRIES ) {
/* fixme: use another algorithm to free some cache slots */
r = user_id_db;
user_id_db = r->next;
release_keyid_list ( r->keyids );
xfree(r);
uid_cache_entries--;
}
r = xmalloc( sizeof *r + uidlen-1 );
r->keyids = keyids;
r->len = uidlen;
memcpy(r->name, uid, r->len);
r->next = user_id_db;
user_id_db = r;
uid_cache_entries++;
}
void
getkey_disable_caches()
{
#if MAX_PK_CACHE_ENTRIES
{
pk_cache_entry_t ce, ce2;
for( ce = pk_cache; ce; ce = ce2 ) {
ce2 = ce->next;
free_public_key( ce->pk );
xfree( ce );
}
pk_cache_disabled=1;
pk_cache_entries = 0;
pk_cache = NULL;
}
#endif
/* fixme: disable user id cache ? */
}
static void
pk_from_block ( GETKEY_CTX ctx, PKT_public_key *pk, KBNODE keyblock )
{
KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
assert ( a->pkt->pkttype == PKT_PUBLIC_KEY
|| a->pkt->pkttype == PKT_PUBLIC_SUBKEY );
-
+
copy_public_key ( pk, a->pkt->pkt.public_key );
}
static void
sk_from_block ( GETKEY_CTX ctx,
PKT_secret_key *sk, KBNODE keyblock )
{
KBNODE a = ctx->found_key ? ctx->found_key : keyblock;
assert ( a->pkt->pkttype == PKT_SECRET_KEY
|| a->pkt->pkttype == PKT_SECRET_SUBKEY );
-
+
copy_secret_key( sk, a->pkt->pkt.secret_key);
}
/****************
* Get a public key and store it into the allocated pk
* can be called with PK set to NULL to just read it into some
* internal structures.
*/
int
get_pubkey( PKT_public_key *pk, u32 *keyid )
{
int internal = 0;
int rc = 0;
#if MAX_PK_CACHE_ENTRIES
if(pk)
{
/* Try to get it from the cache. We don't do this when pk is
NULL as it does not guarantee that the user IDs are
cached. */
pk_cache_entry_t ce;
for( ce = pk_cache; ce; ce = ce->next )
{
if( ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1] )
{
copy_public_key( pk, ce->pk );
return 0;
}
}
}
#endif
/* more init stuff */
if( !pk ) {
pk = xmalloc_clear( sizeof *pk );
internal++;
}
/* do a lookup */
{ struct getkey_ctx_s ctx;
KBNODE kb = NULL;
memset( &ctx, 0, sizeof ctx );
ctx.exact = 1; /* use the key ID exactly as given */
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new (0);
ctx.nitems = 1;
ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
ctx.items[0].u.kid[0] = keyid[0];
ctx.items[0].u.kid[1] = keyid[1];
ctx.req_algo = pk->req_algo;
ctx.req_usage = pk->req_usage;
rc = lookup( &ctx, &kb, 0 );
if ( !rc ) {
pk_from_block ( &ctx, pk, kb );
}
get_pubkey_end( &ctx );
release_kbnode ( kb );
}
if( !rc )
goto leave;
rc = G10ERR_NO_PUBKEY;
leave:
if( !rc )
cache_public_key( pk );
if( internal )
free_public_key(pk);
return rc;
}
/* Get a public key and store it into the allocated pk. This function
differs from get_pubkey() in that it does not do a check of the key
to avoid recursion. It should be used only in very certain cases.
It will only retrieve primary keys. */
int
get_pubkey_fast (PKT_public_key *pk, u32 *keyid)
{
int rc = 0;
KEYDB_HANDLE hd;
KBNODE keyblock;
u32 pkid[2];
-
+
assert (pk);
#if MAX_PK_CACHE_ENTRIES
{ /* Try to get it from the cache */
pk_cache_entry_t ce;
for (ce = pk_cache; ce; ce = ce->next)
{
if (ce->keyid[0] == keyid[0] && ce->keyid[1] == keyid[1])
{
if (pk)
copy_public_key (pk, ce->pk);
return 0;
}
}
}
#endif
hd = keydb_new (0);
rc = keydb_search_kid (hd, keyid);
if (rc == -1)
{
keydb_release (hd);
return G10ERR_NO_PUBKEY;
}
rc = keydb_get_keyblock (hd, &keyblock);
keydb_release (hd);
- if (rc)
+ if (rc)
{
log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
return G10ERR_NO_PUBKEY;
}
assert ( keyblock->pkt->pkttype == PKT_PUBLIC_KEY
|| keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY );
keyid_from_pk(keyblock->pkt->pkt.public_key,pkid);
if(keyid[0]==pkid[0] && keyid[1]==pkid[1])
copy_public_key (pk, keyblock->pkt->pkt.public_key );
else
rc=G10ERR_NO_PUBKEY;
release_kbnode (keyblock);
/* Not caching key here since it won't have all of the fields
properly set. */
return rc;
}
KBNODE
get_pubkeyblock( u32 *keyid )
{
struct getkey_ctx_s ctx;
int rc = 0;
KBNODE keyblock = NULL;
memset( &ctx, 0, sizeof ctx );
/* no need to set exact here because we want the entire block */
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new (0);
ctx.nitems = 1;
ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
ctx.items[0].u.kid[0] = keyid[0];
ctx.items[0].u.kid[1] = keyid[1];
rc = lookup( &ctx, &keyblock, 0 );
get_pubkey_end( &ctx );
return rc ? NULL : keyblock;
}
/****************
* Get a secret key and store it into sk
*/
int
get_seckey( PKT_secret_key *sk, u32 *keyid )
{
int rc;
struct getkey_ctx_s ctx;
KBNODE kb = NULL;
memset( &ctx, 0, sizeof ctx );
ctx.exact = 1; /* use the key ID exactly as given */
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new (1);
ctx.nitems = 1;
ctx.items[0].mode = KEYDB_SEARCH_MODE_LONG_KID;
ctx.items[0].u.kid[0] = keyid[0];
ctx.items[0].u.kid[1] = keyid[1];
ctx.req_algo = sk->req_algo;
ctx.req_usage = sk->req_usage;
rc = lookup( &ctx, &kb, 1 );
if ( !rc ) {
sk_from_block ( &ctx, sk, kb );
}
get_seckey_end( &ctx );
release_kbnode ( kb );
if( !rc ) {
/* check the secret key (this may prompt for a passprase to
* unlock the secret key
*/
rc = check_secret_key( sk, 0 );
}
return rc;
}
/****************
* Check whether the secret key is available. This is just a fast
* check and does not tell us whether the secret key is valid. It
* merely tells other whether there is some secret key.
* Returns: 0 := key is available
* G10ERR_NO_SECKEY := not availabe
*/
int
seckey_available( u32 *keyid )
{
int rc;
KEYDB_HANDLE hd = keydb_new (1);
rc = keydb_search_kid (hd, keyid);
if ( rc == -1 )
rc = G10ERR_NO_SECKEY;
keydb_release (hd);
return rc;
}
/****************
* Return the type of the user id:
*
* Please use the constants KEYDB_SERCH_MODE_xxx
* 0 = Invalid user ID
* 1 = exact match
* 2 = match a substring
* 3 = match an email address
* 4 = match a substring of an email address
* 5 = match an email address, but compare from end
* 6 = word match mode
* 10 = it is a short KEYID (don't care about keyid[0])
* 11 = it is a long KEYID
* 12 = it is a trustdb index (keyid is looked up)
* 16 = it is a 16 byte fingerprint
* 20 = it is a 20 byte fingerprint
* 21 = Unified fingerprint :fpr:pk_algo:
* (We don't use pk_algo yet)
*
* Rules used:
* - If the username starts with 8,9,16 or 17 hex-digits (the first one
* must be in the range 0..9), this is considered a keyid; depending
* on the length a short or complete one.
* - If the username starts with 32,33,40 or 41 hex-digits (the first one
* must be in the range 0..9), this is considered a fingerprint.
* - If the username starts with a left angle, we assume it is a complete
* email address and look only at this part.
- * - If the username starts with a colon we assume it is a unified
- * key specfification.
+ * - If the username starts with a colon we assume it is a unified
+ * key specfification.
* - If the username starts with a '.', we assume it is the ending
* part of an email address
* - If the username starts with an '@', we assume it is a part of an
* email address
* - If the userid start with an '=' an exact compare is done.
* - If the userid starts with a '*' a case insensitive substring search is
* done (This is the default).
* - If the userid starts with a '+' we will compare individual words
* and a match requires that all the words are in the userid.
* Words are delimited by white space or "()<>[]{}.@-+_,;/&!"
* (note that you can't search for these characters). Compare
* is not case sensitive.
*/
int
classify_user_id( const char *name, KEYDB_SEARCH_DESC *desc )
{
const char *s;
int hexprefix = 0;
int hexlength;
- int mode = 0;
+ int mode = 0;
KEYDB_SEARCH_DESC dummy_desc;
if (!desc)
desc = &dummy_desc;
/* clear the structure so that the mode field is set to zero unless
* we set it to the correct value right at the end of this function */
memset (desc, 0, sizeof *desc);
/* skip leading spaces. Fixme: what is with trailing spaces? */
for(s = name; *s && spacep (s); s++ )
;
switch (*s) {
case 0: /* empty string is an error */
return 0;
#if 0
case '.': /* an email address, compare from end */
mode = KEYDB_SEARCH_MODE_MAILEND;
s++;
desc->u.name = s;
break;
#endif
case '<': /* an email address */
mode = KEYDB_SEARCH_MODE_MAIL;
desc->u.name = s;
break;
case '@': /* part of an email address */
mode = KEYDB_SEARCH_MODE_MAILSUB;
s++;
desc->u.name = s;
break;
case '=': /* exact compare */
mode = KEYDB_SEARCH_MODE_EXACT;
s++;
desc->u.name = s;
break;
case '*': /* case insensitive substring search */
mode = KEYDB_SEARCH_MODE_SUBSTR;
s++;
desc->u.name = s;
break;
#if 0
case '+': /* compare individual words */
mode = KEYDB_SEARCH_MODE_WORDS;
s++;
desc->u.name = s;
break;
#endif
case '#': /* local user id */
return 0; /* This is now obsolete and van't not be used anymore*/
-
+
case ':': /*Unified fingerprint */
- {
+ {
const char *se, *si;
int i;
-
+
se = strchr( ++s,':');
if ( !se )
return 0;
for (i=0,si=s; si < se; si++, i++ ) {
if ( !strchr("01234567890abcdefABCDEF", *si ) )
return 0; /* invalid digit */
}
if (i != 32 && i != 40)
return 0; /* invalid length of fpr*/
- for (i=0,si=s; si < se; i++, si +=2)
+ for (i=0,si=s; si < se; i++, si +=2)
desc->u.fpr[i] = hextobyte(si);
for ( ; i < 20; i++)
desc->u.fpr[i]= 0;
s = se + 1;
mode = KEYDB_SEARCH_MODE_FPR;
- }
+ }
break;
-
+
default:
if (s[0] == '0' && s[1] == 'x') {
hexprefix = 1;
s += 2;
}
hexlength = strspn(s, "0123456789abcdefABCDEF");
if (hexlength >= 8 && s[hexlength] =='!') {
desc->exact = 1;
hexlength++; /* just for the following check */
}
/* check if a hexadecimal number is terminated by EOS or blank */
if (hexlength && s[hexlength] && !spacep(s+hexlength)) {
if (hexprefix) /* a "0x" prefix without correct */
return 0; /* termination is an error */
else /* The first chars looked like */
hexlength = 0; /* a hex number, but really were not. */
}
if (desc->exact)
hexlength--;
if (hexlength == 8
|| (!hexprefix && hexlength == 9 && *s == '0')){
/* short keyid */
if (hexlength == 9)
s++;
desc->u.kid[0] = 0;
desc->u.kid[1] = strtoul( s, NULL, 16 );
mode = KEYDB_SEARCH_MODE_SHORT_KID;
}
else if (hexlength == 16
|| (!hexprefix && hexlength == 17 && *s == '0')) {
/* complete keyid */
char buf[9];
if (hexlength == 17)
s++;
mem2str(buf, s, 9 );
desc->u.kid[0] = strtoul( buf, NULL, 16 );
desc->u.kid[1] = strtoul( s+8, NULL, 16 );
mode = KEYDB_SEARCH_MODE_LONG_KID;
}
else if (hexlength == 32 || (!hexprefix && hexlength == 33
&& *s == '0')) {
/* md5 fingerprint */
int i;
if (hexlength == 33)
s++;
- memset(desc->u.fpr+16, 0, 4);
+ memset(desc->u.fpr+16, 0, 4);
for (i=0; i < 16; i++, s+=2) {
int c = hextobyte(s);
if (c == -1)
return 0;
desc->u.fpr[i] = c;
}
mode = KEYDB_SEARCH_MODE_FPR16;
}
else if (hexlength == 40 || (!hexprefix && hexlength == 41
&& *s == '0')) {
/* sha1/rmd160 fingerprint */
int i;
if (hexlength == 41)
s++;
for (i=0; i < 20; i++, s+=2) {
int c = hextobyte(s);
if (c == -1)
return 0;
desc->u.fpr[i] = c;
}
mode = KEYDB_SEARCH_MODE_FPR20;
}
else {
if (hexprefix) /* This was a hex number with a prefix */
return 0; /* and a wrong length */
desc->exact = 0;
desc->u.name = s;
mode = KEYDB_SEARCH_MODE_SUBSTR; /* default mode */
}
}
desc->mode = mode;
return mode;
}
static int
-skip_unusable(void *dummy,u32 *keyid,PKT_user_id *uid)
+skip_unusable(void *dummy, u32 *keyid,PKT_user_id *uid)
{
int unusable=0;
KBNODE keyblock;
+ (void)dummy;
+
keyblock=get_pubkeyblock(keyid);
if(!keyblock)
{
log_error("error checking usability status of %s\n",keystr(keyid));
goto leave;
}
/* Is the user ID in question revoked/expired? */
if(uid)
{
KBNODE node;
for(node=keyblock;node;node=node->next)
{
if(node->pkt->pkttype==PKT_USER_ID)
{
if(cmp_user_ids(uid,node->pkt->pkt.user_id)==0
&& (node->pkt->pkt.user_id->is_revoked
|| node->pkt->pkt.user_id->is_expired))
{
unusable=1;
break;
}
}
}
}
if(!unusable)
unusable=pk_is_disabled(keyblock->pkt->pkt.public_key);
leave:
release_kbnode(keyblock);
return unusable;
}
/****************
* Try to get the pubkey by the userid. This function looks for the
* first pubkey certificate which has the given name in a user_id. if
* pk/sk has the pubkey algo set, the function will only return a
* pubkey with that algo. If namelist is NULL, the first key is
* returned. The caller should provide storage for either the pk or
* the sk. If ret_kb is not NULL the function will return the
* keyblock there.
*/
static int
key_byname( GETKEY_CTX *retctx, STRLIST namelist,
PKT_public_key *pk, PKT_secret_key *sk,
int secmode, int include_unusable,
KBNODE *ret_kb, KEYDB_HANDLE *ret_kdbhd )
{
int rc = 0;
int n;
STRLIST r;
GETKEY_CTX ctx;
KBNODE help_kb = NULL;
-
+
if( retctx ) {/* reset the returned context in case of error */
assert (!ret_kdbhd); /* not allowed because the handle is
stored in the context */
*retctx = NULL;
}
if (ret_kdbhd)
*ret_kdbhd = NULL;
if(!namelist)
{
ctx = xmalloc_clear (sizeof *ctx);
ctx->nitems = 1;
ctx->items[0].mode=KEYDB_SEARCH_MODE_FIRST;
if(!include_unusable)
ctx->items[0].skipfnc=skip_unusable;
}
else
{
/* build the search context */
for(n=0, r=namelist; r; r = r->next )
n++;
ctx = xmalloc_clear (sizeof *ctx + (n-1)*sizeof ctx->items );
ctx->nitems = n;
for(n=0, r=namelist; r; r = r->next, n++ )
{
classify_user_id (r->d, &ctx->items[n]);
-
+
if (ctx->items[n].exact)
ctx->exact = 1;
if (!ctx->items[n].mode)
{
xfree (ctx);
return G10ERR_INV_USER_ID;
}
if(!include_unusable
&& ctx->items[n].mode!=KEYDB_SEARCH_MODE_SHORT_KID
&& ctx->items[n].mode!=KEYDB_SEARCH_MODE_LONG_KID
&& ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR16
&& ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR20
&& ctx->items[n].mode!=KEYDB_SEARCH_MODE_FPR)
ctx->items[n].skipfnc=skip_unusable;
}
}
ctx->kr_handle = keydb_new (secmode);
- if ( !ret_kb )
+ if ( !ret_kb )
ret_kb = &help_kb;
if( secmode ) {
if (sk) {
ctx->req_algo = sk->req_algo;
ctx->req_usage = sk->req_usage;
}
rc = lookup( ctx, ret_kb, 1 );
if ( !rc && sk ) {
sk_from_block ( ctx, sk, *ret_kb );
}
}
else {
if (pk) {
ctx->req_algo = pk->req_algo;
ctx->req_usage = pk->req_usage;
}
rc = lookup( ctx, ret_kb, 0 );
if ( !rc && pk ) {
pk_from_block ( ctx, pk, *ret_kb );
}
}
release_kbnode ( help_kb );
if (retctx) /* caller wants the context */
*retctx = ctx;
else {
if (ret_kdbhd) {
*ret_kdbhd = ctx->kr_handle;
ctx->kr_handle = NULL;
}
get_pubkey_end (ctx);
}
return rc;
}
/* Find a public key from NAME and return the keyblock or the key. If
ret_kdb is not NULL, the KEYDB handle used to locate this keyblock
is returned and the caller is responsible for closing it. If a key
was not found and NAME is a valid RFC822 mailbox and PKA retrieval
has been enabled, we try to import the pkea via the PKA
mechanism. */
int
get_pubkey_byname (PKT_public_key *pk,
const char *name, KBNODE *ret_keyblock,
KEYDB_HANDLE *ret_kdbhd, int include_unusable )
{
int rc;
STRLIST namelist = NULL;
add_to_strlist( &namelist, name );
rc = key_byname( NULL, namelist, pk, NULL, 0,
include_unusable, ret_keyblock, ret_kdbhd);
/* If the requested name resembles a valid mailbox and automatic
retrieval has been enabled, we try to import the key. */
if (rc == G10ERR_NO_PUBKEY && is_valid_mailbox(name))
{
struct akl *akl;
for(akl=opt.auto_key_locate;akl;akl=akl->next)
{
unsigned char *fpr=NULL;
size_t fpr_len;
switch(akl->type)
{
case AKL_CERT:
glo_ctrl.in_auto_key_retrieve++;
rc=keyserver_import_cert(name,&fpr,&fpr_len);
glo_ctrl.in_auto_key_retrieve--;
if(rc==0)
log_info(_("automatically retrieved `%s' via %s\n"),
name,"DNS CERT");
break;
case AKL_PKA:
glo_ctrl.in_auto_key_retrieve++;
rc=keyserver_import_pka(name,&fpr,&fpr_len);
glo_ctrl.in_auto_key_retrieve--;
if(rc==0)
log_info(_("automatically retrieved `%s' via %s\n"),
name,"PKA");
break;
case AKL_LDAP:
glo_ctrl.in_auto_key_retrieve++;
rc=keyserver_import_ldap(name,&fpr,&fpr_len);
glo_ctrl.in_auto_key_retrieve--;
if(rc==0)
log_info(_("automatically retrieved `%s' via %s\n"),
name,"LDAP");
break;
case AKL_KEYSERVER:
/* Strictly speaking, we don't need to only use a valid
mailbox for the getname search, but it helps cut down
on the problem of searching for something like "john"
and getting a whole lot of keys back. */
if(opt.keyserver)
{
glo_ctrl.in_auto_key_retrieve++;
rc=keyserver_import_name(name,&fpr,&fpr_len,opt.keyserver);
glo_ctrl.in_auto_key_retrieve--;
if(rc==0)
log_info(_("automatically retrieved `%s' via %s\n"),
name,opt.keyserver->uri);
}
break;
case AKL_SPEC:
{
struct keyserver_spec *keyserver;
keyserver=keyserver_match(akl->spec);
glo_ctrl.in_auto_key_retrieve++;
rc=keyserver_import_name(name,&fpr,&fpr_len,keyserver);
glo_ctrl.in_auto_key_retrieve--;
if(rc==0)
log_info(_("automatically retrieved `%s' via %s\n"),
name,akl->spec->uri);
}
break;
}
/* Use the fingerprint of the key that we actually fetched.
This helps prevent problems where the key that we fetched
doesn't have the same name that we used to fetch it. In
the case of CERT and PKA, this is an actual security
requirement as the URL might point to a key put in by an
attacker. By forcing the use of the fingerprint, we
won't use the attacker's key here. */
if(rc==0 && fpr)
{
int i;
char fpr_string[MAX_FINGERPRINT_LEN*2+1];
assert(fpr_len<=MAX_FINGERPRINT_LEN);
free_strlist(namelist);
namelist=NULL;
for(i=0;ikbpos, 0, sizeof ctx->kbpos);
keydb_release (ctx->kr_handle);
if( !ctx->not_allocated )
xfree( ctx );
}
}
/****************
* Search for a key with the given fingerprint.
* FIXME:
* We should replace this with the _byname function. Thiscsan be done
- * by creating a userID conforming to the unified fingerprint style.
+ * by creating a userID conforming to the unified fingerprint style.
*/
int
get_pubkey_byfprint( PKT_public_key *pk,
const byte *fprint, size_t fprint_len)
{
int rc;
if( fprint_len == 20 || fprint_len == 16 ) {
struct getkey_ctx_s ctx;
KBNODE kb = NULL;
memset( &ctx, 0, sizeof ctx );
ctx.exact = 1 ;
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new (0);
ctx.nitems = 1;
ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
: KEYDB_SEARCH_MODE_FPR20;
memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
rc = lookup( &ctx, &kb, 0 );
if (!rc && pk )
pk_from_block ( &ctx, pk, kb );
release_kbnode ( kb );
get_pubkey_end( &ctx );
}
else
rc = G10ERR_GENERAL; /* Oops */
return rc;
}
/* Get a public key and store it into the allocated pk. This function
differs from get_pubkey_byfprint() in that it does not do a check
of the key to avoid recursion. It should be used only in very
certain cases. PK may be NULL to check just for the existance of
the key. */
int
get_pubkey_byfprint_fast (PKT_public_key *pk,
const byte *fprint, size_t fprint_len)
{
int rc = 0;
KEYDB_HANDLE hd;
KBNODE keyblock;
byte fprbuf[MAX_FINGERPRINT_LEN];
int i;
-
+
for (i=0; i < MAX_FINGERPRINT_LEN && i < fprint_len; i++)
fprbuf[i] = fprint[i];
- while (i < MAX_FINGERPRINT_LEN)
+ while (i < MAX_FINGERPRINT_LEN)
fprbuf[i++] = 0;
hd = keydb_new (0);
rc = keydb_search_fpr (hd, fprbuf);
if (rc == -1)
{
keydb_release (hd);
return G10ERR_NO_PUBKEY;
}
rc = keydb_get_keyblock (hd, &keyblock);
keydb_release (hd);
- if (rc)
+ if (rc)
{
log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
return G10ERR_NO_PUBKEY;
}
-
+
assert ( keyblock->pkt->pkttype == PKT_PUBLIC_KEY
|| keyblock->pkt->pkttype == PKT_PUBLIC_SUBKEY );
if (pk)
copy_public_key (pk, keyblock->pkt->pkt.public_key );
release_kbnode (keyblock);
/* Not caching key here since it won't have all of the fields
properly set. */
return 0;
}
/****************
* Search for a key with the given fingerprint and return the
* complete keyblock which may have more than only this key.
*/
int
get_keyblock_byfprint( KBNODE *ret_keyblock, const byte *fprint,
size_t fprint_len )
{
int rc;
if( fprint_len == 20 || fprint_len == 16 ) {
struct getkey_ctx_s ctx;
memset( &ctx, 0, sizeof ctx );
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new (0);
ctx.nitems = 1;
ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
: KEYDB_SEARCH_MODE_FPR20;
memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
rc = lookup( &ctx, ret_keyblock, 0 );
get_pubkey_end( &ctx );
}
else
rc = G10ERR_GENERAL; /* Oops */
return rc;
}
/****************
* Get a secret key by name and store it into sk
* If NAME is NULL use the default key
*/
static int
get_seckey_byname2( GETKEY_CTX *retctx,
PKT_secret_key *sk, const char *name, int unprotect,
KBNODE *retblock )
{
STRLIST namelist = NULL;
int rc,include_unusable=1;
/* If we have no name, try to use the default secret key. If we
have no default, we'll use the first usable one. */
if( !name && opt.def_secret_key && *opt.def_secret_key )
add_to_strlist( &namelist, opt.def_secret_key );
else if(name)
add_to_strlist( &namelist, name );
else
include_unusable=0;
rc = key_byname( retctx, namelist, NULL, sk, 1, include_unusable,
retblock, NULL );
free_strlist( namelist );
if( !rc && unprotect )
rc = check_secret_key( sk, 0 );
return rc;
}
-int
+int
get_seckey_byname( PKT_secret_key *sk, const char *name, int unlock )
{
return get_seckey_byname2 ( NULL, sk, name, unlock, NULL );
}
int
get_seckey_bynames( GETKEY_CTX *retctx, PKT_secret_key *sk,
STRLIST names, KBNODE *ret_keyblock )
{
return key_byname( retctx, names, NULL, sk, 1, 1, ret_keyblock, NULL );
}
int
get_seckey_next( GETKEY_CTX ctx, PKT_secret_key *sk, KBNODE *ret_keyblock )
{
int rc;
rc = lookup( ctx, ret_keyblock, 1 );
if ( !rc && sk && ret_keyblock )
sk_from_block ( ctx, sk, *ret_keyblock );
return rc;
}
void
get_seckey_end( GETKEY_CTX ctx )
{
get_pubkey_end( ctx );
}
/****************
* Search for a key with the given fingerprint.
* FIXME:
* We should replace this with the _byname function. Thiscsan be done
- * by creating a userID conforming to the unified fingerprint style.
+ * by creating a userID conforming to the unified fingerprint style.
*/
int
get_seckey_byfprint( PKT_secret_key *sk,
const byte *fprint, size_t fprint_len)
{
int rc;
if( fprint_len == 20 || fprint_len == 16 ) {
struct getkey_ctx_s ctx;
KBNODE kb = NULL;
memset( &ctx, 0, sizeof ctx );
ctx.exact = 1 ;
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new (1);
ctx.nitems = 1;
ctx.items[0].mode = fprint_len==16? KEYDB_SEARCH_MODE_FPR16
: KEYDB_SEARCH_MODE_FPR20;
memcpy( ctx.items[0].u.fpr, fprint, fprint_len );
rc = lookup( &ctx, &kb, 1 );
if (!rc && sk )
sk_from_block ( &ctx, sk, kb );
release_kbnode ( kb );
get_seckey_end( &ctx );
}
else
rc = G10ERR_GENERAL; /* Oops */
return rc;
}
/* Search for a secret key with the given fingerprint and return the
complete keyblock which may have more than only this key. */
int
get_seckeyblock_byfprint (KBNODE *ret_keyblock, const byte *fprint,
size_t fprint_len )
{
int rc;
struct getkey_ctx_s ctx;
-
+
if (fprint_len != 20 && fprint_len == 16)
return G10ERR_GENERAL; /* Oops */
-
+
memset (&ctx, 0, sizeof ctx);
ctx.not_allocated = 1;
ctx.kr_handle = keydb_new (1);
ctx.nitems = 1;
ctx.items[0].mode = (fprint_len==16
? KEYDB_SEARCH_MODE_FPR16
: KEYDB_SEARCH_MODE_FPR20);
memcpy (ctx.items[0].u.fpr, fprint, fprint_len);
rc = lookup (&ctx, ret_keyblock, 1);
get_seckey_end (&ctx);
-
+
return rc;
}
/************************************************
************* Merging stuff ********************
************************************************/
/****************
* merge all selfsignatures with the keys.
* FIXME: replace this at least for the public key parts
* by merge_selfsigs.
* It is still used in keyedit.c and
* at 2 or 3 other places - check whether it is really needed.
* It might be needed by the key edit and import stuff because
* the keylock is changed.
*/
void
merge_keys_and_selfsig( KBNODE keyblock )
{
PKT_public_key *pk = NULL;
PKT_secret_key *sk = NULL;
PKT_signature *sig;
KBNODE k;
u32 kid[2] = { 0, 0 };
u32 sigdate = 0;
if (keyblock && keyblock->pkt->pkttype == PKT_PUBLIC_KEY ) {
/* divert to our new function */
merge_selfsigs (keyblock);
return;
}
/* still need the old one because the new one can't handle secret keys */
for(k=keyblock; k; k = k->next ) {
if( k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
pk = k->pkt->pkt.public_key; sk = NULL;
if( pk->version < 4 )
pk = NULL; /* not needed for old keys */
else if( k->pkt->pkttype == PKT_PUBLIC_KEY )
keyid_from_pk( pk, kid );
else if( !pk->expiredate ) { /* and subkey */
/* insert the expiration date here */
/*FIXME!!! pk->expiredate = subkeys_expiretime( k, kid );*/
}
sigdate = 0;
}
else if( k->pkt->pkttype == PKT_SECRET_KEY
|| k->pkt->pkttype == PKT_SECRET_SUBKEY ) {
pk = NULL; sk = k->pkt->pkt.secret_key;
if( sk->version < 4 )
sk = NULL;
else if( k->pkt->pkttype == PKT_SECRET_KEY )
keyid_from_sk( sk, kid );
sigdate = 0;
}
else if( (pk || sk ) && k->pkt->pkttype == PKT_SIGNATURE
&& (sig=k->pkt->pkt.signature)->sig_class >= 0x10
&& sig->sig_class <= 0x30 && sig->version > 3
&& !(sig->sig_class == 0x18 || sig->sig_class == 0x28)
&& sig->keyid[0] == kid[0] && sig->keyid[1] == kid[1] ) {
/* okay this is a self-signature which can be used.
* This is not used for subkey binding signature, becuase this
* is done above.
* FIXME: We should only use this if the signature is valid
* but this is time consuming - we must provide another
* way to handle this
*/
const byte *p;
u32 ed;
p = parse_sig_subpkt( sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL );
if( pk ) {
ed = p? pk->timestamp + buffer_to_u32(p):0;
if( sig->timestamp > sigdate ) {
pk->expiredate = ed;
sigdate = sig->timestamp;
}
}
else {
ed = p? sk->timestamp + buffer_to_u32(p):0;
if( sig->timestamp > sigdate ) {
sk->expiredate = ed;
sigdate = sig->timestamp;
}
}
}
if(pk && (pk->expiredate==0 ||
(pk->max_expiredate && pk->expiredate>pk->max_expiredate)))
pk->expiredate=pk->max_expiredate;
if(sk && (sk->expiredate==0 ||
(sk->max_expiredate && sk->expiredate>sk->max_expiredate)))
sk->expiredate=sk->max_expiredate;
}
}
static int
parse_key_usage(PKT_signature *sig)
{
int key_usage=0;
const byte *p;
size_t n;
byte flags;
p=parse_sig_subpkt(sig->hashed,SIGSUBPKT_KEY_FLAGS,&n);
if(p && n)
{
/* first octet of the keyflags */
flags=*p;
if(flags & 1)
{
key_usage |= PUBKEY_USAGE_CERT;
flags&=~1;
}
if(flags & 2)
{
key_usage |= PUBKEY_USAGE_SIG;
flags&=~2;
}
/* We do not distinguish between encrypting communications and
encrypting storage. */
if(flags & (0x04|0x08))
{
key_usage |= PUBKEY_USAGE_ENC;
flags&=~(0x04|0x08);
}
if(flags & 0x20)
{
key_usage |= PUBKEY_USAGE_AUTH;
flags&=~0x20;
}
if(flags)
key_usage |= PUBKEY_USAGE_UNKNOWN;
}
/* We set PUBKEY_USAGE_UNKNOWN to indicate that this key has a
capability that we do not handle. This serves to distinguish
between a zero key usage which we handle as the default
capabilities for that algorithm, and a usage that we do not
handle. */
return key_usage;
}
/*
* Apply information from SIGNODE (which is the valid self-signature
* associated with that UID) to the UIDNODE:
* - wether the UID has been revoked
* - assumed creation date of the UID
* - temporary store the keyflags here
* - temporary store the key expiration time here
* - mark whether the primary user ID flag hat been set.
* - store the preferences
*/
static void
fixup_uidnode ( KBNODE uidnode, KBNODE signode, u32 keycreated )
{
PKT_user_id *uid = uidnode->pkt->pkt.user_id;
PKT_signature *sig = signode->pkt->pkt.signature;
const byte *p, *sym, *hash, *zip;
size_t n, nsym, nhash, nzip;
sig->flags.chosen_selfsig = 1; /* we chose this one */
uid->created = 0; /* not created == invalid */
if ( IS_UID_REV ( sig ) )
{
uid->is_revoked = 1;
return; /* has been revoked */
}
else
uid->is_revoked=0;
uid->expiredate = sig->expiredate;
if(sig->flags.expired)
{
uid->is_expired = 1;
return; /* has expired */
}
else
uid->is_expired=0;
uid->created = sig->timestamp; /* this one is okay */
uid->selfsigversion = sig->version;
/* If we got this far, it's not expired :) */
uid->is_expired = 0;
/* store the key flags in the helper variable for later processing */
uid->help_key_usage=parse_key_usage(sig);
/* ditto for the key expiration */
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
if( p && buffer_to_u32(p) )
uid->help_key_expire = keycreated + buffer_to_u32(p);
else
uid->help_key_expire = 0;
/* Set the primary user ID flag - we will later wipe out some
* of them to only have one in our keyblock */
uid->is_primary = 0;
p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PRIMARY_UID, NULL );
if ( p && *p )
uid->is_primary = 2;
/* We could also query this from the unhashed area if it is not in
* the hased area and then later try to decide which is the better
* there should be no security problem with this.
- * For now we only look at the hashed one.
+ * For now we only look at the hashed one.
*/
/* Now build the preferences list. These must come from the
hashed section so nobody can modify the ciphers a key is
willing to accept. */
p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_SYM, &n );
sym = p; nsym = p?n:0;
p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_HASH, &n );
hash = p; nhash = p?n:0;
p = parse_sig_subpkt ( sig->hashed, SIGSUBPKT_PREF_COMPR, &n );
zip = p; nzip = p?n:0;
- if (uid->prefs)
+ if (uid->prefs)
xfree (uid->prefs);
n = nsym + nhash + nzip;
if (!n)
uid->prefs = NULL;
else {
uid->prefs = xmalloc (sizeof (*uid->prefs) * (n+1));
n = 0;
for (; nsym; nsym--, n++) {
uid->prefs[n].type = PREFTYPE_SYM;
uid->prefs[n].value = *sym++;
}
for (; nhash; nhash--, n++) {
uid->prefs[n].type = PREFTYPE_HASH;
uid->prefs[n].value = *hash++;
}
for (; nzip; nzip--, n++) {
uid->prefs[n].type = PREFTYPE_ZIP;
uid->prefs[n].value = *zip++;
}
uid->prefs[n].type = PREFTYPE_NONE; /* end of list marker */
uid->prefs[n].value = 0;
}
/* see whether we have the MDC feature */
uid->flags.mdc = 0;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_FEATURES, &n);
if (p && n && (p[0] & 0x01))
uid->flags.mdc = 1;
/* and the keyserver modify flag */
uid->flags.ks_modify = 1;
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KS_FLAGS, &n);
if (p && n && (p[0] & 0x80))
uid->flags.ks_modify = 0;
}
static void
sig_to_revoke_info(PKT_signature *sig,struct revoke_info *rinfo)
{
rinfo->date = sig->timestamp;
rinfo->algo = sig->pubkey_algo;
rinfo->keyid[0] = sig->keyid[0];
rinfo->keyid[1] = sig->keyid[1];
}
static void
merge_selfsigs_main(KBNODE keyblock, int *r_revoked, struct revoke_info *rinfo)
{
PKT_public_key *pk = NULL;
KBNODE k;
u32 kid[2];
u32 sigdate, uiddate, uiddate2;
KBNODE signode, uidnode, uidnode2;
u32 curtime = make_timestamp ();
unsigned int key_usage = 0;
u32 keytimestamp = 0;
u32 key_expire = 0;
int key_expire_seen = 0;
byte sigversion = 0;
*r_revoked = 0;
memset(rinfo,0,sizeof(*rinfo));
if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY )
BUG ();
pk = keyblock->pkt->pkt.public_key;
keytimestamp = pk->timestamp;
keyid_from_pk( pk, kid );
pk->main_keyid[0] = kid[0];
pk->main_keyid[1] = kid[1];
if ( pk->version < 4 ) {
/* before v4 the key packet itself contains the expiration
* date and there was no way to change it, so we start with
* the one from the key packet */
key_expire = pk->max_expiredate;
key_expire_seen = 1;
}
/* first pass: find the latest direct key self-signature.
* We assume that the newest one overrides all others
*/
/* In case this key was already merged */
xfree(pk->revkey);
pk->revkey=NULL;
pk->numrevkeys=0;
signode = NULL;
sigdate = 0; /* helper to find the latest signature */
for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next ) {
if ( k->pkt->pkttype == PKT_SIGNATURE ) {
PKT_signature *sig = k->pkt->pkt.signature;
- if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
+ if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
if ( check_key_signature( keyblock, k, NULL ) )
; /* signature did not verify */
else if ( IS_KEY_REV (sig) ){
/* key has been revoked - there is no way to override
* such a revocation, so we theoretically can stop now.
* We should not cope with expiration times for revocations
* here because we have to assume that an attacker can
* generate all kinds of signatures. However due to the
* fact that the key has been revoked it does not harm
- * either and by continuing we gather some more info on
+ * either and by continuing we gather some more info on
* that key.
- */
+ */
*r_revoked = 1;
sig_to_revoke_info(sig,rinfo);
}
else if ( IS_KEY_SIG (sig) ) {
/* Add any revocation keys onto the pk. This is
particularly interesting since we normally only
get data from the most recent 1F signature, but
you need multiple 1F sigs to properly handle
revocation keys (PGP does it this way, and a
revocation key could be sensitive and hence in a
different signature). */
if(sig->revkey) {
int i;
pk->revkey=
xrealloc(pk->revkey,sizeof(struct revocation_key)*
(pk->numrevkeys+sig->numrevkeys));
for(i=0;inumrevkeys;i++)
memcpy(&pk->revkey[pk->numrevkeys++],
sig->revkey[i],
sizeof(struct revocation_key));
}
if( sig->timestamp >= sigdate ) {
if(sig->flags.expired)
; /* signature has expired - ignore it */
else {
sigdate = sig->timestamp;
signode = k;
if( sig->version > sigversion )
sigversion = sig->version;
}
}
}
}
}
}
/* Remove dupes from the revocation keys */
if(pk->revkey)
{
int i,j,x,changed=0;
for(i=0;inumrevkeys;i++)
{
for(j=i+1;jnumrevkeys;j++)
{
if(memcmp(&pk->revkey[i],&pk->revkey[j],
sizeof(struct revocation_key))==0)
{
/* remove j */
for(x=j;xnumrevkeys-1;x++)
pk->revkey[x]=pk->revkey[x+1];
pk->numrevkeys--;
j--;
changed=1;
}
}
}
if(changed)
pk->revkey=xrealloc(pk->revkey,
pk->numrevkeys*sizeof(struct revocation_key));
}
if ( signode )
{
/* some information from a direct key signature take precedence
* over the same information given in UID sigs.
*/
PKT_signature *sig = signode->pkt->pkt.signature;
const byte *p;
key_usage=parse_key_usage(sig);
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
if( p && buffer_to_u32(p) )
{
key_expire = keytimestamp + buffer_to_u32(p);
key_expire_seen = 1;
}
- /* mark that key as valid: one direct key signature should
+ /* mark that key as valid: one direct key signature should
* render a key as valid */
pk->is_valid = 1;
}
/* pass 1.5: look for key revocation signatures that were not made
by the key (i.e. did a revocation key issue a revocation for
us?). Only bother to do this if there is a revocation key in
the first place and we're not revoked already. */
if(!*r_revoked && pk->revkey)
for(k=keyblock; k && k->pkt->pkttype != PKT_USER_ID; k = k->next )
{
if ( k->pkt->pkttype == PKT_SIGNATURE )
{
PKT_signature *sig = k->pkt->pkt.signature;
if(IS_KEY_REV(sig) &&
(sig->keyid[0]!=kid[0] || sig->keyid[1]!=kid[1]))
- {
+ {
int rc=check_revocation_keys(pk,sig);
if(rc==0)
{
*r_revoked=2;
sig_to_revoke_info(sig,rinfo);
/* don't continue checking since we can't be any
more revoked than this */
break;
}
else if(rc==G10ERR_NO_PUBKEY)
pk->maybe_revoked=1;
/* A failure here means the sig did not verify, was
not issued by a revocation key, or a revocation
key loop was broken. If a revocation key isn't
findable, however, the key might be revoked and
we don't know it. */
/* TODO: In the future handle subkey and cert
revocations? PGP doesn't, but it's in 2440. */
}
}
}
/* second pass: look at the self-signature of all user IDs */
signode = uidnode = NULL;
sigdate = 0; /* helper to find the latest signature in one user ID */
for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
if ( k->pkt->pkttype == PKT_USER_ID ) {
- if ( uidnode && signode )
+ if ( uidnode && signode )
{
fixup_uidnode ( uidnode, signode, keytimestamp );
pk->is_valid=1;
}
uidnode = k;
signode = NULL;
sigdate = 0;
}
else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode ) {
PKT_signature *sig = k->pkt->pkt.signature;
- if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
+ if ( sig->keyid[0] == kid[0] && sig->keyid[1]==kid[1] ) {
if ( check_key_signature( keyblock, k, NULL ) )
; /* signature did not verify */
else if ( (IS_UID_SIG (sig) || IS_UID_REV (sig))
&& sig->timestamp >= sigdate )
{
/* Note: we allow to invalidate cert revocations
* by a newer signature. An attacker can't use this
* because a key should be revoced with a key revocation.
* The reason why we have to allow for that is that at
* one time an email address may become invalid but later
* the same email address may become valid again (hired,
* fired, hired again).
*/
sigdate = sig->timestamp;
signode = k;
signode->pkt->pkt.signature->flags.chosen_selfsig=0;
if( sig->version > sigversion )
sigversion = sig->version;
}
}
}
}
if ( uidnode && signode ) {
fixup_uidnode ( uidnode, signode, keytimestamp );
pk->is_valid = 1;
}
/* If the key isn't valid yet, and we have
--allow-non-selfsigned-uid set, then force it valid. */
if(!pk->is_valid && opt.allow_non_selfsigned_uid)
{
if(opt.verbose)
log_info(_("Invalid key %s made valid by"
" --allow-non-selfsigned-uid\n"),keystr_from_pk(pk));
pk->is_valid = 1;
}
/* The key STILL isn't valid, so try and find an ultimately
trusted signature. */
if(!pk->is_valid)
{
uidnode=NULL;
for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k=k->next)
{
if ( k->pkt->pkttype == PKT_USER_ID )
uidnode = k;
else if ( k->pkt->pkttype == PKT_SIGNATURE && uidnode )
{
PKT_signature *sig = k->pkt->pkt.signature;
if(sig->keyid[0] != kid[0] || sig->keyid[1]!=kid[1])
{
PKT_public_key *ultimate_pk;
ultimate_pk=xmalloc_clear(sizeof(*ultimate_pk));
/* We don't want to use the full get_pubkey to
avoid infinite recursion in certain cases.
There is no reason to check that an ultimately
trusted key is still valid - if it has been
revoked or the user should also renmove the
ultimate trust flag. */
if(get_pubkey_fast(ultimate_pk,sig->keyid)==0
&& check_key_signature2(keyblock,k,ultimate_pk,
NULL,NULL,NULL,NULL)==0
&& get_ownertrust(ultimate_pk)==TRUST_ULTIMATE)
{
free_public_key(ultimate_pk);
pk->is_valid=1;
break;
}
free_public_key(ultimate_pk);
}
}
}
}
/* Record the highest selfsig version so we know if this is a v3
key through and through, or a v3 key with a v4 selfsig
somewhere. This is useful in a few places to know if the key
must be treated as PGP2-style or OpenPGP-style. Note that a
selfsig revocation with a higher version number will also raise
this value. This is okay since such a revocation must be
issued by the user (i.e. it cannot be issued by someone else to
modify the key behavior.) */
pk->selfsigversion=sigversion;
/* Now that we had a look at all user IDs we can now get some information
* from those user IDs.
*/
-
+
if ( !key_usage ) {
/* find the latest user ID with key flags set */
uiddate = 0; /* helper to find the latest user ID */
for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next ) {
if ( k->pkt->pkttype == PKT_USER_ID ) {
PKT_user_id *uid = k->pkt->pkt.user_id;
if ( uid->help_key_usage && uid->created > uiddate ) {
key_usage = uid->help_key_usage;
uiddate = uid->created;
}
}
}
}
if ( !key_usage ) { /* no key flags at all: get it from the algo */
key_usage = openpgp_pk_algo_usage ( pk->pubkey_algo );
}
else { /* check that the usage matches the usage as given by the algo */
int x = openpgp_pk_algo_usage ( pk->pubkey_algo );
if ( x ) /* mask it down to the actual allowed usage */
- key_usage &= x;
+ key_usage &= x;
}
/* Whatever happens, it's a primary key, so it can certify. */
pk->pubkey_usage = key_usage|PUBKEY_USAGE_CERT;
if ( !key_expire_seen ) {
- /* find the latest valid user ID with a key expiration set
+ /* find the latest valid user ID with a key expiration set
* Note, that this may be a different one from the above because
* some user IDs may have no expiration date set */
- uiddate = 0;
+ uiddate = 0;
for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next ) {
if ( k->pkt->pkttype == PKT_USER_ID ) {
PKT_user_id *uid = k->pkt->pkt.user_id;
if ( uid->help_key_expire && uid->created > uiddate ) {
key_expire = uid->help_key_expire;
uiddate = uid->created;
}
}
}
}
/* Currently only v3 keys have a maximum expiration date, but I'll
bet v5 keys get this feature again. */
if(key_expire==0 || (pk->max_expiredate && key_expire>pk->max_expiredate))
key_expire=pk->max_expiredate;
pk->has_expired = key_expire >= curtime? 0 : key_expire;
pk->expiredate = key_expire;
/* Fixme: we should see how to get rid of the expiretime fields but
* this needs changes at other places too. */
/* and now find the real primary user ID and delete all others */
uiddate = uiddate2 = 0;
uidnode = uidnode2 = NULL;
for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next ) {
if ( k->pkt->pkttype == PKT_USER_ID &&
!k->pkt->pkt.user_id->attrib_data) {
PKT_user_id *uid = k->pkt->pkt.user_id;
if (uid->is_primary)
{
if(uid->created > uiddate)
{
uiddate = uid->created;
uidnode = k;
}
else if(uid->created==uiddate && uidnode)
{
/* The dates are equal, so we need to do a
different (and arbitrary) comparison. This
should rarely, if ever, happen. It's good to
try and guarantee that two different GnuPG
users with two different keyrings at least pick
the same primary. */
if(cmp_user_ids(uid,uidnode->pkt->pkt.user_id)>0)
uidnode=k;
}
}
else
{
if(uid->created > uiddate2)
{
uiddate2 = uid->created;
uidnode2 = k;
}
else if(uid->created==uiddate2 && uidnode2)
{
if(cmp_user_ids(uid,uidnode2->pkt->pkt.user_id)>0)
uidnode2=k;
}
}
}
}
if ( uidnode ) {
for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next ) {
if ( k->pkt->pkttype == PKT_USER_ID &&
!k->pkt->pkt.user_id->attrib_data) {
PKT_user_id *uid = k->pkt->pkt.user_id;
- if ( k != uidnode )
+ if ( k != uidnode )
uid->is_primary = 0;
}
}
}
else if( uidnode2 ) {
/* none is flagged primary - use the latest user ID we have,
and disambiguate with the arbitrary packet comparison. */
uidnode2->pkt->pkt.user_id->is_primary = 1;
}
else
{
/* None of our uids were self-signed, so pick the one that
sorts first to be the primary. This is the best we can do
here since there are no self sigs to date the uids. */
uidnode = NULL;
for(k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next )
{
if(k->pkt->pkttype==PKT_USER_ID
&& !k->pkt->pkt.user_id->attrib_data)
{
if(!uidnode)
{
uidnode=k;
uidnode->pkt->pkt.user_id->is_primary=1;
continue;
}
else
{
if(cmp_user_ids(k->pkt->pkt.user_id,
uidnode->pkt->pkt.user_id)>0)
{
uidnode->pkt->pkt.user_id->is_primary=0;
uidnode=k;
uidnode->pkt->pkt.user_id->is_primary=1;
}
else
k->pkt->pkt.user_id->is_primary=0; /* just to be
safe */
}
}
}
}
}
/* Convert a buffer to a signature. Useful for 0x19 embedded sigs.
Caller must free the signature when they are done. */
static PKT_signature *
buf_to_sig(const byte *buf,size_t len)
{
PKT_signature *sig=xmalloc_clear(sizeof(PKT_signature));
IOBUF iobuf=iobuf_temp_with_content(buf,len);
int save_mode=set_packet_list_mode(0);
if(parse_signature(iobuf,PKT_SIGNATURE,len,sig)!=0)
{
xfree(sig);
sig=NULL;
}
set_packet_list_mode(save_mode);
iobuf_close(iobuf);
return sig;
}
static void
merge_selfsigs_subkey( KBNODE keyblock, KBNODE subnode )
{
PKT_public_key *mainpk = NULL, *subpk = NULL;
PKT_signature *sig;
KBNODE k;
u32 mainkid[2];
u32 sigdate = 0;
KBNODE signode;
u32 curtime = make_timestamp ();
unsigned int key_usage = 0;
u32 keytimestamp = 0;
u32 key_expire = 0;
const byte *p;
if ( subnode->pkt->pkttype != PKT_PUBLIC_SUBKEY )
BUG ();
mainpk = keyblock->pkt->pkt.public_key;
if ( mainpk->version < 4 )
return; /* (actually this should never happen) */
keyid_from_pk( mainpk, mainkid );
subpk = subnode->pkt->pkt.public_key;
keytimestamp = subpk->timestamp;
subpk->is_valid = 0;
subpk->main_keyid[0] = mainpk->main_keyid[0];
subpk->main_keyid[1] = mainpk->main_keyid[1];
/* find the latest key binding self-signature. */
signode = NULL;
sigdate = 0; /* helper to find the latest signature */
for(k=subnode->next; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY;
k = k->next ) {
if ( k->pkt->pkttype == PKT_SIGNATURE ) {
sig = k->pkt->pkt.signature;
- if ( sig->keyid[0] == mainkid[0] && sig->keyid[1]==mainkid[1] ) {
+ if ( sig->keyid[0] == mainkid[0] && sig->keyid[1]==mainkid[1] ) {
if ( check_key_signature( keyblock, k, NULL ) )
; /* signature did not verify */
else if ( IS_SUBKEY_REV (sig) ) {
/* Note that this means that the date on a
revocation sig does not matter - even if the
binding sig is dated after the revocation sig,
the subkey is still marked as revoked. This
seems ok, as it is just as easy to make new
subkeys rather than re-sign old ones as the
problem is in the distribution. Plus, PGP (7)
does this the same way. */
subpk->is_revoked = 1;
sig_to_revoke_info(sig,&subpk->revoked);
- /* although we could stop now, we continue to
+ /* although we could stop now, we continue to
* figure out other information like the old expiration
* time */
}
else if ( IS_SUBKEY_SIG (sig) && sig->timestamp >= sigdate )
{
if(sig->flags.expired)
; /* signature has expired - ignore it */
else
{
sigdate = sig->timestamp;
signode = k;
signode->pkt->pkt.signature->flags.chosen_selfsig=0;
}
}
}
}
}
/* no valid key binding */
if ( !signode )
return;
sig = signode->pkt->pkt.signature;
sig->flags.chosen_selfsig=1; /* so we know which selfsig we chose later */
key_usage=parse_key_usage(sig);
if ( !key_usage )
{
/* no key flags at all: get it from the algo */
key_usage = openpgp_pk_algo_usage ( subpk->pubkey_algo );
}
else
{
/* check that the usage matches the usage as given by the algo */
int x = openpgp_pk_algo_usage ( subpk->pubkey_algo );
if ( x ) /* mask it down to the actual allowed usage */
- key_usage &= x;
+ key_usage &= x;
}
subpk->pubkey_usage = key_usage;
-
+
p = parse_sig_subpkt (sig->hashed, SIGSUBPKT_KEY_EXPIRE, NULL);
if ( p && buffer_to_u32(p) )
key_expire = keytimestamp + buffer_to_u32(p);
else
key_expire = 0;
subpk->has_expired = key_expire >= curtime? 0 : key_expire;
subpk->expiredate = key_expire;
/* Check that algo exists. Elgamal sign+encrypt are only allowed
with option --rfc2440. */
if (RFC2440 && subpk->pubkey_algo == PUBKEY_ALGO_ELGAMAL)
;
else if(check_pubkey_algo(subpk->pubkey_algo))
return;
subpk->is_valid = 1;
/* Find the most recent 0x19 embedded signature on our self-sig. */
if(subpk->backsig==0)
{
int seq=0;
size_t n;
PKT_signature *backsig=NULL;
sigdate=0;
/* We do this while() since there may be other embedded
signatures in the future. We only want 0x19 here. */
while((p=enum_sig_subpkt(sig->hashed,
SIGSUBPKT_SIGNATURE,&n,&seq,NULL)))
if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
{
PKT_signature *tempsig=buf_to_sig(p,n);
if(tempsig)
{
if(tempsig->timestamp>sigdate)
{
if(backsig)
free_seckey_enc(backsig);
backsig=tempsig;
sigdate=backsig->timestamp;
}
else
free_seckey_enc(tempsig);
}
}
seq=0;
/* It is safe to have this in the unhashed area since the 0x19
is located on the selfsig for convenience, not security. */
while((p=enum_sig_subpkt(sig->unhashed,SIGSUBPKT_SIGNATURE,
&n,&seq,NULL)))
if(n>3 && ((p[0]==3 && p[2]==0x19) || (p[0]==4 && p[1]==0x19)))
{
PKT_signature *tempsig=buf_to_sig(p,n);
if(tempsig)
{
if(tempsig->timestamp>sigdate)
{
if(backsig)
free_seckey_enc(backsig);
backsig=tempsig;
sigdate=backsig->timestamp;
}
else
free_seckey_enc(tempsig);
}
}
if(backsig)
{
/* At ths point, backsig contains the most recent 0x19 sig.
Let's see if it is good. */
/* 2==valid, 1==invalid, 0==didn't check */
if(check_backsig(mainpk,subpk,backsig)==0)
subpk->backsig=2;
else
subpk->backsig=1;
free_seckey_enc(backsig);
}
}
}
-/*
+/*
* Merge information from the self-signatures with the key, so that
* we can later use them more easy.
* The function works by first applying the self signatures to the
* primary key and the to each subkey.
* Here are the rules we use to decide which inormation from which
* self-signature is used:
* We check all self signatures or validity and ignore all invalid signatures.
* All signatures are then ordered by their creation date ....
* For the primary key:
- * FIXME the docs
+ * FIXME the docs
*/
static void
merge_selfsigs( KBNODE keyblock )
{
KBNODE k;
int revoked;
struct revoke_info rinfo;
PKT_public_key *main_pk;
prefitem_t *prefs;
int mdc_feature;
if ( keyblock->pkt->pkttype != PKT_PUBLIC_KEY ) {
if (keyblock->pkt->pkttype == PKT_SECRET_KEY ) {
log_error ("expected public key but found secret key "
"- must stop\n");
/* we better exit here becuase a public key is expected at
other places too. FIXME: Figure this out earlier and
don't get to here at all */
g10_exit (1);
}
BUG ();
}
merge_selfsigs_main ( keyblock, &revoked, &rinfo );
/* now merge in the data from each of the subkeys */
for(k=keyblock; k; k = k->next ) {
if ( k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
merge_selfsigs_subkey ( keyblock, k );
}
}
main_pk = keyblock->pkt->pkt.public_key;
if ( revoked || main_pk->has_expired || !main_pk->is_valid ) {
/* if the primary key is revoked, expired, or invalid we
* better set the appropriate flags on that key and all
* subkeys */
for(k=keyblock; k; k = k->next ) {
if ( k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
PKT_public_key *pk = k->pkt->pkt.public_key;
if(!main_pk->is_valid)
pk->is_valid = 0;
if(revoked && !pk->is_revoked)
{
pk->is_revoked = revoked;
memcpy(&pk->revoked,&rinfo,sizeof(rinfo));
}
if(main_pk->has_expired)
pk->has_expired = main_pk->has_expired;
}
}
return;
}
/* set the preference list of all keys to those of the primary real
* user ID. Note: we use these preferences when we don't know by
* which user ID the key has been selected.
* fixme: we should keep atoms of commonly used preferences or
* use reference counting to optimize the preference lists storage.
- * FIXME: it might be better to use the intersection of
+ * FIXME: it might be better to use the intersection of
* all preferences.
* Do a similar thing for the MDC feature flag.
*/
prefs = NULL;
mdc_feature = 0;
for (k=keyblock; k && k->pkt->pkttype != PKT_PUBLIC_SUBKEY; k = k->next) {
if (k->pkt->pkttype == PKT_USER_ID
&& !k->pkt->pkt.user_id->attrib_data
&& k->pkt->pkt.user_id->is_primary) {
prefs = k->pkt->pkt.user_id->prefs;
mdc_feature = k->pkt->pkt.user_id->flags.mdc;
break;
}
- }
+ }
for(k=keyblock; k; k = k->next ) {
if ( k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
PKT_public_key *pk = k->pkt->pkt.public_key;
if (pk->prefs)
xfree (pk->prefs);
pk->prefs = copy_prefs (prefs);
pk->mdc_feature = mdc_feature;
}
}
}
/*
* Merge the secret keys from secblock into the pubblock thereby
* replacing the public (sub)keys with their secret counterparts Hmmm:
* It might be better to get away from the concept of entire secret
* keys at all and have a way to store just the real secret parts
* from the key.
*/
static void
merge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
{
KBNODE pub;
assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
-
+
for (pub=pubblock; pub; pub = pub->next ) {
if ( pub->pkt->pkttype == PKT_PUBLIC_KEY ) {
PKT_public_key *pk = pub->pkt->pkt.public_key;
PKT_secret_key *sk = secblock->pkt->pkt.secret_key;
assert ( pub == pubblock ); /* only in the first node */
/* there is nothing to compare in this case, so just replace
* some information */
copy_public_parts_to_secret_key ( pk, sk );
free_public_key ( pk );
pub->pkt->pkttype = PKT_SECRET_KEY;
pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
}
else if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
KBNODE sec;
PKT_public_key *pk = pub->pkt->pkt.public_key;
/* this is more complicated: it may happen that the sequence
* of the subkeys dosn't match, so we have to find the
* appropriate secret key */
for (sec=secblock->next; sec; sec = sec->next ) {
if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
PKT_secret_key *sk = sec->pkt->pkt.secret_key;
if ( !cmp_public_secret_key ( pk, sk ) ) {
copy_public_parts_to_secret_key ( pk, sk );
free_public_key ( pk );
pub->pkt->pkttype = PKT_SECRET_SUBKEY;
pub->pkt->pkt.secret_key = copy_secret_key (NULL, sk);
break;
}
}
}
- if ( !sec )
+ if ( !sec )
BUG(); /* already checked in premerge */
}
}
}
/* This function checks that for every public subkey a corresponding
* secret subkey is available and deletes the public subkey otherwise.
* We need this function because we can't delete it later when we
* actually merge the secret parts into the pubring.
* The function also plays some games with the node flags.
*/
static void
premerge_public_with_secret ( KBNODE pubblock, KBNODE secblock )
{
KBNODE last, pub;
assert ( pubblock->pkt->pkttype == PKT_PUBLIC_KEY );
assert ( secblock->pkt->pkttype == PKT_SECRET_KEY );
-
+
for (pub=pubblock,last=NULL; pub; last = pub, pub = pub->next ) {
pub->flag &= ~3; /* reset bits 0 and 1 */
if ( pub->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
KBNODE sec;
PKT_public_key *pk = pub->pkt->pkt.public_key;
for (sec=secblock->next; sec; sec = sec->next ) {
if ( sec->pkt->pkttype == PKT_SECRET_SUBKEY ) {
PKT_secret_key *sk = sec->pkt->pkt.secret_key;
if ( !cmp_public_secret_key ( pk, sk ) ) {
if ( sk->protect.s2k.mode == 1001 ) {
/* The secret parts are not available so
we can't use that key for signing etc.
Fix the pubkey usage */
pk->pubkey_usage &= ~(PUBKEY_USAGE_SIG
|PUBKEY_USAGE_AUTH);
}
/* transfer flag bits 0 and 1 to the pubblock */
pub->flag |= (sec->flag &3);
break;
}
}
}
if ( !sec ) {
KBNODE next, ll;
if (opt.verbose)
log_info (_("no secret subkey"
- " for public subkey %s - ignoring\n"),
+ " for public subkey %s - ignoring\n"),
keystr_from_pk (pk));
/* we have to remove the subkey in this case */
assert ( last );
/* find the next subkey */
for (next=pub->next,ll=pub;
next && next->pkt->pkttype != PKT_PUBLIC_SUBKEY;
- ll = next, next = next->next )
+ ll = next, next = next->next )
;
/* make new link */
last->next = next;
/* release this public subkey with all sigs */
ll->next = NULL;
release_kbnode( pub );
/* let the loop continue */
pub = last;
}
}
}
/* We need to copy the found bits (0 and 1) from the secret key to
the public key. This has already been done for the subkeys but
got lost on the primary key - fix it here *. */
pubblock->flag |= (secblock->flag & 3);
}
/* See see whether the key fits
* our requirements and in case we do not
* request the primary key, we should select
* a suitable subkey.
* FIXME: Check against PGP 7 whether we still need a kludge
* to favor type 16 keys over type 20 keys when type 20
* has not been explitely requested.
* Returns: True when a suitable key has been found.
*
* We have to distinguish four cases: FIXME!
* 1. No usage and no primary key requested
* Examples for this case are that we have a keyID to be used
* for decrytion or verification.
* 2. No usage but primary key requested
* This is the case for all functions which work on an
* entire keyblock, e.g. for editing or listing
* 3. Usage and primary key requested
* FXME
* 4. Usage but no primary key requested
* FIXME
* FIXME: Tell what is going to happen here and something about the rationale
* Note: We don't use this function if no specific usage is requested;
* This way the getkey functions can be used for plain key listings.
*
* CTX ist the keyblock we are investigating, if FOUNDK is not NULL this
* is the key we actually found by looking at the keyid or a fingerprint and
* may eitehr point to the primary or one of the subkeys.
*/
static int
finish_lookup (GETKEY_CTX ctx)
{
KBNODE keyblock = ctx->keyblock;
KBNODE k;
KBNODE foundk = NULL;
PKT_user_id *foundu = NULL;
#define USAGE_MASK (PUBKEY_USAGE_SIG|PUBKEY_USAGE_ENC|PUBKEY_USAGE_CERT)
unsigned int req_usage = ( ctx->req_usage & USAGE_MASK );
/* Request the primary if we're certifying another key, and also
if signing data while --pgp6 or --pgp7 is on since pgp 6 and 7
do not understand signatures made by a signing subkey. PGP 8
does. */
int req_prim = (ctx->req_usage & PUBKEY_USAGE_CERT) ||
((PGP6 || PGP7) && (ctx->req_usage & PUBKEY_USAGE_SIG));
u32 latest_date;
KBNODE latest_key;
u32 curtime = make_timestamp ();
assert( keyblock->pkt->pkttype == PKT_PUBLIC_KEY );
-
+
ctx->found_key = NULL;
if (ctx->exact) {
for (k=keyblock; k; k = k->next) {
if ( (k->flag & 1) ) {
assert ( k->pkt->pkttype == PKT_PUBLIC_KEY
|| k->pkt->pkttype == PKT_PUBLIC_SUBKEY );
foundk = k;
break;
}
}
}
for (k=keyblock; k; k = k->next) {
if ( (k->flag & 2) ) {
assert (k->pkt->pkttype == PKT_USER_ID);
foundu = k->pkt->pkt.user_id;
break;
}
}
if ( DBG_CACHE )
log_debug( "finish_lookup: checking key %08lX (%s)(req_usage=%x)\n",
(ulong)keyid_from_pk( keyblock->pkt->pkt.public_key, NULL),
foundk? "one":"all", req_usage);
if (!req_usage) {
latest_key = foundk? foundk:keyblock;
goto found;
}
latest_date = 0;
latest_key = NULL;
/* do not look at subkeys if a certification key is requested */
if ((!foundk || foundk->pkt->pkttype == PKT_PUBLIC_SUBKEY) && !req_prim) {
KBNODE nextk;
/* either start a loop or check just this one subkey */
for (k=foundk?foundk:keyblock; k; k = nextk ) {
PKT_public_key *pk;
nextk = k->next;
if ( k->pkt->pkttype != PKT_PUBLIC_SUBKEY )
continue;
if ( foundk )
nextk = NULL; /* what a hack */
pk = k->pkt->pkt.public_key;
if (DBG_CACHE)
log_debug( "\tchecking subkey %08lX\n",
(ulong)keyid_from_pk( pk, NULL));
if ( !pk->is_valid ) {
if (DBG_CACHE)
log_debug( "\tsubkey not valid\n");
continue;
}
if ( pk->is_revoked ) {
if (DBG_CACHE)
log_debug( "\tsubkey has been revoked\n");
continue;
}
if ( pk->has_expired ) {
if (DBG_CACHE)
log_debug( "\tsubkey has expired\n");
continue;
}
if ( pk->timestamp > curtime && !opt.ignore_valid_from ) {
if (DBG_CACHE)
log_debug( "\tsubkey not yet valid\n");
continue;
}
-
+
if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
if (DBG_CACHE)
log_debug( "\tusage does not match: want=%x have=%x\n",
req_usage, pk->pubkey_usage );
continue;
}
if (DBG_CACHE)
log_debug( "\tsubkey looks fine\n");
if ( pk->timestamp > latest_date ) {
latest_date = pk->timestamp;
latest_key = k;
}
}
}
- /* Okay now try the primary key unless we want an exact
+ /* Okay now try the primary key unless we want an exact
* key ID match on a subkey */
if ((!latest_key && !(ctx->exact && foundk != keyblock)) || req_prim) {
PKT_public_key *pk;
if (DBG_CACHE && !foundk && !req_prim )
log_debug( "\tno suitable subkeys found - trying primary\n");
pk = keyblock->pkt->pkt.public_key;
if ( !pk->is_valid ) {
if (DBG_CACHE)
log_debug( "\tprimary key not valid\n");
}
else if ( pk->is_revoked ) {
if (DBG_CACHE)
log_debug( "\tprimary key has been revoked\n");
}
else if ( pk->has_expired ) {
if (DBG_CACHE)
log_debug( "\tprimary key has expired\n");
}
else if ( !((pk->pubkey_usage&USAGE_MASK) & req_usage) ) {
if (DBG_CACHE)
log_debug( "\tprimary key usage does not match: "
"want=%x have=%x\n",
req_usage, pk->pubkey_usage );
}
else { /* okay */
if (DBG_CACHE)
log_debug( "\tprimary key may be used\n");
latest_key = keyblock;
latest_date = pk->timestamp;
}
}
-
+
if ( !latest_key ) {
if (DBG_CACHE)
log_debug("\tno suitable key found - giving up\n");
return 0;
}
found:
if (DBG_CACHE)
log_debug( "\tusing key %08lX\n",
(ulong)keyid_from_pk( latest_key->pkt->pkt.public_key, NULL) );
if (latest_key) {
PKT_public_key *pk = latest_key->pkt->pkt.public_key;
if (pk->user_id)
free_user_id (pk->user_id);
pk->user_id = scopy_user_id (foundu);
- }
-
+ }
+
ctx->found_key = latest_key;
if (latest_key != keyblock && opt.verbose)
{
char *tempkeystr=
xstrdup(keystr_from_pk(latest_key->pkt->pkt.public_key));
log_info(_("using subkey %s instead of primary key %s\n"),
tempkeystr, keystr_from_pk(keyblock->pkt->pkt.public_key));
xfree(tempkeystr);
}
cache_user_id( keyblock );
-
+
return 1; /* found */
}
static int
lookup( GETKEY_CTX ctx, KBNODE *ret_keyblock, int secmode )
{
int rc;
KBNODE secblock = NULL; /* helper */
int no_suitable_key = 0;
-
+
rc = 0;
while (!(rc = keydb_search (ctx->kr_handle, ctx->items, ctx->nitems))) {
/* If we are searching for the first key we have to make sure
that the next interation does not no an implicit reset.
This can be triggered by an empty key ring. */
if (ctx->nitems && ctx->items->mode == KEYDB_SEARCH_MODE_FIRST)
ctx->items->mode = KEYDB_SEARCH_MODE_NEXT;
rc = keydb_get_keyblock (ctx->kr_handle, &ctx->keyblock);
if (rc) {
log_error ("keydb_get_keyblock failed: %s\n", g10_errstr(rc));
rc = 0;
goto skip;
}
-
+
if ( secmode ) {
- /* find the correspondig public key and use this
+ /* find the correspondig public key and use this
* this one for the selection process */
u32 aki[2];
KBNODE k = ctx->keyblock;
-
+
if (k->pkt->pkttype != PKT_SECRET_KEY)
BUG();
keyid_from_sk (k->pkt->pkt.secret_key, aki);
k = get_pubkeyblock (aki);
if( !k )
{
if (!opt.quiet)
log_info(_("key %s: secret key without public key"
" - skipped\n"), keystr(aki));
goto skip;
}
secblock = ctx->keyblock;
ctx->keyblock = k;
premerge_public_with_secret ( ctx->keyblock, secblock );
}
/* warning: node flag bits 0 and 1 should be preserved by
* merge_selfsigs. For secret keys, premerge did tranfer the
* keys to the keyblock */
merge_selfsigs ( ctx->keyblock );
if ( finish_lookup (ctx) ) {
no_suitable_key = 0;
if ( secmode ) {
merge_public_with_secret ( ctx->keyblock,
secblock);
release_kbnode (secblock);
secblock = NULL;
}
goto found;
}
else
no_suitable_key = 1;
-
+
skip:
/* release resources and continue search */
if ( secmode ) {
release_kbnode( secblock );
secblock = NULL;
}
release_kbnode( ctx->keyblock );
ctx->keyblock = NULL;
}
found:
if( rc && rc != -1 )
log_error("keydb_search failed: %s\n", g10_errstr(rc));
if( !rc ) {
*ret_keyblock = ctx->keyblock; /* return the keyblock */
ctx->keyblock = NULL;
}
else if (rc == -1 && no_suitable_key)
rc = secmode ? G10ERR_UNU_SECKEY : G10ERR_UNU_PUBKEY;
else if( rc == -1 )
rc = secmode ? G10ERR_NO_SECKEY : G10ERR_NO_PUBKEY;
if ( secmode ) {
release_kbnode( secblock );
secblock = NULL;
}
release_kbnode( ctx->keyblock );
ctx->keyblock = NULL;
ctx->last_rc = rc;
return rc;
}
/****************
- * FIXME: Replace by the generic function
- * It does not work as it is right now - it is used at
+ * FIXME: Replace by the generic function
+ * It does not work as it is right now - it is used at
* 2 places: a) to get the key for an anonyous recipient
* b) to get the ultimately trusted keys.
* The a) usage might have some problems.
*
* set with_subkeys true to include subkeys
* set with_spm true to include secret-parts-missing keys
*
* Enumerate all primary secret keys. Caller must use these procedure:
* 1) create a void pointer and initialize it to NULL
* 2) pass this void pointer by reference to this function
* and provide space for the secret key (pass a buffer for sk)
* 3) call this function as long as it does not return -1
* to indicate EOF.
* 4) Always call this function a last time with SK set to NULL,
* so that can free it's context.
*/
int
enum_secret_keys( void **context, PKT_secret_key *sk,
int with_subkeys, int with_spm )
{
int rc=0;
struct {
int eof;
int first;
KEYDB_HANDLE hd;
KBNODE keyblock;
KBNODE node;
} *c = *context;
if( !c ) { /* make a new context */
c = xmalloc_clear( sizeof *c );
*context = c;
c->hd = keydb_new (1);
c->first = 1;
c->keyblock = NULL;
c->node = NULL;
}
if( !sk ) { /* free the context */
keydb_release (c->hd);
release_kbnode (c->keyblock);
xfree( c );
*context = NULL;
return 0;
}
if( c->eof )
return -1;
do {
/* get the next secret key from the current keyblock */
for (; c->node; c->node = c->node->next) {
if ((c->node->pkt->pkttype == PKT_SECRET_KEY
|| (with_subkeys
&& c->node->pkt->pkttype == PKT_SECRET_SUBKEY) )
&& !(c->node->pkt->pkt.secret_key->protect.s2k.mode==1001
&& !with_spm)) {
copy_secret_key (sk, c->node->pkt->pkt.secret_key );
c->node = c->node->next;
return 0; /* found */
}
}
release_kbnode (c->keyblock);
c->keyblock = c->node = NULL;
-
+
rc = c->first? keydb_search_first (c->hd) : keydb_search_next (c->hd);
c->first = 0;
if (rc) {
keydb_release (c->hd); c->hd = NULL;
c->eof = 1;
return -1; /* eof */
}
-
+
rc = keydb_get_keyblock (c->hd, &c->keyblock);
c->node = c->keyblock;
} while (!rc);
return rc; /* error */
}
/*********************************************
*********** user ID printing helpers *******
*********************************************/
/****************
* Return a string with a printable representation of the user_id.
* this string must be freed by xfree.
*/
char*
get_user_id_string( u32 *keyid )
{
user_id_db_t r;
char *p;
int pass=0;
/* try it two times; second pass reads from key resources */
do
{
for(r=user_id_db; r; r = r->next )
{
keyid_list_t a;
for (a=r->keyids; a; a= a->next )
{
if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] )
{
p = xmalloc( keystrlen() + 1 + r->len + 1 );
sprintf(p, "%s %.*s", keystr(keyid), r->len, r->name );
return p;
}
}
}
} while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
p = xmalloc( keystrlen() + 5 );
sprintf(p, "%s [?]", keystr(keyid));
return p;
}
char*
get_user_id_string_native ( u32 *keyid )
{
char *p = get_user_id_string( keyid );
char *p2 = utf8_to_native( p, strlen(p), 0 );
xfree(p);
return p2;
}
char*
get_long_user_id_string( u32 *keyid )
{
user_id_db_t r;
char *p;
int pass=0;
/* try it two times; second pass reads from key resources */
do {
for(r=user_id_db; r; r = r->next ) {
keyid_list_t a;
for (a=r->keyids; a; a= a->next ) {
if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
p = xmalloc( r->len + 20 );
sprintf(p, "%08lX%08lX %.*s",
(ulong)keyid[0], (ulong)keyid[1],
r->len, r->name );
return p;
}
}
}
} while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
p = xmalloc( 25 );
sprintf(p, "%08lX%08lX [?]", (ulong)keyid[0], (ulong)keyid[1] );
return p;
}
char*
get_user_id( u32 *keyid, size_t *rn )
{
user_id_db_t r;
char *p;
int pass=0;
/* try it two times; second pass reads from key resources */
do {
for(r=user_id_db; r; r = r->next ) {
keyid_list_t a;
for (a=r->keyids; a; a= a->next ) {
if( a->keyid[0] == keyid[0] && a->keyid[1] == keyid[1] ) {
p = xmalloc( r->len );
memcpy(p, r->name, r->len );
*rn = r->len;
return p;
}
}
}
} while( ++pass < 2 && !get_pubkey( NULL, keyid ) );
p = xstrdup( user_id_not_found_utf8 () );
*rn = strlen(p);
return p;
}
char*
get_user_id_native( u32 *keyid )
{
size_t rn;
char *p = get_user_id( keyid, &rn );
char *p2 = utf8_to_native( p, rn, 0 );
xfree(p);
return p2;
}
KEYDB_HANDLE
get_ctx_handle(GETKEY_CTX ctx)
{
return ctx->kr_handle;
}
static void
free_akl(struct akl *akl)
{
if(akl->spec)
free_keyserver_spec(akl->spec);
xfree(akl);
}
void
release_akl(void)
{
while(opt.auto_key_locate)
{
struct akl *akl2=opt.auto_key_locate;
opt.auto_key_locate=opt.auto_key_locate->next;
free_akl(akl2);
}
}
int
parse_auto_key_locate(char *options)
{
char *tok;
while((tok=optsep(&options)))
{
struct akl *akl,*check,*last=NULL;
int dupe=0;
if(tok[0]=='\0')
continue;
/* For now we silently ignore the new methods introduced with
- 2.0.10. */
+ 2.0.10. */
if (!ascii_strcasecmp (tok,"nodefault")
|| !ascii_strcasecmp (tok,"local"))
continue;
akl=xmalloc_clear(sizeof(*akl));
if(ascii_strcasecmp(tok,"ldap")==0)
akl->type=AKL_LDAP;
else if(ascii_strcasecmp(tok,"keyserver")==0)
akl->type=AKL_KEYSERVER;
#ifdef USE_DNS_CERT
else if(ascii_strcasecmp(tok,"cert")==0)
akl->type=AKL_CERT;
#endif
#ifdef USE_DNS_PKA
else if(ascii_strcasecmp(tok,"pka")==0)
akl->type=AKL_PKA;
#endif
else if((akl->spec=parse_keyserver_uri(tok,1,NULL,0)))
akl->type=AKL_SPEC;
else
{
free_akl(akl);
return 0;
}
/* We must maintain the order the user gave us */
for(check=opt.auto_key_locate;check;last=check,check=check->next)
{
/* Check for duplicates */
if(check->type==akl->type
&& (akl->type!=AKL_SPEC
|| (akl->type==AKL_SPEC
&& strcmp(check->spec->uri,akl->spec->uri)==0)))
{
dupe=1;
free_akl(akl);
break;
}
}
if(!dupe)
{
if(last)
last->next=akl;
else
opt.auto_key_locate=akl;
}
}
return 1;
}
diff --git a/g10/gpg.c b/g10/gpg.c
index cf2f51b68..28841c0aa 100644
--- a/g10/gpg.c
+++ b/g10/gpg.c
@@ -1,4311 +1,4313 @@
/* gpg.c - The GnuPG utility (main for gpg)
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
* 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#ifdef HAVE_STRINGS_H
#include
#endif
#include
#include
#include
#ifdef HAVE_DOSISH_SYSTEM
#include /* for setmode() */
#endif
#ifdef HAVE_STAT
#include /* for stat() */
#endif
#include
#ifdef HAVE_W32_SYSTEM
#include
#endif
#define INCLUDED_BY_MAIN_MODULE 1
#include "packet.h"
#include "iobuf.h"
#include "memory.h"
#include "util.h"
#include "main.h"
#include "options.h"
#include "keydb.h"
#include "trustdb.h"
#include "mpi.h"
#include "cipher.h"
#include "filter.h"
#include "ttyio.h"
#include "i18n.h"
#include "status.h"
#include "keyserver-internal.h"
#include "exec.h"
#include "cardglue.h"
#ifdef ENABLE_CARD_SUPPORT
#include "ccid-driver.h"
#endif
#if defined(HAVE_DOSISH_SYSTEM) || defined(__CYGWIN__)
#define MY_O_BINARY O_BINARY
#ifndef S_IRGRP
# define S_IRGRP 0
# define S_IWGRP 0
#endif
#else
#define MY_O_BINARY 0
#endif
enum cmd_and_opt_values
{
aNull = 0,
oArmor = 'a',
aDetachedSign = 'b',
aSym = 'c',
aDecrypt = 'd',
aEncr = 'e',
oInteractive = 'i',
oKOption = 'k',
oDryRun = 'n',
oOutput = 'o',
oQuiet = 'q',
oRecipient = 'r',
oHiddenRecipient = 'R',
aSign = 's',
oTextmodeShort= 't',
oLocalUser = 'u',
oVerbose = 'v',
oCompress = 'z',
oSetNotation = 'N',
aListSecretKeys = 'K',
oBatch = 500,
oMaxOutput,
oSigNotation,
oCertNotation,
oShowNotation,
oNoShowNotation,
aEncrFiles,
aEncrSym,
aDecryptFiles,
aClearsign,
aStore,
aKeygen,
aSignEncr,
aSignEncrSym,
aSignSym,
aSignKey,
aLSignKey,
aListConfig,
aGPGConfList,
aGPGConfTest,
aListPackets,
aEditKey,
aDeleteKeys,
aDeleteSecretKeys,
aDeleteSecretAndPublicKeys,
aKMode,
aKModeC,
aImport,
aFastImport,
aVerify,
aVerifyFiles,
aListKeys,
aListSigs,
aSendKeys,
aRecvKeys,
aSearchKeys,
aRefreshKeys,
aFetchKeys,
aExport,
aExportSecret,
aExportSecretSub,
aCheckKeys,
aGenRevoke,
aDesigRevoke,
aPrimegen,
aPrintMD,
aPrintMDs,
aCheckTrustDB,
aUpdateTrustDB,
aFixTrustDB,
aListTrustDB,
aListTrustPath,
aExportOwnerTrust,
aListOwnerTrust,
aImportOwnerTrust,
aDeArmor,
aEnArmor,
aGenRandom,
aPipeMode,
aRebuildKeydbCaches,
aCardStatus,
aCardEdit,
aChangePIN,
oTextmode,
oNoTextmode,
oExpert,
oNoExpert,
oDefSigExpire,
oAskSigExpire,
oNoAskSigExpire,
oDefCertExpire,
oAskCertExpire,
oNoAskCertExpire,
oDefCertLevel,
oMinCertLevel,
oAskCertLevel,
oNoAskCertLevel,
oFingerprint,
oWithFingerprint,
oAnswerYes,
oAnswerNo,
oKeyring,
oPrimaryKeyring,
oSecretKeyring,
oShowKeyring,
oDefaultKey,
oDefRecipient,
oDefRecipientSelf,
oNoDefRecipient,
oOptions,
oDebug,
oDebugAll,
oDebugLevel,
oDebugCCIDDriver,
oStatusFD,
oStatusFile,
oAttributeFD,
oAttributeFile,
oEmitVersion,
oNoEmitVersion,
oCompletesNeeded,
oMarginalsNeeded,
oMaxCertDepth,
oLoadExtension,
oGnuPG,
oRFC1991,
oRFC2440,
oRFC4880,
oOpenPGP,
oPGP2,
oPGP6,
oPGP7,
oPGP8,
oRFC2440Text,
oNoRFC2440Text,
oCipherAlgo,
oDigestAlgo,
oCertDigestAlgo,
oCompressAlgo,
oCompressLevel,
oBZ2CompressLevel,
oBZ2DecompressLowmem,
oPasswd,
oPasswdFD,
oPasswdFile,
oPasswdRepeat,
oCommandFD,
oCommandFile,
oQuickRandom,
oNoVerbose,
oTrustDBName,
oNoSecmemWarn,
oRequireSecmem,
oNoRequireSecmem,
oNoPermissionWarn,
oNoMDCWarn,
oNoArmor,
oNoDefKeyring,
oNoGreeting,
oNoTTY,
oNoOptions,
oNoBatch,
oHomedir,
oWithColons,
oWithKeyData,
oSkipVerify,
oCompressKeys,
oCompressSigs,
oAlwaysTrust,
oTrustModel,
oForceOwnertrust,
oRunAsShmCP,
oSetFilename,
oForYourEyesOnly,
oNoForYourEyesOnly,
oSetPolicyURL,
oSigPolicyURL,
oCertPolicyURL,
oShowPolicyURL,
oNoShowPolicyURL,
oSigKeyserverURL,
oUseEmbeddedFilename,
oNoUseEmbeddedFilename,
oComment,
oDefaultComment,
oNoComments,
oThrowKeyids,
oNoThrowKeyids,
oShowPhotos,
oNoShowPhotos,
oPhotoViewer,
oForceV3Sigs,
oNoForceV3Sigs,
oForceV4Certs,
oNoForceV4Certs,
oForceMDC,
oNoForceMDC,
oDisableMDC,
oNoDisableMDC,
oS2KMode,
oS2KDigest,
oS2KCipher,
oS2KCount,
- oSimpleSKChecksum,
+ oSimpleSKChecksum,
oDisplayCharset,
oNotDashEscaped,
oEscapeFrom,
oNoEscapeFrom,
oLockOnce,
oLockMultiple,
oLockNever,
oKeyServer,
oKeyServerOptions,
oImportOptions,
oExportOptions,
oListOptions,
oVerifyOptions,
oTempDir,
oExecPath,
oEncryptTo,
oHiddenEncryptTo,
oNoEncryptTo,
oLoggerFD,
oLoggerFile,
oUtf8Strings,
oNoUtf8Strings,
oDisableCipherAlgo,
oDisablePubkeyAlgo,
oAllowNonSelfsignedUID,
oNoAllowNonSelfsignedUID,
oAllowFreeformUID,
oNoAllowFreeformUID,
- oAllowSecretKeyImport,
+ oAllowSecretKeyImport,
oEnableSpecialFilenames,
oNoLiteral,
oSetFilesize,
oHonorHttpProxy,
oFastListMode,
oListOnly,
oIgnoreTimeConflict,
oIgnoreValidFrom,
oIgnoreCrcError,
oIgnoreMDCError,
oShowSessionKey,
oOverrideSessionKey,
oNoRandomSeedFile,
oAutoKeyRetrieve,
oNoAutoKeyRetrieve,
oUseAgent,
oNoUseAgent,
oGpgAgentInfo,
oMergeOnly,
oTryAllSecrets,
oTrustedKey,
oNoExpensiveTrustChecks,
oFixedListMode,
oNoSigCache,
oNoSigCreateCheck,
oAutoCheckTrustDB,
oNoAutoCheckTrustDB,
oPreservePermissions,
oDefaultPreferenceList,
oDefaultKeyserverURL,
oPersonalCipherPreferences,
oPersonalDigestPreferences,
oPersonalCompressPreferences,
oDisplay,
oTTYname,
oTTYtype,
oLCctype,
oLCmessages,
oGroup,
oUnGroup,
oNoGroups,
oStrict,
oNoStrict,
oMangleDosFilenames,
oNoMangleDosFilenames,
oEnableProgressFilter,
oMultifile,
oKeyidFormat,
oExitOnStatusWriteError,
oLimitCardInsertTries,
oReaderPort,
octapiDriver,
opcscDriver,
oDisableCCID,
oRequireCrossCert,
oNoRequireCrossCert,
oAutoKeyLocate,
oNoAutoKeyLocate,
oAllowMultisigVerification,
oEnableDSA2,
oDisableDSA2,
oAllowMultipleMessages,
oNoAllowMultipleMessages,
oNoop
};
static ARGPARSE_OPTS opts[] = {
{ 300, NULL, 0, N_("@Commands:\n ") },
{ aSign, "sign", 256, N_("|[file]|make a signature")},
{ aClearsign, "clearsign", 256, N_("|[file]|make a clear text signature")},
{ aDetachedSign, "detach-sign", 256, N_("make a detached signature")},
{ aEncr, "encrypt", 256, N_("encrypt data")},
{ aEncrFiles, "encrypt-files", 256, "@"},
{ aSym, "symmetric", 256, N_("encryption only with symmetric cipher")},
{ aStore, "store", 256, "@"},
{ aDecrypt, "decrypt", 256, N_("decrypt data (default)")},
{ aDecryptFiles, "decrypt-files", 256, "@"},
{ aVerify, "verify" , 256, N_("verify a signature")},
{ aVerifyFiles, "verify-files" , 256, "@" },
{ aListKeys, "list-keys", 256, N_("list keys")},
{ aListKeys, "list-public-keys", 256, "@" },
{ aListSigs, "list-sigs", 256, N_("list keys and signatures")},
{ aCheckKeys, "check-sigs",256, N_("list and check key signatures")},
{ oFingerprint, "fingerprint", 256, N_("list keys and fingerprints")},
{ aListSecretKeys, "list-secret-keys", 256, N_("list secret keys")},
{ aKeygen, "gen-key", 256, N_("generate a new key pair")},
{ aDeleteKeys,"delete-keys",256,N_("remove keys from the public keyring")},
{ aDeleteSecretKeys, "delete-secret-keys",256,
N_("remove keys from the secret keyring")},
{ aSignKey, "sign-key" ,256, N_("sign a key")},
{ aLSignKey, "lsign-key" ,256, N_("sign a key locally")},
{ aEditKey, "edit-key" ,256, N_("sign or edit a key")},
{ aGenRevoke, "gen-revoke",256, N_("generate a revocation certificate")},
{ aDesigRevoke, "desig-revoke",256, "@" },
{ aExport, "export" , 256, N_("export keys") },
{ aSendKeys, "send-keys" , 256, N_("export keys to a key server") },
{ aRecvKeys, "recv-keys" , 256, N_("import keys from a key server") },
{ aSearchKeys, "search-keys" , 256,
N_("search for keys on a key server") },
{ aRefreshKeys, "refresh-keys", 256,
N_("update all keys from a keyserver")},
{ aFetchKeys, "fetch-keys" , 256, "@" },
{ aExportSecret, "export-secret-keys" , 256, "@" },
{ aExportSecretSub, "export-secret-subkeys" , 256, "@" },
{ aImport, "import", 256 , N_("import/merge keys")},
{ aFastImport, "fast-import", 256 , "@"},
#ifdef ENABLE_CARD_SUPPORT
{ aCardStatus, "card-status", 256, N_("print the card status")},
{ aCardEdit, "card-edit", 256, N_("change data on a card")},
{ aChangePIN, "change-pin", 256, N_("change a card's PIN")},
#endif
{ aListConfig, "list-config", 256, "@"},
{ aGPGConfList, "gpgconf-list", 256, "@" },
{ aGPGConfTest, "gpgconf-test", 256, "@" },
{ aListPackets, "list-packets",256, "@"},
{ aExportOwnerTrust, "export-ownertrust", 256, "@"},
{ aImportOwnerTrust, "import-ownertrust", 256, "@"},
{ aUpdateTrustDB,
"update-trustdb",0 , N_("update the trust database")},
{ aCheckTrustDB, "check-trustdb", 0, "@"},
{ aFixTrustDB, "fix-trustdb", 0, "@"},
{ aDeArmor, "dearmor", 256, "@"},
{ aDeArmor, "dearmour", 256, "@"},
{ aEnArmor, "enarmor", 256, "@"},
{ aEnArmor, "enarmour", 256, "@"},
{ aPrintMD, "print-md" , 256, N_("|algo [files]|print message digests")},
{ aPrimegen, "gen-prime" , 256, "@" },
{ aGenRandom, "gen-random" , 256, "@" },
{ 301, NULL, 0, N_("@\nOptions:\n ") },
{ oArmor, "armor", 0, N_("create ascii armored output")},
{ oArmor, "armour", 0, "@" },
{ oRecipient, "recipient", 2, N_("|NAME|encrypt for NAME")},
{ oHiddenRecipient, "hidden-recipient", 2, "@" },
{ oRecipient, "remote-user", 2, "@"}, /* old option name */
{ oDefRecipient, "default-recipient", 2, "@"},
{ oDefRecipientSelf, "default-recipient-self", 0, "@"},
{ oNoDefRecipient, "no-default-recipient", 0, "@" },
{ oTempDir, "temp-directory", 2, "@" },
{ oExecPath, "exec-path", 2, "@" },
{ oEncryptTo, "encrypt-to", 2, "@" },
{ oHiddenEncryptTo, "hidden-encrypt-to", 2, "@" },
{ oNoEncryptTo, "no-encrypt-to", 0, "@" },
{ oLocalUser, "local-user",2, N_("use this user-id to sign or decrypt")},
{ oCompress, NULL, 1, N_("|N|set compress level N (0 disables)") },
{ oCompressLevel, "compress-level", 1, "@" },
{ oBZ2CompressLevel, "bzip2-compress-level", 1, "@" },
{ oBZ2DecompressLowmem, "bzip2-decompress-lowmem", 0, "@" },
{ oTextmodeShort, NULL, 0, "@"},
{ oTextmode, "textmode", 0, N_("use canonical text mode")},
{ oNoTextmode, "no-textmode", 0, "@"},
{ oExpert, "expert", 0, "@"},
{ oNoExpert, "no-expert", 0, "@"},
{ oDefSigExpire, "default-sig-expire", 2, "@"},
{ oAskSigExpire, "ask-sig-expire", 0, "@"},
{ oNoAskSigExpire, "no-ask-sig-expire", 0, "@"},
{ oDefCertExpire, "default-cert-expire", 2, "@"},
{ oAskCertExpire, "ask-cert-expire", 0, "@"},
{ oNoAskCertExpire, "no-ask-cert-expire", 0, "@"},
{ oDefCertLevel, "default-cert-level", 1, "@"},
{ oMinCertLevel, "min-cert-level", 1, "@"},
{ oAskCertLevel, "ask-cert-level", 0, "@"},
{ oNoAskCertLevel, "no-ask-cert-level", 0, "@"},
{ oOutput, "output", 2, N_("use as output file")},
{ oMaxOutput, "max-output", 16|4, "@" },
{ oVerbose, "verbose", 0, N_("verbose") },
{ oQuiet, "quiet", 0, "@"},
{ oNoTTY, "no-tty", 0, "@"},
{ oForceV3Sigs, "force-v3-sigs", 0, "@"},
{ oNoForceV3Sigs, "no-force-v3-sigs", 0, "@"},
{ oForceV4Certs, "force-v4-certs", 0, "@"},
{ oNoForceV4Certs, "no-force-v4-certs", 0, "@"},
{ oForceMDC, "force-mdc", 0, "@"},
{ oNoForceMDC, "no-force-mdc", 0, "@" },
{ oDisableMDC, "disable-mdc", 0, "@"},
{ oNoDisableMDC, "no-disable-mdc", 0, "@" },
{ oDryRun, "dry-run", 0, N_("do not make any changes") },
{ oInteractive, "interactive", 0, N_("prompt before overwriting") },
{ oUseAgent, "use-agent",0, "@"},
{ oNoUseAgent, "no-use-agent",0, "@"},
{ oGpgAgentInfo, "gpg-agent-info",2, "@"},
{ oBatch, "batch", 0, "@"},
{ oAnswerYes, "yes", 0, "@"},
{ oAnswerNo, "no", 0, "@"},
{ oKeyring, "keyring", 2, "@"},
{ oPrimaryKeyring, "primary-keyring",2, "@" },
{ oSecretKeyring, "secret-keyring", 2, "@"},
{ oShowKeyring, "show-keyring", 0, "@"},
{ oDefaultKey, "default-key", 2, "@"},
{ oKeyServer, "keyserver", 2, "@"},
{ oKeyServerOptions, "keyserver-options",2,"@"},
{ oImportOptions, "import-options",2,"@"},
{ oExportOptions, "export-options",2,"@"},
{ oListOptions, "list-options",2,"@"},
{ oVerifyOptions, "verify-options",2,"@"},
{ oDisplayCharset, "display-charset", 2, "@"},
{ oDisplayCharset, "charset", 2, "@"},
{ oOptions, "options", 2, "@"},
{ oDebug, "debug" ,4|16, "@"},
{ oDebugAll, "debug-all" ,0, "@"},
{ oDebugLevel, "debug-level" ,0, "@"},
{ oStatusFD, "status-fd" ,1, "@"},
{ oStatusFile, "status-file" ,2, "@"},
{ oAttributeFD, "attribute-fd" ,1, "@" },
{ oAttributeFile, "attribute-file" ,2, "@" },
{ oNoop, "sk-comments", 0, "@"},
{ oNoop, "no-sk-comments", 0, "@"},
{ oCompletesNeeded, "completes-needed", 1, "@"},
{ oMarginalsNeeded, "marginals-needed", 1, "@"},
{ oMaxCertDepth, "max-cert-depth", 1, "@" },
{ oTrustedKey, "trusted-key", 2, "@"},
{ oLoadExtension, "load-extension", 2, "@"},
{ oGnuPG, "gnupg", 0, "@"},
{ oGnuPG, "no-pgp2", 0, "@"},
{ oGnuPG, "no-pgp6", 0, "@"},
{ oGnuPG, "no-pgp7", 0, "@"},
{ oGnuPG, "no-pgp8", 0, "@"},
{ oRFC1991, "rfc1991", 0, "@"},
{ oRFC2440, "rfc2440", 0, "@" },
{ oRFC4880, "rfc4880", 0, "@" },
{ oOpenPGP, "openpgp", 0, N_("use strict OpenPGP behavior")},
{ oPGP2, "pgp2", 0, N_("generate PGP 2.x compatible messages")},
{ oPGP6, "pgp6", 0, "@"},
{ oPGP7, "pgp7", 0, "@"},
{ oPGP8, "pgp8", 0, "@"},
{ oRFC2440Text, "rfc2440-text", 0, "@"},
{ oNoRFC2440Text, "no-rfc2440-text", 0, "@"},
{ oS2KMode, "s2k-mode", 1, "@"},
{ oS2KDigest, "s2k-digest-algo", 2, "@"},
{ oS2KCipher, "s2k-cipher-algo", 2, "@"},
{ oS2KCount, "s2k-count", 1, "@"},
{ oSimpleSKChecksum, "simple-sk-checksum", 0, "@"},
{ oCipherAlgo, "cipher-algo", 2, "@"},
{ oDigestAlgo, "digest-algo", 2, "@"},
{ oCertDigestAlgo, "cert-digest-algo", 2 , "@" },
{ oCompressAlgo,"compress-algo", 2, "@"},
{ oCompressAlgo, "compression-algo", 2, "@"}, /* Alias */
{ oThrowKeyids, "throw-keyid", 0, "@"},
{ oThrowKeyids, "throw-keyids", 0, "@"},
{ oNoThrowKeyids, "no-throw-keyid", 0, "@" },
{ oNoThrowKeyids, "no-throw-keyids", 0, "@" },
{ oShowPhotos, "show-photos", 0, "@" },
{ oNoShowPhotos, "no-show-photos", 0, "@" },
{ oPhotoViewer, "photo-viewer", 2, "@" },
{ oSetNotation, "set-notation", 2, "@" },
{ oSetNotation, "notation-data", 2, "@" }, /* Alias */
{ oSigNotation, "sig-notation", 2, "@" },
{ oCertNotation, "cert-notation", 2, "@" },
{ 302, NULL, 0, N_(
"@\n(See the man page for a complete listing of all commands and options)\n"
)},
{ 303, NULL, 0, N_("@\nExamples:\n\n"
" -se -r Bob [file] sign and encrypt for user Bob\n"
" --clearsign [file] make a clear text signature\n"
" --detach-sign [file] make a detached signature\n"
" --list-keys [names] show keys\n"
" --fingerprint [names] show fingerprints\n" ) },
/* hidden options */
{ aListOwnerTrust, "list-ownertrust", 256, "@"}, /* deprecated */
{ aPrintMDs, "print-mds" , 256, "@"}, /* old */
{ aListTrustDB, "list-trustdb",0 , "@"},
/* Not yet used */
/* { aListTrustPath, "list-trust-path",0, "@"}, */
{ aPipeMode, "pipemode", 0, "@" },
{ oKOption, NULL, 0, "@"},
{ oPasswd, "passphrase",2, "@" },
{ oPasswdFD, "passphrase-fd",1, "@" },
{ oPasswdFile, "passphrase-file",2, "@" },
{ oPasswdRepeat, "passphrase-repeat", 1, "@"},
{ oCommandFD, "command-fd",1, "@" },
{ oCommandFile, "command-file",2, "@" },
{ oQuickRandom, "quick-random", 0, "@"},
{ oNoVerbose, "no-verbose", 0, "@"},
{ oTrustDBName, "trustdb-name", 2, "@" },
{ oNoSecmemWarn, "no-secmem-warning", 0, "@" },
{ oRequireSecmem,"require-secmem", 0, "@" },
{ oNoRequireSecmem,"no-require-secmem", 0, "@" },
{ oNoPermissionWarn, "no-permission-warning", 0, "@" },
{ oNoMDCWarn, "no-mdc-warning", 0, "@" },
{ oNoArmor, "no-armor", 0, "@"},
{ oNoArmor, "no-armour", 0, "@"},
{ oNoDefKeyring, "no-default-keyring", 0, "@" },
{ oNoGreeting, "no-greeting", 0, "@" },
{ oNoOptions, "no-options", 0, "@" }, /* shortcut for --options /dev/null */
{ oHomedir, "homedir", 2, "@" }, /* defaults to "~/.gnupg" */
{ oNoBatch, "no-batch", 0, "@" },
{ oWithColons, "with-colons", 0, "@"},
{ oWithKeyData,"with-key-data", 0, "@"},
{ aListKeys, "list-key", 0, "@" }, /* alias */
{ aListSigs, "list-sig", 0, "@" }, /* alias */
{ aCheckKeys, "check-sig",0, "@" }, /* alias */
{ oSkipVerify, "skip-verify",0, "@" },
{ oCompressKeys, "compress-keys",0, "@"},
{ oCompressSigs, "compress-sigs",0, "@"},
{ oDefCertLevel, "default-cert-check-level", 1, "@"}, /* Old option */
{ oAlwaysTrust, "always-trust", 0, "@"},
{ oTrustModel, "trust-model", 2, "@"},
{ oForceOwnertrust, "force-ownertrust", 2, "@"},
{ oRunAsShmCP, "run-as-shm-coprocess", 4, "@" },
{ oSetFilename, "set-filename", 2, "@" },
{ oForYourEyesOnly, "for-your-eyes-only", 0, "@" },
{ oNoForYourEyesOnly, "no-for-your-eyes-only", 0, "@" },
{ oSetPolicyURL, "set-policy-url", 2, "@" },
{ oSigPolicyURL, "sig-policy-url", 2, "@" },
{ oCertPolicyURL, "cert-policy-url", 2, "@" },
{ oShowPolicyURL, "show-policy-url", 0, "@" },
{ oNoShowPolicyURL, "no-show-policy-url", 0, "@" },
{ oSigKeyserverURL, "sig-keyserver-url", 2, "@" },
{ oShowNotation, "show-notation", 0, "@" },
{ oNoShowNotation, "no-show-notation", 0, "@" },
{ oComment, "comment", 2, "@" },
{ oDefaultComment, "default-comment", 0, "@" },
{ oNoComments, "no-comments", 0, "@" },
{ oEmitVersion, "emit-version", 0, "@"},
{ oNoEmitVersion, "no-emit-version", 0, "@"},
{ oNoEmitVersion, "no-version", 0, "@"}, /* alias */
{ oNotDashEscaped, "not-dash-escaped", 0, "@" },
{ oEscapeFrom, "escape-from-lines", 0, "@" },
{ oNoEscapeFrom, "no-escape-from-lines", 0, "@" },
{ oLockOnce, "lock-once", 0, "@" },
{ oLockMultiple, "lock-multiple", 0, "@" },
{ oLockNever, "lock-never", 0, "@" },
{ oLoggerFD, "logger-fd",1, "@" },
{ oLoggerFile, "logger-file",2, "@" },
{ oUseEmbeddedFilename, "use-embedded-filename", 0, "@" },
{ oNoUseEmbeddedFilename, "no-use-embedded-filename", 0, "@" },
{ oUtf8Strings, "utf8-strings", 0, "@" },
{ oNoUtf8Strings, "no-utf8-strings", 0, "@" },
{ oWithFingerprint, "with-fingerprint", 0, "@" },
{ oDisableCipherAlgo, "disable-cipher-algo", 2, "@" },
{ oDisablePubkeyAlgo, "disable-pubkey-algo", 2, "@" },
{ oAllowNonSelfsignedUID, "allow-non-selfsigned-uid", 0, "@" },
{ oNoAllowNonSelfsignedUID, "no-allow-non-selfsigned-uid", 0, "@" },
{ oAllowFreeformUID, "allow-freeform-uid", 0, "@" },
{ oNoAllowFreeformUID, "no-allow-freeform-uid", 0, "@" },
{ oNoLiteral, "no-literal", 0, "@" },
{ oSetFilesize, "set-filesize", 20, "@" },
{ oHonorHttpProxy,"honor-http-proxy", 0, "@" },
{ oFastListMode,"fast-list-mode", 0, "@" },
{ oFixedListMode,"fixed-list-mode", 0, "@" },
{ oListOnly, "list-only", 0, "@"},
{ oIgnoreTimeConflict, "ignore-time-conflict", 0, "@" },
{ oIgnoreValidFrom, "ignore-valid-from", 0, "@" },
{ oIgnoreCrcError, "ignore-crc-error", 0,"@" },
{ oIgnoreMDCError, "ignore-mdc-error", 0,"@" },
{ oShowSessionKey, "show-session-key", 0, "@" },
{ oOverrideSessionKey, "override-session-key", 2, "@" },
{ oNoRandomSeedFile, "no-random-seed-file", 0, "@" },
{ oAutoKeyRetrieve, "auto-key-retrieve", 0, "@" },
{ oNoAutoKeyRetrieve, "no-auto-key-retrieve", 0, "@" },
{ oNoSigCache, "no-sig-cache", 0, "@" },
{ oNoSigCreateCheck, "no-sig-create-check", 0, "@" },
{ oAutoCheckTrustDB, "auto-check-trustdb", 0, "@"},
{ oNoAutoCheckTrustDB, "no-auto-check-trustdb", 0, "@"},
{ oMergeOnly, "merge-only", 0, "@" },
{ oAllowSecretKeyImport, "allow-secret-key-import", 0, "@" },
{ oTryAllSecrets, "try-all-secrets", 0, "@" },
{ oEnableSpecialFilenames, "enable-special-filenames", 0, "@" },
{ oNoExpensiveTrustChecks, "no-expensive-trust-checks", 0, "@" },
{ aDeleteSecretAndPublicKeys, "delete-secret-and-public-keys",256, "@" },
{ aRebuildKeydbCaches, "rebuild-keydb-caches", 256, "@"},
{ oPreservePermissions, "preserve-permissions", 0, "@"},
{ oDefaultPreferenceList, "default-preference-list", 2, "@"},
{ oDefaultKeyserverURL, "default-keyserver-url", 2, "@"},
{ oPersonalCipherPreferences, "personal-cipher-preferences", 2, "@"},
{ oPersonalDigestPreferences, "personal-digest-preferences", 2, "@"},
{ oPersonalCompressPreferences, "personal-compress-preferences", 2, "@"},
/* Aliases. I constantly mistype these, and assume other people
do as well. */
{ oPersonalCipherPreferences, "personal-cipher-prefs", 2, "@"},
{ oPersonalDigestPreferences, "personal-digest-prefs", 2, "@"},
{ oPersonalCompressPreferences, "personal-compress-prefs", 2, "@"},
{ oDisplay, "display", 2, "@" },
{ oTTYname, "ttyname", 2, "@" },
{ oTTYtype, "ttytype", 2, "@" },
{ oLCctype, "lc-ctype", 2, "@" },
{ oLCmessages, "lc-messages", 2, "@" },
{ oGroup, "group", 2, "@" },
{ oUnGroup, "ungroup", 2, "@" },
{ oNoGroups, "no-groups", 0, "@" },
{ oStrict, "strict", 0, "@" },
{ oNoStrict, "no-strict", 0, "@" },
{ oMangleDosFilenames, "mangle-dos-filenames", 0, "@" },
{ oNoMangleDosFilenames, "no-mangle-dos-filenames", 0, "@" },
{ oEnableProgressFilter, "enable-progress-filter", 0, "@" },
{ oMultifile, "multifile", 0, "@" },
{ oKeyidFormat, "keyid-format", 2, "@" },
{ oExitOnStatusWriteError, "exit-on-status-write-error", 0, "@" },
{ oLimitCardInsertTries, "limit-card-insert-tries", 1, "@"},
{ oReaderPort, "reader-port", 2, "@"},
{ octapiDriver, "ctapi-driver", 2, "@"},
{ opcscDriver, "pcsc-driver", 2, "@"},
{ oDisableCCID, "disable-ccid", 0, "@"},
#if defined(ENABLE_CARD_SUPPORT) && defined(HAVE_LIBUSB)
{ oDebugCCIDDriver, "debug-ccid-driver", 0, "@"},
#endif
{ oAllowMultisigVerification, "allow-multisig-verification", 0, "@"},
{ oEnableDSA2, "enable-dsa2", 0, "@"},
{ oDisableDSA2, "disable-dsa2", 0, "@"},
{ oAllowMultipleMessages, "allow-multiple-messages", 0, "@"},
{ oNoAllowMultipleMessages, "no-allow-multiple-messages", 0, "@"},
/* These two are aliases to help users of the PGP command line
product use gpg with minimal pain. Many commands are common
already as they seem to have borrowed commands from us. Now
I'm returning the favor. */
{ oLocalUser, "sign-with", 2, "@" },
{ oRecipient, "user", 2, "@" },
{ oRequireCrossCert, "require-backsigs", 0, "@"},
{ oRequireCrossCert, "require-cross-certification", 0, "@"},
{ oNoRequireCrossCert, "no-require-backsigs", 0, "@"},
{ oNoRequireCrossCert, "no-require-cross-certification", 0, "@"},
{ oAutoKeyLocate, "auto-key-locate", 2, "@"},
{ oNoAutoKeyLocate, "no-auto-key-locate", 0, "@"},
{0,NULL,0,NULL}
};
#ifdef ENABLE_SELINUX_HACKS
#define ALWAYS_ADD_KEYRINGS 1
#else
#define ALWAYS_ADD_KEYRINGS 0
#endif
int g10_errors_seen = 0;
static int utf8_strings = 0;
static int maybe_setuid = 1;
static char *build_list( const char *text, char letter,
const char *(*mapf)(int), int (*chkf)(int) );
static void set_cmd( enum cmd_and_opt_values *ret_cmd,
enum cmd_and_opt_values new_cmd );
static void print_mds( const char *fname, int algo );
static void add_notation_data( const char *string, int which );
static void add_policy_url( const char *string, int which );
static void add_keyserver_url( const char *string, int which );
const char *
strusage( int level )
{
static char *digests, *pubkeys, *ciphers, *zips;
const char *p;
switch( level ) {
case 11: p = "gpg (GnuPG)";
break;
case 13: p = VERSION; break;
case 17: p = PRINTABLE_OS_NAME; break;
case 19: p =
_("Please report bugs to .\n");
break;
#ifdef IS_DEVELOPMENT_VERSION
case 20:
p="NOTE: THIS IS A DEVELOPMENT VERSION!";
break;
case 21:
p="It is only intended for test purposes and should NOT be";
break;
case 22:
p="used in a production environment or with production keys!";
break;
#endif
case 1:
case 40: p =
_("Usage: gpg [options] [files] (-h for help)");
break;
case 41: p =
_("Syntax: gpg [options] [files]\n"
"sign, check, encrypt or decrypt\n"
"default operation depends on the input data\n");
break;
case 31: p = "\nHome: "; break;
#ifndef __riscos__
case 32: p = opt.homedir; break;
#else /* __riscos__ */
case 32: p = make_filename(opt.homedir, NULL); break;
#endif /* __riscos__ */
case 33: p = _("\nSupported algorithms:\n"); break;
case 34:
if( !pubkeys )
pubkeys = build_list(_("Pubkey: "), 0, pubkey_algo_to_string,
check_pubkey_algo );
p = pubkeys;
break;
case 35:
if( !ciphers )
ciphers = build_list(_("Cipher: "), 'S', cipher_algo_to_string,
check_cipher_algo );
p = ciphers;
break;
case 36:
if( !digests )
digests = build_list(_("Hash: "), 'H', digest_algo_to_string,
check_digest_algo );
p = digests;
break;
case 37:
if( !zips )
zips = build_list(_("Compression: "),'Z',compress_algo_to_string,
check_compress_algo);
p = zips;
break;
default: p = default_strusage(level);
}
return p;
}
static char *
build_list( const char *text, char letter,
const char * (*mapf)(int), int (*chkf)(int) )
{
int i;
const char *s;
size_t n=strlen(text)+2;
char *list, *p, *line=NULL;
if( maybe_setuid )
secmem_init( 0 ); /* drop setuid */
for(i=0; i <= 110; i++ )
if( !chkf(i) && (s=mapf(i)) )
n += strlen(s) + 7 + 2;
list = xmalloc( 21 + n ); *list = 0;
for(p=NULL, i=0; i <= 110; i++ ) {
if( !chkf(i) && (s=mapf(i)) ) {
if( !p ) {
p = stpcpy( list, text );
line=p;
}
else
p = stpcpy( p, ", ");
if(strlen(line)>60) {
int spaces=strlen(text);
list=xrealloc(list,n+spaces+1);
/* realloc could move the block, so find the end again */
p=list;
while(*p)
p++;
p=stpcpy(p, "\n");
line=p;
for(;spaces;spaces--)
p=stpcpy(p, " ");
}
p = stpcpy(p, s );
if(opt.verbose && letter)
{
char num[8];
sprintf(num," (%c%d)",letter,i);
p = stpcpy(p,num);
}
}
}
if( p )
p = stpcpy(p, "\n" );
return list;
}
static void
i18n_init(void)
{
#ifdef USE_SIMPLE_GETTEXT
set_gettext_file (PACKAGE, "Software\\GNU\\GnuPG");
#else
#ifdef ENABLE_NLS
setlocale( LC_ALL, "" );
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain( PACKAGE );
#endif
#endif
}
static void
wrong_args( const char *text)
{
fputs(_("usage: gpg [options] "),stderr);
fputs(text,stderr);
putc('\n',stderr);
g10_exit(2);
}
static char *
make_username( const char *string )
{
char *p;
if( utf8_strings )
p = xstrdup(string);
else
p = native_to_utf8( string );
return p;
}
static void
set_debug(void)
{
if( opt.debug & DBG_MEMORY_VALUE )
memory_debug_mode = 1;
if( opt.debug & DBG_MEMSTAT_VALUE )
memory_stat_debug_mode = 1;
if( opt.debug & DBG_MPI_VALUE )
mpi_debug_mode = 1;
if( opt.debug & DBG_CIPHER_VALUE )
g10c_debug_mode = 1;
if( opt.debug & DBG_IOBUF_VALUE )
iobuf_debug_mode = 1;
}
/* We need the home directory also in some other directories, so make
sure that both variables are always in sync. */
static void
set_homedir (char *dir)
{
if (!dir)
dir = "";
g10_opt_homedir = opt.homedir = dir;
}
/* We set the screen dimensions for UI purposes. Do not allow screens
smaller than 80x24 for the sake of simplicity. */
static void
set_screen_dimensions(void)
{
#ifndef _WIN32
char *str;
str=getenv("COLUMNS");
if(str)
opt.screen_columns=atoi(str);
str=getenv("LINES");
if(str)
opt.screen_lines=atoi(str);
#endif
if(opt.screen_columns<80 || opt.screen_columns>255)
opt.screen_columns=80;
if(opt.screen_lines<24 || opt.screen_lines>255)
opt.screen_lines=24;
}
/* Helper to open a file FNAME either for reading or writing to be
used with --status-file etc functions. Not generally useful but it
avoids the riscos specific functions and well some Windows people
might like it too. Prints an error message and returns -1 on
error. On success the file descriptor is returned. */
static int
open_info_file (const char *fname, int for_write)
{
#ifdef __riscos__
return riscos_fdopenfile (fname, for_write);
#elif defined (ENABLE_SELINUX_HACKS)
/* We can't allow these even when testing for a secured filename
because files to be secured might not yet been secured. This is
similar to the option file but in that case it is unlikely that
sensitive information may be retrieved by means of error
messages. */
return -1;
-#else
+#else
int fd;
/* if (is_secured_filename (fname)) */
/* { */
/* fd = -1; */
/* errno = EPERM; */
/* } */
/* else */
/* { */
do
{
if (for_write)
fd = open (fname, O_CREAT | O_TRUNC | O_WRONLY,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
else
fd = open (fname, O_RDONLY | MY_O_BINARY);
}
while (fd == -1 && errno == EINTR);
/* } */
if ( fd == -1)
log_error ( for_write? _("can't create `%s': %s\n")
: _("can't open `%s': %s\n"), fname, strerror(errno));
-
+
return fd;
#endif
}
static void
set_cmd( enum cmd_and_opt_values *ret_cmd, enum cmd_and_opt_values new_cmd )
{
enum cmd_and_opt_values cmd = *ret_cmd;
if( !cmd || cmd == new_cmd )
cmd = new_cmd;
else if( cmd == aSign && new_cmd == aEncr )
cmd = aSignEncr;
else if( cmd == aEncr && new_cmd == aSign )
cmd = aSignEncr;
else if( cmd == aSign && new_cmd == aSym )
cmd = aSignSym;
else if( cmd == aSym && new_cmd == aSign )
cmd = aSignSym;
else if( cmd == aSym && new_cmd == aEncr )
cmd = aEncrSym;
else if( cmd == aEncr && new_cmd == aSym )
cmd = aEncrSym;
else if( cmd == aKMode && new_cmd == aSym )
cmd = aKModeC;
else if (cmd == aSignEncr && new_cmd == aSym)
cmd = aSignEncrSym;
else if (cmd == aSignSym && new_cmd == aEncr)
cmd = aSignEncrSym;
else if (cmd == aEncrSym && new_cmd == aSign)
cmd = aSignEncrSym;
else if( ( cmd == aSign && new_cmd == aClearsign )
|| ( cmd == aClearsign && new_cmd == aSign ) )
cmd = aClearsign;
else {
log_error(_("conflicting commands\n"));
g10_exit(2);
}
*ret_cmd = cmd;
}
static void
add_group(char *string)
{
char *name,*value;
struct groupitem *item;
/* Break off the group name */
name=strsep(&string,"=");
if(string==NULL)
{
log_error(_("no = sign found in group definition `%s'\n"),name);
return;
}
trim_trailing_ws(name,strlen(name));
/* Does this group already exist? */
for(item=opt.grouplist;item;item=item->next)
if(strcasecmp(item->name,name)==0)
break;
if(!item)
{
item=xmalloc(sizeof(struct groupitem));
item->name=name;
item->next=opt.grouplist;
item->values=NULL;
opt.grouplist=item;
}
/* Break apart the values */
while ((value= strsep(&string," \t")))
{
if (*value)
add_to_strlist2(&item->values,value,utf8_strings);
}
}
static void
rm_group(char *name)
{
struct groupitem *item,*last=NULL;
trim_trailing_ws(name,strlen(name));
for(item=opt.grouplist;item;last=item,item=item->next)
{
if(strcasecmp(item->name,name)==0)
{
if(last)
last->next=item->next;
else
opt.grouplist=item->next;
free_strlist(item->values);
xfree(item);
break;
}
}
}
/* We need to check three things.
0) The homedir. It must be x00, a directory, and owned by the
user.
1) The options/gpg.conf file. Okay unless it or its containing
directory is group or other writable or not owned by us. Disable
exec in this case.
2) Extensions. Same as #1.
Returns true if the item is unsafe. */
static int
check_permissions(const char *path,int item)
{
#if defined(HAVE_STAT) && !defined(HAVE_DOSISH_SYSTEM)
static int homedir_cache=-1;
char *tmppath,*dir;
struct stat statbuf,dirbuf;
int homedir=0,ret=0,checkonly=0;
int perm=0,own=0,enc_dir_perm=0,enc_dir_own=0;
if(opt.no_perm_warn)
return 0;
assert(item==0 || item==1 || item==2);
/* extensions may attach a path */
if(item==2 && path[0]!=DIRSEP_C)
{
if(strchr(path,DIRSEP_C))
tmppath=make_filename(path,NULL);
else
tmppath=make_filename(GNUPG_LIBDIR,path,NULL);
}
else
tmppath=xstrdup(path);
/* If the item is located in the homedir, but isn't the homedir,
don't continue if we already checked the homedir itself. This is
to avoid user confusion with an extra options file warning which
could be rectified if the homedir itself had proper
permissions. */
if(item!=0 && homedir_cache>-1
&& ascii_strncasecmp(opt.homedir,tmppath,strlen(opt.homedir))==0)
{
ret=homedir_cache;
goto end;
}
/* It's okay if the file or directory doesn't exist */
if(stat(tmppath,&statbuf)!=0)
{
ret=0;
goto end;
}
/* Now check the enclosing directory. Theoretically, we could walk
this test up to the root directory /, but for the sake of sanity,
I'm stopping at one level down. */
dir=make_dirname(tmppath);
if(stat(dir,&dirbuf)!=0 || !S_ISDIR(dirbuf.st_mode))
{
/* Weird error */
ret=1;
goto end;
}
xfree(dir);
/* Assume failure */
ret=1;
if(item==0)
{
/* The homedir must be x00, a directory, and owned by the user. */
if(S_ISDIR(statbuf.st_mode))
{
if(statbuf.st_uid==getuid())
{
if((statbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
ret=0;
else
perm=1;
}
else
own=1;
homedir_cache=ret;
}
}
else if(item==1 || item==2)
{
/* The options or extension file. Okay unless it or its
containing directory is group or other writable or not owned
by us or root. */
if(S_ISREG(statbuf.st_mode))
{
if(statbuf.st_uid==getuid() || statbuf.st_uid==0)
{
if((statbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
{
/* it's not writable, so make sure the enclosing
directory is also not writable */
if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
{
if((dirbuf.st_mode & (S_IWGRP|S_IWOTH))==0)
ret=0;
else
enc_dir_perm=1;
}
else
enc_dir_own=1;
}
else
{
/* it's writable, so the enclosing directory had
better not let people get to it. */
if(dirbuf.st_uid==getuid() || dirbuf.st_uid==0)
{
if((dirbuf.st_mode & (S_IRWXG|S_IRWXO))==0)
ret=0;
else
perm=enc_dir_perm=1; /* unclear which one to fix! */
}
else
enc_dir_own=1;
}
}
else
own=1;
}
}
else
BUG();
if(!checkonly)
{
if(own)
{
if(item==0)
log_info(_("WARNING: unsafe ownership on"
" homedir `%s'\n"),tmppath);
else if(item==1)
log_info(_("WARNING: unsafe ownership on"
" configuration file `%s'\n"),tmppath);
else
log_info(_("WARNING: unsafe ownership on"
" extension `%s'\n"),tmppath);
}
if(perm)
{
if(item==0)
log_info(_("WARNING: unsafe permissions on"
" homedir `%s'\n"),tmppath);
else if(item==1)
log_info(_("WARNING: unsafe permissions on"
" configuration file `%s'\n"),tmppath);
else
log_info(_("WARNING: unsafe permissions on"
" extension `%s'\n"),tmppath);
}
if(enc_dir_own)
{
if(item==0)
log_info(_("WARNING: unsafe enclosing directory ownership on"
" homedir `%s'\n"),tmppath);
else if(item==1)
log_info(_("WARNING: unsafe enclosing directory ownership on"
" configuration file `%s'\n"),tmppath);
else
log_info(_("WARNING: unsafe enclosing directory ownership on"
" extension `%s'\n"),tmppath);
}
if(enc_dir_perm)
{
if(item==0)
log_info(_("WARNING: unsafe enclosing directory permissions on"
" homedir `%s'\n"),tmppath);
else if(item==1)
log_info(_("WARNING: unsafe enclosing directory permissions on"
" configuration file `%s'\n"),tmppath);
else
log_info(_("WARNING: unsafe enclosing directory permissions on"
" extension `%s'\n"),tmppath);
}
}
end:
xfree(tmppath);
if(homedir)
homedir_cache=ret;
return ret;
#endif /* HAVE_STAT && !HAVE_DOSISH_SYSTEM */
return 0;
}
static void
print_algo_numbers(int (*checker)(int))
{
int i,first=1;
for(i=0;i<=110;i++)
{
if(!checker(i))
{
if(first)
first=0;
else
printf(";");
printf("%d",i);
}
}
}
static void
print_algo_names(int (*checker)(int),const char *(*mapper)(int))
{
int i,first=1;
for(i=0;i<=110;i++)
{
if(!checker(i))
{
if(first)
first=0;
else
printf(";");
printf("%s",mapper(i));
}
}
}
/* In the future, we can do all sorts of interesting configuration
output here. For now, just give "group" as the Enigmail folks need
it, and pubkey, cipher, hash, and compress as they may be useful
for frontends. */
static void
list_config(char *items)
{
int show_all=(items==NULL);
char *name=NULL;
if(!opt.with_colons)
return;
while(show_all || (name=strsep(&items," ")))
{
int any=0;
if(show_all || ascii_strcasecmp(name,"group")==0)
{
struct groupitem *iter;
for(iter=opt.grouplist;iter;iter=iter->next)
{
STRLIST sl;
printf("cfg:group:");
print_string(stdout,iter->name,strlen(iter->name),':');
printf(":");
for(sl=iter->values;sl;sl=sl->next)
{
print_string2(stdout,sl->d,strlen(sl->d),':',';');
if(sl->next)
printf(";");
}
printf("\n");
}
any=1;
}
if(show_all || ascii_strcasecmp(name,"version")==0)
{
printf("cfg:version:");
print_string(stdout,VERSION,strlen(VERSION),':');
printf("\n");
any=1;
}
if(show_all || ascii_strcasecmp(name,"pubkey")==0)
{
printf("cfg:pubkey:");
print_algo_numbers(check_pubkey_algo);
printf("\n");
any=1;
}
if(show_all || ascii_strcasecmp(name,"cipher")==0)
{
printf("cfg:cipher:");
print_algo_numbers(check_cipher_algo);
printf("\n");
any=1;
}
if(show_all || ascii_strcasecmp(name,"ciphername")==0)
{
printf("cfg:ciphername:");
print_algo_names(check_cipher_algo,cipher_algo_to_string);
printf("\n");
any=1;
}
if(show_all
|| ascii_strcasecmp(name,"digest")==0
|| ascii_strcasecmp(name,"hash")==0)
{
printf("cfg:digest:");
print_algo_numbers(check_digest_algo);
printf("\n");
any=1;
}
if(show_all
|| ascii_strcasecmp(name,"digestname")==0
|| ascii_strcasecmp(name,"hashname")==0)
{
printf("cfg:digestname:");
print_algo_names(check_digest_algo,digest_algo_to_string);
printf("\n");
any=1;
}
if(show_all || ascii_strcasecmp(name,"compress")==0)
{
printf("cfg:compress:");
print_algo_numbers(check_compress_algo);
printf("\n");
any=1;
}
if(show_all || ascii_strcasecmp(name,"ccid-reader-id")==0)
{
#if defined(ENABLE_CARD_SUPPORT) && defined(HAVE_LIBUSB)
char *p, *p2, *list = ccid_get_reader_list ();
for (p=list; p && (p2 = strchr (p, '\n')); p = p2+1)
{
*p2 = 0;
printf("cfg:ccid-reader-id:%s\n", p);
}
free (list);
#endif
any=1;
}
if(show_all)
break;
if(!any)
log_error(_("unknown configuration item `%s'\n"),name);
}
}
/* List options and default values in the GPG Conf format. This is a
new tool distributed with gnupg 1.9.x but we also want some limited
support in older gpg versions. The output is the name of the
configuration file and a list of options available for editing by
gpgconf. */
static void
gpgconf_list (const char *configfile)
{
/* The following definitions are taken from gnupg/tools/gpgconf-comp.c. */
#define GC_OPT_FLAG_NONE 0UL
#define GC_OPT_FLAG_DEFAULT (1UL << 4)
printf ("gpgconf-gpg.conf:%lu:\"%s\n",
GC_OPT_FLAG_DEFAULT,configfile?configfile:"/dev/null");
printf ("verbose:%lu:\n", GC_OPT_FLAG_NONE);
printf ("quiet:%lu:\n", GC_OPT_FLAG_NONE);
printf ("keyserver:%lu:\n", GC_OPT_FLAG_NONE);
printf ("reader-port:%lu:\n", GC_OPT_FLAG_NONE);
}
static int
parse_subpacket_list(char *list)
{
char *tok;
byte subpackets[128],i;
int count=0;
if(!list)
{
/* No arguments means all subpackets */
memset(subpackets+1,1,sizeof(subpackets)-1);
count=127;
}
else
{
memset(subpackets,0,sizeof(subpackets));
/* Merge with earlier copy */
if(opt.show_subpackets)
{
byte *in;
for(in=opt.show_subpackets;*in;in++)
{
if(*in>127 || *in<1)
BUG();
if(!subpackets[*in])
count++;
subpackets[*in]=1;
}
}
while((tok=strsep(&list," ,")))
{
if(!*tok)
continue;
i=atoi(tok);
if(i>127 || i<1)
return 0;
if(!subpackets[i])
count++;
subpackets[i]=1;
}
}
xfree(opt.show_subpackets);
opt.show_subpackets=xmalloc(count+1);
opt.show_subpackets[count--]=0;
for(i=1;i<128 && count>=0;i++)
if(subpackets[i])
opt.show_subpackets[count--]=i;
return 1;
}
static int
parse_list_options(char *str)
{
char *subpackets=""; /* something that isn't NULL */
struct parse_options lopts[]=
{
{"show-photos",LIST_SHOW_PHOTOS,NULL,
N_("display photo IDs during key listings")},
{"show-policy-urls",LIST_SHOW_POLICY_URLS,NULL,
N_("show policy URLs during signature listings")},
{"show-notations",LIST_SHOW_NOTATIONS,NULL,
N_("show all notations during signature listings")},
{"show-std-notations",LIST_SHOW_STD_NOTATIONS,NULL,
N_("show IETF standard notations during signature listings")},
{"show-standard-notations",LIST_SHOW_STD_NOTATIONS,NULL,
NULL},
{"show-user-notations",LIST_SHOW_USER_NOTATIONS,NULL,
N_("show user-supplied notations during signature listings")},
{"show-keyserver-urls",LIST_SHOW_KEYSERVER_URLS,NULL,
N_("show preferred keyserver URLs during signature listings")},
{"show-uid-validity",LIST_SHOW_UID_VALIDITY,NULL,
N_("show user ID validity during key listings")},
{"show-unusable-uids",LIST_SHOW_UNUSABLE_UIDS,NULL,
N_("show revoked and expired user IDs in key listings")},
{"show-unusable-subkeys",LIST_SHOW_UNUSABLE_SUBKEYS,NULL,
N_("show revoked and expired subkeys in key listings")},
{"show-keyring",LIST_SHOW_KEYRING,NULL,
N_("show the keyring name in key listings")},
{"show-sig-expire",LIST_SHOW_SIG_EXPIRE,NULL,
N_("show expiration dates during signature listings")},
{"show-sig-subpackets",LIST_SHOW_SIG_SUBPACKETS,NULL,
NULL},
{NULL,0,NULL,NULL}
};
/* C99 allows for non-constant initializers, but we'd like to
compile everywhere, so fill in the show-sig-subpackets argument
here. Note that if the parse_options array changes, we'll have
to change the subscript here. */
lopts[12].value=&subpackets;
if(parse_options(str,&opt.list_options,lopts,1))
{
if(opt.list_options&LIST_SHOW_SIG_SUBPACKETS)
{
/* Unset so users can pass multiple lists in. */
opt.list_options&=~LIST_SHOW_SIG_SUBPACKETS;
if(!parse_subpacket_list(subpackets))
return 0;
}
else if(subpackets==NULL && opt.show_subpackets)
{
/* User did 'no-show-subpackets' */
xfree(opt.show_subpackets);
opt.show_subpackets=NULL;
}
return 1;
}
else
return 0;
}
/* Collapses argc/argv into a single string that must be freed */
static char *
collapse_args(int argc,char *argv[])
{
char *str=NULL;
int i,first=1,len=0;
for(i=0;i=65011712)
return 255;
/* Need count to be in the range 16-31 */
for(count=iterations>>6;count>=32;count>>=1)
c++;
result=(c<<4)|(count-16);
if(S2K_DECODE_COUNT(result)flags=2;
break;
case oShowKeyring:
deprecated_warning(configname,configlineno,"--show-keyring",
"--list-options ","show-keyring");
opt.list_options|=LIST_SHOW_KEYRING;
break;
case oDebug: opt.debug |= pargs.r.ret_ulong; break;
case oDebugAll: opt.debug = ~0; break;
case oDebugLevel: break; /* Not supported. */
- case oDebugCCIDDriver:
+ case oDebugCCIDDriver:
#if defined(ENABLE_CARD_SUPPORT) && defined(HAVE_LIBUSB)
ccid_set_debug_level (ccid_set_debug_level (1)+1);
#endif
break;
case oStatusFD:
set_status_fd( iobuf_translate_file_handle (pargs.r.ret_int, 1) );
break;
case oStatusFile:
set_status_fd ( open_info_file (pargs.r.ret_str, 1) );
break;
case oAttributeFD:
set_attrib_fd(iobuf_translate_file_handle (pargs.r.ret_int, 1));
break;
case oAttributeFile:
set_attrib_fd ( open_info_file (pargs.r.ret_str, 1) );
break;
case oLoggerFD:
log_set_logfile( NULL,
iobuf_translate_file_handle (pargs.r.ret_int, 1));
break;
case oLoggerFile:
/* Our log code does not support the socket feature. Thus
we ignore such log files to avoid problems with
gpg.conf files which are also used by gpg2. */
if (strncmp (pargs.r.ret_str, "socket://", 9))
log_set_logfile( NULL, open_info_file (pargs.r.ret_str, 1) );
break;
case oWithFingerprint:
opt.with_fingerprint = 1;
opt.fingerprint++;
break;
case oFingerprint:
opt.fingerprint++;
fpr_maybe_cmd = 1;
break;
case oSecretKeyring:
append_to_strlist( &sec_nrings, pargs.r.ret_str);
break;
case oOptions:
/* config files may not be nested (silently ignore them) */
if( !configfp ) {
xfree(configname);
configname = xstrdup(pargs.r.ret_str);
goto next_pass;
}
break;
case oNoArmor: opt.no_armor=1; opt.armor=0; break;
case oNoDefKeyring: default_keyring = 0; break;
case oNoGreeting: nogreeting = 1; break;
case oNoVerbose: g10_opt_verbose = 0;
opt.verbose = 0; opt.list_sigs=0; break;
case oQuickRandom: quick_random_gen(1); break;
case oEmitVersion: opt.no_version=0; break;
case oNoEmitVersion: opt.no_version=1; break;
case oCompletesNeeded: opt.completes_needed = pargs.r.ret_int; break;
case oMarginalsNeeded: opt.marginals_needed = pargs.r.ret_int; break;
case oMaxCertDepth: opt.max_cert_depth = pargs.r.ret_int; break;
case oTrustDBName: trustdb_name = pargs.r.ret_str; break;
case oDefaultKey: opt.def_secret_key = pargs.r.ret_str; break;
case oDefRecipient:
if( *pargs.r.ret_str )
opt.def_recipient = make_username(pargs.r.ret_str);
break;
case oDefRecipientSelf:
xfree(opt.def_recipient); opt.def_recipient = NULL;
opt.def_recipient_self = 1;
break;
case oNoDefRecipient:
xfree(opt.def_recipient); opt.def_recipient = NULL;
opt.def_recipient_self = 0;
break;
case oNoOptions: opt.no_homedir_creation = 1; break; /* no-options */
case oHomedir: break;
case oNoBatch: opt.batch = 0; break;
case oWithKeyData: opt.with_key_data=1; /* fall thru */
case oWithColons: opt.with_colons=':'; break;
case oSkipVerify: opt.skip_verify=1; break;
case oCompressKeys: opt.compress_keys = 1; break;
case aListSecretKeys: set_cmd( &cmd, aListSecretKeys); break;
/* There are many programs (like mutt) that call gpg with
--always-trust so keep this option around for a long
time. */
case oAlwaysTrust: opt.trust_model=TM_ALWAYS; break;
case oTrustModel:
parse_trust_model(pargs.r.ret_str);
break;
case oForceOwnertrust:
log_info(_("NOTE: %s is not for normal use!\n"),
"--force-ownertrust");
opt.force_ownertrust=string_to_trust_value(pargs.r.ret_str);
if(opt.force_ownertrust==-1)
{
log_error("invalid ownertrust `%s'\n",pargs.r.ret_str);
opt.force_ownertrust=0;
}
break;
case oLoadExtension:
#ifndef __riscos__
#if defined(USE_DYNAMIC_LINKING) || defined(_WIN32)
if(check_permissions(pargs.r.ret_str,2))
log_info(_("cipher extension `%s' not loaded due to"
" unsafe permissions\n"),pargs.r.ret_str);
else
register_cipher_extension(orig_argc? *orig_argv:NULL,
pargs.r.ret_str);
#endif
#else /* __riscos__ */
riscos_not_implemented("load-extension");
#endif /* __riscos__ */
break;
case oRFC1991:
opt.compliance = CO_RFC1991;
opt.force_v4_certs = 0;
opt.escape_from = 1;
break;
case oOpenPGP:
case oRFC4880:
/* This is effectively the same as RFC2440, but with
"--enable-dsa2 --no-rfc2440-text --escape-from-lines
--require-cross-certification". */
opt.compliance = CO_RFC4880;
opt.flags.dsa2 = 1;
opt.flags.require_cross_cert = 1;
opt.rfc2440_text = 0;
opt.allow_non_selfsigned_uid = 1;
opt.allow_freeform_uid = 1;
opt.pgp2_workarounds = 0;
opt.escape_from = 1;
opt.force_v3_sigs = 0;
opt.compress_keys = 0; /* not mandated, but we do it */
opt.compress_sigs = 0; /* ditto. */
opt.not_dash_escaped = 0;
opt.def_cipher_algo = 0;
opt.def_digest_algo = 0;
opt.cert_digest_algo = 0;
opt.compress_algo = -1;
opt.s2k_mode = 3; /* iterated+salted */
opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
break;
case oRFC2440:
opt.compliance = CO_RFC2440;
opt.flags.dsa2 = 0;
opt.rfc2440_text = 1;
opt.allow_non_selfsigned_uid = 1;
opt.allow_freeform_uid = 1;
opt.pgp2_workarounds = 0;
opt.escape_from = 0;
opt.force_v3_sigs = 0;
opt.compress_keys = 0; /* not mandated, but we do it */
opt.compress_sigs = 0; /* ditto. */
opt.not_dash_escaped = 0;
opt.def_cipher_algo = 0;
opt.def_digest_algo = 0;
opt.cert_digest_algo = 0;
opt.compress_algo = -1;
opt.s2k_mode = 3; /* iterated+salted */
opt.s2k_digest_algo = DIGEST_ALGO_SHA1;
opt.s2k_cipher_algo = CIPHER_ALGO_3DES;
break;
case oPGP2: opt.compliance = CO_PGP2; break;
case oPGP6: opt.compliance = CO_PGP6; break;
case oPGP7: opt.compliance = CO_PGP7; break;
case oPGP8: opt.compliance = CO_PGP8; break;
case oGnuPG: opt.compliance = CO_GNUPG; break;
case oCompressSigs: opt.compress_sigs = 1; break;
case oRFC2440Text: opt.rfc2440_text=1; break;
case oNoRFC2440Text: opt.rfc2440_text=0; break;
case oRunAsShmCP:
#ifndef __riscos__
# ifndef USE_SHM_COPROCESSING
/* not possible in the option file,
* but we print the warning here anyway */
log_error("shared memory coprocessing is not available\n");
# endif
#else /* __riscos__ */
riscos_not_implemented("run-as-shm-coprocess");
#endif /* __riscos__ */
break;
case oSetFilename:
if(utf8_strings)
opt.set_filename = pargs.r.ret_str;
else
opt.set_filename = native_to_utf8(pargs.r.ret_str);
break;
case oForYourEyesOnly: eyes_only = 1; break;
case oNoForYourEyesOnly: eyes_only = 0; break;
case oSetPolicyURL:
add_policy_url(pargs.r.ret_str,0);
add_policy_url(pargs.r.ret_str,1);
break;
case oSigPolicyURL: add_policy_url(pargs.r.ret_str,0); break;
case oCertPolicyURL: add_policy_url(pargs.r.ret_str,1); break;
case oShowPolicyURL:
deprecated_warning(configname,configlineno,"--show-policy-url",
"--list-options ","show-policy-urls");
deprecated_warning(configname,configlineno,"--show-policy-url",
"--verify-options ","show-policy-urls");
opt.list_options|=LIST_SHOW_POLICY_URLS;
opt.verify_options|=VERIFY_SHOW_POLICY_URLS;
break;
case oNoShowPolicyURL:
deprecated_warning(configname,configlineno,"--no-show-policy-url",
"--list-options ","no-show-policy-urls");
deprecated_warning(configname,configlineno,"--no-show-policy-url",
"--verify-options ","no-show-policy-urls");
opt.list_options&=~LIST_SHOW_POLICY_URLS;
opt.verify_options&=~VERIFY_SHOW_POLICY_URLS;
break;
case oSigKeyserverURL: add_keyserver_url(pargs.r.ret_str,0); break;
case oUseEmbeddedFilename:
opt.flags.use_embedded_filename=1;
break;
case oNoUseEmbeddedFilename:
opt.flags.use_embedded_filename=0;
break;
case oComment:
if(pargs.r.ret_str[0])
append_to_strlist(&opt.comments,pargs.r.ret_str);
break;
case oDefaultComment:
deprecated_warning(configname,configlineno,
"--default-comment","--no-comments","");
/* fall through */
case oNoComments:
free_strlist(opt.comments);
opt.comments=NULL;
break;
case oThrowKeyids: opt.throw_keyid = 1; break;
case oNoThrowKeyids: opt.throw_keyid = 0; break;
case oShowPhotos:
deprecated_warning(configname,configlineno,"--show-photos",
"--list-options ","show-photos");
deprecated_warning(configname,configlineno,"--show-photos",
"--verify-options ","show-photos");
opt.list_options|=LIST_SHOW_PHOTOS;
opt.verify_options|=VERIFY_SHOW_PHOTOS;
break;
case oNoShowPhotos:
deprecated_warning(configname,configlineno,"--no-show-photos",
"--list-options ","no-show-photos");
deprecated_warning(configname,configlineno,"--no-show-photos",
"--verify-options ","no-show-photos");
opt.list_options&=~LIST_SHOW_PHOTOS;
opt.verify_options&=~VERIFY_SHOW_PHOTOS;
break;
case oPhotoViewer: opt.photo_viewer = pargs.r.ret_str; break;
case oForceV3Sigs: opt.force_v3_sigs = 1; break;
case oNoForceV3Sigs: opt.force_v3_sigs = 0; break;
case oForceV4Certs: opt.force_v4_certs = 1; break;
case oNoForceV4Certs: opt.force_v4_certs = 0; break;
case oForceMDC: opt.force_mdc = 1; break;
case oNoForceMDC: opt.force_mdc = 0; break;
case oDisableMDC: opt.disable_mdc = 1; break;
case oNoDisableMDC: opt.disable_mdc = 0; break;
case oS2KMode: opt.s2k_mode = pargs.r.ret_int; break;
case oS2KDigest: s2k_digest_string = xstrdup(pargs.r.ret_str); break;
case oS2KCipher: s2k_cipher_string = xstrdup(pargs.r.ret_str); break;
case oS2KCount:
opt.s2k_count=encode_s2k_iterations(pargs.r.ret_int);
break;
case oSimpleSKChecksum: opt.simple_sk_checksum = 1; break;
case oNoEncryptTo: opt.no_encrypt_to = 1; break;
case oEncryptTo: /* store the recipient in the second list */
sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
sl->flags = 1;
break;
case oHiddenEncryptTo: /* store the recipient in the second list */
sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
sl->flags = 1|2;
break;
case oRecipient: /* store the recipient */
add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
any_explicit_recipient = 1;
break;
case oHiddenRecipient: /* store the recipient with a flag */
sl = add_to_strlist2( &remusr, pargs.r.ret_str, utf8_strings );
sl->flags = 2;
any_explicit_recipient = 1;
break;
case oTextmodeShort: opt.textmode = 2; break;
case oTextmode: opt.textmode=1; break;
case oNoTextmode: opt.textmode=0; break;
case oExpert: opt.expert = 1; break;
case oNoExpert: opt.expert = 0; break;
case oDefSigExpire:
if(*pargs.r.ret_str!='\0')
{
if(parse_expire_string(0,pargs.r.ret_str)==(u32)-1)
log_error(_("`%s' is not a valid signature expiration\n"),
pargs.r.ret_str);
else
opt.def_sig_expire=pargs.r.ret_str;
}
break;
case oAskSigExpire: opt.ask_sig_expire = 1; break;
case oNoAskSigExpire: opt.ask_sig_expire = 0; break;
case oDefCertExpire:
if(*pargs.r.ret_str!='\0')
{
if(parse_expire_string(0,pargs.r.ret_str)==(u32)-1)
log_error(_("`%s' is not a valid signature expiration\n"),
pargs.r.ret_str);
else
opt.def_cert_expire=pargs.r.ret_str;
}
break;
case oAskCertExpire: opt.ask_cert_expire = 1; break;
case oNoAskCertExpire: opt.ask_cert_expire = 0; break;
case oDefCertLevel: opt.def_cert_level=pargs.r.ret_int; break;
case oMinCertLevel: opt.min_cert_level=pargs.r.ret_int; break;
case oAskCertLevel: opt.ask_cert_level = 1; break;
case oNoAskCertLevel: opt.ask_cert_level = 0; break;
case oLocalUser: /* store the local users */
add_to_strlist2( &locusr, pargs.r.ret_str, utf8_strings );
break;
case oCompress:
/* this is the -z command line option */
opt.compress_level = opt.bz2_compress_level = pargs.r.ret_int;
break;
case oCompressLevel: opt.compress_level = pargs.r.ret_int; break;
case oBZ2CompressLevel: opt.bz2_compress_level = pargs.r.ret_int; break;
case oBZ2DecompressLowmem: opt.bz2_decompress_lowmem=1; break;
case oPasswd:
set_passphrase_from_string(pargs.r.ret_str);
break;
case oPasswdFD:
pwfd = iobuf_translate_file_handle (pargs.r.ret_int, 0);
opt.use_agent = 0;
break;
case oPasswdFile:
pwfd = open_info_file (pargs.r.ret_str, 0);
break;
case oPasswdRepeat: opt.passwd_repeat=pargs.r.ret_int; break;
case oCommandFD:
opt.command_fd = iobuf_translate_file_handle (pargs.r.ret_int, 0);
break;
case oCommandFile:
opt.command_fd = open_info_file (pargs.r.ret_str, 0);
break;
- case oCipherAlgo:
+ case oCipherAlgo:
def_cipher_string = xstrdup(pargs.r.ret_str);
break;
case oDigestAlgo:
def_digest_string = xstrdup(pargs.r.ret_str);
break;
case oCompressAlgo:
/* If it is all digits, stick a Z in front of it for
later. This is for backwards compatibility with
versions that took the compress algorithm number. */
{
char *pt=pargs.r.ret_str;
while(*pt)
{
if (!isascii (*pt) || !isdigit (*pt))
break;
pt++;
}
if(*pt=='\0')
{
compress_algo_string=xmalloc(strlen(pargs.r.ret_str)+2);
strcpy(compress_algo_string,"Z");
strcat(compress_algo_string,pargs.r.ret_str);
}
else
compress_algo_string = xstrdup(pargs.r.ret_str);
}
break;
case oCertDigestAlgo: cert_digest_string = xstrdup(pargs.r.ret_str); break;
case oNoSecmemWarn: secmem_set_flags( secmem_get_flags() | 1 ); break;
case oRequireSecmem: require_secmem=1; break;
case oNoRequireSecmem: require_secmem=0; break;
case oNoPermissionWarn: opt.no_perm_warn=1; break;
case oNoMDCWarn: opt.no_mdc_warn=1; break;
case oDisplayCharset:
if( set_native_charset( pargs.r.ret_str ) )
log_error(_("`%s' is not a valid character set\n"),
pargs.r.ret_str);
break;
case oNotDashEscaped: opt.not_dash_escaped = 1; break;
case oEscapeFrom: opt.escape_from = 1; break;
case oNoEscapeFrom: opt.escape_from = 0; break;
case oLockOnce: opt.lock_once = 1; break;
case oLockNever:
disable_dotlock ();
random_disable_locking ();
break;
case oLockMultiple:
#ifndef __riscos__
opt.lock_once = 0;
#else /* __riscos__ */
riscos_not_implemented("lock-multiple");
#endif /* __riscos__ */
break;
case oKeyServer:
{
struct keyserver_spec *keyserver;
keyserver=parse_keyserver_uri(pargs.r.ret_str,0,
configname,configlineno);
if(!keyserver)
log_error(_("could not parse keyserver URL\n"));
else
{
keyserver->next=opt.keyserver;
opt.keyserver=keyserver;
}
}
break;
case oKeyServerOptions:
if(!parse_keyserver_options(pargs.r.ret_str))
{
if(configname)
log_error(_("%s:%d: invalid keyserver options\n"),
configname,configlineno);
else
log_error(_("invalid keyserver options\n"));
}
break;
case oImportOptions:
if(!parse_import_options(pargs.r.ret_str,&opt.import_options,1))
{
if(configname)
log_error(_("%s:%d: invalid import options\n"),
configname,configlineno);
else
log_error(_("invalid import options\n"));
}
break;
case oExportOptions:
if(!parse_export_options(pargs.r.ret_str,&opt.export_options,1))
{
if(configname)
log_error(_("%s:%d: invalid export options\n"),
configname,configlineno);
else
log_error(_("invalid export options\n"));
}
break;
case oListOptions:
if(!parse_list_options(pargs.r.ret_str))
{
if(configname)
log_error(_("%s:%d: invalid list options\n"),
configname,configlineno);
else
log_error(_("invalid list options\n"));
}
break;
case oVerifyOptions:
{
struct parse_options vopts[]=
{
{"show-photos",VERIFY_SHOW_PHOTOS,NULL,
N_("display photo IDs during signature verification")},
{"show-policy-urls",VERIFY_SHOW_POLICY_URLS,NULL,
N_("show policy URLs during signature verification")},
{"show-notations",VERIFY_SHOW_NOTATIONS,NULL,
N_("show all notations during signature verification")},
{"show-std-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
N_("show IETF standard notations during signature verification")},
{"show-standard-notations",VERIFY_SHOW_STD_NOTATIONS,NULL,
NULL},
{"show-user-notations",VERIFY_SHOW_USER_NOTATIONS,NULL,
N_("show user-supplied notations during signature verification")},
{"show-keyserver-urls",VERIFY_SHOW_KEYSERVER_URLS,NULL,
N_("show preferred keyserver URLs during signature verification")},
{"show-uid-validity",VERIFY_SHOW_UID_VALIDITY,NULL,
N_("show user ID validity during signature verification")},
{"show-unusable-uids",VERIFY_SHOW_UNUSABLE_UIDS,NULL,
N_("show revoked and expired user IDs in signature verification")},
{"show-primary-uid-only",VERIFY_SHOW_PRIMARY_UID_ONLY,NULL,
N_("show only the primary user ID in signature verification")},
{"pka-lookups",VERIFY_PKA_LOOKUPS,NULL,
N_("validate signatures with PKA data")},
{"pka-trust-increase",VERIFY_PKA_TRUST_INCREASE,NULL,
N_("elevate the trust of signatures with valid PKA data")},
{NULL,0,NULL,NULL}
};
if(!parse_options(pargs.r.ret_str,&opt.verify_options,vopts,1))
{
if(configname)
log_error(_("%s:%d: invalid verify options\n"),
configname,configlineno);
else
log_error(_("invalid verify options\n"));
}
}
break;
case oTempDir: opt.temp_dir=pargs.r.ret_str; break;
case oExecPath:
if(set_exec_path(pargs.r.ret_str))
log_error(_("unable to set exec-path to %s\n"),pargs.r.ret_str);
else
opt.exec_path_set=1;
break;
case oSetNotation:
add_notation_data( pargs.r.ret_str, 0 );
add_notation_data( pargs.r.ret_str, 1 );
break;
case oSigNotation: add_notation_data( pargs.r.ret_str, 0 ); break;
case oCertNotation: add_notation_data( pargs.r.ret_str, 1 ); break;
case oShowNotation:
deprecated_warning(configname,configlineno,"--show-notation",
"--list-options ","show-notations");
deprecated_warning(configname,configlineno,"--show-notation",
"--verify-options ","show-notations");
opt.list_options|=LIST_SHOW_NOTATIONS;
opt.verify_options|=VERIFY_SHOW_NOTATIONS;
break;
case oNoShowNotation:
deprecated_warning(configname,configlineno,"--no-show-notation",
"--list-options ","no-show-notations");
deprecated_warning(configname,configlineno,"--no-show-notation",
"--verify-options ","no-show-notations");
opt.list_options&=~LIST_SHOW_NOTATIONS;
opt.verify_options&=~VERIFY_SHOW_NOTATIONS;
break;
case oUtf8Strings: utf8_strings = 1; break;
case oNoUtf8Strings: utf8_strings = 0; break;
case oDisableCipherAlgo:
disable_cipher_algo( string_to_cipher_algo(pargs.r.ret_str) );
break;
case oDisablePubkeyAlgo:
disable_pubkey_algo( string_to_pubkey_algo(pargs.r.ret_str) );
break;
case oNoSigCache: opt.no_sig_cache = 1; break;
case oNoSigCreateCheck: opt.no_sig_create_check = 1; break;
case oAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid = 1; break;
case oNoAllowNonSelfsignedUID: opt.allow_non_selfsigned_uid=0; break;
case oAllowFreeformUID: opt.allow_freeform_uid = 1; break;
case oNoAllowFreeformUID: opt.allow_freeform_uid = 0; break;
case oNoLiteral: opt.no_literal = 1; break;
case oSetFilesize: opt.set_filesize = pargs.r.ret_ulong; break;
case oHonorHttpProxy:
add_to_strlist(&opt.keyserver_options.other,"http-proxy");
deprecated_warning(configname,configlineno,
"--honor-http-proxy",
"--keyserver-options ","http-proxy");
break;
case oFastListMode: opt.fast_list_mode = 1; break;
case oFixedListMode: opt.fixed_list_mode = 1; break;
case oListOnly: opt.list_only=1; break;
case oIgnoreTimeConflict: opt.ignore_time_conflict = 1; break;
case oIgnoreValidFrom: opt.ignore_valid_from = 1; break;
case oIgnoreCrcError: opt.ignore_crc_error = 1; break;
case oIgnoreMDCError: opt.ignore_mdc_error = 1; break;
case oNoRandomSeedFile: use_random_seed = 0; break;
case oAutoKeyRetrieve:
case oNoAutoKeyRetrieve:
if(pargs.r_opt==oAutoKeyRetrieve)
opt.keyserver_options.options|=KEYSERVER_AUTO_KEY_RETRIEVE;
else
opt.keyserver_options.options&=~KEYSERVER_AUTO_KEY_RETRIEVE;
deprecated_warning(configname,configlineno,
pargs.r_opt==oAutoKeyRetrieve?"--auto-key-retrieve":
"--no-auto-key-retrieve","--keyserver-options ",
pargs.r_opt==oAutoKeyRetrieve?"auto-key-retrieve":
"no-auto-key-retrieve");
break;
case oShowSessionKey: opt.show_session_key = 1; break;
case oOverrideSessionKey:
opt.override_session_key = pargs.r.ret_str;
break;
case oMergeOnly:
deprecated_warning(configname,configlineno,"--merge-only",
"--import-options ","merge-only");
opt.import_options|=IMPORT_MERGE_ONLY;
break;
case oAllowSecretKeyImport: /* obsolete */ break;
case oTryAllSecrets: opt.try_all_secrets = 1; break;
case oTrustedKey: register_trusted_key( pargs.r.ret_str ); break;
case oEnableSpecialFilenames:
iobuf_enable_special_filenames (1);
break;
case oNoExpensiveTrustChecks: opt.no_expensive_trust_checks=1; break;
case oAutoCheckTrustDB: opt.no_auto_check_trustdb=0; break;
case oNoAutoCheckTrustDB: opt.no_auto_check_trustdb=1; break;
case oPreservePermissions: opt.preserve_permissions=1; break;
case oDefaultPreferenceList:
opt.def_preference_list = pargs.r.ret_str;
break;
case oDefaultKeyserverURL:
{
struct keyserver_spec *keyserver;
keyserver=parse_keyserver_uri(pargs.r.ret_str,1,
configname,configlineno);
if(!keyserver)
log_error(_("could not parse keyserver URL\n"));
else
free_keyserver_spec(keyserver);
opt.def_keyserver_url = pargs.r.ret_str;
}
break;
case oPersonalCipherPreferences:
pers_cipher_list=pargs.r.ret_str;
break;
case oPersonalDigestPreferences:
pers_digest_list=pargs.r.ret_str;
break;
case oPersonalCompressPreferences:
pers_compress_list=pargs.r.ret_str;
break;
case oDisplay: opt.display = pargs.r.ret_str; break;
case oTTYname: opt.ttyname = pargs.r.ret_str; break;
case oTTYtype: opt.ttytype = pargs.r.ret_str; break;
case oLCctype: opt.lc_ctype = pargs.r.ret_str; break;
case oLCmessages: opt.lc_messages = pargs.r.ret_str; break;
case oGroup: add_group(pargs.r.ret_str); break;
case oUnGroup: rm_group(pargs.r.ret_str); break;
case oNoGroups:
while(opt.grouplist)
{
struct groupitem *iter=opt.grouplist;
free_strlist(iter->values);
opt.grouplist=opt.grouplist->next;
xfree(iter);
}
break;
case oStrict: opt.strict=1; log_set_strict(1); break;
case oNoStrict: opt.strict=0; log_set_strict(0); break;
case oMangleDosFilenames: opt.mangle_dos_filenames = 1; break;
case oNoMangleDosFilenames: opt.mangle_dos_filenames = 0; break;
case oEnableProgressFilter: opt.enable_progress_filter = 1; break;
case oMultifile: multifile=1; break;
case oKeyidFormat:
if(ascii_strcasecmp(pargs.r.ret_str,"short")==0)
opt.keyid_format=KF_SHORT;
else if(ascii_strcasecmp(pargs.r.ret_str,"long")==0)
opt.keyid_format=KF_LONG;
else if(ascii_strcasecmp(pargs.r.ret_str,"0xshort")==0)
opt.keyid_format=KF_0xSHORT;
else if(ascii_strcasecmp(pargs.r.ret_str,"0xlong")==0)
opt.keyid_format=KF_0xLONG;
else
log_error("unknown keyid-format `%s'\n",pargs.r.ret_str);
break;
case oExitOnStatusWriteError:
opt.exit_on_status_write_error = 1;
break;
- case oLimitCardInsertTries:
- opt.limit_card_insert_tries = pargs.r.ret_int;
+ case oLimitCardInsertTries:
+ opt.limit_card_insert_tries = pargs.r.ret_int;
break;
case oRequireCrossCert: opt.flags.require_cross_cert=1; break;
case oNoRequireCrossCert: opt.flags.require_cross_cert=0; break;
case oAutoKeyLocate:
if(!parse_auto_key_locate(pargs.r.ret_str))
{
if(configname)
log_error(_("%s:%d: invalid auto-key-locate list\n"),
configname,configlineno);
else
log_error(_("invalid auto-key-locate list\n"));
}
break;
case oNoAutoKeyLocate:
release_akl();
break;
case oEnableDSA2: opt.flags.dsa2=1; break;
case oDisableDSA2: opt.flags.dsa2=0; break;
case oAllowMultisigVerification:
case oAllowMultipleMessages:
opt.flags.allow_multiple_messages=1;
break;
case oNoAllowMultipleMessages:
opt.flags.allow_multiple_messages=0;
break;
case oNoop: break;
default : pargs.err = configfp? 1:2; break;
}
}
if( configfp ) {
fclose( configfp );
configfp = NULL;
/* Remember the first config file name. */
if (!save_configname)
save_configname = configname;
else
xfree(configname);
configname = NULL;
goto next_pass;
}
xfree( configname ); configname = NULL;
if( log_get_errorcount(0) )
g10_exit(2);
/* The command --gpgconf-list is pretty simple and may be called
directly after the option parsing. */
if (cmd == aGPGConfList)
{
gpgconf_list (save_configname ? save_configname : default_configname);
g10_exit (0);
}
xfree (save_configname);
xfree (default_configname);
if( nogreeting )
greeting = 0;
if( greeting ) {
fprintf(stderr, "%s %s; %s\n",
strusage(11), strusage(13), strusage(14) );
fprintf(stderr, "%s\n", strusage(15) );
}
#ifdef IS_DEVELOPMENT_VERSION
if( !opt.batch )
{
const char *s;
if((s=strusage(20)))
log_info("%s\n",s);
if((s=strusage(21)))
log_info("%s\n",s);
if((s=strusage(22)))
log_info("%s\n",s);
}
#endif
if (opt.verbose > 2)
log_info ("using character set `%s'\n", get_native_charset ());
if( may_coredump && !opt.quiet )
log_info(_("WARNING: program may create a core file!\n"));
if (eyes_only) {
if (opt.set_filename)
log_info(_("WARNING: %s overrides %s\n"),
"--for-your-eyes-only","--set-filename");
opt.set_filename="_CONSOLE";
}
if (opt.no_literal) {
log_info(_("NOTE: %s is not for normal use!\n"), "--no-literal");
if (opt.textmode)
log_error(_("%s not allowed with %s!\n"),
"--textmode", "--no-literal" );
if (opt.set_filename)
log_error(_("%s makes no sense with %s!\n"),
eyes_only?"--for-your-eyes-only":"--set-filename",
"--no-literal" );
}
-#ifndef ENABLE_AGENT_SUPPORT
+#ifndef ENABLE_AGENT_SUPPORT
if (opt.use_agent) {
log_info(_("NOTE: %s is not available in this version\n"),
"--use-agent");
opt.use_agent = 0;
}
#endif /*!ENABLE_AGENT_SUPPORT*/
if (opt.set_filesize)
log_info(_("NOTE: %s is not for normal use!\n"), "--set-filesize");
if( opt.batch )
tty_batchmode( 1 );
secmem_set_flags( secmem_get_flags() & ~2 ); /* resume warnings */
if(require_secmem && !got_secmem)
{
log_info(_("will not run with insecure memory due to %s\n"),
"--require-secmem");
g10_exit(2);
}
set_debug();
/* Do these after the switch(), so they can override settings. */
if(PGP2)
{
int unusable=0;
if(cmd==aSign && !detached_sig)
{
log_info(_("you can only make detached or clear signatures "
"while in --pgp2 mode\n"));
unusable=1;
}
else if(cmd==aSignEncr || cmd==aSignSym)
{
log_info(_("you can't sign and encrypt at the "
"same time while in --pgp2 mode\n"));
unusable=1;
}
else if(argc==0 && (cmd==aSign || cmd==aEncr || cmd==aSym))
{
log_info(_("you must use files (and not a pipe) when "
"working with --pgp2 enabled.\n"));
unusable=1;
}
else if(cmd==aEncr || cmd==aSym)
{
/* Everything else should work without IDEA (except using
a secret key encrypted with IDEA and setting an IDEA
preference, but those have their own error
messages). */
if(check_cipher_algo(CIPHER_ALGO_IDEA))
{
log_info(_("encrypting a message in --pgp2 mode requires "
"the IDEA cipher\n"));
idea_cipher_warn(1);
unusable=1;
}
else if(cmd==aSym)
{
/* This only sets IDEA for symmetric encryption
since it is set via select_algo_from_prefs for
pk encryption. */
xfree(def_cipher_string);
def_cipher_string = xstrdup("idea");
}
/* PGP2 can't handle the output from the textmode
filter, so we disable it for anything that could
create a literal packet (only encryption and
symmetric encryption, since we disable signing
above). */
if(!unusable)
opt.textmode=0;
}
if(unusable)
compliance_failure();
else
{
opt.force_v4_certs = 0;
opt.escape_from = 1;
opt.force_v3_sigs = 1;
opt.pgp2_workarounds = 1;
opt.ask_sig_expire = 0;
opt.ask_cert_expire = 0;
xfree(def_digest_string);
def_digest_string = xstrdup("md5");
xfree(s2k_digest_string);
s2k_digest_string = xstrdup("md5");
opt.compress_algo = COMPRESS_ALGO_ZIP;
}
}
else if(PGP6)
{
opt.disable_mdc=1;
opt.escape_from=1;
opt.force_v3_sigs=1;
opt.ask_sig_expire=0;
}
else if(PGP7)
{
opt.escape_from=1;
opt.force_v3_sigs=1;
opt.ask_sig_expire=0;
}
else if(PGP8)
{
opt.escape_from=1;
}
/* must do this after dropping setuid, because string_to...
* may try to load an module */
if( def_cipher_string ) {
opt.def_cipher_algo = string_to_cipher_algo(def_cipher_string);
if(opt.def_cipher_algo==0 &&
(ascii_strcasecmp(def_cipher_string,"idea")==0
|| ascii_strcasecmp(def_cipher_string,"s1")==0))
- idea_cipher_warn(1);
+ {
+ idea_cipher_warn(1);
+ }
xfree(def_cipher_string); def_cipher_string = NULL;
if( check_cipher_algo(opt.def_cipher_algo) )
log_error(_("selected cipher algorithm is invalid\n"));
}
if( def_digest_string ) {
opt.def_digest_algo = string_to_digest_algo(def_digest_string);
xfree(def_digest_string); def_digest_string = NULL;
if( check_digest_algo(opt.def_digest_algo) )
log_error(_("selected digest algorithm is invalid\n"));
}
if( compress_algo_string ) {
opt.compress_algo = string_to_compress_algo(compress_algo_string);
xfree(compress_algo_string); compress_algo_string = NULL;
if( check_compress_algo(opt.compress_algo) )
log_error(_("selected compression algorithm is invalid\n"));
}
if( cert_digest_string ) {
opt.cert_digest_algo = string_to_digest_algo(cert_digest_string);
xfree(cert_digest_string); cert_digest_string = NULL;
if( check_digest_algo(opt.cert_digest_algo) )
log_error(_("selected certification digest algorithm is invalid\n"));
}
if( s2k_cipher_string ) {
opt.s2k_cipher_algo = string_to_cipher_algo(s2k_cipher_string);
xfree(s2k_cipher_string); s2k_cipher_string = NULL;
if( check_cipher_algo(opt.s2k_cipher_algo) )
log_error(_("selected cipher algorithm is invalid\n"));
}
if( s2k_digest_string ) {
opt.s2k_digest_algo = string_to_digest_algo(s2k_digest_string);
xfree(s2k_digest_string); s2k_digest_string = NULL;
if( check_digest_algo(opt.s2k_digest_algo) )
log_error(_("selected digest algorithm is invalid\n"));
}
if( opt.completes_needed < 1 )
log_error(_("completes-needed must be greater than 0\n"));
if( opt.marginals_needed < 2 )
log_error(_("marginals-needed must be greater than 1\n"));
if( opt.max_cert_depth < 1 || opt.max_cert_depth > 255 )
log_error(_("max-cert-depth must be in the range from 1 to 255\n"));
if(opt.def_cert_level<0 || opt.def_cert_level>3)
log_error(_("invalid default-cert-level; must be 0, 1, 2, or 3\n"));
if( opt.min_cert_level < 1 || opt.min_cert_level > 3 )
log_error(_("invalid min-cert-level; must be 1, 2, or 3\n"));
switch( opt.s2k_mode ) {
case 0:
log_info(_("NOTE: simple S2K mode (0) is strongly discouraged\n"));
break;
case 1: case 3: break;
default:
log_error(_("invalid S2K mode; must be 0, 1 or 3\n"));
}
/* This isn't actually needed, but does serve to error out if the
string is invalid. */
if(opt.def_preference_list &&
keygen_set_std_prefs(opt.def_preference_list,0))
log_error(_("invalid default preferences\n"));
if(pers_cipher_list &&
keygen_set_std_prefs(pers_cipher_list,PREFTYPE_SYM))
log_error(_("invalid personal cipher preferences\n"));
if(pers_digest_list &&
keygen_set_std_prefs(pers_digest_list,PREFTYPE_HASH))
log_error(_("invalid personal digest preferences\n"));
if(pers_compress_list &&
keygen_set_std_prefs(pers_compress_list,PREFTYPE_ZIP))
log_error(_("invalid personal compress preferences\n"));
/* We don't support all possible commands with multifile yet */
if(multifile)
{
char *cmdname;
switch(cmd)
{
case aSign:
cmdname="--sign";
break;
case aClearsign:
cmdname="--clearsign";
break;
case aDetachedSign:
cmdname="--detach-sign";
break;
case aSym:
cmdname="--symmetric";
break;
case aEncrSym:
cmdname="--symmetric --encrypt";
break;
case aStore:
cmdname="--store";
break;
default:
cmdname=NULL;
break;
}
if(cmdname)
log_error(_("%s does not yet work with %s\n"),cmdname,"--multifile");
}
if( log_get_errorcount(0) )
g10_exit(2);
if(opt.compress_level==0)
opt.compress_algo=COMPRESS_ALGO_NONE;
/* Check our chosen algorithms against the list of legal
algorithms. */
if(!GNUPG)
{
const char *badalg=NULL;
preftype_t badtype=PREFTYPE_NONE;
if(opt.def_cipher_algo
&& !algo_available(PREFTYPE_SYM,opt.def_cipher_algo,NULL))
{
badalg=cipher_algo_to_string(opt.def_cipher_algo);
badtype=PREFTYPE_SYM;
}
else if(opt.def_digest_algo
&& !algo_available(PREFTYPE_HASH,opt.def_digest_algo,NULL))
{
badalg=digest_algo_to_string(opt.def_digest_algo);
badtype=PREFTYPE_HASH;
}
else if(opt.cert_digest_algo
&& !algo_available(PREFTYPE_HASH,opt.cert_digest_algo,NULL))
{
badalg=digest_algo_to_string(opt.cert_digest_algo);
badtype=PREFTYPE_HASH;
}
else if(opt.compress_algo!=-1
&& !algo_available(PREFTYPE_ZIP,opt.compress_algo,NULL))
{
badalg=compress_algo_to_string(opt.compress_algo);
badtype=PREFTYPE_ZIP;
}
if(badalg)
{
switch(badtype)
{
case PREFTYPE_SYM:
log_info(_("you may not use cipher algorithm `%s'"
" while in %s mode\n"),
badalg,compliance_option_string());
break;
case PREFTYPE_HASH:
log_info(_("you may not use digest algorithm `%s'"
" while in %s mode\n"),
badalg,compliance_option_string());
break;
case PREFTYPE_ZIP:
log_info(_("you may not use compression algorithm `%s'"
" while in %s mode\n"),
badalg,compliance_option_string());
break;
default:
BUG();
}
compliance_failure();
}
}
/* set the random seed file */
if( use_random_seed ) {
char *p = make_filename(opt.homedir, "random_seed", NULL );
set_random_seed_file(p);
if (!access (p, F_OK))
register_secured_file (p);
xfree(p);
}
/* If there is no command but the --fingerprint is given, default
to the --list-keys command. */
if (!cmd && fpr_maybe_cmd)
{
set_cmd (&cmd, aListKeys);
}
if( cmd == aKMode || cmd == aKModeC ) { /* kludge to be compatible to pgp */
if( cmd == aKModeC ) {
opt.fingerprint = 1;
cmd = aKMode;
}
opt.list_sigs = 0;
if( opt.verbose > 2 )
opt.check_sigs++;
if( opt.verbose > 1 )
opt.list_sigs++;
opt.verbose = opt.verbose > 1;
g10_opt_verbose = opt.verbose;
}
/* kludge to let -sat generate a clear text signature */
if( opt.textmode == 2 && !detached_sig && opt.armor && cmd == aSign )
cmd = aClearsign;
if( opt.verbose > 1 )
set_packet_list_mode(1);
if (cmd == aGPGConfTest)
g10_exit(0);
/* Add the keyrings, but not for some special commands and not in
case of "-kvv userid keyring". Also avoid adding the secret
keyring for a couple of commands to avoid unneeded access in
case the secrings are stored on a floppy.
-
+
We always need to add the keyrings if we are running under
SELinux, this is so that the rings are added to the list of
secured files. */
- if( ALWAYS_ADD_KEYRINGS
+ if( ALWAYS_ADD_KEYRINGS
|| (cmd != aDeArmor && cmd != aEnArmor
- && !(cmd == aKMode && argc == 2 )) )
+ && !(cmd == aKMode && argc == 2 )) )
{
if (ALWAYS_ADD_KEYRINGS
|| (cmd != aCheckKeys && cmd != aListSigs && cmd != aListKeys
&& cmd != aVerify && cmd != aSym))
{
if (!sec_nrings || default_keyring) /* add default secret rings */
keydb_add_resource ("secring" EXTSEP_S "gpg", 4, 1);
for (sl = sec_nrings; sl; sl = sl->next)
keydb_add_resource ( sl->d, 0, 1 );
}
if( !nrings || default_keyring ) /* add default ring */
keydb_add_resource ("pubring" EXTSEP_S "gpg", 4, 0);
for(sl = nrings; sl; sl = sl->next )
keydb_add_resource ( sl->d, sl->flags, 0 );
}
FREE_STRLIST(nrings);
FREE_STRLIST(sec_nrings);
if( pwfd != -1 ) /* read the passphrase now. */
read_passphrase_from_fd( pwfd );
fname = argc? *argv : NULL;
if(fname && utf8_strings)
opt.flags.utf8_filename=1;
switch( cmd ) {
case aPrimegen:
case aPrintMD:
case aPrintMDs:
case aGenRandom:
case aDeArmor:
case aEnArmor:
break;
case aFixTrustDB:
case aExportOwnerTrust: rc = setup_trustdb( 0, trustdb_name ); break;
case aListTrustDB: rc = setup_trustdb( argc? 1:0, trustdb_name ); break;
default: rc = setup_trustdb(1, trustdb_name ); break;
}
if( rc )
log_error(_("failed to initialize the TrustDB: %s\n"), g10_errstr(rc));
switch (cmd)
{
- case aStore:
- case aSym:
- case aSign:
- case aSignSym:
- case aClearsign:
+ case aStore:
+ case aSym:
+ case aSign:
+ case aSignSym:
+ case aClearsign:
if (!opt.quiet && any_explicit_recipient)
log_info (_("WARNING: recipients (-r) given "
"without using public key encryption\n"));
break;
default:
break;
}
switch( cmd )
{
case aStore: /* only store the file */
if( argc > 1 )
wrong_args(_("--store [filename]"));
if( (rc = encode_store(fname)) )
log_error ("storing `%s' failed: %s\n",
print_fname_stdin(fname),g10_errstr(rc) );
break;
case aSym: /* encrypt the given file only with the symmetric cipher */
if( argc > 1 )
wrong_args(_("--symmetric [filename]"));
if( (rc = encode_symmetric(fname)) )
log_error (_("symmetric encryption of `%s' failed: %s\n"),
print_fname_stdin(fname),g10_errstr(rc) );
break;
case aEncr: /* encrypt the given file */
if(multifile)
encode_crypt_files(argc, argv, remusr);
else
{
if( argc > 1 )
wrong_args(_("--encrypt [filename]"));
if( (rc = encode_crypt(fname,remusr,0)) )
log_error("%s: encryption failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
}
break;
case aEncrSym:
/* This works with PGP 8 in the sense that it acts just like a
symmetric message. It doesn't work at all with 2 or 6. It
might work with 7, but alas, I don't have a copy to test
with right now. */
if( argc > 1 )
wrong_args(_("--symmetric --encrypt [filename]"));
else if(opt.s2k_mode==0)
log_error(_("you cannot use --symmetric --encrypt"
" with --s2k-mode 0\n"));
else if(PGP2 || PGP6 || PGP7 || RFC1991)
log_error(_("you cannot use --symmetric --encrypt"
" while in %s mode\n"),compliance_option_string());
else
{
if( (rc = encode_crypt(fname,remusr,1)) )
log_error("%s: encryption failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
}
break;
case aSign: /* sign the given file */
sl = NULL;
if( detached_sig ) { /* sign all files */
for( ; argc; argc--, argv++ )
add_to_strlist( &sl, *argv );
}
else {
if( argc > 1 )
wrong_args(_("--sign [filename]"));
if( argc ) {
sl = xmalloc_clear( sizeof *sl + strlen(fname));
strcpy(sl->d, fname);
}
}
if( (rc = sign_file( sl, detached_sig, locusr, 0, NULL, NULL)) )
log_error("signing failed: %s\n", g10_errstr(rc) );
free_strlist(sl);
break;
case aSignEncr: /* sign and encrypt the given file */
if( argc > 1 )
wrong_args(_("--sign --encrypt [filename]"));
if( argc ) {
sl = xmalloc_clear( sizeof *sl + strlen(fname));
strcpy(sl->d, fname);
}
else
sl = NULL;
if( (rc = sign_file(sl, detached_sig, locusr, 1, remusr, NULL)) )
log_error("%s: sign+encrypt failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
free_strlist(sl);
break;
case aSignEncrSym: /* sign and encrypt the given file */
if( argc > 1 )
wrong_args(_("--symmetric --sign --encrypt [filename]"));
else if(opt.s2k_mode==0)
log_error(_("you cannot use --symmetric --sign --encrypt"
" with --s2k-mode 0\n"));
else if(PGP2 || PGP6 || PGP7 || RFC1991)
log_error(_("you cannot use --symmetric --sign --encrypt"
" while in %s mode\n"),compliance_option_string());
else
{
if( argc )
{
sl = xmalloc_clear( sizeof *sl + strlen(fname));
strcpy(sl->d, fname);
}
else
sl = NULL;
if( (rc = sign_file(sl, detached_sig, locusr, 2, remusr, NULL)) )
log_error("%s: symmetric+sign+encrypt failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
free_strlist(sl);
}
break;
case aSignSym: /* sign and conventionally encrypt the given file */
if (argc > 1)
wrong_args(_("--sign --symmetric [filename]"));
rc = sign_symencrypt_file (fname, locusr);
if (rc)
log_error("%s: sign+symmetric failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
break;
case aClearsign: /* make a clearsig */
if( argc > 1 )
wrong_args(_("--clearsign [filename]"));
if( (rc = clearsign_file(fname, locusr, NULL)) )
log_error("%s: clearsign failed: %s\n",
print_fname_stdin(fname), g10_errstr(rc) );
break;
case aVerify:
if(multifile)
{
if( (rc = verify_files( argc, argv ) ))
log_error("verify files failed: %s\n", g10_errstr(rc) );
}
else
{
if( (rc = verify_signatures( argc, argv ) ))
log_error("verify signatures failed: %s\n", g10_errstr(rc) );
}
break;
case aDecrypt:
if(multifile)
decrypt_messages(argc, argv);
else
{
if( argc > 1 )
wrong_args(_("--decrypt [filename]"));
if( (rc = decrypt_message( fname ) ))
log_error("decrypt_message failed: %s\n", g10_errstr(rc) );
}
break;
-
+
case aSignKey:
if( argc != 1 )
wrong_args(_("--sign-key user-id"));
/* fall through */
case aLSignKey:
if( argc != 1 )
wrong_args(_("--lsign-key user-id"));
/* fall through */
sl=NULL;
if(cmd==aSignKey)
append_to_strlist(&sl,"sign");
else if(cmd==aLSignKey)
append_to_strlist(&sl,"lsign");
else
BUG();
append_to_strlist( &sl, "save" );
username = make_username( fname );
keyedit_menu(username, locusr, sl, 0, 0 );
xfree(username);
free_strlist(sl);
break;
case aEditKey: /* Edit a key signature */
if( !argc )
wrong_args(_("--edit-key user-id [commands]"));
username = make_username( fname );
if( argc > 1 ) {
sl = NULL;
for( argc--, argv++ ; argc; argc--, argv++ )
append_to_strlist( &sl, *argv );
keyedit_menu( username, locusr, sl, 0, 1 );
free_strlist(sl);
}
else
keyedit_menu(username, locusr, NULL, 0, 1 );
xfree(username);
break;
case aDeleteKeys:
case aDeleteSecretKeys:
case aDeleteSecretAndPublicKeys:
sl = NULL;
/* I'm adding these in reverse order as add_to_strlist2
reverses them again, and it's easier to understand in the
proper order :) */
for( ; argc; argc-- )
add_to_strlist2( &sl, argv[argc-1], utf8_strings );
delete_keys(sl,cmd==aDeleteSecretKeys,cmd==aDeleteSecretAndPublicKeys);
free_strlist(sl);
break;
case aCheckKeys:
opt.check_sigs = 1;
case aListSigs:
opt.list_sigs = 1;
case aListKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
add_to_strlist2( &sl, *argv, utf8_strings );
public_key_list( sl );
free_strlist(sl);
break;
case aListSecretKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
add_to_strlist2( &sl, *argv, utf8_strings );
secret_key_list( sl );
free_strlist(sl);
break;
case aKMode: /* list keyring -- NOTE: This will be removed soon */
if( argc < 2 ) { /* -kv [userid] */
sl = NULL;
if (argc && **argv)
add_to_strlist2( &sl, *argv, utf8_strings );
public_key_list( sl );
free_strlist(sl);
}
else if( argc == 2 ) { /* -kv userid keyring */
if( access( argv[1], R_OK ) ) {
log_error(_("can't open `%s': %s\n"),
print_fname_stdin(argv[1]), strerror(errno));
}
else {
/* add keyring (default keyrings are not registered in this
* special case */
keydb_add_resource( argv[1], 0, 0 );
sl = NULL;
if (**argv)
add_to_strlist2( &sl, *argv, utf8_strings );
public_key_list( sl );
free_strlist(sl);
}
}
else
wrong_args(_("-k[v][v][v][c] [user-id] [keyring]") );
break;
case aKeygen: /* generate a key */
if( opt.batch ) {
if( argc > 1 )
wrong_args("--gen-key [parameterfile]");
generate_keypair( argc? *argv : NULL, NULL, NULL );
}
else {
if( argc )
wrong_args("--gen-key");
generate_keypair(NULL, NULL, NULL);
}
break;
case aFastImport:
opt.import_options |= IMPORT_FAST;
case aImport:
import_keys( argc? argv:NULL, argc, NULL, opt.import_options );
break;
/* TODO: There are a number of command that use this same
"make strlist, call function, report error, free strlist"
pattern. Join them together here and avoid all that
duplicated code. */
case aExport:
case aSendKeys:
case aRecvKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
append_to_strlist2( &sl, *argv, utf8_strings );
if( cmd == aSendKeys )
rc=keyserver_export( sl );
else if( cmd == aRecvKeys )
rc=keyserver_import( sl );
else
rc=export_pubkeys( sl, opt.export_options );
if(rc)
{
if(cmd==aSendKeys)
log_error(_("keyserver send failed: %s\n"),g10_errstr(rc));
else if(cmd==aRecvKeys)
log_error(_("keyserver receive failed: %s\n"),g10_errstr(rc));
else
log_error(_("key export failed: %s\n"),g10_errstr(rc));
}
free_strlist(sl);
break;
case aSearchKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
append_to_strlist2( &sl, *argv, utf8_strings );
rc=keyserver_search( sl );
if(rc)
log_error(_("keyserver search failed: %s\n"),g10_errstr(rc));
free_strlist(sl);
break;
case aRefreshKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
append_to_strlist2( &sl, *argv, utf8_strings );
rc=keyserver_refresh(sl);
if(rc)
log_error(_("keyserver refresh failed: %s\n"),g10_errstr(rc));
free_strlist(sl);
break;
case aFetchKeys:
sl = NULL;
for( ; argc; argc--, argv++ )
append_to_strlist2( &sl, *argv, utf8_strings );
rc=keyserver_fetch(sl);
if(rc)
log_error("key fetch failed: %s\n",g10_errstr(rc));
free_strlist(sl);
break;
case aExportSecret:
sl = NULL;
for( ; argc; argc--, argv++ )
add_to_strlist2( &sl, *argv, utf8_strings );
export_seckeys( sl );
free_strlist(sl);
break;
case aExportSecretSub:
sl = NULL;
for( ; argc; argc--, argv++ )
add_to_strlist2( &sl, *argv, utf8_strings );
export_secsubkeys( sl );
free_strlist(sl);
break;
case aGenRevoke:
if( argc != 1 )
wrong_args("--gen-revoke user-id");
username = make_username(*argv);
gen_revoke( username );
xfree( username );
break;
case aDesigRevoke:
if( argc != 1 )
wrong_args("--desig-revoke user-id");
username = make_username(*argv);
gen_desig_revoke( username, locusr );
xfree( username );
break;
case aDeArmor:
if( argc > 1 )
wrong_args("--dearmor [file]");
rc = dearmor_file( argc? *argv: NULL );
if( rc )
log_error(_("dearmoring failed: %s\n"), g10_errstr(rc));
break;
case aEnArmor:
if( argc > 1 )
wrong_args("--enarmor [file]");
rc = enarmor_file( argc? *argv: NULL );
if( rc )
log_error(_("enarmoring failed: %s\n"), g10_errstr(rc));
break;
case aPrimegen:
{ int mode = argc < 2 ? 0 : atoi(*argv);
if( mode == 1 && argc == 2 ) {
mpi_print( stdout, generate_public_prime( atoi(argv[1]) ), 1);
}
else if( mode == 2 && argc == 3 ) {
mpi_print( stdout, generate_elg_prime(
0, atoi(argv[1]),
atoi(argv[2]), NULL,NULL ), 1);
}
else if( mode == 3 && argc == 3 ) {
MPI *factors;
mpi_print( stdout, generate_elg_prime(
1, atoi(argv[1]),
atoi(argv[2]), NULL,&factors ), 1);
putchar('\n');
mpi_print( stdout, factors[0], 1 ); /* print q */
}
else if( mode == 4 && argc == 3 ) {
MPI g = mpi_alloc(1);
mpi_print( stdout, generate_elg_prime(
0, atoi(argv[1]),
atoi(argv[2]), g, NULL ), 1);
putchar('\n');
mpi_print( stdout, g, 1 );
mpi_free(g);
}
else
wrong_args("--gen-prime mode bits [qbits] ");
putchar('\n');
}
break;
case aGenRandom:
{
int level = argc ? atoi(*argv):0;
int count = argc > 1 ? atoi(argv[1]): 0;
int endless = !count;
if( argc < 1 || argc > 2 || level < 0 || level > 2 || count < 0 )
wrong_args("--gen-random 0|1|2 [count]");
while( endless || count ) {
byte *p;
/* Wee need a multiple of 3, so that in case of
armored output we get a correct string. No
linefolding is done, as it is best to levae this to
other tools */
size_t n = !endless && count < 99? count : 99;
p = get_random_bits( n*8, level, 0);
#ifdef HAVE_DOSISH_SYSTEM
setmode ( fileno(stdout), O_BINARY );
#endif
if (opt.armor) {
char *tmp = make_radix64_string (p, n);
fputs (tmp, stdout);
xfree (tmp);
if (n%3 == 1)
putchar ('=');
if (n%3)
putchar ('=');
} else {
fwrite( p, n, 1, stdout );
}
xfree(p);
if( !endless )
count -= n;
}
if (opt.armor)
putchar ('\n');
}
break;
case aPrintMD:
if( argc < 1)
wrong_args("--print-md algo [files]");
{
int all_algos = (**argv=='*' && !(*argv)[1]);
int algo = all_algos? 0 : string_to_digest_algo(*argv);
if( !algo && !all_algos )
log_error(_("invalid hash algorithm `%s'\n"), *argv );
else {
argc--; argv++;
if( !argc )
print_mds(NULL, algo);
else {
for(; argc; argc--, argv++ )
print_mds(*argv, algo);
}
}
}
break;
case aPrintMDs: /* old option */
if( !argc )
print_mds(NULL,0);
else {
for(; argc; argc--, argv++ )
print_mds(*argv,0);
}
break;
case aListTrustDB:
if( !argc )
list_trustdb(NULL);
else {
for( ; argc; argc--, argv++ )
list_trustdb( *argv );
}
break;
case aUpdateTrustDB:
if( argc )
wrong_args("--update-trustdb");
update_trustdb();
break;
case aCheckTrustDB:
/* Old versions allowed for arguments - ignore them */
check_trustdb();
break;
case aFixTrustDB:
how_to_fix_the_trustdb ();
break;
case aListTrustPath:
if( !argc )
wrong_args("--list-trust-path ");
for( ; argc; argc--, argv++ ) {
username = make_username( *argv );
list_trust_path( username );
xfree(username);
}
break;
case aExportOwnerTrust:
if( argc )
wrong_args("--export-ownertrust");
export_ownertrust();
break;
case aImportOwnerTrust:
if( argc > 1 )
wrong_args("--import-ownertrust [file]");
import_ownertrust( argc? *argv:NULL );
break;
-
+
case aPipeMode:
if ( argc )
wrong_args ("--pipemode");
run_in_pipemode ();
break;
case aRebuildKeydbCaches:
if (argc)
wrong_args ("--rebuild-keydb-caches");
keydb_rebuild_caches (1);
break;
#ifdef ENABLE_CARD_SUPPORT
case aCardStatus:
if (argc)
wrong_args ("--card-status");
card_status (stdout, NULL, 0);
break;
case aCardEdit:
if (argc) {
sl = NULL;
for (argc--, argv++ ; argc; argc--, argv++)
append_to_strlist (&sl, *argv);
card_edit (sl);
free_strlist (sl);
}
else
card_edit (NULL);
break;
case aChangePIN:
if (!argc)
change_pin (0,1);
else if (argc == 1)
change_pin (atoi (*argv),1);
else
wrong_args ("--change-pin [no]");
break;
#endif /* ENABLE_CARD_SUPPORT*/
case aListConfig:
{
char *str=collapse_args(argc,argv);
list_config(str);
xfree(str);
}
break;
case aListPackets:
opt.list_packets=2;
default:
if( argc > 1 )
wrong_args(_("[filename]"));
/* Issue some output for the unix newbie */
if( !fname && !opt.outfile && isatty( fileno(stdin) )
&& isatty( fileno(stdout) ) && isatty( fileno(stderr) ) )
log_info(_("Go ahead and type your message ...\n"));
a = iobuf_open(fname);
if (a && is_secured_file (iobuf_get_fd (a)))
{
iobuf_close (a);
a = NULL;
errno = EPERM;
}
if( !a )
log_error(_("can't open `%s'\n"), print_fname_stdin(fname));
else {
if( !opt.no_armor ) {
if( use_armor_filter( a ) ) {
memset( &afx, 0, sizeof afx);
iobuf_push_filter( a, armor_filter, &afx );
}
}
if( cmd == aListPackets ) {
set_packet_list_mode(1);
opt.list_packets=1;
}
rc = proc_packets(NULL, a );
if( rc )
log_error("processing message failed: %s\n", g10_errstr(rc) );
iobuf_close(a);
}
break;
}
/* cleanup */
FREE_STRLIST(remusr);
FREE_STRLIST(locusr);
g10_exit(0);
return 8; /*NEVER REACHED*/
}
void
g10_exit( int rc )
{
#ifdef ENABLE_CARD_SUPPORT
card_close ();
#endif
update_random_seed_file();
if( opt.debug & DBG_MEMSTAT_VALUE ) {
m_print_stats("on exit");
random_dump_stats();
}
if( opt.debug )
secmem_dump_stats();
secmem_term();
rc = rc? rc : log_get_errorcount(0)? 2 :
g10_errors_seen? 1 : 0;
exit(rc );
}
/* Pretty-print hex hashes. This assumes at least an 80-character
display, but there are a few other similar assumptions in the
display code. */
static void
print_hex( MD_HANDLE md, int algo, const char *fname )
{
int i,n,count,indent=0;
const byte *p;
if(fname)
indent=printf("%s: ",fname);
if(indent>40)
{
printf("\n");
indent=0;
}
if(algo==DIGEST_ALGO_RMD160)
indent+=printf("RMD160 = ");
else if(algo>0)
indent+=printf("%6s = ",digest_algo_to_string(algo));
else
algo=abs(algo);
count=indent;
p = md_read( md, algo );
n = md_digest_length(algo);
count+=printf("%02X",*p++);
for(i=1;i79)
{
printf("\n%*s",indent," ");
count=indent;
}
else
count+=printf(" ");
if(!(i%8))
count+=printf(" ");
}
else if (n==20)
{
if(!(i%2))
{
if(count+4>79)
{
printf("\n%*s",indent," ");
count=indent;
}
else
count+=printf(" ");
}
if(!(i%10))
count+=printf(" ");
}
else
{
if(!(i%4))
{
if(count+8>79)
{
printf("\n%*s",indent," ");
count=indent;
}
else
count+=printf(" ");
}
}
count+=printf("%02X",*p);
}
printf("\n");
}
static void
print_hashline( MD_HANDLE md, int algo, const char *fname )
{
int i, n;
const byte *p;
-
+
if ( fname ) {
for (p = fname; *p; p++ ) {
if ( *p <= 32 || *p > 127 || *p == ':' || *p == '%' )
printf("%%%02X", *p );
- else
+ else
putchar( *p );
}
}
putchar(':');
printf("%d:", algo );
p = md_read( md, algo );
n = md_digest_length(algo);
- for(i=0; i < n ; i++, p++ )
+ for(i=0; i < n ; i++, p++ )
printf("%02X", *p );
putchar(':');
putchar('\n');
}
static void
print_mds( const char *fname, int algo )
{
FILE *fp;
char buf[1024];
size_t n;
MD_HANDLE md;
if( !fname ) {
fp = stdin;
#ifdef HAVE_DOSISH_SYSTEM
setmode ( fileno(fp) , O_BINARY );
#endif
}
else {
fp = fopen( fname, "rb" );
if (fp && is_secured_file (fileno (fp)))
{
fclose (fp);
fp = NULL;
errno = EPERM;
}
}
if( !fp ) {
log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
return;
}
md = md_open( 0, 0 );
if( algo )
md_enable( md, algo );
else {
md_enable( md, DIGEST_ALGO_MD5 );
md_enable( md, DIGEST_ALGO_SHA1 );
md_enable( md, DIGEST_ALGO_RMD160 );
#ifdef USE_SHA256
md_enable( md, DIGEST_ALGO_SHA224 );
md_enable( md, DIGEST_ALGO_SHA256 );
#endif
#ifdef USE_SHA512
md_enable( md, DIGEST_ALGO_SHA384 );
md_enable( md, DIGEST_ALGO_SHA512 );
#endif
}
while( (n=fread( buf, 1, DIM(buf), fp )) )
md_write( md, buf, n );
if( ferror(fp) )
log_error("%s: %s\n", fname?fname:"[stdin]", strerror(errno) );
else {
md_final(md);
if ( opt.with_colons ) {
- if ( algo )
+ if ( algo )
print_hashline( md, algo, fname );
else {
print_hashline( md, DIGEST_ALGO_MD5, fname );
print_hashline( md, DIGEST_ALGO_SHA1, fname );
print_hashline( md, DIGEST_ALGO_RMD160, fname );
#ifdef USE_SHA256
print_hashline( md, DIGEST_ALGO_SHA224, fname );
print_hashline( md, DIGEST_ALGO_SHA256, fname );
#endif
#ifdef USE_SHA512
print_hashline( md, DIGEST_ALGO_SHA384, fname );
print_hashline( md, DIGEST_ALGO_SHA512, fname );
#endif
}
}
else {
if( algo )
print_hex(md,-algo,fname);
else {
print_hex( md, DIGEST_ALGO_MD5, fname );
print_hex( md, DIGEST_ALGO_SHA1, fname );
print_hex( md, DIGEST_ALGO_RMD160, fname );
#ifdef USE_SHA256
print_hex( md, DIGEST_ALGO_SHA224, fname );
print_hex( md, DIGEST_ALGO_SHA256, fname );
#endif
#ifdef USE_SHA512
print_hex( md, DIGEST_ALGO_SHA384, fname );
print_hex( md, DIGEST_ALGO_SHA512, fname );
#endif
}
}
}
md_close(md);
if( fp != stdin )
fclose(fp);
}
/****************
* Check the supplied name,value string and add it to the notation
* data to be used for signatures. which==0 for sig notations, and 1
* for cert notations.
*/
static void
add_notation_data( const char *string, int which )
{
struct notation *notation;
notation=string_to_notation(string,utf8_strings);
if(notation)
{
if(which)
{
notation->next=opt.cert_notations;
opt.cert_notations=notation;
}
else
{
notation->next=opt.sig_notations;
opt.sig_notations=notation;
}
}
}
static void
add_policy_url( const char *string, int which )
{
unsigned int i,critical=0;
STRLIST sl;
if(*string=='!')
{
string++;
critical=1;
}
for(i=0;iflags |= 1;
+ sl->flags |= 1;
}
static void
add_keyserver_url( const char *string, int which )
{
unsigned int i,critical=0;
STRLIST sl;
if(*string=='!')
{
string++;
critical=1;
}
for(i=0;iflags |= 1;
+ sl->flags |= 1;
}
diff --git a/g10/keydb.c b/g10/keydb.c
index a0c0e5747..5a62f18c0 100644
--- a/g10/keydb.c
+++ b/g10/keydb.c
@@ -1,810 +1,812 @@
/* keydb.c - key database dispatcher
* Copyright (C) 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include "util.h"
#include "options.h"
#include "main.h" /*try_make_homedir ()*/
#include "packet.h"
#include "keyring.h"
-#include "keydb.h"
+#include "keydb.h"
#include "i18n.h"
static int active_handles;
typedef enum {
KEYDB_RESOURCE_TYPE_NONE = 0,
KEYDB_RESOURCE_TYPE_KEYRING
} KeydbResourceType;
#define MAX_KEYDB_RESOURCES 40
struct resource_item {
KeydbResourceType type;
union {
KEYRING_HANDLE kr;
} u;
void *token;
int secret;
};
static struct resource_item all_resources[MAX_KEYDB_RESOURCES];
static int used_resources;
static void *primary_keyring=NULL;
struct keydb_handle {
int locked;
int found;
int current;
int used; /* items in active */
struct resource_item active[MAX_KEYDB_RESOURCES];
};
static int lock_all (KEYDB_HANDLE hd);
static void unlock_all (KEYDB_HANDLE hd);
/* Handle the creation of a keyring if it does not yet exist. Take
into acount that other processes might have the keyring already
locked. This lock check does not work if the directory itself is
not yet available. */
static int
maybe_create_keyring (char *filename, int force)
{
DOTLOCK lockhd = NULL;
IOBUF iobuf;
int rc;
mode_t oldmask;
char *last_slash_in_filename;
/* A quick test whether the filename already exists. */
if (!access (filename, F_OK))
return 0;
/* If we don't want to create a new file at all, there is no need to
go any further - bail out right here. */
- if (!force)
+ if (!force)
return G10ERR_OPEN_FILE;
/* First of all we try to create the home directory. Note, that we
don't do any locking here because any sane application of gpg
would create the home directory by itself and not rely on gpg's
tricky auto-creation which is anyway only done for some home
directory name patterns. */
last_slash_in_filename = strrchr (filename, DIRSEP_C);
*last_slash_in_filename = 0;
if (access(filename, F_OK))
- {
+ {
static int tried;
-
+
if (!tried)
{
tried = 1;
try_make_homedir (filename);
}
if (access (filename, F_OK))
{
rc = G10ERR_OPEN_FILE;
*last_slash_in_filename = DIRSEP_C;
goto leave;
}
}
*last_slash_in_filename = DIRSEP_C;
/* To avoid races with other instances of gpg trying to create or
update the keyring (it is removed during an update for a short
time), we do the next stuff in a locked state. */
lockhd = create_dotlock (filename);
if (!lockhd)
{
/* A reason for this to fail is that the directory is not
writable. However, this whole locking stuff does not make
sense if this is the case. An empty non-writable directory
with no keyring is not really useful at all. */
if (opt.verbose)
log_info ("can't allocate lock for `%s'\n", filename );
- if (!force)
- return G10ERR_OPEN_FILE;
+ if (!force)
+ return G10ERR_OPEN_FILE;
else
return G10ERR_GENERAL;
}
if ( make_dotlock (lockhd, -1) )
{
/* This is something bad. Probably a stale lockfile. */
log_info ("can't lock `%s'\n", filename );
rc = G10ERR_GENERAL;
goto leave;
}
/* Now the real test while we are locked. */
if (!access(filename, F_OK))
{
rc = 0; /* Okay, we may access the file now. */
goto leave;
}
/* The file does not yet exist, create it now. */
oldmask = umask (077);
if (is_secured_filename (filename))
{
iobuf = NULL;
errno = EPERM;
}
else
iobuf = iobuf_create (filename);
umask (oldmask);
- if (!iobuf)
+ if (!iobuf)
{
log_error ( _("error creating keyring `%s': %s\n"),
filename, strerror(errno));
rc = G10ERR_OPEN_FILE;
goto leave;
}
if (!opt.quiet)
log_info (_("keyring `%s' created\n"), filename);
iobuf_close (iobuf);
/* Must invalidate that ugly cache */
iobuf_ioctl (NULL, 2, 0, filename);
rc = 0;
leave:
if (lockhd)
{
release_dotlock (lockhd);
destroy_dotlock (lockhd);
}
return rc;
}
/*
* Register a resource (which currently may only be a keyring file).
* The first keyring which is added by this function is
* created if it does not exist.
* Note: this function may be called before secure memory is
* available.
* Flag 1 == force
* Flag 2 == mark resource as primary
* Flag 4 == This is a default resources
* Flag 8 == Readonly
*/
int
keydb_add_resource (const char *url, int flags, int secret)
{
static int any_secret, any_public;
const char *resname = url;
char *filename = NULL;
int force=(flags&1);
int read_only=!!(flags&8);
int rc = 0;
KeydbResourceType rt = KEYDB_RESOURCE_TYPE_NONE;
void *token;
if (read_only)
force = 0;
/* Do we have an URL?
* gnupg-ring:filename := this is a plain keyring
* filename := See what is is, but create as plain keyring.
*/
if (strlen (resname) > 11) {
if (!strncmp( resname, "gnupg-ring:", 11) ) {
rt = KEYDB_RESOURCE_TYPE_KEYRING;
resname += 11;
}
#if !defined(HAVE_DRIVE_LETTERS) && !defined(__riscos__)
else if (strchr (resname, ':')) {
log_error ("invalid key resource URL `%s'\n", url );
rc = G10ERR_GENERAL;
goto leave;
}
#endif /* !HAVE_DRIVE_LETTERS && !__riscos__ */
}
if (*resname != DIRSEP_C ) { /* do tilde expansion etc */
if (strchr(resname, DIRSEP_C) )
filename = make_filename (resname, NULL);
else
filename = make_filename (opt.homedir, resname, NULL);
}
else
filename = xstrdup (resname);
if (!force && !read_only)
force = secret? !any_secret : !any_public;
/* see whether we can determine the filetype */
if (rt == KEYDB_RESOURCE_TYPE_NONE) {
FILE *fp = fopen( filename, "rb" );
if (fp) {
u32 magic;
if (fread( &magic, 4, 1, fp) == 1 ) {
if (magic == 0x13579ace || magic == 0xce9a5713)
; /* GDBM magic - no more support */
else
rt = KEYDB_RESOURCE_TYPE_KEYRING;
}
else /* maybe empty: assume ring */
rt = KEYDB_RESOURCE_TYPE_KEYRING;
fclose( fp );
}
else /* no file yet: create ring */
rt = KEYDB_RESOURCE_TYPE_KEYRING;
}
switch (rt) {
case KEYDB_RESOURCE_TYPE_NONE:
log_error ("unknown type of key resource `%s'\n", url );
rc = G10ERR_GENERAL;
goto leave;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = maybe_create_keyring (filename, force);
if (rc)
goto leave;
if(keyring_register_filename (filename, secret, &token))
{
if (used_resources >= MAX_KEYDB_RESOURCES)
rc = G10ERR_RESOURCE_LIMIT;
- else
+ else
{
if(flags&2)
primary_keyring=token;
all_resources[used_resources].type = rt;
all_resources[used_resources].u.kr = NULL; /* Not used here */
all_resources[used_resources].token = token;
all_resources[used_resources].secret = secret;
used_resources++;
}
}
else
{
/* This keyring was already registered, so ignore it.
However, we can still mark it as primary even if it was
already registered. */
if(flags&2)
primary_keyring=token;
}
break;
default:
log_error ("resource type of `%s' not supported\n", url);
rc = G10ERR_GENERAL;
goto leave;
}
/* fixme: check directory permissions and print a warning */
leave:
if (rc)
{
/* Secret keyrings are not required in all cases. To avoid
having gpg return failure we use log_info here if the
rewsource is a secret one and marked as default
resource. */
if ((flags&4) && secret)
log_info (_("keyblock resource `%s': %s\n"),
filename, g10_errstr(rc));
else
log_error (_("keyblock resource `%s': %s\n"),
filename, g10_errstr(rc));
}
else if (secret)
any_secret = 1;
else
any_public = 1;
xfree (filename);
return rc;
}
KEYDB_HANDLE
keydb_new (int secret)
{
KEYDB_HANDLE hd;
int i, j;
-
+
hd = xmalloc_clear (sizeof *hd);
hd->found = -1;
-
+
assert (used_resources <= MAX_KEYDB_RESOURCES);
for (i=j=0; i < used_resources; i++)
{
if (!all_resources[i].secret != !secret)
continue;
switch (all_resources[i].type)
{
case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
hd->active[j].type = all_resources[i].type;
hd->active[j].token = all_resources[i].token;
hd->active[j].secret = all_resources[i].secret;
hd->active[j].u.kr = keyring_new (all_resources[i].token, secret);
if (!hd->active[j].u.kr) {
xfree (hd);
return NULL; /* fixme: release all previously allocated handles*/
}
j++;
break;
}
}
hd->used = j;
-
+
active_handles++;
return hd;
}
-void
+void
keydb_release (KEYDB_HANDLE hd)
{
int i;
if (!hd)
return;
assert (active_handles > 0);
active_handles--;
unlock_all (hd);
for (i=0; i < hd->used; i++) {
switch (hd->active[i].type) {
case KEYDB_RESOURCE_TYPE_NONE:
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
keyring_release (hd->active[i].u.kr);
break;
}
}
xfree (hd);
}
/*
* Return the name of the current resource. This is function first
* looks for the last found found, then for the current search
* position, and last returns the first available resource. The
* returned string is only valid as long as the handle exists. This
* function does only return NULL if no handle is specified, in all
* other error cases an empty string is returned.
*/
const char *
keydb_get_resource_name (KEYDB_HANDLE hd)
{
int idx;
const char *s = NULL;
- if (!hd)
+ if (!hd)
return NULL;
- if ( hd->found >= 0 && hd->found < hd->used)
+ if ( hd->found >= 0 && hd->found < hd->used)
idx = hd->found;
- else if ( hd->current >= 0 && hd->current < hd->used)
+ else if ( hd->current >= 0 && hd->current < hd->used)
idx = hd->current;
else
idx = 0;
switch (hd->active[idx].type) {
case KEYDB_RESOURCE_TYPE_NONE:
- s = NULL;
+ s = NULL;
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
s = keyring_get_resource_name (hd->active[idx].u.kr);
break;
}
return s? s: "";
}
-static int
+static int
lock_all (KEYDB_HANDLE hd)
{
int i, rc = 0;
for (i=0; !rc && i < hd->used; i++) {
switch (hd->active[i].type) {
case KEYDB_RESOURCE_TYPE_NONE:
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_lock (hd->active[i].u.kr, 1);
break;
}
}
if (rc) {
/* revert the already set locks */
for (i--; i >= 0; i--) {
switch (hd->active[i].type) {
case KEYDB_RESOURCE_TYPE_NONE:
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
keyring_lock (hd->active[i].u.kr, 0);
break;
}
}
}
else
hd->locked = 1;
return rc;
}
static void
unlock_all (KEYDB_HANDLE hd)
{
int i;
if (!hd->locked)
return;
for (i=hd->used-1; i >= 0; i--) {
switch (hd->active[i].type) {
case KEYDB_RESOURCE_TYPE_NONE:
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
keyring_lock (hd->active[i].u.kr, 0);
break;
}
}
hd->locked = 0;
}
/*
* Return the last found keyring. Caller must free it.
* The returned keyblock has the kbode flag bit 0 set for the node with
- * the public key used to locate the keyblock or flag bit 1 set for
+ * the public key used to locate the keyblock or flag bit 1 set for
* the user ID node.
*/
int
keydb_get_keyblock (KEYDB_HANDLE hd, KBNODE *ret_kb)
{
int rc = 0;
if (!hd)
return G10ERR_INV_ARG;
- if ( hd->found < 0 || hd->found >= hd->used)
+ if ( hd->found < 0 || hd->found >= hd->used)
return -1; /* nothing found */
switch (hd->active[hd->found].type) {
case KEYDB_RESOURCE_TYPE_NONE:
rc = G10ERR_GENERAL; /* oops */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_get_keyblock (hd->active[hd->found].u.kr, ret_kb);
break;
}
return rc;
}
-/*
+/*
* update the current keyblock with KB
*/
int
keydb_update_keyblock (KEYDB_HANDLE hd, KBNODE kb)
{
int rc = 0;
if (!hd)
return G10ERR_INV_ARG;
- if ( hd->found < 0 || hd->found >= hd->used)
+ if ( hd->found < 0 || hd->found >= hd->used)
return -1; /* nothing found */
if( opt.dry_run )
return 0;
rc = lock_all (hd);
if (rc)
return rc;
switch (hd->active[hd->found].type) {
case KEYDB_RESOURCE_TYPE_NONE:
rc = G10ERR_GENERAL; /* oops */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_update_keyblock (hd->active[hd->found].u.kr, kb);
break;
}
unlock_all (hd);
return rc;
}
-/*
- * Insert a new KB into one of the resources.
+/*
+ * Insert a new KB into one of the resources.
*/
int
keydb_insert_keyblock (KEYDB_HANDLE hd, KBNODE kb)
{
int rc = -1;
int idx;
- if (!hd)
+ if (!hd)
return G10ERR_INV_ARG;
if( opt.dry_run )
return 0;
- if ( hd->found >= 0 && hd->found < hd->used)
+ if ( hd->found >= 0 && hd->found < hd->used)
idx = hd->found;
- else if ( hd->current >= 0 && hd->current < hd->used)
+ else if ( hd->current >= 0 && hd->current < hd->used)
idx = hd->current;
else
return G10ERR_GENERAL;
rc = lock_all (hd);
if (rc)
return rc;
switch (hd->active[idx].type) {
case KEYDB_RESOURCE_TYPE_NONE:
rc = G10ERR_GENERAL; /* oops */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_insert_keyblock (hd->active[idx].u.kr, kb);
break;
}
unlock_all (hd);
return rc;
}
-/*
+/*
* The current keyblock will be deleted.
*/
int
keydb_delete_keyblock (KEYDB_HANDLE hd)
{
int rc = -1;
if (!hd)
return G10ERR_INV_ARG;
- if ( hd->found < 0 || hd->found >= hd->used)
+ if ( hd->found < 0 || hd->found >= hd->used)
return -1; /* nothing found */
if( opt.dry_run )
return 0;
rc = lock_all (hd);
if (rc)
return rc;
switch (hd->active[hd->found].type) {
case KEYDB_RESOURCE_TYPE_NONE:
rc = G10ERR_GENERAL; /* oops */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_delete_keyblock (hd->active[hd->found].u.kr);
break;
}
unlock_all (hd);
return rc;
}
/*
* Locate the default writable key resource, so that the next
* operation (which is only relevant for inserts) will be done on this
- * resource.
+ * resource.
*/
int
keydb_locate_writable (KEYDB_HANDLE hd, const char *reserved)
{
int rc;
-
+
+ (void)reserved;
+
if (!hd)
return G10ERR_INV_ARG;
-
+
rc = keydb_search_reset (hd); /* this does reset hd->current */
if (rc)
return rc;
/* If we have a primary set, try that one first */
if(primary_keyring)
{
for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
{
if(hd->active[hd->current].token==primary_keyring)
{
if(keyring_is_writable (hd->active[hd->current].token))
return 0;
else
break;
}
}
rc = keydb_search_reset (hd); /* this does reset hd->current */
if (rc)
return rc;
}
- for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
+ for ( ; hd->current >= 0 && hd->current < hd->used; hd->current++)
{
- switch (hd->active[hd->current].type)
+ switch (hd->active[hd->current].type)
{
case KEYDB_RESOURCE_TYPE_NONE:
BUG();
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
if (keyring_is_writable (hd->active[hd->current].token))
return 0; /* found (hd->current is set to it) */
break;
}
}
-
+
return -1;
}
/*
* Rebuild the caches of all key resources.
*/
void
keydb_rebuild_caches (int noisy)
{
int i, rc;
-
+
for (i=0; i < used_resources; i++)
{
if (all_resources[i].secret)
continue;
switch (all_resources[i].type)
{
case KEYDB_RESOURCE_TYPE_NONE: /* ignore */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_rebuild_cache (all_resources[i].token,noisy);
if (rc)
log_error (_("failed to rebuild keyring cache: %s\n"),
g10_errstr (rc));
break;
}
}
}
-/*
+/*
* Start the next search on this handle right at the beginning
*/
-int
+int
keydb_search_reset (KEYDB_HANDLE hd)
{
int i, rc = 0;
if (!hd)
return G10ERR_INV_ARG;
- hd->current = 0;
+ hd->current = 0;
hd->found = -1;
/* and reset all resources */
for (i=0; !rc && i < hd->used; i++) {
switch (hd->active[i].type) {
case KEYDB_RESOURCE_TYPE_NONE:
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_search_reset (hd->active[i].u.kr);
break;
}
}
- return rc;
+ return rc;
}
-/*
+/*
* Search through all keydb resources, starting at the current position,
* for a keyblock which contains one of the keys described in the DESC array.
*/
-int
+int
keydb_search2 (KEYDB_HANDLE hd, KEYDB_SEARCH_DESC *desc,
size_t ndesc, size_t *descindex)
{
int rc = -1;
if (!hd)
return G10ERR_INV_ARG;
while (rc == -1 && hd->current >= 0 && hd->current < hd->used) {
switch (hd->active[hd->current].type) {
case KEYDB_RESOURCE_TYPE_NONE:
BUG(); /* we should never see it here */
break;
case KEYDB_RESOURCE_TYPE_KEYRING:
rc = keyring_search (hd->active[hd->current].u.kr, desc,
ndesc, descindex);
break;
}
if (rc == -1) /* EOF -> switch to next resource */
- hd->current++;
+ hd->current++;
else if (!rc)
hd->found = hd->current;
}
- return rc;
+ return rc;
}
int
keydb_search_first (KEYDB_HANDLE hd)
{
KEYDB_SEARCH_DESC desc;
memset (&desc, 0, sizeof desc);
desc.mode = KEYDB_SEARCH_MODE_FIRST;
return keydb_search (hd, &desc, 1);
}
int
keydb_search_next (KEYDB_HANDLE hd)
{
KEYDB_SEARCH_DESC desc;
memset (&desc, 0, sizeof desc);
desc.mode = KEYDB_SEARCH_MODE_NEXT;
return keydb_search (hd, &desc, 1);
}
int
keydb_search_kid (KEYDB_HANDLE hd, u32 *kid)
{
KEYDB_SEARCH_DESC desc;
memset (&desc, 0, sizeof desc);
desc.mode = KEYDB_SEARCH_MODE_LONG_KID;
desc.u.kid[0] = kid[0];
desc.u.kid[1] = kid[1];
return keydb_search (hd, &desc, 1);
}
int
keydb_search_fpr (KEYDB_HANDLE hd, const byte *fpr)
{
KEYDB_SEARCH_DESC desc;
memset (&desc, 0, sizeof desc);
desc.mode = KEYDB_SEARCH_MODE_FPR;
memcpy (desc.u.fpr, fpr, MAX_FINGERPRINT_LEN);
return keydb_search (hd, &desc, 1);
}
diff --git a/g10/keyid.c b/g10/keyid.c
index 57e9fc8e9..f04bea635 100644
--- a/g10/keyid.c
+++ b/g10/keyid.c
@@ -1,759 +1,761 @@
/* keyid.c - key ID and fingerprint handling
* Copyright (C) 1998, 1999, 2000, 2001, 2003,
* 2004 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include
#include "util.h"
#include "main.h"
#include "packet.h"
#include "options.h"
#include "mpi.h"
#include "keydb.h"
#include "i18n.h"
#ifdef HAVE_UNSIGNED_TIME_T
# define INVALID_TIME_CHECK(a) ((a) == (time_t)(-1))
-#else
+#else
/* Error or 32 bit time_t and value after 2038-01-19. */
# define INVALID_TIME_CHECK(a) ((a) < 0)
#endif
int
pubkey_letter( int algo )
{
switch( algo ) {
case PUBKEY_ALGO_RSA: return 'R' ;
case PUBKEY_ALGO_RSA_E: return 'r' ;
case PUBKEY_ALGO_RSA_S: return 's' ;
case PUBKEY_ALGO_ELGAMAL_E: return 'g';
case PUBKEY_ALGO_ELGAMAL: return 'G' ;
case PUBKEY_ALGO_DSA: return 'D' ;
+ case PUBKEY_ALGO_ECDSA: return 'E' ; /* ECC DSA (sign only) */
+ case PUBKEY_ALGO_ECDH: return 'e' ; /* ECC DH (encrypt only) */
default: return '?';
}
}
/* This function is useful for v4 fingerprints and v3 or v4 key
signing. */
void
hash_public_key( MD_HANDLE md, PKT_public_key *pk )
{
unsigned n=6;
unsigned nb[PUBKEY_MAX_NPKEY];
unsigned nn[PUBKEY_MAX_NPKEY];
byte *pp[PUBKEY_MAX_NPKEY];
int i;
int npkey = pubkey_get_npkey( pk->pubkey_algo );
/* Two extra bytes for the expiration date in v3 */
if(pk->version<4)
n+=2;
if(npkey==0 && pk->pkey[0] && mpi_is_opaque(pk->pkey[0]))
{
pp[0]=mpi_get_opaque(pk->pkey[0],&nn[0]);
n+=nn[0];
}
else
for(i=0; i < npkey; i++ )
{
nb[i] = mpi_get_nbits(pk->pkey[i]);
pp[i] = mpi_get_buffer( pk->pkey[i], nn+i, NULL );
n += 2 + nn[i];
}
md_putc( md, 0x99 ); /* ctb */
/* What does it mean if n is greater than than 0xFFFF ? */
md_putc( md, n >> 8 ); /* 2 byte length header */
md_putc( md, n );
md_putc( md, pk->version );
md_putc( md, pk->timestamp >> 24 );
md_putc( md, pk->timestamp >> 16 );
md_putc( md, pk->timestamp >> 8 );
md_putc( md, pk->timestamp );
if(pk->version<4)
{
u16 days=0;
if(pk->expiredate)
days=(u16)((pk->expiredate - pk->timestamp) / 86400L);
-
+
md_putc( md, days >> 8 );
md_putc( md, days );
}
md_putc( md, pk->pubkey_algo );
if(npkey==0 && pk->pkey[0] && mpi_is_opaque(pk->pkey[0]))
md_write(md,pp[0],nn[0]);
else
for(i=0; i < npkey; i++ )
{
md_putc( md, nb[i]>>8);
md_putc( md, nb[i] );
md_write( md, pp[i], nn[i] );
xfree(pp[i]);
}
}
static MD_HANDLE
do_fingerprint_md( PKT_public_key *pk )
{
MD_HANDLE md;
md = md_open( DIGEST_ALGO_SHA1, 0);
hash_public_key(md,pk);
md_final( md );
return md;
}
static MD_HANDLE
do_fingerprint_md_sk( PKT_secret_key *sk )
{
PKT_public_key pk;
int npkey = pubkey_get_npkey( sk->pubkey_algo ); /* npkey is correct! */
int i;
if(npkey==0)
return NULL;
pk.pubkey_algo = sk->pubkey_algo;
pk.version = sk->version;
pk.timestamp = sk->timestamp;
pk.expiredate = sk->expiredate;
pk.pubkey_algo = sk->pubkey_algo;
for( i=0; i < npkey; i++ )
pk.pkey[i] = sk->skey[i];
return do_fingerprint_md( &pk );
}
size_t
keystrlen(void)
{
switch(opt.keyid_format)
{
case KF_SHORT:
return 8;
case KF_LONG:
return 16;
case KF_0xSHORT:
return 10;
case KF_0xLONG:
return 18;
default:
BUG();
}
}
const char *
keystr(u32 *keyid)
-{
+{
static char keyid_str[19];
switch(opt.keyid_format)
{
case KF_SHORT:
sprintf(keyid_str,"%08lX",(ulong)keyid[1]);
break;
case KF_LONG:
if(keyid[0])
sprintf(keyid_str,"%08lX%08lX",(ulong)keyid[0],(ulong)keyid[1]);
else
sprintf(keyid_str,"%08lX",(ulong)keyid[1]);
break;
case KF_0xSHORT:
sprintf(keyid_str,"0x%08lX",(ulong)keyid[1]);
break;
case KF_0xLONG:
if(keyid[0])
sprintf(keyid_str,"0x%08lX%08lX",(ulong)keyid[0],(ulong)keyid[1]);
else
sprintf(keyid_str,"0x%08lX",(ulong)keyid[1]);
break;
default:
BUG();
}
return keyid_str;
}
const char *
keystr_from_pk(PKT_public_key *pk)
{
keyid_from_pk(pk,NULL);
return keystr(pk->keyid);
}
const char *
keystr_from_sk(PKT_secret_key *sk)
{
keyid_from_sk(sk,NULL);
return keystr(sk->keyid);
}
const char *
keystr_from_desc(KEYDB_SEARCH_DESC *desc)
{
switch(desc->mode)
{
case KEYDB_SEARCH_MODE_LONG_KID:
case KEYDB_SEARCH_MODE_SHORT_KID:
return keystr(desc->u.kid);
case KEYDB_SEARCH_MODE_FPR20:
{
u32 keyid[2];
keyid[0] = (unsigned char)desc->u.fpr[12] << 24
| (unsigned char)desc->u.fpr[13] << 16
| (unsigned char)desc->u.fpr[14] << 8
| (unsigned char)desc->u.fpr[15] ;
keyid[1] = (unsigned char)desc->u.fpr[16] << 24
| (unsigned char)desc->u.fpr[17] << 16
| (unsigned char)desc->u.fpr[18] << 8
| (unsigned char)desc->u.fpr[19] ;
return keystr(keyid);
}
case KEYDB_SEARCH_MODE_FPR16:
return "?v3 fpr?";
default:
BUG();
}
}
/****************
* Get the keyid from the secret key and put it into keyid
* if this is not NULL. Return the 32 low bits of the keyid.
*/
u32
keyid_from_sk( PKT_secret_key *sk, u32 *keyid )
{
u32 lowbits;
u32 dummy_keyid[2];
if( !keyid )
keyid = dummy_keyid;
if( sk->keyid[0] || sk->keyid[1] )
{
keyid[0] = sk->keyid[0];
keyid[1] = sk->keyid[1];
lowbits = keyid[1];
}
else if( sk->version < 4 )
{
if( is_RSA(sk->pubkey_algo) )
{
lowbits = pubkey_get_npkey(sk->pubkey_algo) ?
mpi_get_keyid( sk->skey[0], keyid ) : 0; /* take n */
sk->keyid[0]=keyid[0];
sk->keyid[1]=keyid[1];
}
else
sk->keyid[0]=sk->keyid[1]=keyid[0]=keyid[1]=lowbits=0xFFFFFFFF;
}
else
{
const byte *dp;
MD_HANDLE md;
md = do_fingerprint_md_sk(sk);
if(md)
{
dp = md_read( md, 0 );
keyid[0] = dp[12] << 24 | dp[13] << 16 | dp[14] << 8 | dp[15] ;
keyid[1] = dp[16] << 24 | dp[17] << 16 | dp[18] << 8 | dp[19] ;
lowbits = keyid[1];
md_close(md);
sk->keyid[0] = keyid[0];
sk->keyid[1] = keyid[1];
}
else
sk->keyid[0]=sk->keyid[1]=keyid[0]=keyid[1]=lowbits=0xFFFFFFFF;
}
return lowbits;
}
/****************
* Get the keyid from the public key and put it into keyid
* if this is not NULL. Return the 32 low bits of the keyid.
*/
u32
keyid_from_pk( PKT_public_key *pk, u32 *keyid )
{
u32 lowbits;
u32 dummy_keyid[2];
if( !keyid )
keyid = dummy_keyid;
if( pk->keyid[0] || pk->keyid[1] )
{
keyid[0] = pk->keyid[0];
keyid[1] = pk->keyid[1];
lowbits = keyid[1];
}
else if( pk->version < 4 )
{
if( is_RSA(pk->pubkey_algo) )
{
lowbits = pubkey_get_npkey(pk->pubkey_algo) ?
mpi_get_keyid( pk->pkey[0], keyid ) : 0 ; /* from n */
pk->keyid[0] = keyid[0];
pk->keyid[1] = keyid[1];
}
else
pk->keyid[0]=pk->keyid[1]=keyid[0]=keyid[1]=lowbits=0xFFFFFFFF;
}
else
{
const byte *dp;
MD_HANDLE md;
md = do_fingerprint_md(pk);
if(md)
{
dp = md_read( md, 0 );
keyid[0] = dp[12] << 24 | dp[13] << 16 | dp[14] << 8 | dp[15] ;
keyid[1] = dp[16] << 24 | dp[17] << 16 | dp[18] << 8 | dp[19] ;
lowbits = keyid[1];
md_close(md);
pk->keyid[0] = keyid[0];
pk->keyid[1] = keyid[1];
}
else
pk->keyid[0]=pk->keyid[1]=keyid[0]=keyid[1]=lowbits=0xFFFFFFFF;
}
return lowbits;
}
/****************
* Get the keyid from the fingerprint. This function is simple for most
* keys, but has to do a keylookup for old stayle keys.
*/
u32
keyid_from_fingerprint( const byte *fprint, size_t fprint_len, u32 *keyid )
{
u32 dummy_keyid[2];
if( !keyid )
keyid = dummy_keyid;
if( fprint_len != 20 ) {
/* This is special as we have to lookup the key first */
PKT_public_key pk;
int rc;
memset( &pk, 0, sizeof pk );
rc = get_pubkey_byfprint( &pk, fprint, fprint_len );
if( rc ) {
log_error("Oops: keyid_from_fingerprint: no pubkey\n");
keyid[0] = 0;
keyid[1] = 0;
}
else
keyid_from_pk( &pk, keyid );
}
else {
const byte *dp = fprint;
keyid[0] = dp[12] << 24 | dp[13] << 16 | dp[14] << 8 | dp[15] ;
keyid[1] = dp[16] << 24 | dp[17] << 16 | dp[18] << 8 | dp[19] ;
}
return keyid[1];
}
u32
keyid_from_sig( PKT_signature *sig, u32 *keyid )
{
if( keyid ) {
keyid[0] = sig->keyid[0];
keyid[1] = sig->keyid[1];
}
return sig->keyid[1];
}
byte *
namehash_from_uid(PKT_user_id *uid)
{
if(uid->namehash==NULL)
{
uid->namehash=xmalloc(20);
if(uid->attrib_data)
rmd160_hash_buffer(uid->namehash,uid->attrib_data,uid->attrib_len);
else
rmd160_hash_buffer(uid->namehash,uid->name,uid->len);
}
return uid->namehash;
}
/****************
* return the number of bits used in the pk
*/
unsigned
nbits_from_pk( PKT_public_key *pk )
{
return pubkey_nbits( pk->pubkey_algo, pk->pkey );
}
/****************
* return the number of bits used in the sk
*/
unsigned
nbits_from_sk( PKT_secret_key *sk )
{
return pubkey_nbits( sk->pubkey_algo, sk->skey );
}
static const char *
mk_datestr (char *buffer, time_t atime)
{
struct tm *tp;
if (INVALID_TIME_CHECK (atime))
strcpy (buffer, "????" "-??" "-??"); /* Mark this as invalid. */
else {
tp = gmtime (&atime);
sprintf (buffer,"%04d-%02d-%02d",
1900+tp->tm_year, tp->tm_mon+1, tp->tm_mday );
}
return buffer;
}
/****************
* return a string with the creation date of the pk
* Note: this is alloced in a static buffer.
* Format is: yyyy-mm-dd
*/
const char *
datestr_from_pk( PKT_public_key *pk )
{
static char buffer[11+5];
time_t atime = pk->timestamp;
return mk_datestr (buffer, atime);
}
const char *
datestr_from_sk( PKT_secret_key *sk )
{
static char buffer[11+5];
time_t atime = sk->timestamp;
return mk_datestr (buffer, atime);
}
const char *
datestr_from_sig( PKT_signature *sig )
{
static char buffer[11+5];
time_t atime = sig->timestamp;
return mk_datestr (buffer, atime);
}
const char *
expirestr_from_pk( PKT_public_key *pk )
{
static char buffer[11+5];
time_t atime;
if( !pk->expiredate )
return _("never ");
atime = pk->expiredate;
return mk_datestr (buffer, atime);
}
const char *
expirestr_from_sk( PKT_secret_key *sk )
{
static char buffer[11+5];
time_t atime;
if( !sk->expiredate )
return _("never ");
atime = sk->expiredate;
return mk_datestr (buffer, atime);
}
const char *
expirestr_from_sig( PKT_signature *sig )
{
static char buffer[11+5];
time_t atime;
if(!sig->expiredate)
return _("never ");
atime=sig->expiredate;
return mk_datestr (buffer, atime);
}
const char *
revokestr_from_pk( PKT_public_key *pk )
{
static char buffer[11+5];
time_t atime;
if(!pk->revoked.date)
return _("never ");
atime=pk->revoked.date;
return mk_datestr (buffer, atime);
}
const char *
usagestr_from_pk( PKT_public_key *pk )
{
static char buffer[10];
int i = 0;
unsigned int use = pk->pubkey_usage;
if ( use & PUBKEY_USAGE_SIG )
buffer[i++] = 'S';
if ( use & PUBKEY_USAGE_CERT )
buffer[i++] = 'C';
if ( use & PUBKEY_USAGE_ENC )
buffer[i++] = 'E';
if ( (use & PUBKEY_USAGE_AUTH) )
buffer[i++] = 'A';
while (i < 4)
buffer[i++] = ' ';
buffer[i] = 0;
return buffer;
}
const char *
colon_strtime (u32 t)
{
if (!t)
return "";
if (opt.fixed_list_mode) {
static char buf[15];
sprintf (buf, "%lu", (ulong)t);
return buf;
}
return strtimestamp(t);
}
const char *
colon_datestr_from_pk (PKT_public_key *pk)
{
if (opt.fixed_list_mode) {
static char buf[15];
sprintf (buf, "%lu", (ulong)pk->timestamp);
return buf;
}
return datestr_from_pk (pk);
}
const char *
colon_datestr_from_sk (PKT_secret_key *sk)
{
if (opt.fixed_list_mode) {
static char buf[15];
sprintf (buf, "%lu", (ulong)sk->timestamp);
return buf;
}
return datestr_from_sk (sk);
}
const char *
colon_datestr_from_sig (PKT_signature *sig)
{
if (opt.fixed_list_mode) {
static char buf[15];
sprintf (buf, "%lu", (ulong)sig->timestamp);
return buf;
}
return datestr_from_sig (sig);
}
const char *
colon_expirestr_from_sig (PKT_signature *sig)
{
if(!sig->expiredate)
return "";
if (opt.fixed_list_mode) {
static char buf[15];
sprintf (buf, "%lu", (ulong)sig->expiredate);
return buf;
}
return expirestr_from_sig (sig);
}
/**************** .
* Return a byte array with the fingerprint for the given PK/SK
* The length of the array is returned in ret_len. Caller must free
* the array or provide an array of length MAX_FINGERPRINT_LEN.
*/
byte *
fingerprint_from_pk( PKT_public_key *pk, byte *array, size_t *ret_len )
{
byte *p, *buf;
const byte *dp;
size_t len;
unsigned int n;
if( pk->version < 4 )
{
if( is_RSA(pk->pubkey_algo) )
{
/* RSA in version 3 packets is special */
MD_HANDLE md;
md = md_open( DIGEST_ALGO_MD5, 0);
if( pubkey_get_npkey( pk->pubkey_algo ) > 1 ) {
p = buf = mpi_get_buffer( pk->pkey[0], &n, NULL );
md_write( md, p, n );
xfree(buf);
p = buf = mpi_get_buffer( pk->pkey[1], &n, NULL );
md_write( md, p, n );
xfree(buf);
}
md_final(md);
if( !array )
array = xmalloc( 16 );
len = 16;
memcpy(array, md_read(md, DIGEST_ALGO_MD5), 16 );
md_close(md);
}
else
{
if(!array)
array=xmalloc(16);
len=16;
memset(array,0,16);
}
}
else {
MD_HANDLE md;
md = do_fingerprint_md(pk);
dp = md_read( md, 0 );
len = md_digest_length( md_get_algo( md ) );
assert( len <= MAX_FINGERPRINT_LEN );
if( !array )
array = xmalloc( len );
memcpy(array, dp, len );
pk->keyid[0] = dp[12] << 24 | dp[13] << 16 | dp[14] << 8 | dp[15] ;
pk->keyid[1] = dp[16] << 24 | dp[17] << 16 | dp[18] << 8 | dp[19] ;
md_close(md);
}
*ret_len = len;
return array;
}
byte *
fingerprint_from_sk( PKT_secret_key *sk, byte *array, size_t *ret_len )
{
byte *p, *buf;
const char *dp;
size_t len;
unsigned n;
if( sk->version < 4 )
{
if( is_RSA(sk->pubkey_algo) )
{
/* RSA in version 3 packets is special */
MD_HANDLE md;
md = md_open( DIGEST_ALGO_MD5, 0);
if( pubkey_get_npkey( sk->pubkey_algo ) > 1 ) {
p = buf = mpi_get_buffer( sk->skey[0], &n, NULL );
md_write( md, p, n );
xfree(buf);
p = buf = mpi_get_buffer( sk->skey[1], &n, NULL );
md_write( md, p, n );
xfree(buf);
}
md_final(md);
if( !array )
array = xmalloc( 16 );
len = 16;
memcpy(array, md_read(md, DIGEST_ALGO_MD5), 16 );
md_close(md);
}
else
{
if(!array)
array=xmalloc(16);
len=16;
memset(array,0,16);
}
}
else {
MD_HANDLE md;
md = do_fingerprint_md_sk(sk);
if(md)
{
dp = md_read( md, 0 );
len = md_digest_length( md_get_algo( md ) );
assert( len <= MAX_FINGERPRINT_LEN );
if( !array )
array = xmalloc( len );
memcpy(array, dp, len );
md_close(md);
}
else
{
len=MAX_FINGERPRINT_LEN;
if(!array)
array=xmalloc(len);
memset(array,0,len);
}
}
*ret_len = len;
return array;
}
diff --git a/g10/mainproc.c b/g10/mainproc.c
index f46895d54..3ffb049bc 100644
--- a/g10/mainproc.c
+++ b/g10/mainproc.c
@@ -1,2135 +1,2137 @@
/* mainproc.c - handle packets
* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
* 2008 Free Software Foundation, Inc.
*
* This file is part of GnuPG.
*
* GnuPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GnuPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see .
*/
#include
#include
#include
#include
#include
#include
#include "packet.h"
#include "iobuf.h"
#include "memory.h"
#include "options.h"
#include "util.h"
#include "cipher.h"
#include "keydb.h"
#include "filter.h"
#include "main.h"
#include "status.h"
#include "i18n.h"
#include "trustdb.h"
#include "keyserver-internal.h"
#include "photoid.h"
struct kidlist_item {
struct kidlist_item *next;
u32 kid[2];
int pubkey_algo;
int reason;
};
/****************
* Structure to hold the context
*/
typedef struct mainproc_context *CTX;
struct mainproc_context
{
struct mainproc_context *anchor; /* May be useful in the future. */
PKT_public_key *last_pubkey;
PKT_secret_key *last_seckey;
PKT_user_id *last_user_id;
md_filter_context_t mfx;
int sigs_only; /* Process only signatures and reject all other stuff. */
int encrypt_only; /* Process only encryption messages. */
STRLIST signed_data;
const char *sigfilename;
DEK *dek;
int last_was_session_key;
KBNODE list; /* The current list of packets. */
int have_data;
IOBUF iobuf; /* Used to get the filename etc. */
int trustletter; /* Temporary usage in list_node. */
ulong symkeys;
struct kidlist_item *pkenc_list; /* List of encryption packets. */
- struct
+ struct
{
int op;
int stop_now;
} pipemode;
int any_sig_seen; /* Set to true if a signature packet has been seen. */
};
static int do_proc_packets( CTX c, IOBUF a );
static void list_node( CTX c, KBNODE node );
static void proc_tree( CTX c, KBNODE node );
static int literals_seen;
void
reset_literals_seen(void)
{
literals_seen=0;
}
static void
release_list( CTX c )
{
if( !c->list )
return;
proc_tree(c, c->list );
release_kbnode( c->list );
while( c->pkenc_list ) {
struct kidlist_item *tmp = c->pkenc_list->next;
xfree( c->pkenc_list );
c->pkenc_list = tmp;
}
c->pkenc_list = NULL;
c->list = NULL;
c->have_data = 0;
c->last_was_session_key = 0;
c->pipemode.op = 0;
c->pipemode.stop_now = 0;
xfree(c->dek); c->dek = NULL;
}
static int
add_onepass_sig( CTX c, PACKET *pkt )
{
KBNODE node;
if ( c->list ) /* add another packet */
add_kbnode( c->list, new_kbnode( pkt ));
else /* insert the first one */
c->list = node = new_kbnode( pkt );
return 1;
}
static int
add_gpg_control( CTX c, PACKET *pkt )
{
if ( pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START ) {
/* New clear text signature.
* Process the last one and reset everything */
release_list(c);
- }
+ }
else if ( pkt->pkt.gpg_control->control == CTRLPKT_PIPEMODE ) {
/* Pipemode control packet */
- if ( pkt->pkt.gpg_control->datalen < 2 )
+ if ( pkt->pkt.gpg_control->datalen < 2 )
log_fatal ("invalid pipemode control packet length\n");
if (pkt->pkt.gpg_control->data[0] == 1) {
/* start the whole thing */
assert ( !c->list ); /* we should be in a pretty virgin state */
assert ( !c->pipemode.op );
c->pipemode.op = pkt->pkt.gpg_control->data[1];
}
else if (pkt->pkt.gpg_control->data[0] == 2) {
/* the signed material follows in a plaintext packet */
assert ( c->pipemode.op == 'B' );
}
else if (pkt->pkt.gpg_control->data[0] == 3) {
assert ( c->pipemode.op == 'B' );
release_list (c);
/* and tell the outer loop to terminate */
c->pipemode.stop_now = 1;
}
- else
+ else
log_fatal ("invalid pipemode control packet code\n");
return 0; /* no need to store the packet */
- }
+ }
if( c->list ) /* add another packet */
add_kbnode( c->list, new_kbnode( pkt ));
else /* insert the first one */
c->list = new_kbnode( pkt );
return 1;
}
static int
add_user_id( CTX c, PACKET *pkt )
{
if( !c->list ) {
log_error("orphaned user ID\n" );
return 0;
}
add_kbnode( c->list, new_kbnode( pkt ) );
return 1;
}
static int
add_subkey( CTX c, PACKET *pkt )
{
if( !c->list ) {
log_error("subkey w/o mainkey\n" );
return 0;
}
add_kbnode( c->list, new_kbnode( pkt ) );
return 1;
}
static int
add_ring_trust( CTX c, PACKET *pkt )
{
if( !c->list ) {
log_error("ring trust w/o key\n" );
return 0;
}
add_kbnode( c->list, new_kbnode( pkt ) );
return 1;
}
static int
add_signature( CTX c, PACKET *pkt )
{
KBNODE node;
c->any_sig_seen = 1;
if( pkt->pkttype == PKT_SIGNATURE && !c->list ) {
/* This is the first signature for the following datafile.
* GPG does not write such packets; instead it always uses
* onepass-sig packets. The drawback of PGP's method
* of prepending the signature to the data is
* that it is not possible to make a signature from data read
* from stdin. (GPG is able to read PGP stuff anyway.) */
node = new_kbnode( pkt );
c->list = node;
return 1;
}
else if( !c->list )
return 0; /* oops (invalid packet sequence)*/
else if( !c->list->pkt )
BUG(); /* so nicht */
/* add a new signature node id at the end */
node = new_kbnode( pkt );
add_kbnode( c->list, node );
return 1;
}
static int
symkey_decrypt_seskey( DEK *dek, byte *seskey, size_t slen )
{
CIPHER_HANDLE hd;
if(slen < 17 || slen > 33)
{
log_error ( _("weird size for an encrypted session key (%d)\n"),
(int)slen);
return G10ERR_BAD_KEY;
}
hd = cipher_open( dek->algo, CIPHER_MODE_CFB, 1 );
cipher_setkey( hd, dek->key, dek->keylen );
cipher_setiv( hd, NULL, 0 );
cipher_decrypt( hd, seskey, seskey, slen );
cipher_close( hd );
/* now we replace the dek components with the real session key to
decrypt the contents of the sequencing packet. */
dek->keylen=slen-1;
dek->algo=seskey[0];
if(dek->keylen > DIM(dek->key))
BUG ();
/* This is not completely accurate, since a bad passphrase may have
resulted in a garbage algorithm byte, but it's close enough since
a bogus byte here will fail later. */
if(dek->algo==CIPHER_ALGO_IDEA)
- idea_cipher_warn(0);
+ {
+ idea_cipher_warn(0);
+ }
memcpy(dek->key, seskey + 1, dek->keylen);
/*log_hexdump( "thekey", dek->key, dek->keylen );*/
return 0;
-}
+}
static void
proc_symkey_enc( CTX c, PACKET *pkt )
{
PKT_symkey_enc *enc;
enc = pkt->pkt.symkey_enc;
if (!enc)
log_error ("invalid symkey encrypted packet\n");
else if(!c->dek)
{
int algo = enc->cipher_algo;
const char *s = cipher_algo_to_string (algo);
if(s)
{
if(!opt.quiet)
{
if(enc->seskeylen)
log_info(_("%s encrypted session key\n"), s );
else
log_info(_("%s encrypted data\n"), s );
}
}
else
log_error(_("encrypted with unknown algorithm %d\n"), algo );
if(check_digest_algo(enc->s2k.hash_algo))
{
log_error(_("passphrase generated with unknown digest"
" algorithm %d\n"),enc->s2k.hash_algo);
s=NULL;
}
c->last_was_session_key = 2;
if(!s || opt.list_only)
goto leave;
if(opt.override_session_key)
{
c->dek = xmalloc_clear( sizeof *c->dek );
if(get_override_session_key(c->dek, opt.override_session_key))
{
xfree(c->dek);
c->dek = NULL;
}
}
else
{
int canceled;
c->dek = passphrase_to_dek (NULL, 0, algo, &enc->s2k, 0,
NULL, &canceled);
if (canceled)
{
/* For unknown reasons passphrase_to_dek does only
return NULL if a new passphrase has been requested
and has not been repeated correctly. Thus even
with a cancel requested (by means of the gpg-agent)
it won't return NULL but an empty passphrase. We
take the most conservative approach for now and
work around it right here. */
xfree (c->dek);
c->dek = NULL;
}
if(c->dek)
{
c->dek->symmetric=1;
/* FIXME: This doesn't work perfectly if a symmetric
key comes before a public key in the message - if
the user doesn't know the passphrase, then there is
a chance that the "decrypted" algorithm will happen
to be a valid one, which will make the returned dek
appear valid, so we won't try any public keys that
come later. */
if(enc->seskeylen)
{
if(symkey_decrypt_seskey(c->dek, enc->seskey,
enc->seskeylen))
{
xfree(c->dek);
c->dek=NULL;
}
}
else
c->dek->algo_info_printed = 1;
}
}
}
leave:
c->symkeys++;
free_packet(pkt);
}
static void
proc_pubkey_enc( CTX c, PACKET *pkt )
{
PKT_pubkey_enc *enc;
int result = 0;
/* check whether the secret key is available and store in this case */
c->last_was_session_key = 1;
enc = pkt->pkt.pubkey_enc;
/*printf("enc: encrypted by a pubkey with keyid %08lX\n", enc->keyid[1] );*/
/* Hmmm: why do I have this algo check here - anyway there is
* function to check it. */
if( opt.verbose )
log_info(_("public key is %s\n"), keystr(enc->keyid) );
if( is_status_enabled() ) {
char buf[50];
sprintf(buf, "%08lX%08lX %d 0",
(ulong)enc->keyid[0], (ulong)enc->keyid[1], enc->pubkey_algo );
write_status_text( STATUS_ENC_TO, buf );
}
if( !opt.list_only && opt.override_session_key ) {
/* It does not make much sense to store the session key in
* secure memory because it has already been passed on the
* command line and the GCHQ knows about it. */
c->dek = xmalloc_clear( sizeof *c->dek );
result = get_override_session_key ( c->dek, opt.override_session_key );
if ( result ) {
xfree(c->dek); c->dek = NULL;
}
}
else if( is_ELGAMAL(enc->pubkey_algo)
|| enc->pubkey_algo == PUBKEY_ALGO_DSA
- || is_RSA(enc->pubkey_algo)
+ || is_RSA(enc->pubkey_algo)
|| (RFC2440 && enc->pubkey_algo == PUBKEY_ALGO_ELGAMAL)) {
/* Note that we also allow type 20 Elgamal keys for decryption.
There are still a couple of those keys in active use as a
subkey. */
/* FIXME: Store this all in a list and process it later so that
we can prioritize what key to use. This gives a better user
experience if wildcard keyids are used. */
if ( !c->dek && ((!enc->keyid[0] && !enc->keyid[1])
|| opt.try_all_secrets
|| !seckey_available( enc->keyid )) ) {
if( opt.list_only )
result = -1;
else {
c->dek = xmalloc_secure_clear( sizeof *c->dek );
if( (result = get_session_key( enc, c->dek )) ) {
/* error: delete the DEK */
xfree(c->dek); c->dek = NULL;
}
}
}
else
result = G10ERR_NO_SECKEY;
}
else
result = G10ERR_PUBKEY_ALGO;
if( result == -1 )
;
else
{
/* store it for later display */
struct kidlist_item *x = xmalloc( sizeof *x );
x->kid[0] = enc->keyid[0];
x->kid[1] = enc->keyid[1];
x->pubkey_algo = enc->pubkey_algo;
x->reason = result;
x->next = c->pkenc_list;
c->pkenc_list = x;
if( !result && opt.verbose > 1 )
log_info( _("public key encrypted data: good DEK\n") );
}
free_packet(pkt);
}
/****************
* Print the list of public key encrypted packets which we could
* not decrypt.
*/
static void
print_pkenc_list( struct kidlist_item *list, int failed )
{
for( ; list; list = list->next ) {
PKT_public_key *pk;
const char *algstr;
-
+
if ( failed && !list->reason )
continue;
if ( !failed && list->reason )
continue;
algstr = pubkey_algo_to_string( list->pubkey_algo );
pk = xmalloc_clear( sizeof *pk );
if( !algstr )
algstr = "[?]";
pk->pubkey_algo = list->pubkey_algo;
if( !get_pubkey( pk, list->kid ) )
{
char *p;
log_info( _("encrypted with %u-bit %s key, ID %s, created %s\n"),
nbits_from_pk( pk ), algstr, keystr_from_pk(pk),
strtimestamp(pk->timestamp) );
p=get_user_id_native(list->kid);
fprintf(log_stream(),_(" \"%s\"\n"),p);
xfree(p);
}
else
log_info(_("encrypted with %s key, ID %s\n"),
algstr,keystr(list->kid));
free_public_key( pk );
if( list->reason == G10ERR_NO_SECKEY ) {
if( is_status_enabled() ) {
char buf[20];
sprintf(buf,"%08lX%08lX", (ulong)list->kid[0],
(ulong)list->kid[1] );
write_status_text( STATUS_NO_SECKEY, buf );
}
}
else if (list->reason)
{
log_info(_("public key decryption failed: %s\n"),
g10_errstr(list->reason));
if (is_status_enabled ())
{
char buf[20+30];
snprintf (buf, sizeof buf, "pkdecrypt_failed %d", list->reason);
write_status_text (STATUS_ERROR, buf);
}
}
}
}
static void
proc_encrypted( CTX c, PACKET *pkt )
{
int result = 0;
if (!opt.quiet)
{
if(c->symkeys>1)
log_info(_("encrypted with %lu passphrases\n"),c->symkeys);
else if(c->symkeys==1)
log_info(_("encrypted with 1 passphrase\n"));
print_pkenc_list ( c->pkenc_list, 1 );
print_pkenc_list ( c->pkenc_list, 0 );
}
/* FIXME: Figure out the session key by looking at all pkenc packets. */
write_status( STATUS_BEGIN_DECRYPTION );
/*log_debug("dat: %sencrypted data\n", c->dek?"":"conventional ");*/
if( opt.list_only )
result = -1;
else if( !c->dek && !c->last_was_session_key ) {
int algo;
STRING2KEY s2kbuf, *s2k = NULL;
if(opt.override_session_key)
{
c->dek = xmalloc_clear( sizeof *c->dek );
result=get_override_session_key(c->dek, opt.override_session_key);
if(result)
{
xfree(c->dek);
c->dek = NULL;
}
}
else
{
/* assume this is old style conventional encrypted data */
if ( (algo = opt.def_cipher_algo))
log_info (_("assuming %s encrypted data\n"),
cipher_algo_to_string(algo));
else if ( check_cipher_algo(CIPHER_ALGO_IDEA) )
{
algo = opt.def_cipher_algo;
if (!algo)
algo = opt.s2k_cipher_algo;
idea_cipher_warn(1);
log_info (_("IDEA cipher unavailable, "
"optimistically attempting to use %s instead\n"),
cipher_algo_to_string(algo));
}
else
{
algo = CIPHER_ALGO_IDEA;
if (!opt.s2k_digest_algo)
{
/* If no digest is given we assume MD5 */
s2kbuf.mode = 0;
s2kbuf.hash_algo = DIGEST_ALGO_MD5;
s2k = &s2kbuf;
}
log_info (_("assuming %s encrypted data\n"), "IDEA");
}
c->dek = passphrase_to_dek ( NULL, 0, algo, s2k, 0, NULL, NULL );
if (c->dek)
c->dek->algo_info_printed = 1;
}
}
else if( !c->dek )
result = G10ERR_NO_SECKEY;
if( !result )
result = decrypt_data( c, pkt->pkt.encrypted, c->dek );
if( result == -1 )
;
else if( !result || (result==G10ERR_BAD_SIGN && opt.ignore_mdc_error)) {
write_status( STATUS_DECRYPTION_OKAY );
if( opt.verbose > 1 )
log_info(_("decryption okay\n"));
if( pkt->pkt.encrypted->mdc_method && !result )
write_status( STATUS_GOODMDC );
else if(!opt.no_mdc_warn)
log_info (_("WARNING: message was not integrity protected\n"));
if(opt.show_session_key)
{
int i;
char *buf = xmalloc ( c->dek->keylen*2 + 20 );
sprintf ( buf, "%d:", c->dek->algo );
for(i=0; i < c->dek->keylen; i++ )
sprintf(buf+strlen(buf), "%02X", c->dek->key[i] );
log_info( "session key: `%s'\n", buf );
write_status_text ( STATUS_SESSION_KEY, buf );
}
}
else if( result == G10ERR_BAD_SIGN ) {
log_error(_("WARNING: encrypted message has been manipulated!\n"));
write_status( STATUS_BADMDC );
write_status( STATUS_DECRYPTION_FAILED );
}
else {
write_status( STATUS_DECRYPTION_FAILED );
log_error(_("decryption failed: %s\n"), g10_errstr(result));
/* Hmmm: does this work when we have encrypted using multiple
* ways to specify the session key (symmmetric and PK)*/
}
xfree(c->dek); c->dek = NULL;
free_packet(pkt);
c->last_was_session_key = 0;
write_status( STATUS_END_DECRYPTION );
}
static void
proc_plaintext( CTX c, PACKET *pkt )
{
PKT_plaintext *pt = pkt->pkt.plaintext;
int any, clearsig, only_md5, rc;
KBNODE n;
literals_seen++;
if( pt->namelen == 8 && !memcmp( pt->name, "_CONSOLE", 8 ) )
log_info(_("NOTE: sender requested \"for-your-eyes-only\"\n"));
else if( opt.verbose )
log_info(_("original file name='%.*s'\n"), pt->namelen, pt->name);
free_md_filter_context( &c->mfx );
c->mfx.md = md_open( 0, 0);
/* fixme: we may need to push the textfilter if we have sigclass 1
* and no armoring - Not yet tested
* Hmmm, why don't we need it at all if we have sigclass 1
* Should we assume that plaintext in mode 't' has always sigclass 1??
* See: Russ Allbery's mail 1999-02-09
*/
any = clearsig = only_md5 = 0;
for(n=c->list; n; n = n->next )
{
if( n->pkt->pkttype == PKT_ONEPASS_SIG )
{
/* For the onepass signature case */
if( n->pkt->pkt.onepass_sig->digest_algo )
{
md_enable( c->mfx.md, n->pkt->pkt.onepass_sig->digest_algo );
if( !any && n->pkt->pkt.onepass_sig->digest_algo
== DIGEST_ALGO_MD5 )
only_md5 = 1;
else
only_md5 = 0;
any = 1;
}
if( n->pkt->pkt.onepass_sig->sig_class != 0x01 )
only_md5 = 0;
}
else if( n->pkt->pkttype == PKT_GPG_CONTROL
&& n->pkt->pkt.gpg_control->control
== CTRLPKT_CLEARSIGN_START )
{
/* For the clearsigned message case */
size_t datalen = n->pkt->pkt.gpg_control->datalen;
const byte *data = n->pkt->pkt.gpg_control->data;
/* check that we have at least the sigclass and one hash */
if ( datalen < 2 )
- log_fatal("invalid control packet CTRLPKT_CLEARSIGN_START\n");
+ log_fatal("invalid control packet CTRLPKT_CLEARSIGN_START\n");
/* Note that we don't set the clearsig flag for not-dash-escaped
* documents */
clearsig = (*data == 0x01);
for( data++, datalen--; datalen; datalen--, data++ )
md_enable( c->mfx.md, *data );
any = 1;
break; /* Stop here as one-pass signature packets are not
expected. */
}
else if(n->pkt->pkttype==PKT_SIGNATURE)
{
/* For the SIG+LITERAL case that PGP used to use. */
md_enable( c->mfx.md, n->pkt->pkt.signature->digest_algo );
any=1;
}
}
if( !any && !opt.skip_verify )
{
/* This is for the old GPG LITERAL+SIG case. It's not legal
according to 2440, so hopefully it won't come up that
often. There is no good way to specify what algorithms to
use in that case, so these three are the historical
answer. */
md_enable( c->mfx.md, DIGEST_ALGO_RMD160 );
md_enable( c->mfx.md, DIGEST_ALGO_SHA1 );
md_enable( c->mfx.md, DIGEST_ALGO_MD5 );
}
if( opt.pgp2_workarounds && only_md5 && !opt.skip_verify ) {
/* This is a kludge to work around a bug in pgp2. It does only
* catch those mails which are armored. To catch the non-armored
* pgp mails we could see whether there is the signature packet
* in front of the plaintext. If someone needs this, send me a patch.
*/
c->mfx.md2 = md_open( DIGEST_ALGO_MD5, 0);
}
if ( DBG_HASHING ) {
md_start_debug( c->mfx.md, "verify" );
if ( c->mfx.md2 )
md_start_debug( c->mfx.md2, "verify2" );
}
rc=0;
if(literals_seen>1)
{
log_info(_("WARNING: multiple plaintexts seen\n"));
if(!opt.flags.allow_multiple_messages)
{
write_status_text (STATUS_ERROR, "proc_pkt.plaintext 89_BAD_DATA");
log_inc_errorcount();
rc=G10ERR_UNEXPECTED;
}
}
if(!rc)
{
if ( c->pipemode.op == 'B' )
rc = handle_plaintext( pt, &c->mfx, 1, 0 );
else
{
rc = handle_plaintext( pt, &c->mfx, c->sigs_only, clearsig );
if( rc == G10ERR_CREATE_FILE && !c->sigs_only)
{
/* can't write output but we hash it anyway to
* check the signature */
rc = handle_plaintext( pt, &c->mfx, 1, clearsig );
}
}
}
if( rc )
log_error( "handle plaintext failed: %s\n", g10_errstr(rc));
free_packet(pkt);
c->last_was_session_key = 0;
/* We add a marker control packet instead of the plaintext packet.
* This is so that we can later detect invalid packet sequences.
*/
n = new_kbnode (create_gpg_control (CTRLPKT_PLAINTEXT_MARK, NULL, 0));
if (c->list)
add_kbnode (c->list, n);
- else
+ else
c->list = n;
}
static int
proc_compressed_cb( IOBUF a, void *info )
{
return proc_signature_packets( info, a, ((CTX)info)->signed_data,
((CTX)info)->sigfilename );
}
static int
proc_encrypt_cb( IOBUF a, void *info )
{
return proc_encryption_packets( info, a );
}
static void
proc_compressed( CTX c, PACKET *pkt )
{
PKT_compressed *zd = pkt->pkt.compressed;
int rc;
/*printf("zip: compressed data packet\n");*/
if( !zd->algorithm )
rc=G10ERR_COMPR_ALGO;
else if( c->sigs_only )
rc = handle_compressed( c, zd, proc_compressed_cb, c );
else if( c->encrypt_only )
rc = handle_compressed( c, zd, proc_encrypt_cb, c );
else
rc = handle_compressed( c, zd, NULL, NULL );
if( rc )
log_error("uncompressing failed: %s\n", g10_errstr(rc));
free_packet(pkt);
c->last_was_session_key = 0;
}
/****************
* check the signature
* Returns: 0 = valid signature or an error code
*/
static int
do_check_sig( CTX c, KBNODE node, int *is_selfsig,
int *is_expkey, int *is_revkey )
{
PKT_signature *sig;
MD_HANDLE md = NULL, md2 = NULL;
int algo, rc;
assert( node->pkt->pkttype == PKT_SIGNATURE );
if( is_selfsig )
*is_selfsig = 0;
sig = node->pkt->pkt.signature;
algo = sig->digest_algo;
if( (rc=check_digest_algo(algo)) )
return rc;
if( sig->sig_class == 0x00 ) {
if( c->mfx.md )
md = md_copy( c->mfx.md );
else /* detached signature */
md = md_open( 0, 0 ); /* signature_check() will enable the md*/
}
else if( sig->sig_class == 0x01 ) {
/* how do we know that we have to hash the (already hashed) text
* in canonical mode ??? (calculating both modes???) */
if( c->mfx.md ) {
md = md_copy( c->mfx.md );
if( c->mfx.md2 )
md2 = md_copy( c->mfx.md2 );
}
else { /* detached signature */
log_debug("Do we really need this here?");
md = md_open( 0, 0 ); /* signature_check() will enable the md*/
md2 = md_open( 0, 0 );
}
}
else if( (sig->sig_class&~3) == 0x10
|| sig->sig_class == 0x18
|| sig->sig_class == 0x1f
|| sig->sig_class == 0x20
|| sig->sig_class == 0x28
- || sig->sig_class == 0x30 ) {
+ || sig->sig_class == 0x30 ) {
if( c->list->pkt->pkttype == PKT_PUBLIC_KEY
|| c->list->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
return check_key_signature( c->list, node, is_selfsig );
}
else if( sig->sig_class == 0x20 ) {
log_error (_("standalone revocation - "
"use \"gpg --import\" to apply\n"));
return G10ERR_NOT_PROCESSED;
}
else {
log_error("invalid root packet for sigclass %02x\n",
sig->sig_class);
return G10ERR_SIG_CLASS;
}
}
else
return G10ERR_SIG_CLASS;
rc = signature_check2( sig, md, NULL, is_expkey, is_revkey, NULL );
if( rc == G10ERR_BAD_SIGN && md2 )
rc = signature_check2( sig, md2, NULL, is_expkey, is_revkey, NULL );
md_close(md);
md_close(md2);
return rc;
}
static void
print_userid( PACKET *pkt )
{
if( !pkt )
BUG();
if( pkt->pkttype != PKT_USER_ID ) {
printf("ERROR: unexpected packet type %d", pkt->pkttype );
return;
}
if( opt.with_colons )
{
if(pkt->pkt.user_id->attrib_data)
printf("%u %lu",
pkt->pkt.user_id->numattribs,
pkt->pkt.user_id->attrib_len);
else
print_string( stdout, pkt->pkt.user_id->name,
pkt->pkt.user_id->len, ':');
}
else
print_utf8_string( stdout, pkt->pkt.user_id->name,
pkt->pkt.user_id->len );
}
/****************
* List the certificate in a user friendly way
*/
static void
list_node( CTX c, KBNODE node )
{
int any=0;
int mainkey;
if( !node )
;
else if( (mainkey = (node->pkt->pkttype == PKT_PUBLIC_KEY) )
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
PKT_public_key *pk = node->pkt->pkt.public_key;
if( opt.with_colons )
{
u32 keyid[2];
keyid_from_pk( pk, keyid );
if( mainkey )
c->trustletter = opt.fast_list_mode?
0 : get_validity_info( pk, NULL );
printf("%s:", mainkey? "pub":"sub" );
if( c->trustletter )
putchar( c->trustletter );
printf(":%u:%d:%08lX%08lX:%s:%s::",
nbits_from_pk( pk ),
pk->pubkey_algo,
(ulong)keyid[0],(ulong)keyid[1],
colon_datestr_from_pk( pk ),
colon_strtime (pk->expiredate) );
if( mainkey && !opt.fast_list_mode )
putchar( get_ownertrust_info (pk) );
putchar(':');
if( node->next && node->next->pkt->pkttype == PKT_RING_TRUST) {
putchar('\n'); any=1;
if( opt.fingerprint )
print_fingerprint( pk, NULL, 0 );
printf("rtv:1:%u:\n",
node->next->pkt->pkt.ring_trust->trustval );
}
}
else
printf("%s %4u%c/%s %s%s",
mainkey? "pub":"sub", nbits_from_pk( pk ),
pubkey_letter( pk->pubkey_algo ), keystr_from_pk( pk ),
datestr_from_pk( pk ), mainkey?" ":"");
if( mainkey ) {
/* and now list all userids with their signatures */
for( node = node->next; node; node = node->next ) {
if( node->pkt->pkttype == PKT_SIGNATURE ) {
if( !any ) {
if( node->pkt->pkt.signature->sig_class == 0x20 )
puts("[revoked]");
else
putchar('\n');
any = 1;
}
list_node(c, node );
}
else if( node->pkt->pkttype == PKT_USER_ID ) {
if( any ) {
if( opt.with_colons )
printf("%s:::::::::",
node->pkt->pkt.user_id->attrib_data?"uat":"uid");
else
printf( "uid%*s", 28, "" );
}
print_userid( node->pkt );
if( opt.with_colons )
putchar(':');
putchar('\n');
if( opt.fingerprint && !any )
print_fingerprint( pk, NULL, 0 );
if( opt.with_colons
&& node->next
&& node->next->pkt->pkttype == PKT_RING_TRUST ) {
printf("rtv:2:%u:\n",
node->next->pkt->pkt.ring_trust?
node->next->pkt->pkt.ring_trust->trustval : 0);
}
any=1;
}
else if( node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
if( !any ) {
putchar('\n');
any = 1;
}
list_node(c, node );
}
}
}
else
{
/* of subkey */
if( pk->is_revoked )
{
printf(" [");
printf(_("revoked: %s"),revokestr_from_pk(pk));
printf("]");
}
else if( pk->expiredate )
{
printf(" [");
printf(_("expires: %s"),expirestr_from_pk(pk));
printf("]");
}
}
if( !any )
putchar('\n');
if( !mainkey && opt.fingerprint > 1 )
print_fingerprint( pk, NULL, 0 );
}
else if( (mainkey = (node->pkt->pkttype == PKT_SECRET_KEY) )
|| node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
PKT_secret_key *sk = node->pkt->pkt.secret_key;
if( opt.with_colons )
{
u32 keyid[2];
keyid_from_sk( sk, keyid );
printf("%s::%u:%d:%08lX%08lX:%s:%s:::",
mainkey? "sec":"ssb",
nbits_from_sk( sk ),
sk->pubkey_algo,
(ulong)keyid[0],(ulong)keyid[1],
colon_datestr_from_sk( sk ),
colon_strtime (sk->expiredate)
/* fixme: add LID */ );
}
else
printf("%s %4u%c/%s %s ", mainkey? "sec":"ssb",
nbits_from_sk( sk ), pubkey_letter( sk->pubkey_algo ),
keystr_from_sk( sk ), datestr_from_sk( sk ));
if( mainkey ) {
/* and now list all userids with their signatures */
for( node = node->next; node; node = node->next ) {
if( node->pkt->pkttype == PKT_SIGNATURE ) {
if( !any ) {
if( node->pkt->pkt.signature->sig_class == 0x20 )
puts("[revoked]");
else
putchar('\n');
any = 1;
}
list_node(c, node );
}
else if( node->pkt->pkttype == PKT_USER_ID ) {
if( any ) {
if( opt.with_colons )
printf("%s:::::::::",
node->pkt->pkt.user_id->attrib_data?"uat":"uid");
else
printf( "uid%*s", 28, "" );
}
print_userid( node->pkt );
if( opt.with_colons )
putchar(':');
putchar('\n');
if( opt.fingerprint && !any )
print_fingerprint( NULL, sk, 0 );
any=1;
}
else if( node->pkt->pkttype == PKT_SECRET_SUBKEY ) {
if( !any ) {
putchar('\n');
any = 1;
}
list_node(c, node );
}
}
}
if( !any )
putchar('\n');
if( !mainkey && opt.fingerprint > 1 )
print_fingerprint( NULL, sk, 0 );
}
else if( node->pkt->pkttype == PKT_SIGNATURE ) {
PKT_signature *sig = node->pkt->pkt.signature;
int is_selfsig = 0;
int rc2=0;
size_t n;
char *p;
int sigrc = ' ';
if( !opt.verbose )
return;
if( sig->sig_class == 0x20 || sig->sig_class == 0x30 )
fputs("rev", stdout);
else
fputs("sig", stdout);
if( opt.check_sigs ) {
fflush(stdout);
switch( (rc2=do_check_sig( c, node, &is_selfsig, NULL, NULL )) ) {
case 0: sigrc = '!'; break;
case G10ERR_BAD_SIGN: sigrc = '-'; break;
- case G10ERR_NO_PUBKEY:
+ case G10ERR_NO_PUBKEY:
case G10ERR_UNU_PUBKEY: sigrc = '?'; break;
default: sigrc = '%'; break;
}
}
else { /* check whether this is a self signature */
u32 keyid[2];
if( c->list->pkt->pkttype == PKT_PUBLIC_KEY
|| c->list->pkt->pkttype == PKT_SECRET_KEY ) {
if( c->list->pkt->pkttype == PKT_PUBLIC_KEY )
keyid_from_pk( c->list->pkt->pkt.public_key, keyid );
else
keyid_from_sk( c->list->pkt->pkt.secret_key, keyid );
if( keyid[0] == sig->keyid[0] && keyid[1] == sig->keyid[1] )
is_selfsig = 1;
}
}
if( opt.with_colons ) {
putchar(':');
if( sigrc != ' ' )
putchar(sigrc);
printf("::%d:%08lX%08lX:%s:%s:", sig->pubkey_algo,
(ulong)sig->keyid[0], (ulong)sig->keyid[1],
colon_datestr_from_sig(sig),
colon_expirestr_from_sig(sig));
if(sig->trust_depth || sig->trust_value)
printf("%d %d",sig->trust_depth,sig->trust_value);
printf(":");
if(sig->trust_regexp)
print_string(stdout,sig->trust_regexp,
strlen(sig->trust_regexp),':');
printf(":");
}
else
printf("%c %s %s ",
sigrc, keystr(sig->keyid), datestr_from_sig(sig));
if( sigrc == '%' )
printf("[%s] ", g10_errstr(rc2) );
else if( sigrc == '?' )
;
else if( is_selfsig ) {
if( opt.with_colons )
putchar(':');
fputs( sig->sig_class == 0x18? "[keybind]":"[selfsig]", stdout);
if( opt.with_colons )
putchar(':');
}
else if( !opt.fast_list_mode ) {
p = get_user_id( sig->keyid, &n );
print_string( stdout, p, n, opt.with_colons );
xfree(p);
}
if( opt.with_colons )
printf(":%02x%c:", sig->sig_class, sig->flags.exportable?'x':'l');
putchar('\n');
}
else
log_error("invalid node with packet of type %d\n", node->pkt->pkttype);
}
int
proc_packets( void *anchor, IOBUF a )
{
int rc;
CTX c = xmalloc_clear( sizeof *c );
c->anchor = anchor;
rc = do_proc_packets( c, a );
xfree( c );
return rc;
}
int
proc_signature_packets( void *anchor, IOBUF a,
STRLIST signedfiles, const char *sigfilename )
{
CTX c = xmalloc_clear( sizeof *c );
int rc;
c->anchor = anchor;
c->sigs_only = 1;
c->signed_data = signedfiles;
c->sigfilename = sigfilename;
rc = do_proc_packets( c, a );
/* If we have not encountered any signature we print an error
messages, send a NODATA status back and return an error code.
Using log_error is required because verify_files does not check
error codes for each file but we want to terminate the process
- with an error. */
+ with an error. */
if (!rc && !c->any_sig_seen)
{
write_status_text (STATUS_NODATA, "4");
log_error (_("no signature found\n"));
rc = G10ERR_NO_DATA;
}
/* Propagate the signature seen flag upward. Do this only on
success so that we won't issue the nodata status several
times. */
if (!rc && c->anchor && c->any_sig_seen)
c->anchor->any_sig_seen = 1;
xfree( c );
return rc;
}
int
proc_encryption_packets( void *anchor, IOBUF a )
{
CTX c = xmalloc_clear( sizeof *c );
int rc;
c->anchor = anchor;
c->encrypt_only = 1;
rc = do_proc_packets( c, a );
xfree( c );
return rc;
}
int
do_proc_packets( CTX c, IOBUF a )
{
PACKET *pkt = xmalloc( sizeof *pkt );
int rc=0;
int any_data=0;
int newpkt;
c->iobuf = a;
init_packet(pkt);
while( (rc=parse_packet(a, pkt)) != -1 ) {
any_data = 1;
if( rc ) {
free_packet(pkt);
/* stop processing when an invalid packet has been encountered
* but don't do so when we are doing a --list-packets. */
if( rc == G10ERR_INVALID_PACKET && opt.list_packets != 2 )
break;
continue;
}
newpkt = -1;
if( opt.list_packets ) {
switch( pkt->pkttype ) {
case PKT_PUBKEY_ENC: proc_pubkey_enc( c, pkt ); break;
case PKT_SYMKEY_ENC: proc_symkey_enc( c, pkt ); break;
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break;
case PKT_COMPRESSED: proc_compressed( c, pkt ); break;
default: newpkt = 0; break;
}
}
else if( c->sigs_only ) {
switch( pkt->pkttype ) {
case PKT_PUBLIC_KEY:
case PKT_SECRET_KEY:
case PKT_USER_ID:
case PKT_SYMKEY_ENC:
case PKT_PUBKEY_ENC:
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC:
write_status_text( STATUS_UNEXPECTED, "0" );
rc = G10ERR_UNEXPECTED;
goto leave;
case PKT_SIGNATURE: newpkt = add_signature( c, pkt ); break;
case PKT_PLAINTEXT: proc_plaintext( c, pkt ); break;
case PKT_COMPRESSED: proc_compressed( c, pkt ); break;
case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break;
case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
default: newpkt = 0; break;
}
}
else if( c->encrypt_only ) {
switch( pkt->pkttype ) {
case PKT_PUBLIC_KEY:
case PKT_SECRET_KEY:
case PKT_USER_ID:
write_status_text( STATUS_UNEXPECTED, "0" );
rc = G10ERR_UNEXPECTED;
goto leave;
case PKT_SIGNATURE: newpkt = add_signature( c, pkt ); break;
case PKT_SYMKEY_ENC: proc_symkey_enc( c, pkt ); break;
case PKT_PUBKEY_ENC: proc_pubkey_enc( c, pkt ); break;
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break;
case PKT_PLAINTEXT: proc_plaintext( c, pkt ); break;
case PKT_COMPRESSED: proc_compressed( c, pkt ); break;
case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break;
case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
default: newpkt = 0; break;
}
}
else {
switch( pkt->pkttype ) {
case PKT_PUBLIC_KEY:
case PKT_SECRET_KEY:
release_list( c );
c->list = new_kbnode( pkt );
newpkt = 1;
break;
case PKT_PUBLIC_SUBKEY:
case PKT_SECRET_SUBKEY:
newpkt = add_subkey( c, pkt );
break;
case PKT_USER_ID: newpkt = add_user_id( c, pkt ); break;
case PKT_SIGNATURE: newpkt = add_signature( c, pkt ); break;
case PKT_PUBKEY_ENC: proc_pubkey_enc( c, pkt ); break;
case PKT_SYMKEY_ENC: proc_symkey_enc( c, pkt ); break;
case PKT_ENCRYPTED:
case PKT_ENCRYPTED_MDC: proc_encrypted( c, pkt ); break;
case PKT_PLAINTEXT: proc_plaintext( c, pkt ); break;
case PKT_COMPRESSED: proc_compressed( c, pkt ); break;
case PKT_ONEPASS_SIG: newpkt = add_onepass_sig( c, pkt ); break;
case PKT_GPG_CONTROL: newpkt = add_gpg_control(c, pkt); break;
case PKT_RING_TRUST: newpkt = add_ring_trust( c, pkt ); break;
default: newpkt = 0; break;
}
}
/* This is a very ugly construct and frankly, I don't remember why
* I used it. Adding the MDC check here is a hack.
* The right solution is to initiate another context for encrypted
* packet and not to reuse the current one ... It works right
* when there is a compression packet inbetween which adds just
* an extra layer.
- * Hmmm: Rewrite this whole module here??
+ * Hmmm: Rewrite this whole module here??
*/
if( pkt->pkttype != PKT_SIGNATURE && pkt->pkttype != PKT_MDC )
c->have_data = pkt->pkttype == PKT_PLAINTEXT;
if( newpkt == -1 )
;
else if( newpkt ) {
pkt = xmalloc( sizeof *pkt );
init_packet(pkt);
}
else
free_packet(pkt);
if ( c->pipemode.stop_now ) {
- /* we won't get an EOF in pipemode, so we have to
- * break the loop here */
+ /* we won't get an EOF in pipemode, so we have to
+ * break the loop here */
rc = -1;
break;
}
}
if( rc == G10ERR_INVALID_PACKET )
write_status_text( STATUS_NODATA, "3" );
if( any_data )
rc = 0;
else if( rc == -1 )
write_status_text( STATUS_NODATA, "2" );
leave:
release_list( c );
xfree(c->dek);
free_packet( pkt );
xfree( pkt );
free_md_filter_context( &c->mfx );
return rc;
}
/* Helper for pka_uri_from_sig to parse the to-be-verified address out
of the notation data. */
static pka_info_t *
get_pka_address (PKT_signature *sig)
{
pka_info_t *pka = NULL;
struct notation *nd,*notation;
notation=sig_to_notation(sig);
for(nd=notation;nd;nd=nd->next)
{
if(strcmp(nd->name,"pka-address@gnupg.org")!=0)
continue; /* Not the notation we want. */
/* For now we only use the first valid PKA notation. In future
we might want to keep additional PKA notations in a linked
list. */
if (is_valid_mailbox (nd->value))
{
pka = xmalloc (sizeof *pka + strlen(nd->value));
pka->valid = 0;
pka->checked = 0;
pka->uri = NULL;
strcpy (pka->email, nd->value);
break;
}
}
free_notation(notation);
return pka;
}
/* Return the URI from a DNS PKA record. If this record has already
be retrieved for the signature we merely return it; if not we go
out and try to get that DNS record. */
static const char *
pka_uri_from_sig (PKT_signature *sig)
{
if (!sig->flags.pka_tried)
{
assert (!sig->pka_info);
sig->flags.pka_tried = 1;
sig->pka_info = get_pka_address (sig);
if (sig->pka_info)
{
char *uri;
uri = get_pka_info (sig->pka_info->email, sig->pka_info->fpr);
if (uri)
{
sig->pka_info->valid = 1;
if (!*uri)
xfree (uri);
else
sig->pka_info->uri = uri;
}
}
}
return sig->pka_info? sig->pka_info->uri : NULL;
}
static int
check_sig_and_print( CTX c, KBNODE node )
{
PKT_signature *sig = node->pkt->pkt.signature;
const char *astr;
int rc, is_expkey=0, is_revkey=0;
if (opt.skip_verify)
{
log_info(_("signature verification suppressed\n"));
return 0;
}
/* Check that the message composition is valid.
Per RFC-2440bis (-15) allowed:
S{1,n} -- detached signature.
S{1,n} P -- old style PGP2 signature
O{1,n} P S{1,n} -- standard OpenPGP signature.
C P S{1,n} -- cleartext signature.
-
+
O = One-Pass Signature packet.
S = Signature packet.
P = OpenPGP Message packet (Encrypted | Compressed | Literal)
(Note that the current rfc2440bis draft also allows
for a signed message but that does not work as it
introduces ambiguities.)
We keep track of these packages using the marker packet
CTRLPKT_PLAINTEXT_MARK.
C = Marker packet for cleartext signatures.
We reject all other messages.
-
+
Actually we are calling this too often, i.e. for verification of
each message but better have some duplicate work than to silently
introduce a bug here.
*/
{
KBNODE n;
int n_onepass, n_sig;
/* log_debug ("checking signature packet composition\n"); */
/* dump_kbnode (c->list); */
n = c->list;
assert (n);
- if ( n->pkt->pkttype == PKT_SIGNATURE )
+ if ( n->pkt->pkttype == PKT_SIGNATURE )
{
/* This is either "S{1,n}" case (detached signature) or
"S{1,n} P" (old style PGP2 signature). */
for (n = n->next; n; n = n->next)
if (n->pkt->pkttype != PKT_SIGNATURE)
break;
if (!n)
; /* Okay, this is a detached signature. */
else if (n->pkt->pkttype == PKT_GPG_CONTROL
&& (n->pkt->pkt.gpg_control->control
== CTRLPKT_PLAINTEXT_MARK) )
{
if (n->next)
goto ambiguous; /* We only allow one P packet. */
}
else
goto ambiguous;
}
- else if (n->pkt->pkttype == PKT_ONEPASS_SIG)
+ else if (n->pkt->pkttype == PKT_ONEPASS_SIG)
{
/* This is the "O{1,n} P S{1,n}" case (standard signature). */
for (n_onepass=1, n = n->next;
n && n->pkt->pkttype == PKT_ONEPASS_SIG; n = n->next)
n_onepass++;
if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
&& (n->pkt->pkt.gpg_control->control
== CTRLPKT_PLAINTEXT_MARK)))
goto ambiguous;
for (n_sig=0, n = n->next;
n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
n_sig++;
if (!n_sig)
goto ambiguous;
/* If we wanted to disallow multiple sig verification, we'd do
something like this:
if (n && !opt.allow_multisig_verification)
goto ambiguous;
However, now that we have --allow-multiple-messages, this
can stay allowable as we can't get here unless multiple
messages (i.e. multiple literals) are allowed. */
if (n_onepass != n_sig)
{
log_info ("number of one-pass packets does not match "
"number of signature packets\n");
goto ambiguous;
}
}
else if (n->pkt->pkttype == PKT_GPG_CONTROL
&& n->pkt->pkt.gpg_control->control == CTRLPKT_CLEARSIGN_START )
{
/* This is the "C P S{1,n}" case (clear text signature). */
n = n->next;
if (!n || !(n->pkt->pkttype == PKT_GPG_CONTROL
&& (n->pkt->pkt.gpg_control->control
== CTRLPKT_PLAINTEXT_MARK)))
goto ambiguous;
for (n_sig=0, n = n->next;
n && n->pkt->pkttype == PKT_SIGNATURE; n = n->next)
n_sig++;
if (n || !n_sig)
goto ambiguous;
}
- else
+ else
{
ambiguous:
log_error(_("can't handle this ambiguous signature data\n"));
return 0;
}
}
/* (Indendation below not yet changed to GNU style.) */
astr = pubkey_algo_to_string( sig->pubkey_algo );
if(keystrlen()>8)
{
log_info(_("Signature made %s\n"),asctimestamp(sig->timestamp));
log_info(_(" using %s key %s\n"),
astr? astr: "?",keystr(sig->keyid));
}
else
log_info(_("Signature made %s using %s key ID %s\n"),
asctimestamp(sig->timestamp), astr? astr: "?",
keystr(sig->keyid));
rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
/* If the key isn't found, check for a preferred keyserver */
if(rc==G10ERR_NO_PUBKEY && sig->flags.pref_ks)
{
const byte *p;
int seq=0;
size_t n;
while((p=enum_sig_subpkt(sig->hashed,SIGSUBPKT_PREF_KS,&n,&seq,NULL)))
{
/* According to my favorite copy editor, in English
grammar, you say "at" if the key is located on a web
page, but "from" if it is located on a keyserver. I'm
not going to even try to make two strings here :) */
log_info(_("Key available at: ") );
print_utf8_string( log_stream(), p, n );
putc( '\n', log_stream() );
if(opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE
&& opt.keyserver_options.options&KEYSERVER_HONOR_KEYSERVER_URL)
{
struct keyserver_spec *spec;
spec=parse_preferred_keyserver(sig);
if(spec)
{
int res;
glo_ctrl.in_auto_key_retrieve++;
res=keyserver_import_keyid(sig->keyid,spec);
glo_ctrl.in_auto_key_retrieve--;
if(!res)
rc=do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
free_keyserver_spec(spec);
if(!rc)
break;
}
}
}
}
/* If the preferred keyserver thing above didn't work, our second
try is to use the URI from a DNS PKA record. */
- if ( rc == G10ERR_NO_PUBKEY
+ if ( rc == G10ERR_NO_PUBKEY
&& opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE
&& opt.keyserver_options.options&KEYSERVER_HONOR_PKA_RECORD)
{
const char *uri = pka_uri_from_sig (sig);
-
+
if (uri)
{
/* FIXME: We might want to locate the key using the
fingerprint instead of the keyid. */
int res;
struct keyserver_spec *spec;
-
+
spec = parse_keyserver_uri (uri, 1, NULL, 0);
if (spec)
{
glo_ctrl.in_auto_key_retrieve++;
res = keyserver_import_keyid (sig->keyid, spec);
glo_ctrl.in_auto_key_retrieve--;
free_keyserver_spec (spec);
if (!res)
rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
}
}
}
/* If the preferred keyserver thing above didn't work and we got
no information from the DNS PKA, this is a third try. */
if( rc == G10ERR_NO_PUBKEY && opt.keyserver
&& opt.keyserver_options.options&KEYSERVER_AUTO_KEY_RETRIEVE)
{
int res;
glo_ctrl.in_auto_key_retrieve++;
res=keyserver_import_keyid ( sig->keyid, opt.keyserver );
glo_ctrl.in_auto_key_retrieve--;
if(!res)
rc = do_check_sig(c, node, NULL, &is_expkey, &is_revkey );
}
if( !rc || rc == G10ERR_BAD_SIGN ) {
KBNODE un, keyblock;
int count=0, statno;
char keyid_str[50];
PKT_public_key *pk=NULL;
if(rc)
statno=STATUS_BADSIG;
else if(sig->flags.expired)
statno=STATUS_EXPSIG;
else if(is_expkey)
statno=STATUS_EXPKEYSIG;
else if(is_revkey)
statno=STATUS_REVKEYSIG;
else
statno=STATUS_GOODSIG;
keyblock = get_pubkeyblock( sig->keyid );
sprintf (keyid_str, "%08lX%08lX [uncertain] ",
(ulong)sig->keyid[0], (ulong)sig->keyid[1]);
/* find and print the primary user ID */
for( un=keyblock; un; un = un->next ) {
char *p;
int valid;
if(un->pkt->pkttype==PKT_PUBLIC_KEY)
{
pk=un->pkt->pkt.public_key;
continue;
}
if( un->pkt->pkttype != PKT_USER_ID )
continue;
if ( !un->pkt->pkt.user_id->created )
continue;
if ( un->pkt->pkt.user_id->is_revoked )
continue;
if ( un->pkt->pkt.user_id->is_expired )
continue;
if ( !un->pkt->pkt.user_id->is_primary )
continue;
/* We want the textual primary user ID here */
if ( un->pkt->pkt.user_id->attrib_data )
continue;
assert(pk);
/* Get it before we print anything to avoid interrupting
the output with the "please do a --check-trustdb"
line. */
valid=get_validity(pk,un->pkt->pkt.user_id);
keyid_str[17] = 0; /* cut off the "[uncertain]" part */
write_status_text_and_buffer (statno, keyid_str,
un->pkt->pkt.user_id->name,
- un->pkt->pkt.user_id->len,
+ un->pkt->pkt.user_id->len,
-1 );
p=utf8_to_native(un->pkt->pkt.user_id->name,
un->pkt->pkt.user_id->len,0);
if(rc)
log_info(_("BAD signature from \"%s\""),p);
else if(sig->flags.expired)
log_info(_("Expired signature from \"%s\""),p);
else
log_info(_("Good signature from \"%s\""),p);
xfree(p);
if(opt.verify_options&VERIFY_SHOW_UID_VALIDITY)
fprintf(log_stream()," [%s]\n",trust_value_to_string(valid));
else
fputs("\n", log_stream() );
count++;
}
if( !count ) { /* just in case that we have no valid textual
userid */
char *p;
/* Try for an invalid textual userid */
for( un=keyblock; un; un = un->next ) {
if( un->pkt->pkttype == PKT_USER_ID &&
!un->pkt->pkt.user_id->attrib_data )
break;
}
/* Try for any userid at all */
if(!un) {
for( un=keyblock; un; un = un->next ) {
if( un->pkt->pkttype == PKT_USER_ID )
break;
}
}
if (opt.trust_model==TM_ALWAYS || !un)
keyid_str[17] = 0; /* cut off the "[uncertain]" part */
write_status_text_and_buffer (statno, keyid_str,
un? un->pkt->pkt.user_id->name:"[?]",
- un? un->pkt->pkt.user_id->len:3,
+ un? un->pkt->pkt.user_id->len:3,
-1 );
if(un)
p=utf8_to_native(un->pkt->pkt.user_id->name,
un->pkt->pkt.user_id->len,0);
else
p=xstrdup("[?]");
if(rc)
log_info(_("BAD signature from \"%s\""),p);
else if(sig->flags.expired)
log_info(_("Expired signature from \"%s\""),p);
else
log_info(_("Good signature from \"%s\""),p);
if (opt.trust_model!=TM_ALWAYS && un)
{
putc(' ', log_stream() );
fputs(_("[uncertain]"), log_stream() );
}
fputs("\n", log_stream() );
}
- /* If we have a good signature and already printed
+ /* If we have a good signature and already printed
* the primary user ID, print all the other user IDs */
if ( count && !rc
&& !(opt.verify_options&VERIFY_SHOW_PRIMARY_UID_ONLY) ) {
char *p;
for( un=keyblock; un; un = un->next ) {
if( un->pkt->pkttype != PKT_USER_ID )
continue;
if((un->pkt->pkt.user_id->is_revoked
|| un->pkt->pkt.user_id->is_expired)
&& !(opt.verify_options&VERIFY_SHOW_UNUSABLE_UIDS))
continue;
/* Only skip textual primaries */
if ( un->pkt->pkt.user_id->is_primary &&
!un->pkt->pkt.user_id->attrib_data )
continue;
if(un->pkt->pkt.user_id->attrib_data)
{
dump_attribs(un->pkt->pkt.user_id,pk,NULL);
if(opt.verify_options&VERIFY_SHOW_PHOTOS)
show_photos(un->pkt->pkt.user_id->attribs,
un->pkt->pkt.user_id->numattribs,
pk,NULL,un->pkt->pkt.user_id);
}
p=utf8_to_native(un->pkt->pkt.user_id->name,
un->pkt->pkt.user_id->len,0);
log_info(_(" aka \"%s\""),p);
xfree(p);
if(opt.verify_options&VERIFY_SHOW_UID_VALIDITY)
{
const char *valid;
if(un->pkt->pkt.user_id->is_revoked)
valid=_("revoked");
else if(un->pkt->pkt.user_id->is_expired)
valid=_("expired");
else
valid=trust_value_to_string(get_validity(pk,
un->pkt->
pkt.user_id));
fprintf(log_stream()," [%s]\n",valid);
}
else
fputs("\n", log_stream() );
}
}
release_kbnode( keyblock );
if( !rc )
{
if(opt.verify_options&VERIFY_SHOW_POLICY_URLS)
show_policy_url(sig,0,1);
else
show_policy_url(sig,0,2);
if(opt.verify_options&VERIFY_SHOW_KEYSERVER_URLS)
show_keyserver_url(sig,0,1);
else
show_keyserver_url(sig,0,2);
if(opt.verify_options&VERIFY_SHOW_NOTATIONS)
show_notation(sig,0,1,
((opt.verify_options&VERIFY_SHOW_STD_NOTATIONS)?1:0)+
((opt.verify_options&VERIFY_SHOW_USER_NOTATIONS)?2:0));
else
show_notation(sig,0,2,0);
}
if( !rc && is_status_enabled() ) {
/* print a status response with the fingerprint */
PKT_public_key *vpk = xmalloc_clear( sizeof *vpk );
if( !get_pubkey( vpk, sig->keyid ) ) {
byte array[MAX_FINGERPRINT_LEN], *p;
char buf[MAX_FINGERPRINT_LEN*4+90], *bufp;
size_t i, n;
bufp = buf;
fingerprint_from_pk( vpk, array, &n );
p = array;
for(i=0; i < n ; i++, p++, bufp += 2)
sprintf(bufp, "%02X", *p );
/* TODO: Replace the reserved '0' in the field below
with bits for status flags (policy url, notation,
etc.). Remember to make the buffer larger to
match! */
sprintf(bufp, " %s %lu %lu %d 0 %d %d %02X ",
strtimestamp( sig->timestamp ),
(ulong)sig->timestamp,(ulong)sig->expiredate,
sig->version,sig->pubkey_algo,sig->digest_algo,
sig->sig_class);
bufp = bufp + strlen (bufp);
if (!vpk->is_primary) {
u32 akid[2];
-
+
akid[0] = vpk->main_keyid[0];
akid[1] = vpk->main_keyid[1];
free_public_key (vpk);
vpk = xmalloc_clear( sizeof *vpk );
if (get_pubkey (vpk, akid)) {
/* impossible error, we simply return a zeroed out fpr */
n = MAX_FINGERPRINT_LEN < 20? MAX_FINGERPRINT_LEN : 20;
memset (array, 0, n);
}
else
fingerprint_from_pk( vpk, array, &n );
}
p = array;
for(i=0; i < n ; i++, p++, bufp += 2)
sprintf(bufp, "%02X", *p );
write_status_text( STATUS_VALIDSIG, buf );
}
free_public_key( vpk );
}
if (!rc)
{
if(opt.verify_options&VERIFY_PKA_LOOKUPS)
pka_uri_from_sig (sig); /* Make sure PKA info is available. */
rc = check_signatures_trust( sig );
}
if(sig->flags.expired)
{
log_info(_("Signature expired %s\n"),
asctimestamp(sig->expiredate));
rc=G10ERR_GENERAL; /* need a better error here? */
}
else if(sig->expiredate)
log_info(_("Signature expires %s\n"),asctimestamp(sig->expiredate));
if(opt.verbose)
log_info(_("%s signature, digest algorithm %s\n"),
sig->sig_class==0x00?_("binary"):
sig->sig_class==0x01?_("textmode"):_("unknown"),
digest_algo_to_string(sig->digest_algo));
if( rc )
g10_errors_seen = 1;
if( opt.batch && rc )
g10_exit(1);
}
else {
char buf[50];
sprintf(buf, "%08lX%08lX %d %d %02x %lu %d",
(ulong)sig->keyid[0], (ulong)sig->keyid[1],
sig->pubkey_algo, sig->digest_algo,
sig->sig_class, (ulong)sig->timestamp, rc );
write_status_text( STATUS_ERRSIG, buf );
if( rc == G10ERR_NO_PUBKEY ) {
buf[16] = 0;
write_status_text( STATUS_NO_PUBKEY, buf );
}
if( rc != G10ERR_NOT_PROCESSED )
log_error(_("Can't check signature: %s\n"), g10_errstr(rc) );
}
return rc;
}
/****************
* Process the tree which starts at node
*/
static void
proc_tree( CTX c, KBNODE node )
{
KBNODE n1;
int rc;
if( opt.list_packets || opt.list_only )
return;
/* we must skip our special plaintext marker packets here becuase
they may be the root packet. These packets are only used in
addionla checks and skipping them here doesn't matter */
while ( node
&& node->pkt->pkttype == PKT_GPG_CONTROL
&& node->pkt->pkt.gpg_control->control
== CTRLPKT_PLAINTEXT_MARK ) {
node = node->next;
}
if (!node)
return;
c->trustletter = ' ';
if( node->pkt->pkttype == PKT_PUBLIC_KEY
|| node->pkt->pkttype == PKT_PUBLIC_SUBKEY ) {
merge_keys_and_selfsig( node );
list_node( c, node );
}
else if( node->pkt->pkttype == PKT_SECRET_KEY ) {
merge_keys_and_selfsig( node );
list_node( c, node );
}
else if( node->pkt->pkttype == PKT_ONEPASS_SIG ) {
/* check all signatures */
if( !c->have_data ) {
free_md_filter_context( &c->mfx );
/* prepare to create all requested message digests */
c->mfx.md = md_open(0, 0);
/* fixme: why looking for the signature packet and not the
one-pass packet? */
for( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); ) {
md_enable( c->mfx.md, n1->pkt->pkt.signature->digest_algo);
}
/* ask for file and hash it */
if( c->sigs_only ) {
rc = hash_datafiles( c->mfx.md, NULL,
c->signed_data, c->sigfilename,
n1? (n1->pkt->pkt.onepass_sig->sig_class == 0x01):0 );
}
else {
rc = ask_for_detached_datafile( c->mfx.md, c->mfx.md2,
iobuf_get_real_fname(c->iobuf),
n1? (n1->pkt->pkt.onepass_sig->sig_class == 0x01):0 );
}
if( rc ) {
log_error("can't hash datafile: %s\n", g10_errstr(rc));
return;
}
}
else if ( c->signed_data ) {
log_error (_("not a detached signature\n") );
return;
}
for( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); )
check_sig_and_print( c, n1 );
}
else if( node->pkt->pkttype == PKT_GPG_CONTROL
&& node->pkt->pkt.gpg_control->control
== CTRLPKT_CLEARSIGN_START ) {
/* clear text signed message */
if( !c->have_data ) {
log_error("cleartext signature without data\n" );
return;
}
else if ( c->signed_data ) {
log_error (_("not a detached signature\n") );
return;
}
-
+
for( n1 = node; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )); )
check_sig_and_print( c, n1 );
}
else if( node->pkt->pkttype == PKT_SIGNATURE ) {
PKT_signature *sig = node->pkt->pkt.signature;
int multiple_ok=1;
n1=find_next_kbnode(node, PKT_SIGNATURE);
if(n1)
{
byte class=sig->sig_class;
byte hash=sig->digest_algo;
for(; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE)))
{
/* We can't currently handle multiple signatures of
different classes or digests (we'd pretty much have
to run a different hash context for each), but if
they are all the same, make an exception. */
if(n1->pkt->pkt.signature->sig_class!=class
|| n1->pkt->pkt.signature->digest_algo!=hash)
{
multiple_ok=0;
log_info(_("WARNING: multiple signatures detected. "
"Only the first will be checked.\n"));
break;
}
}
}
if( sig->sig_class != 0x00 && sig->sig_class != 0x01 )
log_info(_("standalone signature of class 0x%02x\n"),
sig->sig_class);
else if( !c->have_data ) {
/* detached signature */
free_md_filter_context( &c->mfx );
c->mfx.md = md_open(sig->digest_algo, 0);
if( !opt.pgp2_workarounds )
;
else if( sig->digest_algo == DIGEST_ALGO_MD5
&& is_RSA( sig->pubkey_algo ) ) {
/* enable a workaround for a pgp2 bug */
c->mfx.md2 = md_open( DIGEST_ALGO_MD5, 0 );
}
else if( sig->digest_algo == DIGEST_ALGO_SHA1
&& sig->pubkey_algo == PUBKEY_ALGO_DSA
&& sig->sig_class == 0x01 ) {
/* enable the workaround also for pgp5 when the detached
* signature has been created in textmode */
c->mfx.md2 = md_open( sig->digest_algo, 0 );
}
#if 0 /* workaround disabled */
/* Here we have another hack to work around a pgp 2 bug
* It works by not using the textmode for detached signatures;
* this will let the first signature check (on md) fail
* but the second one (on md2) which adds an extra CR should
* then produce the "correct" hash. This is very, very ugly
* hack but it may help in some cases (and break others)
*/
/* c->mfx.md2? 0 :(sig->sig_class == 0x01) */
#endif
if ( DBG_HASHING ) {
md_start_debug( c->mfx.md, "verify" );
if ( c->mfx.md2 )
md_start_debug( c->mfx.md2, "verify2" );
}
if( c->sigs_only ) {
rc = hash_datafiles( c->mfx.md, c->mfx.md2,
c->signed_data, c->sigfilename,
(sig->sig_class == 0x01) );
}
else {
rc = ask_for_detached_datafile( c->mfx.md, c->mfx.md2,
iobuf_get_real_fname(c->iobuf),
(sig->sig_class == 0x01) );
}
if( rc ) {
log_error("can't hash datafile: %s\n", g10_errstr(rc));
return;
}
}
else if ( c->signed_data ) {
log_error (_("not a detached signature\n") );
return;
}
else if ( c->pipemode.op == 'B' )
; /* this is a detached signature trough the pipemode handler */
else if (!opt.quiet)
log_info(_("old style (PGP 2.x) signature\n"));
if(multiple_ok)
for( n1 = node; n1; (n1 = find_next_kbnode(n1, PKT_SIGNATURE )) )
check_sig_and_print( c, n1 );
else
check_sig_and_print( c, node );
}
else {
dump_kbnode (c->list);
log_error(_("invalid root packet detected in proc_tree()\n"));
dump_kbnode (node);
}
}
diff --git a/include/cipher.h b/include/cipher.h
index 2bc57d6e1..9c25605a8 100644
--- a/include/cipher.h
+++ b/include/cipher.h
@@ -1,211 +1,214 @@
/* cipher.h
* Copyright (C) 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007,
* 2008 Free Software Foundation, Inc.
*
* This file is part of GNUPG.
*
* GNUPG is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GNUPG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see .
*/
#ifndef G10_CIPHER_H
#define G10_CIPHER_H
#define DBG_CIPHER g10c_debug_mode
#include "mpi.h"
#include "../cipher/random.h"
#define CIPHER_ALGO_NONE 0
#define CIPHER_ALGO_IDEA 1
#define CIPHER_ALGO_3DES 2
#define CIPHER_ALGO_CAST5 3
#define CIPHER_ALGO_BLOWFISH 4 /* blowfish 128 bit key */
/* 5 & 6 are reserved */
#define CIPHER_ALGO_AES 7
#define CIPHER_ALGO_AES192 8
#define CIPHER_ALGO_AES256 9
#define CIPHER_ALGO_TWOFISH 10 /* twofish 256 bit */
#define CIPHER_ALGO_CAMELLIA128 11
#define CIPHER_ALGO_CAMELLIA192 12
#define CIPHER_ALGO_CAMELLIA256 13
#define CIPHER_ALGO_DUMMY 110 /* no encryption at all */
#define PUBKEY_ALGO_RSA 1
#define PUBKEY_ALGO_RSA_E 2 /* RSA encrypt only */
#define PUBKEY_ALGO_RSA_S 3 /* RSA sign only */
#define PUBKEY_ALGO_ELGAMAL_E 16 /* encrypt only ElGamal (but not for v3)*/
#define PUBKEY_ALGO_DSA 17
+#define PUBKEY_ALGO_ECDH 18
+#define PUBKEY_ALGO_ECDSA 19
#define PUBKEY_ALGO_ELGAMAL 20 /* sign and encrypt elgamal */
+
#define PUBKEY_USAGE_SIG 1 /* key is good for signatures */
#define PUBKEY_USAGE_ENC 2 /* key is good for encryption */
#define PUBKEY_USAGE_CERT 4 /* key is also good to certify other keys*/
#define PUBKEY_USAGE_AUTH 8 /* key is good for authentication */
#define PUBKEY_USAGE_UNKNOWN 128 /* key has an unknown usage bit */
#define DIGEST_ALGO_MD5 1
#define DIGEST_ALGO_SHA1 2
#define DIGEST_ALGO_RMD160 3
/* 4, 5, 6, and 7 are reserved */
#define DIGEST_ALGO_SHA256 8
#define DIGEST_ALGO_SHA384 9
#define DIGEST_ALGO_SHA512 10
#define DIGEST_ALGO_SHA224 11
#define COMPRESS_ALGO_NONE 0
#define COMPRESS_ALGO_ZIP 1
#define COMPRESS_ALGO_ZLIB 2
#define COMPRESS_ALGO_BZIP2 3
#define is_RSA(a) ((a)==PUBKEY_ALGO_RSA || (a)==PUBKEY_ALGO_RSA_E \
|| (a)==PUBKEY_ALGO_RSA_S )
#define is_ELGAMAL(a) ((a)==PUBKEY_ALGO_ELGAMAL_E)
#define is_DSA(a) ((a)==PUBKEY_ALGO_DSA)
typedef struct
{
int algo;
int keylen;
int algo_info_printed;
int use_mdc;
int symmetric;
byte key[32]; /* this is the largest used keylen (256 bit) */
} DEK;
struct cipher_handle_s;
typedef struct cipher_handle_s *CIPHER_HANDLE;
#define CIPHER_MODE_ECB 1
#define CIPHER_MODE_CFB 2
#define CIPHER_MODE_PHILS_CFB 3
#define CIPHER_MODE_AUTO_CFB 4
#define CIPHER_MODE_DUMMY 5 /* used with algo DUMMY for no encryption */
#define CIPHER_MODE_CBC 6
struct md_digest_list_s;
struct gcry_md_context {
int secure;
FILE *debug;
int finalized;
struct md_digest_list_s *list;
int bufcount;
int bufsize;
byte buffer[1];
};
typedef struct gcry_md_context *MD_HANDLE;
#ifndef EXTERN_UNLESS_MAIN_MODULE
#if defined (__riscos__) && !defined (INCLUDED_BY_MAIN_MODULE)
#define EXTERN_UNLESS_MAIN_MODULE extern
#else
-#define EXTERN_UNLESS_MAIN_MODULE
+#define EXTERN_UNLESS_MAIN_MODULE
#endif
#endif
EXTERN_UNLESS_MAIN_MODULE int g10c_debug_mode;
EXTERN_UNLESS_MAIN_MODULE int g10_opt_verbose;
EXTERN_UNLESS_MAIN_MODULE const char *g10_opt_homedir;
/*-- dynload.c --*/
void register_cipher_extension( const char *mainpgm, const char *fname );
/*-- md.c --*/
int string_to_digest_algo( const char *string );
const char * digest_algo_to_string( int algo );
int check_digest_algo( int algo );
MD_HANDLE md_open( int algo, int secure );
void md_enable( MD_HANDLE hd, int algo );
MD_HANDLE md_copy( MD_HANDLE a );
void md_reset( MD_HANDLE a );
void md_close(MD_HANDLE a);
void md_write( MD_HANDLE a, const byte *inbuf, size_t inlen);
void md_final(MD_HANDLE a);
byte *md_read( MD_HANDLE a, int algo );
int md_digest( MD_HANDLE a, int algo, byte *buffer, int buflen );
int md_get_algo( MD_HANDLE a );
int md_algo_present( MD_HANDLE a, int algo );
int md_digest_length( int algo );
const byte *md_asn_oid( int algo, size_t *asnlen, size_t *mdlen );
void md_start_debug( MD_HANDLE a, const char *suffix );
void md_stop_debug( MD_HANDLE a );
#define md_is_secure(a) ((a)->secure)
#define md_putc(h,c) \
do { \
if( (h)->bufcount == (h)->bufsize ) \
md_write( (h), NULL, 0 ); \
(h)->buffer[(h)->bufcount++] = (c) & 0xff; \
} while(0)
void rmd160_hash_buffer (char *outbuf, const char *buffer, size_t length);
/*-- cipher.c --*/
int string_to_cipher_algo( const char *string );
const char * cipher_algo_to_string( int algo );
void disable_cipher_algo( int algo );
int check_cipher_algo( int algo );
unsigned cipher_get_keylen( int algo );
unsigned cipher_get_blocksize( int algo );
CIPHER_HANDLE cipher_open( int algo, int mode, int secure );
void cipher_close( CIPHER_HANDLE c );
int cipher_setkey( CIPHER_HANDLE c, byte *key, unsigned keylen );
void cipher_setiv( CIPHER_HANDLE c, const byte *iv, unsigned ivlen );
void cipher_encrypt( CIPHER_HANDLE c, byte *out, byte *in, unsigned nbytes );
void cipher_decrypt( CIPHER_HANDLE c, byte *out, byte *in, unsigned nbytes );
void cipher_sync( CIPHER_HANDLE c );
/*-- pubkey.c --*/
#define PUBKEY_MAX_NPKEY 4
#define PUBKEY_MAX_NSKEY 6
#define PUBKEY_MAX_NSIG 2
#define PUBKEY_MAX_NENC 2
int string_to_pubkey_algo( const char *string );
const char * pubkey_algo_to_string( int algo );
void disable_pubkey_algo( int algo );
int check_pubkey_algo( int algo );
int check_pubkey_algo2( int algo, unsigned use );
int pubkey_get_npkey( int algo );
int pubkey_get_nskey( int algo );
int pubkey_get_nsig( int algo );
int pubkey_get_nenc( int algo );
unsigned pubkey_nbits( int algo, MPI *pkey );
int pubkey_generate( int algo, unsigned nbits, MPI *skey, MPI **retfactors );
int dsa2_generate( int algo, unsigned nbits, unsigned qbits,
MPI *skey, MPI **retfactors );
int pubkey_check_secret_key( int algo, MPI *skey );
int pubkey_encrypt( int algo, MPI *resarr, MPI data, MPI *pkey );
int pubkey_decrypt( int algo, MPI *result, MPI *data, MPI *skey );
int pubkey_sign( int algo, MPI *resarr, MPI hash, MPI *skey );
int pubkey_verify( int algo, MPI hash, MPI *data, MPI *pkey );
/*-- smallprime.c --*/
extern ushort small_prime_numbers[];
/*-- primegen.c --*/
void register_primegen_progress ( void (*cb)( void *, int), void *cb_data );
MPI generate_secret_prime( unsigned nbits );
MPI generate_public_prime( unsigned nbits );
MPI generate_elg_prime( int mode, unsigned pbits, unsigned qbits,
MPI g, MPI **factors );
/*-- elsewhere --*/
void register_pk_dsa_progress ( void (*cb)( void *, int), void *cb_data );
void register_pk_elg_progress ( void (*cb)( void *, int), void *cb_data );
#endif /*G10_CIPHER_H*/