playing with smartcard: rsa key upload?

Danny De Cock godot at ulyssis.org
Mon Nov 4 04:14:57 EST 2002


hi,

the attachment contains a source file which solves the segmentation
faults: a few type conflicts caused fatal misunderstandings between
several routines of openssl and openssh.

the current status is that the smartcard holds a private key and a
corresponding certificate, and the server holds the key pair's public key,
but when connecting to that server, no smartcard authentication seems to
happen.

any suggestions?

<output> `ssh -I 0 g -v`
OpenSSH_3.5p1, SSH protocols 1.5/2.0, OpenSSL 0x0090607f
debug1: Reading configuration data /usr/local/etc/ssh_config
debug1: Rhosts Authentication disabled, originating port will not be
trusted.
debug1: ssh_connect: needpriv 0
debug1: Connecting to g [192.168.1.5] port 22.
debug1: Connection established.
debug1: sc_get_keys called: reader id = 0
debug1: sc_read_pubkey() with cert id 45
debug1: fingerprint 1024 d7:32:98:fa:bc:33:3f:26:fb:ab:09:66:14:5e:a4:4a
debug1: identity file /home/decockd/.ssh/identity type -1
debug1: identity file /home/decockd/.ssh/id_rsa type 1
debug1: identity file /home/decockd/.ssh/id_dsa type -1
debug1: Remote protocol version 1.99, remote software version
OpenSSH_3.4p1 Debian 1:3.4p1-1
debug1: match: OpenSSH_3.4p1 Debian 1:3.4p1-1 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_3.5p1
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug1: dh_gen_key: priv key bits set: 124/256
debug1: bits set: 1605/3191
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Host 'g' is known and matches the RSA host key.
debug1: Found key in /home/decockd/.ssh/known_hosts:4
debug1: bits set: 1597/3191
debug1: ssh_rsa_verify: signature correct
debug1: kex_derive_keys
debug1: newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: waiting for SSH2_MSG_NEWKEYS
debug1: newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: done: ssh_kex2.
debug1: send SSH2_MSG_SERVICE_REQUEST
debug1: service_accept: ssh-userauth
debug1: got SSH2_MSG_SERVICE_ACCEPT
debug1: authentications that can continue:
publickey,password,keyboard-interactive
debug1: next auth method to try is publickey
debug1: try pubkey: smartcard key
debug1: authentications that can continue:
publickey,password,keyboard-interactive
debug1: try privkey: /home/decockd/.ssh/identity
debug1: try pubkey: /home/decockd/.ssh/id_rsa
debug1: authentications that can continue:
publickey,password,keyboard-interactive
debug1: try privkey: /home/decockd/.ssh/id_dsa
debug1: next auth method to try is keyboard-interactive
debug1: authentications that can continue:
publickey,password,keyboard-interactive
debug1: next auth method to try is password
decockd at g's password:
</output>

On Wed, 30 Oct 2002, Danny De Cock wrote:

> hi,
>
> some additional information after some straightforward debugging
> learns me this:
>
> the segmentation fault occurs in the openssl-package source file
> crypto/engine/engine_lib.c. more precisely, it happens the second time
> ENGINE_init(...) is called when trying to accomplish the assignment:
>         if((e->funct_ref == 0) && e->init){
>                 /* This is the first functional reference and the engine
>                  * requires initialisation so we do it now. */
>                 to_return = e->init();
>                 }
>
> so the first time ENGINE_init(...) is executed, there is no problem, and
> the second time is triggered by sc_read_pubkey(), which calls
> RSA_set_method.  it is this RSA_set_method that triggers the segmentation
> fault.
>
> for the record: I am using the binaries produced by opensc-snap-20021029,
> openssl-engine-0.9.6g.tar.gz and openssh-3.5p1.tar.gz.
>
> cu, danny.
>
> On Wed, 30 Oct 2002, Danny De Cock wrote:
>
> > hi,
> >
> > my the subscription to this list is still in progress, i.e., could you
> > include my emailaddress when replying to this email.
> >
> > I am using the opensc-cvs-snapshot of october 29th, in combination
> > with openssh 3.5p1 on a woody debian machine with pcsclite-1.1.2, and
> > have been trying to get a gemplus gpk16000 smartcard working with
> > openssh.
> >
> > the problem I am faced with is a segmentation fault of a command such
> > as `ssh -I 0 server`
> >
> > the commands I have been using are these:
> >
> > pkcs15-init -dddddd -E -C
> > pkcs15-init -dddddd -P -a 45 -i 45
> > pkcs15-init -dddddd -S privkey.pem -a 45 -i 45
> > pkcs15-init -dddddd -X cert.pem
> > ssh -I 0 192.168.1.2 -v
> >
> > the log file /var/log/auth.log of the other machine indicates this after
> > the ssh-client has failed:
> > Oct 30 13:00:13 g sshd[24750]: Did not receive identification string from 192.168.1.11
> >
> > fyi: the led of the smartcard reader starts to blink just before the
> > segmentation fault.
> >
> > does any of you have any idea how to solve this problem?
> >
> > many thanks, danny.
> >
> > ---------------------------
> >
> > the first four these commands have accomplished their tasks
> > succesfully:
> >
> > <output of pkcs15-tool --list-pins  -c -k>
> > Connecting to card in reader Towitoko Chipdrive Reader 0 0...
> > Using card driver: Gemplus GPK driver
> > Trying to find a PKCS#15 compatible card...
> > Found OpenSC Card!
> > Card has 1 certificate(s).
> >
> > X.509 Certificate [Certificate]
> >         Flags    : 2
> >         Authority: no
> >         Path     : 3F0050159000
> >         ID       : 45
> >
> > Card has 1 private key(s).
> >
> > Private RSA Key [Private Key]
> >         Com. Flags  : 1D
> >         Usage       : [0x4], sign
> >         Access Flags: [0x0]
> >         ModLength   : 1024
> >         Key ref     : 0
> >         Native      : yes
> >         Path        : 3F0050150006
> >         Auth ID     : 45
> >         ID          : 45
> >
> > Card has 2 PIN code(s).
> >
> > PIN [Security Officer PIN]
> >         Com. Flags: 0x3
> >         Auth ID   : FF
> >         Flags     : [0xB2], local, initialized, needs-padding, soPin
> >         Length    : 6..8
> >         Pad char  : 0x00
> >         Reference : 8
> >         Type      : 1
> >         Path      : 3F005015
> >
> > PIN []
> >         Com. Flags: 0x3
> >         Auth ID   : 45
> >         Flags     : [0x32], local, initialized, needs-padding
> >         Length    : 4..8
> >         Pad char  : 0x00
> >         Reference : 12
> >         Type      : 1
> >         Path      : 3F005015
> >
> > but the fifth command fails badly:
> > <output>
> > ssh -I 0 192.168.1.2 -v
> > OpenSSH_3.5p1, SSH protocols 1.5/2.0, OpenSSL 0x0090607f
> > debug1: Reading configuration data /usr/local/etc/ssh_config
> > debug1: Rhosts Authentication disabled, originating port will not be trusted.
> > debug1: ssh_connect: needpriv 0
> > debug1: Connecting to lien [192.168.1.2] port 22.
> > debug1: Connection established.
> > debug1: sc_get_keys called: id = 0
> > debug1: sc_read_pubkey() with cert id 45
> > Segmentation fault
> > </output>
> >
> > > On Thu, 17 Oct 2002, Andreas Hasenack wrote:
> > >
> > > > Is there a tool to upload an openssh rsa key to a smart card so that I
> > > > can use it with ssh -I later on? Should I just upload it as a regular
> > > > file? Any pointers to some documentation explaining how to do this with
> > > > openssh?
> > >
> > > The current SC related code in openssh is a bit absurd anyway.
> > > I'm currently rewriting the code into some more generic,
> > > like pkcs#11 support. After this you can use opensc-pkcs11.so
> > > to upload your keys.
> > >
> > > Hopefully Theo and the rest of OpenSSH guys are willing to
> > > ditch the current code base, ugly sectok and less ugly opensc
> > > support entirely.
> > >
> > > -Antti
> > >
> > > _______________________________________________
> > > openssh-unix-dev at mindrot.org mailing list
> > > http://www.mindrot.org/mailman/listinfo/openssh-unix-dev
> >
> >
> >
> >
>
>

-- 
-----------------------------------------------------------------------------
Don't kid yourself.  Little is relevant, and nothing lasts forever.
-----------------------------------------------------------------------------
Mail : Danny.DeCock at esat.kuleuven.ac.be              daniel.decock at postbox.be
WWW  : http://ace.ulyssis.org/~godot                        godot at advalvas.be
-------------- next part --------------
/*
 * Copyright (c) 2002 Juha Yrj?l?.  All rights reserved.
 * Copyright (c) 2001 Markus Friedl.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "includes.h"
#if defined(SMARTCARD) && defined(USE_OPENSC)

#include <openssl/evp.h>
#include <openssl/x509.h>

#include <opensc/opensc.h>
#include <opensc/pkcs15.h>

#include "key.h"
#include "log.h"
#include "xmalloc.h"
#include "readpass.h"
#include "scard.h"

#if OPENSSL_VERSION_NUMBER < 0x00907000L && defined(CRYPTO_LOCK_ENGINE)
#define USE_ENGINE
#define RSA_get_default_method RSA_get_default_openssl_method
#else
#endif

#ifdef USE_ENGINE
#include <openssl/engine.h>
#define sc_get_rsa sc_get_engine
#else
#define sc_get_rsa sc_get_rsa_method
#endif

static int sc_reader_id;
static sc_context_t *ctx = NULL;
static sc_card_t *card = NULL;
static sc_pkcs15_card_t *p15card = NULL;

static char *sc_pin = NULL;

struct sc_priv_data
{
	struct sc_pkcs15_id cert_id;
	int ref_count;
};

void
sc_close(void)
{
	if (p15card) {
		sc_pkcs15_unbind(p15card);
		p15card = NULL;
	}
	if (card) {
		sc_disconnect_card(card, 0);
		card = NULL;
	}
	if (ctx) {
		sc_release_context(ctx);
		ctx = NULL;
	}
}

static int 
sc_init(void)
{
	int r;

	r = sc_establish_context(&ctx, "openssh");
	if (r)
		goto err;
	r = sc_connect_card(ctx->reader[sc_reader_id], 0, &card);
	if (r)
		goto err;
	r = sc_pkcs15_bind(card, &p15card);
	if (r)
		goto err;
	return 0;
err:
	sc_close();
	return r;
}

/* private key operations */

static int
sc_prkey_op_init(RSA *rsa, struct sc_pkcs15_object **key_obj_out)
{
	int r;
	struct sc_priv_data *priv;
	struct sc_pkcs15_object *key_obj;
	struct sc_pkcs15_prkey_info *key;
	struct sc_pkcs15_object *pin_obj;
	struct sc_pkcs15_pin_info *pin;

	priv = (struct sc_priv_data *) RSA_get_app_data(rsa);
	if (priv == NULL)
		return -1;
	if (p15card == NULL) {
		sc_close();
		r = sc_init();
		if (r) {
			error("SmartCard init failed: %s", sc_strerror(r));
			goto err;
		}
	}
	r = sc_pkcs15_find_prkey_by_id(p15card, &priv->cert_id, &key_obj);
	if (r) {
		error("Unable to find private key from SmartCard: %s",
		      sc_strerror(r));
		goto err;
	}
	key = key_obj->data;
	r = sc_pkcs15_find_pin_by_auth_id(p15card, &key_obj->auth_id,
					  &pin_obj);
	if (r) {
		error("Unable to find PIN object from SmartCard: %s",
		      sc_strerror(r));
		goto err;
	}
	pin = pin_obj->data;
	r = sc_lock(card);
	if (r) {
		error("Unable to lock smartcard: %s", sc_strerror(r));
		goto err;
	}
	if (sc_pin != NULL) {
		r = sc_pkcs15_verify_pin(p15card, pin, sc_pin,
					 strlen(sc_pin));
		if (r) {
			sc_unlock(card);
			error("PIN code verification failed: %s",
			      sc_strerror(r));
			goto err;
		}
	}
	*key_obj_out = key_obj;
	return 0;
err:
	sc_close();
	return -1;
}

static int
sc_private_decrypt(int flen, u_char *from, u_char *to, RSA *rsa,
    int padding)
{
	struct sc_pkcs15_object *key_obj;
	int r;

	if (padding != RSA_PKCS1_PADDING)
		return -1;	
	r = sc_prkey_op_init(rsa, &key_obj);
	if (r)
		return -1;
	r = sc_pkcs15_decipher(p15card, key_obj, 0, from, flen, to, flen);
	sc_unlock(card);
	if (r < 0) {
		error("sc_pkcs15_decipher() failed: %s", sc_strerror(r));
		goto err;
	}
	return r;
err:
	sc_close();
	return -1;
}

static int
sc_sign(int type, u_char *m, unsigned int m_len,
	unsigned char *sigret, unsigned int *siglen, RSA *rsa)
{
	struct sc_pkcs15_object *key_obj;
	int r;
	unsigned long flags = 0;

	r = sc_prkey_op_init(rsa, &key_obj);
	if (r)
		return -1;
	/* FIXME: length of sigret correct? */
	/* FIXME: check 'type' and modify flags accordingly */
	flags = SC_ALGORITHM_RSA_PAD_PKCS1 | SC_ALGORITHM_RSA_HASH_SHA1;
	r = sc_pkcs15_compute_signature(p15card, key_obj, flags,
					m, m_len, sigret, RSA_size(rsa));
	sc_unlock(card);
	if (r < 0) {
		error("sc_pkcs15_compute_signature() failed: %s",
		      sc_strerror(r));
		goto err;
	}
	*siglen = r;
	return 1;
err:
	sc_close();
	return 0;
}

static int
sc_private_encrypt(int flen, u_char *from, u_char *to, RSA *rsa,
    int padding)
{
	error("Private key encryption not supported");
	return -1;
}

/* called on free */

static int (*orig_finish)(RSA *rsa) = NULL;

static int
sc_finish(RSA *rsa)
{
	struct sc_priv_data *priv;

	priv = RSA_get_app_data(rsa);
	priv->ref_count--;
	if (priv->ref_count == 0) {
		free(priv);
		sc_close();
	}
	if (orig_finish)
		orig_finish(rsa);
	return 1;
}

/* engine for overloading private key operations */

static ENGINE *
sc_get_rsa_method(void)
{static ENGINE *engine=NULL;
	static RSA_METHOD smart_rsa;
	const RSA_METHOD *def = RSA_get_default_method();


	/* use the OpenSSL version */
	memcpy(&smart_rsa, def, sizeof(smart_rsa));

	smart_rsa.name		= "opensc";

	/* overload */
	smart_rsa.rsa_priv_enc	= sc_private_encrypt;
	smart_rsa.rsa_priv_dec	= sc_private_decrypt;
	smart_rsa.rsa_sign	= sc_sign;

	/* save original */
	orig_finish		= def->finish;

     if (!ENGINE_init(engine)){   
                 return 0;
                 }

	smart_rsa.finish	= sc_finish;

     if (!ENGINE_init(engine)){   
               return 0;
               }
	ENGINE_set_RSA(engine,&smart_rsa);
	return &smart_rsa;

return engine;
}

#ifdef USE_ENGINE
static ENGINE *
sc_get_engine(void)
{
	static ENGINE *smart_engine = NULL;

	if ((smart_engine = ENGINE_new()) == NULL)
		fatal("ENGINE_new failed");

	ENGINE_set_id(smart_engine, "opensc");
	ENGINE_set_name(smart_engine, "OpenSC");

	ENGINE_set_RSA(smart_engine, ENGINE_get_RSA(sc_get_rsa_method()));
	ENGINE_set_DSA(smart_engine, DSA_get_default_openssl_method());
	ENGINE_set_DH(smart_engine, DH_get_default_openssl_method());
	ENGINE_set_RAND(smart_engine, RAND_SSLeay());
	ENGINE_set_BN_mod_exp(smart_engine, BN_mod_exp);

	return smart_engine;
}
#endif

static void
convert_rsa_to_rsa1(Key * in, Key * out)
{
	struct sc_priv_data *priv;
	ENGINE *engine=NULL;
	
	
	out->rsa->flags = in->rsa->flags;
	out->flags = in->flags;
     if (!ENGINE_init(engine)){   
	return 0;
        }

	ENGINE_set_RSA(engine,RSA_get_method(in->rsa));
	RSA_set_method(out->rsa,engine);
	BN_copy(out->rsa->n, in->rsa->n);
	BN_copy(out->rsa->e, in->rsa->e);
	priv = RSA_get_app_data(in->rsa);
	priv->ref_count++;
	RSA_set_app_data(out->rsa, priv);
	return;
}

static int 
sc_read_pubkey(Key * k, const struct sc_pkcs15_object *cert_obj)
{
	int r;
	sc_pkcs15_cert_t *cert = NULL;
	struct sc_priv_data *priv = NULL;
	sc_pkcs15_cert_info_t *cinfo = cert_obj->data;

	X509 *x509 = NULL;
	EVP_PKEY *pubkey = NULL;
	u8 *p;
	char *tmp;
	
	debug("sc_read_pubkey() with cert id %02X", cinfo->id.value[0]);
	r = sc_pkcs15_read_certificate(p15card, cinfo, &cert);
	if (r) {
		log("Certificate read failed: %s", sc_strerror(r));
		goto err;
	}

	x509 = X509_new();
	if (x509 == NULL) {
		r = -1; 
		goto err;
	}
	p = cert->data;
	if (!d2i_X509(&x509, &p, cert->data_len)) {
		log("Unable to parse X.509 certificate");
		r = -1;
		goto err;
	}

	sc_pkcs15_free_certificate(cert);
	cert = NULL;
	pubkey = X509_get_pubkey(x509);
	X509_free(x509);
	x509 = NULL;
	if (pubkey->type != EVP_PKEY_RSA) {
		log("Public key is of unknown type");
		r = -1;
		goto err;
	}

	k->rsa = EVP_PKEY_get1_RSA(pubkey);

	EVP_PKEY_free(pubkey);

	k->rsa->flags |= RSA_FLAG_SIGN_VER;

{
	ENGINE *e=sc_get_rsa_method();
	RSA_set_method(k->rsa, e);
}
	priv = xmalloc(sizeof(struct sc_priv_data));

	priv->cert_id = cinfo->id;

	priv->ref_count = 1;

	RSA_set_app_data(k->rsa, priv);

	k->flags = KEY_FLAG_EXT;
	tmp = key_fingerprint(k, SSH_FP_MD5, SSH_FP_HEX);
	debug("fingerprint %d %s", key_size(k), tmp);
	xfree(tmp);
	
	return 0;
err:
	if (cert)
		sc_pkcs15_free_certificate(cert);
	if (pubkey)
		EVP_PKEY_free(pubkey);
	if (x509)
		X509_free(x509);

	return r;
}

Key **
sc_get_keys(const char *id, const char *pin)
{
	Key *k, **keys;
	int i, r, real_count = 0, key_count;
	sc_pkcs15_id_t cert_id;
	sc_pkcs15_object_t *certs[32];
	char *buf = xstrdup(id), *p;

	debug("sc_get_keys called: reader id = %s", id);
	if (sc_pin != NULL)
		xfree(sc_pin);
	sc_pin = (pin == NULL) ? NULL : xstrdup(pin);

	cert_id.len = 0;
	if ((p = strchr(buf, ':')) != NULL) {
		*p = 0;
		p++;
		sc_pkcs15_hex_string_to_id(p, &cert_id);
	}
	r = sscanf(buf, "%d", &sc_reader_id);
	xfree(buf);
	if (r != 1)
		goto err;
	if (p15card == NULL) {
		sc_close();
		r = sc_init();
		if (r) {
			error("Smartcard init failed: %s", sc_strerror(r));
			goto err;
		}
	}
	if (cert_id.len) {
		r = sc_pkcs15_find_cert_by_id(p15card, &cert_id, &certs[0]);
		if (r < 0)
			goto err;
		key_count = 1;
	} else {
		r = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_CERT_X509,
					  certs, 32);
		if (r == 0) {
			log("No certificates found on smartcard");
			r = -1;
			goto err;
		} else if (r < 0) {
			error("Certificate enumeration failed: %s",
			      sc_strerror(r));
			goto err;
		}
		key_count = r;
	}
	/* FIXME: only keep entries with a corresponding private key */
	keys = xmalloc(sizeof(Key *) * (key_count*2+1));
	for (i = 0; i < key_count; i++) {
		k = key_new(KEY_RSA);
		if (k == NULL)
			break;
		r = sc_read_pubkey(k, certs[i]);
		if (r) {
			error("sc_read_pubkey failed: %s", sc_strerror(r));
			key_free(k);
			continue;
		}
		keys[real_count] = k;
		real_count++;
		k = key_new(KEY_RSA1);
		if (k == NULL){
			break;
			}
		convert_rsa_to_rsa1(keys[real_count-1], k);
		keys[real_count] = k;
		real_count++;
	}
	keys[real_count] = NULL;

	return keys;
err:
	sc_close();
	return NULL;
}

int
sc_put_key(Key *prv, const char *id)
{
	error("key uploading not yet supported");
	return -1;
}

#endif /* SMARTCARD */


More information about the openssh-unix-dev mailing list