Page MenuHome GnuPG

No OneTemporary

diff --git a/scd/ChangeLog b/scd/ChangeLog
index b06603315..e0cfda805 100644
--- a/scd/ChangeLog
+++ b/scd/ChangeLog
@@ -1,49 +1,71 @@
+2002-08-09 Werner Koch <wk@gnupg.org>
+
+ * card.c (card_get_serial_and_stamp): Use the tokeinfo serial
+ number as a fallback. Add a special prefix for serial numbers.
+
+2002-07-30 Werner Koch <wk@gnupg.org>
+
+ Changes to cope with OpenSC 0.7.0:
+
+ * card.c: Removed the check for the packed opensc version.
+ Changed include file names of opensc.
+ (map_sc_err): Adjusted error codes for new opensc version.
+ * card-p15.c: Changed include filename of opensc.
+ * card-dinsig.c: Ditto.
+
+ * card-p15.c (p15_decipher): Add flags argument to OpenSC call.
+
+2002-07-24 Werner Koch <wk@gnupg.org>
+
+ * card.c (find_simple_tlv, find_iccsn): New.
+ (card_get_serial_and_stamp): Improved serial number parser.
+
2002-06-27 Werner Koch <wk@gnupg.org>
* scdaemon.c (main): Use GNUPG_DEFAULT_HOMEDIR constant.
2002-06-15 Werner Koch <wk@gnupg.org>
* card-dinsig.c: Documented some stuff from the DIN norm.
2002-04-15 Werner Koch <wk@gnupg.org>
* command.c (cmd_pksign, cmd_pkdecrypt): Use a copy of the key ID.
2002-04-12 Werner Koch <wk@gnupg.org>
* scdaemon.c: New option --debug-sc N.
* card.c (card_open): set it here.
* card-p15.c (p15_prepare_key): Factored out common code from ...
(p15_sign, p15_decipher): here and made the decryption work the
regular way.
2002-04-10 Werner Koch <wk@gnupg.org>
* card.c (card_open): Return immediately when no reader is available.
2002-03-27 Werner Koch <wk@gnupg.org>
* card.c (card_open, card_close): Adjusted for changes in OpenSC.
2002-03-10 Werner Koch <wk@gnupg.org>
* card-p15.c, card-dinsig.c, card-common.h: New.
* card.c: Factored most code out to the new modules, so that we
can better support different types of card applications.
2002-01-26 Werner Koch <wk@gnupg.org>
* scdaemon.c scdaemon.h, command.c: New. Based on the code from
the gpg-agent.
Copyright 2002 Free Software Foundation, Inc.
This file is free software; as a special exception the author gives
unlimited permission to copy and/or distribute it, with or without
modifications, as long as this notice is preserved.
This file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
diff --git a/scd/card-dinsig.c b/scd/card-dinsig.c
index 4080350c6..161d5dbfc 100644
--- a/scd/card-dinsig.c
+++ b/scd/card-dinsig.c
@@ -1,256 +1,256 @@
/* card-dinsig.c - German signature law (DINSIG) functions
* Copyright (C) 2002 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/* The German signature law and its bylaw (SigG and SigV) is currently
used with an interface specification described in DIN V 66291-1.
The AID to be used is: 'D27600006601'.
The file IDs for certificates utilize the generic format:
Cxyz
C being the hex digit 'C' (12).
x being the service indicator:
'0' := SigG conform digital signature.
'1' := entity authentication.
'2' := key encipherment.
'3' := data encipherment.
'4' := key agreement.
other values are reserved for future use.
y being the security environment number using '0' for cards
not supporting a SE number.
z being the certificate type:
'0' := C.CH (base certificate of ard holder) or C.ICC.
'1' .. '7' := C.CH (business or professional certificate
of card holder.
'8' .. 'D' := C.CA (certificate of a CA issue by the Root-CA).
'E' := C.RCA (self certified certificate of the Root-CA).
'F' := reserved.
The file IDs used by default are:
'1F00' EF.SSD (security service descriptor). [o,o]
'2F02' EF.GDO (global data objects) [m,m]
'A000' EF.PROT (signature log). Cyclic file with 20 records of 53 byte.
Read and update after user authentication. [o,o]
'B000' EF.PK.RCA.DS (public keys of Root-CA). Size is 512b or size
of keys. [m (unless a 'C00E' is present),m]
'B001' EF.PK.CA.DS (public keys of CAs). Size is 512b or size
of keys. [o,o]
'C00n' EF.C.CH.DS (digital signature certificate of card holder)
with n := 0 .. 7. Size is 2k or size of cert. Read and
update allowed after user authentication. [m,m]
'C00m' EF.C.CA.DS (digital signature certificate of CA)
with m := 8 .. E. Size is 1k or size of cert. Read always
allowed, update after uder authentication. [o,o]
'C100' EF.C.ICC.AUT (AUT certificate of ICC) [o,m]
'C108' EF.C.CA.AUT (AUT certificate of CA) [o,m]
'D000' EF.DM (display message) [-,m]
The letters in brackets indicate optional or mandatory files: The
first for card terminals under full control and the second for
"business" card terminals.
FIXME: Needs a lot more explanation.
*/
#include <config.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
-#include <opensc-pkcs15.h>
+#include <opensc/pkcs15.h>
#include <ksba.h>
#include "scdaemon.h"
#include "card-common.h"
static int dinsig_read_cert (CARD card, const char *certidstr,
unsigned char **cert, size_t *ncert);
/* See card.c for interface description. Frankly we don't do any real
enumeration but just check whether the well know files are
available. */
static int
dinsig_enum_keypairs (CARD card, int idx,
unsigned char *keygrip, char **keyid)
{
int rc;
unsigned char *buf;
size_t buflen;
KsbaError krc;
KsbaCert cert;
/* fixme: We should locate the application via the EF(DIR) and not
assume a Netkey card */
if (!idx)
rc = dinsig_read_cert (card, "DINSIG-DF01.C000", &buf, &buflen);
else if (idx == 1)
rc = dinsig_read_cert (card, "DINSIG-DF01.C200", &buf, &buflen);
else
rc = -1;
if (rc)
return rc;
cert = ksba_cert_new ();
if (!cert)
{
xfree (buf);
return GNUPG_Out_Of_Core;
}
krc = ksba_cert_init_from_mem (cert, buf, buflen);
xfree (buf);
if (krc)
{
log_error ("failed to parse the certificate at idx %d: %s\n",
idx, ksba_strerror (krc));
ksba_cert_release (cert);
return GNUPG_Card_Error;
}
if (card_help_get_keygrip (cert, keygrip))
{
log_error ("failed to calculate the keygrip at index %d\n", idx);
ksba_cert_release (cert);
return GNUPG_Card_Error;
}
ksba_cert_release (cert);
/* return the iD */
if (keyid)
{
*keyid = xtrymalloc (17);
if (!*keyid)
return GNUPG_Out_Of_Core;
if (!idx)
strcpy (*keyid, "DINSIG-DF01.C000");
else
strcpy (*keyid, "DINSIG-DF01.C200");
}
return 0;
}
/* See card.c for interface description */
static int
dinsig_read_cert (CARD card, const char *certidstr,
unsigned char **cert, size_t *ncert)
{
int rc;
struct sc_path path;
struct sc_file *file;
unsigned char *buf;
int buflen;
if (!strcmp (certidstr, "DINSIG-DF01.C000"))
sc_format_path ("3F00DF01C000", &path);
else if (!strcmp (certidstr, "DINSIG-DF01.C200"))
sc_format_path ("3F00DF01C200", &path);
else
return GNUPG_Invalid_Id;
rc = sc_select_file (card->scard, &path, &file);
if (rc)
{
log_error ("sc_select_file failed: %s\n", sc_strerror (rc));
return map_sc_err (rc);
}
if (file->type != SC_FILE_TYPE_WORKING_EF
|| file->ef_structure != SC_FILE_EF_TRANSPARENT)
{
log_error ("wrong type or structure of certificate EF\n");
sc_file_free (file);
return GNUPG_Card_Error;
}
if (file->size < 20) /* check against a somewhat arbitrary length */
{
log_error ("certificate EF too short\n");
sc_file_free (file);
return GNUPG_Card_Error;
}
buf = xtrymalloc (file->size);
if (!buf)
{
sc_file_free (file);
return GNUPG_Out_Of_Core;
}
rc = sc_read_binary (card->scard, 0, buf, file->size, 0);
if (rc >= 0 && rc != file->size)
{
log_error ("short read on certificate EF\n");
sc_file_free (file);
xfree (buf);
return GNUPG_Card_Error;
}
sc_file_free (file);
if (rc < 0)
{
log_error ("error reading certificate EF: %s\n", sc_strerror (rc));
xfree (buf);
return map_sc_err (rc);
}
buflen = rc;
/* The object is not a plain certificate but wrapped into id-at
userCertificate - fixme: we should check the specs and decided
whether libksba should support it */
if (buflen > 9 && buf[0] == 0x30 && buf[4] == 6 && buf[5] == 3
&& buf[6] == 0x55 && buf[7] == 4 && buf[8] == 0x24)
{
/* We have to strip the padding. Although this is a good idea
anyway, we have to do it due to a KSBA problem; KSBA does not
work correct when the buffer is larger than the ASN.1
structure and the certificates here are padded with FF. So
as a workaround we look at the outer structure to get the
size of the entire thing and adjust the buflen. We can only
do this when there is a 2 byte length field */
size_t seqlen;
if (buf[1] == 0x82)
{
seqlen = ((buf[2] << 8) | buf[3]) + 4;
if (seqlen < buflen)
buflen = seqlen;
}
memmove (buf, buf+9, buflen-9);
buflen -= 9;
}
*cert = buf;
*ncert = buflen;
return 0;
}
/* Bind our operations to the card */
void
card_dinsig_bind (CARD card)
{
card->fnc.enum_keypairs = dinsig_enum_keypairs;
card->fnc.read_cert = dinsig_read_cert;
}
diff --git a/scd/card-p15.c b/scd/card-p15.c
index a70bc665e..6248ddfe2 100644
--- a/scd/card-p15.c
+++ b/scd/card-p15.c
@@ -1,377 +1,378 @@
/* card-p15.c - PKCS-15 based card access
* Copyright (C) 2002 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include <config.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
-#include <opensc-pkcs15.h>
+#include <opensc/pkcs15.h>
#include <ksba.h>
#include "scdaemon.h"
#include "card-common.h"
/* See card.c for interface description */
static int
p15_enum_keypairs (CARD card, int idx,
unsigned char *keygrip, char **keyid)
{
int rc;
KsbaError krc;
struct sc_pkcs15_object *objs[32], *tmpobj;
int nobjs;
struct sc_pkcs15_prkey_info *pinfo;
struct sc_pkcs15_cert_info *certinfo;
struct sc_pkcs15_cert *certder;
KsbaCert cert;
rc = sc_pkcs15_get_objects (card->p15card, SC_PKCS15_TYPE_PRKEY_RSA,
objs, DIM (objs));
if (rc < 0)
{
log_error ("private keys enumeration failed: %s\n", sc_strerror (rc));
return GNUPG_Card_Error;
}
nobjs = rc;
rc = 0;
if (idx >= nobjs)
return -1;
pinfo = objs[idx]->data;
/* now we need to read the certificate so that we can calculate the
keygrip */
rc = sc_pkcs15_find_cert_by_id (card->p15card, &pinfo->id, &tmpobj);
if (rc)
{
log_info ("certificate for private key %d not found: %s\n",
idx, sc_strerror (rc));
/* note, that we return the ID anyway */
rc = GNUPG_Missing_Certificate;
goto return_keyid;
}
certinfo = tmpobj->data;
rc = sc_pkcs15_read_certificate (card->p15card, certinfo, &certder);
if (rc)
{
log_info ("failed to read certificate for private key %d: %s\n",
idx, sc_strerror (rc));
return GNUPG_Card_Error;
}
cert = ksba_cert_new ();
if (!cert)
{
sc_pkcs15_free_certificate (certder);
return GNUPG_Out_Of_Core;
}
krc = ksba_cert_init_from_mem (cert, certder->data, certder->data_len);
sc_pkcs15_free_certificate (certder);
if (krc)
{
log_error ("failed to parse the certificate for private key %d: %s\n",
idx, ksba_strerror (krc));
ksba_cert_release (cert);
return GNUPG_Card_Error;
}
if (card_help_get_keygrip (cert, keygrip))
{
log_error ("failed to calculate the keygrip of private key %d\n", idx);
ksba_cert_release (cert);
return GNUPG_Card_Error;
}
ksba_cert_release (cert);
rc = 0;
return_keyid:
if (keyid)
{
char *p;
int i;
*keyid = p = xtrymalloc (9+pinfo->id.len*2+1);
if (!*keyid)
return GNUPG_Out_Of_Core;
p = stpcpy (p, "P15-5015.");
for (i=0; i < pinfo->id.len; i++, p += 2)
sprintf (p, "%02X", pinfo->id.value[i]);
*p = 0;
}
return rc;
}
static int
idstr_to_id (const char *idstr, struct sc_pkcs15_id *id)
{
const char *s;
int n;
/* For now we only support the standard DF */
if (strncmp (idstr, "P15-5015.", 9) )
return GNUPG_Invalid_Id;
for (s=idstr+9, n=0; hexdigitp (s); s++, n++)
;
if (*s || (n&1))
return GNUPG_Invalid_Id; /* invalid or odd number of digits */
n /= 2;
if (!n || n > SC_PKCS15_MAX_ID_SIZE)
return GNUPG_Invalid_Id; /* empty or too large */
for (s=idstr+9, n=0; *s; s += 2, n++)
id->value[n] = xtoi_2 (s);
id->len = n;
return 0;
}
/* See card.c for interface description */
static int
p15_read_cert (CARD card, const char *certidstr,
unsigned char **cert, size_t *ncert)
{
struct sc_pkcs15_object *tmpobj;
struct sc_pkcs15_id certid;
struct sc_pkcs15_cert_info *certinfo;
struct sc_pkcs15_cert *certder;
int rc;
if (!card || !certidstr || !cert || !ncert)
return GNUPG_Invalid_Value;
if (!card->p15card)
return GNUPG_No_PKCS15_App;
rc = idstr_to_id (certidstr, &certid);
if (rc)
return rc;
rc = sc_pkcs15_find_cert_by_id (card->p15card, &certid, &tmpobj);
if (rc)
{
log_info ("certificate '%s' not found: %s\n",
certidstr, sc_strerror (rc));
return -1;
}
certinfo = tmpobj->data;
rc = sc_pkcs15_read_certificate (card->p15card, certinfo, &certder);
if (rc)
{
log_info ("failed to read certificate '%s': %s\n",
certidstr, sc_strerror (rc));
return GNUPG_Card_Error;
}
*cert = xtrymalloc (certder->data_len);
if (!*cert)
{
sc_pkcs15_free_certificate (certder);
return GNUPG_Out_Of_Core;
}
memcpy (*cert, certder->data, certder->data_len);
*ncert = certder->data_len;
sc_pkcs15_free_certificate (certder);
return 0;
}
static int
p15_prepare_key (CARD card, const char *keyidstr,
int (pincb)(void*, const char *, char **),
void *pincb_arg, struct sc_pkcs15_object **r_keyobj)
{
struct sc_pkcs15_id keyid;
struct sc_pkcs15_pin_info *pin;
struct sc_pkcs15_object *keyobj, *pinobj;
char *pinvalue;
int rc;
rc = idstr_to_id (keyidstr, &keyid);
if (rc)
return rc;
rc = sc_pkcs15_find_prkey_by_id (card->p15card, &keyid, &keyobj);
if (rc < 0)
{
log_error ("private key not found: %s\n", sc_strerror(rc));
return GNUPG_No_Secret_Key;
}
rc = sc_pkcs15_find_pin_by_auth_id (card->p15card,
&keyobj->auth_id, &pinobj);
if (rc)
{
log_error ("failed to find PIN by auth ID: %s\n", sc_strerror (rc));
return GNUPG_Bad_PIN_Method;
}
pin = pinobj->data;
/* Fixme: pack this into a verification loop */
/* Fixme: we might want to pass pin->min_length and
pin->stored_length */
rc = pincb (pincb_arg, pinobj->label, &pinvalue);
if (rc)
{
log_info ("PIN callback returned error: %s\n", gnupg_strerror (rc));
return rc;
}
rc = sc_pkcs15_verify_pin (card->p15card, pin,
pinvalue, strlen (pinvalue));
xfree (pinvalue);
if (rc)
{
log_info ("PIN verification failed: %s\n", sc_strerror (rc));
return GNUPG_Bad_PIN;
}
/* fixme: check wheter we need to release KEYOBJ in case of an error */
*r_keyobj = keyobj;
return 0;
}
/* See card.c for interface description */
static int
p15_sign (CARD card, const char *keyidstr, int hashalgo,
int (pincb)(void*, const char *, char **),
void *pincb_arg,
const void *indata, size_t indatalen,
void **outdata, size_t *outdatalen )
{
unsigned int cryptflags;
struct sc_pkcs15_object *keyobj;
int rc;
unsigned char *outbuf = NULL;
size_t outbuflen;
if (hashalgo != GCRY_MD_SHA1)
return GNUPG_Unsupported_Algorithm;
rc = p15_prepare_key (card, keyidstr, pincb, pincb_arg, &keyobj);
if (rc)
return rc;
cryptflags = SC_ALGORITHM_RSA_PAD_PKCS1;
outbuflen = 1024;
outbuf = xtrymalloc (outbuflen);
if (!outbuf)
return GNUPG_Out_Of_Core;
rc = sc_pkcs15_compute_signature (card->p15card, keyobj,
cryptflags,
indata, indatalen,
outbuf, outbuflen );
if (rc < 0)
{
log_error ("failed to create signature: %s\n", sc_strerror (rc));
rc = GNUPG_Card_Error;
}
else
{
*outdatalen = rc;
*outdata = outbuf;
outbuf = NULL;
rc = 0;
}
xfree (outbuf);
return rc;
}
/* See card.c for description */
static int
p15_decipher (CARD card, const char *keyidstr,
int (pincb)(void*, const char *, char **),
void *pincb_arg,
const void *indata, size_t indatalen,
void **outdata, size_t *outdatalen )
{
struct sc_pkcs15_object *keyobj;
int rc;
unsigned char *outbuf = NULL;
size_t outbuflen;
rc = p15_prepare_key (card, keyidstr, pincb, pincb_arg, &keyobj);
if (rc)
return rc;
if (card && card->scard && card->scard->driver
&& !strcasecmp (card->scard->driver->short_name, "tcos"))
{
/* very ugly hack to force the use of a local key. We need this
until we have fixed the initialization code for TCOS cards */
struct sc_pkcs15_prkey_info *prkey = keyobj->data;
if ( !(prkey->key_reference & 0x80))
{
prkey->key_reference |= 0x80;
log_debug ("using TCOS hack to force the use of local keys\n");
}
if (*keyidstr && keyidstr[strlen(keyidstr)-1] == '6')
{
prkey->key_reference |= 1;
log_debug ("warning: using even more TCOS hacks\n");
}
}
outbuflen = indatalen < 256? 256 : indatalen;
outbuf = xtrymalloc (outbuflen);
if (!outbuf)
return GNUPG_Out_Of_Core;
rc = sc_pkcs15_decipher (card->p15card, keyobj,
+ 0,
indata, indatalen,
outbuf, outbuflen);
if (rc < 0)
{
log_error ("failed to decipher the data: %s\n", sc_strerror (rc));
rc = GNUPG_Card_Error;
}
else
{
*outdatalen = rc;
*outdata = outbuf;
outbuf = NULL;
rc = 0;
}
xfree (outbuf);
return rc;
}
/* Bind our operations to the card */
void
card_p15_bind (CARD card)
{
card->fnc.enum_keypairs = p15_enum_keypairs;
card->fnc.read_cert = p15_read_cert;
card->fnc.sign = p15_sign;
card->fnc.decipher = p15_decipher;
}
diff --git a/scd/card.c b/scd/card.c
index d17ae1947..9c22867a1 100644
--- a/scd/card.c
+++ b/scd/card.c
@@ -1,422 +1,505 @@
/* card.c - SCdaemon card functions
* Copyright (C) 2002 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include <config.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
-#include <opensc-pkcs15.h>
+#include <opensc/pkcs15.h>
#include <ksba.h>
-#if SC_MAX_SEC_ATTR_SIZE < 36
-# error This is not the patched OpenSC version
-#endif
-
#include "scdaemon.h"
#include "card-common.h"
/* Map the SC error codes to the GNUPG ones */
int
map_sc_err (int rc)
{
switch (rc)
{
case 0: rc = 0; break;
- case SC_ERROR_CMD_TOO_SHORT: rc = GNUPG_Card_Error; break;
- case SC_ERROR_CMD_TOO_LONG: rc = GNUPG_Card_Error; break;
case SC_ERROR_NOT_SUPPORTED: rc = GNUPG_Not_Supported; break;
- case SC_ERROR_TRANSMIT_FAILED: rc = GNUPG_Card_Error; break;
- case SC_ERROR_FILE_NOT_FOUND: rc = GNUPG_Card_Error; break;
- case SC_ERROR_INVALID_ARGUMENTS: rc = GNUPG_Card_Error; break;
case SC_ERROR_PKCS15_APP_NOT_FOUND: rc = GNUPG_No_PKCS15_App; break;
- case SC_ERROR_REQUIRED_PARAMETER_NOT_FOUND: rc = GNUPG_Card_Error; break;
case SC_ERROR_OUT_OF_MEMORY: rc = GNUPG_Out_Of_Core; break;
- case SC_ERROR_NO_READERS_FOUND: rc = GNUPG_Card_Error; break;
- case SC_ERROR_OBJECT_NOT_VALID: rc = GNUPG_Card_Error; break;
- case SC_ERROR_ILLEGAL_RESPONSE: rc = GNUPG_Card_Error; break;
- case SC_ERROR_PIN_CODE_INCORRECT: rc = GNUPG_Card_Error; break;
- case SC_ERROR_SECURITY_STATUS_NOT_SATISFIED: rc = GNUPG_Card_Error; break;
- case SC_ERROR_CONNECTING_TO_RES_MGR: rc = GNUPG_Card_Error; break;
- case SC_ERROR_INVALID_ASN1_OBJECT: rc = GNUPG_Card_Error; break;
- case SC_ERROR_BUFFER_TOO_SMALL: rc = GNUPG_Card_Error; break;
case SC_ERROR_CARD_NOT_PRESENT: rc = GNUPG_Card_Not_Present; break;
- case SC_ERROR_RESOURCE_MANAGER: rc = GNUPG_Card_Error; break;
case SC_ERROR_CARD_REMOVED: rc = GNUPG_Card_Removed; break;
- case SC_ERROR_INVALID_PIN_LENGTH: rc = GNUPG_Card_Error; break;
- case SC_ERROR_UNKNOWN_SMARTCARD: rc = GNUPG_Card_Error; break;
- case SC_ERROR_UNKNOWN_REPLY: rc = GNUPG_Card_Error; break;
- case SC_ERROR_OBJECT_NOT_FOUND: rc = GNUPG_Card_Error; break;
- case SC_ERROR_CARD_RESET: rc = GNUPG_Card_Reset; break;
- case SC_ERROR_ASN1_OBJECT_NOT_FOUND: rc = GNUPG_Card_Error; break;
- case SC_ERROR_ASN1_END_OF_CONTENTS: rc = GNUPG_Card_Error; break;
- case SC_ERROR_TOO_MANY_OBJECTS: rc = GNUPG_Card_Error; break;
case SC_ERROR_INVALID_CARD: rc = GNUPG_Invalid_Card; break;
- case SC_ERROR_WRONG_LENGTH: rc = GNUPG_Card_Error; break;
- case SC_ERROR_RECORD_NOT_FOUND: rc = GNUPG_Card_Error; break;
- case SC_ERROR_INTERNAL: rc = GNUPG_Card_Error; break;
default: rc = GNUPG_Card_Error; break;
}
return rc;
}
/* Get the keygrip from CERT, return 0 on success */
int
card_help_get_keygrip (KsbaCert cert, unsigned char *array)
{
GCRY_SEXP s_pkey;
int rc;
KsbaSexp p;
size_t n;
p = ksba_cert_get_public_key (cert);
if (!p)
return -1; /* oops */
n = gcry_sexp_canon_len (p, 0, NULL, NULL);
if (!n)
return -1; /* libksba did not return a proper S-expression */
rc = gcry_sexp_sscan ( &s_pkey, NULL, p, n);
xfree (p);
if (rc)
return -1; /* can't parse that S-expression */
array = gcry_pk_get_keygrip (s_pkey, array);
gcry_sexp_release (s_pkey);
if (!array)
return -1; /* failed to calculate the keygrip */
return 0;
}
/* Create a new context for the card and figures out some basic
information of the card. Detects whgether a PKCS_15 application is
stored.
Common errors: GNUPG_Card_Not_Present */
int
card_open (CARD *rcard)
{
CARD card;
int rc;
card = xtrycalloc (1, sizeof *card);
if (!card)
return GNUPG_Out_Of_Core;
card->reader = 0;
rc = sc_establish_context (&card->ctx, "scdaemon");
if (rc)
{
log_error ("failed to establish SC context: %s\n", sc_strerror (rc));
rc = map_sc_err (rc);
goto leave;
}
if (card->reader >= card->ctx->reader_count)
{
log_error ("no card reader available\n");
rc = GNUPG_Card_Error;
goto leave;
}
card->ctx->error_file = log_get_stream ();
card->ctx->debug = opt.debug_sc;
card->ctx->debug_file = log_get_stream ();
if (sc_detect_card_presence (card->ctx->reader[card->reader], 0) != 1)
{
rc = GNUPG_Card_Not_Present;
goto leave;
}
rc = sc_connect_card (card->ctx->reader[card->reader], 0, &card->scard);
if (rc)
{
log_error ("failed to connect card in reader %d: %s\n",
card->reader, sc_strerror (rc));
rc = map_sc_err (rc);
goto leave;
}
if (opt.verbose)
log_info ("connected to card in reader %d using driver `%s'\n",
card->reader, card->scard->driver->name);
rc = sc_lock (card->scard);
if (rc)
{
log_error ("can't lock card in reader %d: %s\n",
card->reader, sc_strerror (rc));
rc = map_sc_err (rc);
goto leave;
}
leave:
if (rc)
card_close (card);
else
*rcard = card;
return rc;
}
/* Close a card and release all resources */
void
card_close (CARD card)
{
if (card)
{
if (card->p15card)
{
sc_pkcs15_unbind (card->p15card);
card->p15card = NULL;
}
if (card->scard)
{
sc_unlock (card->scard);
sc_disconnect_card (card->scard, 0);
card->scard = NULL;
}
if (card->ctx)
{
sc_release_context (card->ctx);
card->ctx = NULL;
}
xfree (card);
}
}
+/* Locate a simple TLV encoded data object in BUFFER of LENGTH and
+ return a pointer to value as well as its length in NBYTES. Return
+ NULL if it was not found. Note, that the function does not check
+ whether the value fits into the provided buffer. */
+static const char *
+find_simple_tlv (const unsigned char *buffer, size_t length,
+ int tag, size_t *nbytes)
+{
+ const char *s = buffer;
+ size_t n = length;
+ size_t len;
+
+ for (;;)
+ {
+ buffer = s;
+ if (n < 2)
+ return NULL; /* buffer too short for tag and length. */
+ len = s[1];
+ s += 2; n -= 2;
+ if (len == 255)
+ {
+ if (n < 2)
+ return NULL; /* we expected 2 more bytes with the length. */
+ len = (s[0] << 8) | s[1];
+ s += 2; n -= 2;
+ }
+ if (*buffer == tag)
+ {
+ *nbytes = len;
+ return s;
+ }
+ if (len > n)
+ return NULL; /* buffer too short to skip to the next tag. */
+ s += len; n -= len;
+ }
+}
+
+/* Find the ICC Serial Number within the provided BUFFER of LENGTH
+ (which should contain the GDO file) and return it as a hex encoded
+ string and allocated string in SERIAL. Return an error code when
+ the ICCSN was not found. */
+static int
+find_iccsn (const unsigned char *buffer, size_t length, char **serial)
+{
+ size_t n;
+ const unsigned char *s;
+ char *p;
+
+ s = find_simple_tlv (buffer, length, 0x5A, &n);
+ if (!s)
+ return GNUPG_Card_Error;
+ length -= s - buffer;
+ if (n > length)
+ {
+ /* Oops, it does not fit into the buffer. This is an invalid
+ encoding (or the buffer is too short. However, I have some
+ test cards with such an invalid encoding and therefore I use
+ this ugly workaround to return something I can further
+ experiment with. */
+ if (n == 0x0D && length+1 == n)
+ {
+ log_debug ("enabling BMI testcard workaround\n");
+ n--;
+ }
+ else
+ return GNUPG_Card_Error; /* Bad encoding; does not fit into buffer. */
+ }
+ if (!n)
+ return GNUPG_Card_Error; /* Well, that is too short. */
+
+ *serial = p = xtrymalloc (2*n+1);
+ if (!*serial)
+ return GNUPG_Out_Of_Core;
+ for (; n; n--, p += 2, s++)
+ sprintf (p, "%02X", *s);
+ *p = 0;
+ return 0;
+}
/* Retrieve the serial number and the time of the last update of the
card. The serial number is returned as a malloced string (hex
encoded) in SERIAL and the time of update is returned in STAMP.
If no update time is available the returned value is 0. The serial
is mandatory for a PKCS_15 application and an error will be
returned if this value is not availbale. For non-PKCS-15 cards a
serial number is constructed by other means. Caller must free
SERIAL unless the function returns an error. */
int
card_get_serial_and_stamp (CARD card, char **serial, time_t *stamp)
{
- char *s;
int rc;
struct sc_path path;
struct sc_file *file;
- unsigned char buf[12];
- int i;
+ unsigned char buf[256];
+ int buflen;
if (!card || !serial || !stamp)
return GNUPG_Invalid_Value;
*serial = NULL;
*stamp = 0; /* not available */
if (!card->fnc.initialized)
{
card->fnc.initialized = 1;
/* The first use of this card tries to figure out the type of the card
and sets up the function pointers. */
rc = sc_pkcs15_bind (card->scard, &card->p15card);
if (rc)
{
if (rc != SC_ERROR_PKCS15_APP_NOT_FOUND)
log_error ("binding of existing PKCS-15 failed in reader %d: %s\n",
card->reader, sc_strerror (rc));
card->p15card = NULL;
rc = 0;
}
if (card->p15card)
card_p15_bind (card);
else
card_dinsig_bind (card);
card->fnc.initialized = 1;
}
/* We should lookup the iso 7812-1 and 8583-3 - argh ISO
practice is suppressing innovation - IETF rules! So we
always get the serialnumber from the 2F02 GDO file. */
/* FIXME: in case we can't parse the 2F02 EF and we have a P15 card,
we should get the serial number from the respective P15 file */
sc_format_path ("3F002F02", &path);
rc = sc_select_file (card->scard, &path, &file);
if (rc)
{
log_error ("sc_select_file failed: %s\n", sc_strerror (rc));
return GNUPG_Card_Error;
}
if (file->type != SC_FILE_TYPE_WORKING_EF
|| file->ef_structure != SC_FILE_EF_TRANSPARENT)
{
log_error ("wrong type or structure of GDO file\n");
sc_file_free (file);
return GNUPG_Card_Error;
}
- if (file->size != 12)
+
+ if (!file->size || file->size >= DIM(buf) )
{ /* FIXME: Use a real parser */
- log_error ("unsupported size of GDO file\n");
+ log_error ("unsupported size of GDO file (%d)\n", file->size);
sc_file_free (file);
return GNUPG_Card_Error;
}
+ buflen = file->size;
- rc = sc_read_binary (card->scard, 0, buf, DIM (buf), 0);
+ rc = sc_read_binary (card->scard, 0, buf, buflen, 0);
sc_file_free (file);
if (rc < 0)
{
log_error ("error reading GDO file: %s\n", sc_strerror (rc));
return GNUPG_Card_Error;
}
- if (rc != file->size)
+ if (rc != buflen)
{
log_error ("short read on GDO file\n");
return GNUPG_Card_Error;
}
- if (buf[0] != 0x5a || buf[1] != 10)
- {
- log_error ("invalid structure of GDO file\n");
- return GNUPG_Card_Error;
+
+ rc = find_iccsn (buf, buflen, serial);
+ if (rc == GNUPG_Card_Error)
+ log_error ("invalid structure of GDO file\n");
+ if (!rc && card->p15card && !strcmp (*serial, "D27600000000000000000000"))
+ { /* This is a German card with a silly serial number. Try to get
+ the serial number from the EF(TokenInfo). We indicate such a
+ serial number by the using the prefix: "FF0100". */
+ const char *efser = card->p15card->serial_number;
+ char *p;
+
+ if (!efser)
+ efser = "";
+
+ xfree (*serial);
+ *serial = NULL;
+ p = xtrymalloc (strlen (efser) + 7);
+ if (!p)
+ rc = GNUPG_Out_Of_Core;
+ else
+ {
+ strcpy (p, "FF0100");
+ strcpy (p+6, efser);
+ *serial = p;
+ }
}
- *serial = s = xtrymalloc (21);
- if (!*serial)
- return GNUPG_Out_Of_Core;
- for (i=0; i < 10; i++, s += 2)
- sprintf (s, "%02X", buf[2+i]);
- return 0;
+ else if (!rc && **serial == 'F' && (*serial)[1] == 'F')
+ { /* The serial number starts with our special prefix. This
+ requires that we put our default prefix "FF0000" in front. */
+ char *p = xtrymalloc (strlen (*serial) + 7);
+ if (!p)
+ {
+ xfree (*serial);
+ *serial = NULL;
+ rc = GNUPG_Out_Of_Core;
+ }
+ else
+ {
+ strcpy (p, "FF0000");
+ strcpy (p+6, *serial);
+ xfree (*serial);
+ *serial = p;
+ }
+ }
+ return rc;
}
/* Enumerate all keypairs on the card and return the Keygrip as well
as the internal identification of the key. KEYGRIP must be a
caller provided buffer with a size of 20 bytes which will receive
the KEYGRIP of the keypair. If KEYID is not NULL, it returns the
ID field of the key in allocated memory; this is a string without
spaces. The function returns -1 when all keys have been
enumerated. Note that the error GNUPG_Missing_Certificate may be
returned if there is just the private key but no public key (ie.e a
certificate) available. Applications might want to continue
enumerating after this error.*/
int
card_enum_keypairs (CARD card, int idx,
unsigned char *keygrip,
char **keyid)
{
int rc;
if (keyid)
*keyid = NULL;
if (!card || !keygrip)
return GNUPG_Invalid_Value;
if (idx < 0)
return GNUPG_Invalid_Index;
if (!card->fnc.initialized)
return GNUPG_Card_Not_Initialized;
if (!card->fnc.enum_keypairs)
return GNUPG_Unsupported_Operation;
rc = card->fnc.enum_keypairs (card, idx, keygrip, keyid);
if (opt.verbose)
log_info ("card operation enum_keypairs result: %s\n",
gnupg_strerror (rc));
return rc;
}
/* Read the certificate identified by CERTIDSTR which is the
hexadecimal encoded ID of the certificate, prefixed with the string
"3F005015.". The certificate is return in DER encoded form in CERT
and NCERT. */
int
card_read_cert (CARD card, const char *certidstr,
unsigned char **cert, size_t *ncert)
{
int rc;
if (!card || !certidstr || !cert || !ncert)
return GNUPG_Invalid_Value;
if (!card->fnc.initialized)
return GNUPG_Card_Not_Initialized;
if (!card->fnc.read_cert)
return GNUPG_Unsupported_Operation;
rc = card->fnc.read_cert (card, certidstr, cert, ncert);
if (opt.verbose)
log_info ("card operation read_cert result: %s\n", gnupg_strerror (rc));
return rc;
}
/* Create the signature and return the allocated result in OUTDATA.
If a PIN is required the PINCB will be used to ask for the PIN; it
should return the PIN in an allocated buffer and put it into PIN. */
int
card_sign (CARD card, const char *keyidstr, int hashalgo,
int (pincb)(void*, const char *, char **),
void *pincb_arg,
const void *indata, size_t indatalen,
void **outdata, size_t *outdatalen )
{
int rc;
if (!card || !indata || !indatalen || !outdata || !outdatalen || !pincb)
return GNUPG_Invalid_Value;
if (!card->fnc.initialized)
return GNUPG_Card_Not_Initialized;
if (!card->fnc.sign)
return GNUPG_Unsupported_Operation;
rc = card->fnc.sign (card, keyidstr, hashalgo,
pincb, pincb_arg,
indata, indatalen,
outdata, outdatalen);
if (opt.verbose)
log_info ("card operation sign result: %s\n", gnupg_strerror (rc));
return rc;
}
/* Create the signature and return the allocated result in OUTDATA.
If a PIN is required the PINCB will be used to ask for the PIN; it
should return the PIN in an allocated buffer and put it into PIN. */
int
card_decipher (CARD card, const char *keyidstr,
int (pincb)(void*, const char *, char **),
void *pincb_arg,
const void *indata, size_t indatalen,
void **outdata, size_t *outdatalen )
{
int rc;
if (!card || !indata || !indatalen || !outdata || !outdatalen || !pincb)
return GNUPG_Invalid_Value;
if (!card->fnc.initialized)
return GNUPG_Card_Not_Initialized;
if (!card->fnc.decipher)
return GNUPG_Unsupported_Operation;
rc = card->fnc.decipher (card, keyidstr,
pincb, pincb_arg,
indata, indatalen,
outdata, outdatalen);
if (opt.verbose)
log_info ("card operation decipher result: %s\n", gnupg_strerror (rc));
return rc;
}
diff --git a/scd/scdaemon.c b/scd/scdaemon.c
index d1402b5ee..1d8bad21d 100644
--- a/scd/scdaemon.c
+++ b/scd/scdaemon.c
@@ -1,626 +1,626 @@
/* scdaemon.c - The GnuPG Smartcard Daemon
* Copyright (C) 2001, 2002 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 2 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, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <time.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <signal.h>
#include <ksba.h>
#include <gcrypt.h>
#define JNLIB_NEED_LOG_LOGV
#include "scdaemon.h"
#include "../assuan/assuan.h" /* malloc hooks */
#include "sysutils.h"
#define N_(a) a
#define _(a) a
enum cmd_and_opt_values
{ aNull = 0,
oCsh = 'c',
oQuiet = 'q',
oSh = 's',
oVerbose = 'v',
oNoVerbose = 500,
oOptions,
oDebug,
oDebugAll,
oDebugWait,
oDebugSC,
oNoGreeting,
oNoOptions,
oHomedir,
oNoDetach,
oNoGrab,
oLogFile,
oServer,
oBatch,
aTest };
static ARGPARSE_OPTS opts[] = {
{ 301, NULL, 0, N_("@Options:\n ") },
{ oServer, "server", 0, N_("run in server mode") },
{ oVerbose, "verbose", 0, N_("verbose") },
{ oQuiet, "quiet", 0, N_("be somewhat more quiet") },
{ oSh, "sh", 0, N_("sh-style command output") },
{ oCsh, "csh", 0, N_("csh-style command output") },
{ oOptions, "options" , 2, N_("read options from file")},
{ oDebug, "debug" ,4|16, N_("set debugging flags")},
{ oDebugAll, "debug-all" ,0, N_("enable full debugging")},
{ oDebugWait,"debug-wait",1, "@"},
- { oDebugSC, "debug-sc", 1, N_("N|set OpenSC debug level to N")},
+ { oDebugSC, "debug-sc", 1, N_("|N|set OpenSC debug level to N")},
{ oNoDetach, "no-detach" ,0, N_("do not detach from the console")},
- { oLogFile, "log-file" ,2, N_("use a log file for the server")},
+ { oLogFile, "log-file" ,2, N_("use a log file for the server")},
{0}
};
static volatile int caught_fatal_sig = 0;
/* It is possible that we are currently running under setuid permissions */
static int maybe_setuid = 1;
/* Name of the communication socket */
static char socket_name[128];
static const char *
my_strusage (int level)
{
const char *p;
switch (level)
{
case 11: p = "scdaemon (GnuPG)";
break;
case 13: p = VERSION; break;
case 17: p = PRINTABLE_OS_NAME; break;
case 19: p = _("Please report bugs to <" PACKAGE_BUGREPORT ">.\n");
break;
case 1:
case 40: p = _("Usage: scdaemon [options] (-h for help)");
break;
case 41: p = _("Syntax: scdaemon [options] [command [args]]\n"
"Smartcard daemon for GnuPG\n");
break;
default: p = NULL;
}
return p;
}
static void
i18n_init (void)
{
#ifdef USE_SIMPLE_GETTEXT
set_gettext_file( PACKAGE );
#else
#ifdef ENABLE_NLS
/* gtk_set_locale (); HMMM: We have not yet called gtk_init */
bindtextdomain( PACKAGE, GNUPG_LOCALEDIR );
textdomain( PACKAGE );
#endif
#endif
}
/* Used by gcry for logging */
static void
my_gcry_logger (void *dummy, int level, const char *fmt, va_list arg_ptr)
{
/* translate the log levels */
switch (level)
{
case GCRY_LOG_CONT: level = JNLIB_LOG_CONT; break;
case GCRY_LOG_INFO: level = JNLIB_LOG_INFO; break;
case GCRY_LOG_WARN: level = JNLIB_LOG_WARN; break;
case GCRY_LOG_ERROR:level = JNLIB_LOG_ERROR; break;
case GCRY_LOG_FATAL:level = JNLIB_LOG_FATAL; break;
case GCRY_LOG_BUG: level = JNLIB_LOG_BUG; break;
case GCRY_LOG_DEBUG:level = JNLIB_LOG_DEBUG; break;
default: level = JNLIB_LOG_ERROR; break;
}
log_logv (level, fmt, arg_ptr);
}
static void
cleanup (void)
{
if (*socket_name)
{
char *p;
remove (socket_name);
p = strrchr (socket_name, '/');
if (p)
{
*p = 0;
rmdir (socket_name);
*p = '/';
}
*socket_name = 0;
}
}
static RETSIGTYPE
cleanup_sh (int sig)
{
if (caught_fatal_sig)
raise (sig);
caught_fatal_sig = 1;
/* gcry_control( GCRYCTL_TERM_SECMEM );*/
cleanup ();
#ifndef HAVE_DOSISH_SYSTEM
{ /* reset action to default action and raise signal again */
struct sigaction nact;
nact.sa_handler = SIG_DFL;
sigemptyset( &nact.sa_mask );
nact.sa_flags = 0;
sigaction( sig, &nact, NULL);
}
#endif
raise( sig );
}
int
main (int argc, char **argv )
{
ARGPARSE_ARGS pargs;
int orig_argc;
int may_coredump;
char **orig_argv;
FILE *configfp = NULL;
char *configname = NULL;
const char *shell;
unsigned configlineno;
int parse_debug = 0;
int default_config =1;
int greeting = 0;
int nogreeting = 0;
int pipe_server = 0;
int nodetach = 0;
int csh_style = 0;
char *logfile = NULL;
int debug_wait = 0;
set_strusage (my_strusage);
gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
/* Please note that we may running SUID(ROOT), so be very CAREFUL
when adding any stuff between here and the call to INIT_SECMEM()
somewhere after the option parsing */
log_set_prefix ("scdaemon", 1|4);
i18n_init ();
/* check that the libraries are suitable. Do it here because
the option parsing may need services of the library */
if (!gcry_check_version ( "1.1.5" ) )
{
log_fatal( _("libgcrypt is too old (need %s, have %s)\n"),
"1.1.5", gcry_check_version (NULL) );
}
ksba_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
assuan_set_malloc_hooks (gcry_malloc, gcry_realloc, gcry_free);
gcry_set_log_handler (my_gcry_logger, NULL);
gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);
may_coredump = disable_core_dumps ();
shell = getenv ("SHELL");
if (shell && strlen (shell) >= 3 && !strcmp (shell+strlen (shell)-3, "csh") )
csh_style = 1;
/* FIXME: Using this homedir option does only make sense when not
running as a system service. We might want to check for this by
looking at the uid or ebtter use an explict option for this */
opt.homedir = getenv("GNUPGHOME");
if (!opt.homedir || !*opt.homedir)
opt.homedir = GNUPG_DEFAULT_HOMEDIR;
/* check whether we have a config file on the commandline */
orig_argc = argc;
orig_argv = argv;
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags= 1|(1<<6); /* do not remove the args, ignore version */
while (arg_parse( &pargs, opts))
{
if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
parse_debug++;
else if (pargs.r_opt == oOptions)
{ /* yes there is one, so we do not try the default one, but
read the option file when it is encountered at the
commandline */
default_config = 0;
}
else if (pargs.r_opt == oNoOptions)
default_config = 0; /* --no-options */
else if (pargs.r_opt == oHomedir)
opt.homedir = pargs.r.ret_str;
}
/* initialize the secure memory. */
gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
maybe_setuid = 0;
/*
Now we are working under our real uid
*/
if (default_config)
configname = make_filename (opt.homedir, "scdaemon.conf", NULL );
argc = orig_argc;
argv = orig_argv;
pargs.argc = &argc;
pargs.argv = &argv;
pargs.flags= 1; /* do not remove the args */
next_pass:
if (configname)
{
configlineno = 0;
configfp = fopen (configname, "r");
if (!configfp)
{
if (default_config)
{
if( parse_debug )
log_info (_("NOTE: no default option file `%s'\n"),
configname );
}
else
{
log_error (_("option file `%s': %s\n"),
configname, strerror(errno) );
exit(2);
}
xfree (configname);
configname = NULL;
}
if (parse_debug && configname )
log_info (_("reading options from `%s'\n"), configname );
default_config = 0;
}
while (optfile_parse( configfp, configname, &configlineno, &pargs, opts) )
{
switch (pargs.r_opt)
{
case oQuiet: opt.quiet = 1; break;
case oVerbose: opt.verbose++; break;
case oBatch: opt.batch=1; break;
case oDebug: opt.debug |= pargs.r.ret_ulong; break;
case oDebugAll: opt.debug = ~0; break;
case oDebugWait: debug_wait = pargs.r.ret_int; break;
case oDebugSC: opt.debug_sc = pargs.r.ret_int; 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 oNoGreeting: nogreeting = 1; break;
case oNoVerbose: opt.verbose = 0; break;
case oNoOptions: break; /* no-options */
case oHomedir: opt.homedir = pargs.r.ret_str; break;
case oNoDetach: nodetach = 1; break;
case oLogFile: logfile = pargs.r.ret_str; break;
case oCsh: csh_style = 1; break;
case oSh: csh_style = 0; break;
case oServer: pipe_server = 1; break;
default : pargs.err = configfp? 1:2; break;
}
}
if (configfp)
{
fclose( configfp );
configfp = NULL;
xfree(configname);
configname = NULL;
goto next_pass;
}
xfree (configname);
configname = NULL;
if (log_get_errorcount(0))
exit(2);
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
log_info ("NOTE: this is a development version!\n");
#endif
if (atexit (cleanup))
{
log_error ("atexit failed\n");
cleanup ();
exit (1);
}
if (debug_wait && pipe_server)
{
log_debug ("waiting for debugger - my pid is %u .....\n",
(unsigned int)getpid());
sleep (debug_wait);
log_debug ("... okay\n");
}
/* now start with logging to a file if this is desired */
if (logfile)
{
log_set_file (logfile);
log_set_prefix (NULL, 1|2|4);
}
if (pipe_server)
{ /* this is the simple pipe based server */
scd_command_handler (-1);
}
else
{ /* regular server mode */
int fd;
pid_t pid;
int i;
int len;
struct sockaddr_un serv_addr;
char *p;
/* fixme: if there is already a running gpg-agent we should
sahre the same directory - and vice versa */
*socket_name = 0;
snprintf (socket_name, DIM(socket_name)-1,
"/tmp/gpg-XXXXXX/S.scdaemon");
socket_name[DIM(socket_name)-1] = 0;
p = strrchr (socket_name, '/');
if (!p)
BUG ();
*p = 0;;
if (!mkdtemp(socket_name))
{
log_error ("can't create directory `%s': %s\n",
socket_name, strerror(errno) );
exit (1);
}
*p = '/';
if (strchr (socket_name, ':') )
{
log_error ("colons are not allowed in the socket name\n");
exit (1);
}
if (strlen (socket_name)+1 >= sizeof serv_addr.sun_path )
{
log_error ("name of socket to long\n");
exit (1);
}
fd = socket (AF_UNIX, SOCK_STREAM, 0);
if (fd == -1)
{
log_error ("can't create socket: %s\n", strerror(errno) );
exit (1);
}
memset (&serv_addr, 0, sizeof serv_addr);
serv_addr.sun_family = AF_UNIX;
strcpy (serv_addr.sun_path, socket_name);
len = (offsetof (struct sockaddr_un, sun_path)
+ strlen(serv_addr.sun_path) + 1);
if (bind (fd, (struct sockaddr*)&serv_addr, len) == -1)
{
log_error ("error binding socket to `%s': %s\n",
serv_addr.sun_path, strerror (errno) );
close (fd);
exit (1);
}
if (listen (fd, 5 ) == -1)
{
log_error ("listen() failed: %s\n", strerror (errno));
close (fd);
exit (1);
}
if (opt.verbose)
log_info ("listening on socket `%s'\n", socket_name );
fflush (NULL);
pid = fork ();
if (pid == (pid_t)-1)
{
log_fatal ("fork failed: %s\n", strerror (errno) );
exit (1);
}
else if (pid)
{ /* we are the parent */
char *infostr;
close (fd);
/* create the info string: <name>:<pid>:<protocol_version> */
if (asprintf (&infostr, "SCDAEMON_INFO=%s:%lu:1",
socket_name, (ulong)pid ) < 0)
{
log_error ("out of core\n");
kill (pid, SIGTERM);
exit (1);
}
*socket_name = 0; /* don't let cleanup() remove the socket -
the child should do this from now on */
if (argc)
{ /* run the program given on the commandline */
if (putenv (infostr))
{
log_error ("failed to set environment: %s\n",
strerror (errno) );
kill (pid, SIGTERM );
exit (1);
}
execvp (argv[0], argv);
log_error ("failed to run the command: %s\n", strerror (errno));
kill (pid, SIGTERM);
exit (1);
}
else
{
/* print the environment string, so that the caller can use
shell's eval to set it */
if (csh_style)
{
*strchr (infostr, '=') = ' ';
printf ( "setenv %s\n", infostr);
}
else
{
printf ( "%s; export SCDAEMON_INFO;\n", infostr);
}
free (infostr);
exit (0);
}
/* NOTREACHED */
} /* end parent */
/* this is the child */
/* detach from tty and put process into a new session */
if (!nodetach )
{ /* close stdin, stdout and stderr unless it is the log stream */
for (i=0; i <= 2; i++)
{
if ( log_get_fd () != i)
close (i);
}
if (setsid() == -1)
{
log_error ("setsid() failed: %s\n", strerror(errno) );
cleanup ();
exit (1);
}
}
/* setup signals */
{
struct sigaction oact, nact;
nact.sa_handler = cleanup_sh;
sigemptyset (&nact.sa_mask);
nact.sa_flags = 0;
sigaction (SIGHUP, NULL, &oact);
if (oact.sa_handler != SIG_IGN)
sigaction (SIGHUP, &nact, NULL);
sigaction( SIGTERM, NULL, &oact );
if (oact.sa_handler != SIG_IGN)
sigaction (SIGTERM, &nact, NULL);
nact.sa_handler = SIG_IGN;
sigaction (SIGPIPE, &nact, NULL);
sigaction (SIGINT, &nact, NULL);
}
if (chdir("/"))
{
log_error ("chdir to / failed: %s\n", strerror (errno));
exit (1);
}
scd_command_handler (fd);
close (fd);
}
return 0;
}
void
scd_exit (int rc)
{
#if 0
#warning no update_random_seed_file
update_random_seed_file();
#endif
#if 0
/* at this time a bit annoying */
if (opt.debug & DBG_MEMSTAT_VALUE)
{
gcry_control( GCRYCTL_DUMP_MEMORY_STATS );
gcry_control( GCRYCTL_DUMP_RANDOM_STATS );
}
if (opt.debug)
gcry_control (GCRYCTL_DUMP_SECMEM_STATS );
#endif
gcry_control (GCRYCTL_TERM_SECMEM );
rc = rc? rc : log_get_errorcount(0)? 2 : 0;
exit (rc);
}
void
scd_init_default_ctrl (CTRL ctrl)
{
}

File Metadata

Mime Type
text/x-diff
Expires
Thu, Dec 18, 8:45 AM (1 d, 11 h)
Storage Engine
local-disk
Storage Format
Raw Data
Storage Handle
e2/e6/fafa733a2db53419ead245245b49

Event Timeline