diff --git a/src/agent.c b/src/agent.c index 9e1919b..edadf35 100644 --- a/src/agent.c +++ b/src/agent.c @@ -1,1132 +1,1132 @@ /* agent.c - Talking to gpg-agent. * Copyright (C) 2006, 2007, 2008, 2015, 2019 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #if HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #ifdef HAVE_W32_SYSTEM # define PATHSEP_C ';' # define WINVER 0x0500 /* Required for AllowSetForegroundWindow. */ # include # include #else # define PATHSEP_C ':' #endif #include #include #include "debug.h" #include "support.h" #include "sexp-parse.h" #include "cert.h" #include "agent.h" /* The global agent context. */ static assuan_context_t agent_ctx; /* Hack required for Windows. */ void gnupg_allow_set_foregound_window (pid_t pid) { if (!pid || pid == (pid_t)(-1)) return; #ifdef HAVE_W32_SYSTEM else if (!AllowSetForegroundWindow (pid)) DEBUG (DBG_CRIT, "AllowSetForegroundWindow(%lu) failed: %u\n", (unsigned long)pid, (unsigned int)GetLastError ()); #endif } /* Establish a connection to a running GPG agent. */ static gpg_error_t agent_connect (assuan_context_t *ctx_r) { gpg_error_t err = 0; assuan_context_t ctx = NULL; char buffer[512]; #ifndef HAVE_W32_SYSTEM DEBUG (DBG_INFO, "agent_connect: uid=%lu euid=%lu", (unsigned long)getuid (), (unsigned long)geteuid ()); #endif /* Use gpgconf to make sure that gpg-agent is started and to obtain * the socket name. For older version of gnupg we will fallback to * using two gpgconf commands with the same effect. */ /* FIXME: We should make sure that USER has no spaces. */ snprintf (buffer, sizeof buffer, "%s %s%s --show-socket --launch gpg-agent", get_gpgconf_path (), _scute_opt.user? "--chuid=":"", _scute_opt.user? _scute_opt.user:""); err = read_first_line (buffer, buffer, sizeof buffer); if (gpg_err_code (err) == GPG_ERR_NO_AGENT && is_gnupg_older_than (2, 2, 14)) { snprintf (buffer, sizeof buffer, "%s --launch gpg-agent", get_gpgconf_path ()); err = read_first_line (buffer, NULL, 0); if (!err) { snprintf (buffer, sizeof buffer, "%s --list-dirs agent-socket", get_gpgconf_path ()); err = read_first_line (buffer, buffer, sizeof buffer); } } DEBUG (DBG_INFO, "agent_connect: agent socket is '%s'", buffer); /* Then connect to the socket we got. */ if (!err) { err = assuan_new (&ctx); if (!err) { err = assuan_socket_connect (ctx, buffer, 0, 0); if (!err) { *ctx_r = ctx; if (_scute_opt.debug_flags & DBG_ASSUAN) assuan_set_log_stream (*ctx_r, _scute_debug_stream); } else assuan_release (ctx); } } /* We do not try any harder. If gpg-connect-agent somehow failed * to give us a suitable socket, we probably cannot do better. */ if (err) DEBUG (DBG_CRIT, "cannot connect to GPG agent: %s", gpg_strerror (err)); return err; } /* * Check whether STRING starts with KEYWORD. The keyword is * delimited by end of string, a space or a tab. Returns NULL if not * found or a pointer into STRING to the next non-space character * after the KEYWORD (which may be end of string). */ static char * has_leading_keyword (const char *string, const char *keyword) { size_t n = strlen (keyword); if (!strncmp (string, keyword, n) && (!string[n] || string[n] == ' ' || string[n] == '\t')) { string += n; while (*string == ' ' || *string == '\t') string++; return (char*)string; } return NULL; } /* This is the default inquiry callback. It mainly handles the Pinentry notifications. */ static gpg_error_t default_inq_cb (void *opaque, const char *line) { const char *s; (void)opaque; if ((s = has_leading_keyword (line, "PINENTRY_LAUNCHED"))) { gnupg_allow_set_foregound_window ((pid_t)strtoul (s, NULL, 10)); /* We do not pass errors to avoid breaking other code. */ } else DEBUG (DBG_CRIT, "ignoring gpg-agent inquiry `%s'\n", line); return 0; } /* Send a simple command to the agent. */ static gpg_error_t agent_simple_cmd (assuan_context_t ctx, const char *fmt, ...) { gpg_error_t err; char *optstr; va_list arg; int res; va_start (arg, fmt); res = vasprintf (&optstr, fmt, arg); va_end (arg); if (res < 0) return gpg_error_from_errno (errno); err = assuan_transact (ctx, optstr, NULL, NULL, default_inq_cb, NULL, NULL, NULL); if (err) DEBUG (DBG_CRIT, "gpg-agent command '%s' failed: %s", optstr, gpg_strerror (err)); free (optstr); return err; } /* Configure the GPG agent at connection CTX. */ static gpg_error_t agent_configure (assuan_context_t ctx) { gpg_error_t err = 0; char *dft_display = NULL; char *dft_ttyname = NULL; char *dft_ttytype = NULL; #if defined(HAVE_SETLOCALE) && (defined(LC_CTYPE) || defined(LC_MESSAGES)) char *old_lc = NULL; char *dft_lc = NULL; #endif char *dft_xauthority = NULL; char *dft_pinentry_user_data = NULL; err = agent_simple_cmd (ctx, "RESET"); if (err) return err; /* Set up display, terminal and locale options. */ dft_display = getenv ("DISPLAY"); if (dft_display) err = agent_simple_cmd (ctx, "OPTION display=%s", dft_display); if (err) return err; dft_ttyname = getenv ("GPG_TTY"); if ((!dft_ttyname || !*dft_ttyname) && ttyname (0)) dft_ttyname = ttyname (0); if (dft_ttyname) { err = agent_simple_cmd (ctx, "OPTION ttyname=%s", dft_ttyname); if (err) return err; } dft_ttytype = getenv ("TERM"); if (dft_ttytype) err = agent_simple_cmd (ctx, "OPTION ttytype=%s", dft_ttytype); if (err) return err; #if defined(HAVE_SETLOCALE) && defined(LC_CTYPE) old_lc = setlocale (LC_CTYPE, NULL); if (old_lc) { old_lc = strdup (old_lc); if (!old_lc) return gpg_error_from_errno (errno); } dft_lc = setlocale (LC_CTYPE, ""); if (dft_lc) err = agent_simple_cmd ("OPTION lc-ctype=%s", dft_lc); if (old_lc) { setlocale (LC_CTYPE, old_lc); free (old_lc); } #endif if (err) return err; #if defined(HAVE_SETLOCALE) && defined(LC_MESSAGES) old_lc = setlocale (LC_MESSAGES, NULL); if (old_lc) { old_lc = strdup (old_lc); if (!old_lc) err = gpg_error_from_errno (errno); } dft_lc = setlocale (LC_MESSAGES, ""); if (dft_lc) err = agent_simple_cmd ("OPTION lc-messages=%s", dft_lc); if (old_lc) { setlocale (LC_MESSAGES, old_lc); free (old_lc); } #endif dft_xauthority = getenv ("XAUTHORITY"); if (dft_xauthority) err = agent_simple_cmd (ctx, "OPTION xauthority=%s", dft_xauthority); if (gpg_err_code (err) == GPG_ERR_UNKNOWN_OPTION) err = 0; else if (err) return err; dft_pinentry_user_data = getenv ("PINENTRY_USER_DATA"); if (dft_pinentry_user_data) err = agent_simple_cmd (ctx, "OPTION pinentry_user_data=%s", dft_pinentry_user_data); if (err && gpg_err_code (err) != GPG_ERR_UNKNOWN_OPTION) return err; err = agent_simple_cmd (ctx, "OPTION allow-pinentry-notify"); if (err && gpg_err_code (err) != GPG_ERR_UNKNOWN_OPTION) return err; return err; } /* Check for a broken pipe, that is a lost connection to the agent. * Update the gloabls so that a re-connect is done the next time. * Returns ERR or the modified code GPG_ERR_NO_AGENT. */ static gpg_error_t check_broken_pipe (gpg_error_t err) { /* Note that Scute _currently_ uses GPG_ERR_SOURCE_ANY. */ if (gpg_err_code (err) == GPG_ERR_EPIPE && gpg_err_source (err) == GPG_ERR_SOURCE_ANY) { DEBUG (DBG_INFO, "Broken connection to the gpg-agent"); scute_agent_finalize (); err = gpg_error (GPG_ERR_NO_AGENT); } return err; } /* If the connection to the agent was lost earlier and detected by * check_broken_pipe we try to reconnect. */ static gpg_error_t ensure_agent_connection (void) { gpg_error_t err; if (agent_ctx) return 0; /* Connection still known. */ DEBUG (DBG_INFO, "Re-connecting to gpg-agent"); err = agent_connect (&agent_ctx); if (err) return err; err = agent_configure (agent_ctx); return check_broken_pipe (err); } /* Try to connect to the agent via socket. Handle the server's initial greeting. This is used only once when SCute is loaded. Re-connection is done using ensure_agent_connection. */ gpg_error_t scute_agent_initialize (void) { gpg_error_t err = 0; if (agent_ctx) { DEBUG (DBG_CRIT, "GPG Agent connection already established"); return 0; } DEBUG (DBG_INFO, "Establishing connection to gpg-agent"); err = agent_connect (&agent_ctx); if (err) return err; err = agent_configure (agent_ctx); if (err) scute_agent_finalize (); return err; } /* Call the agent to get the list of devices. */ gpg_error_t scute_agent_serialno (void) { gpg_error_t err = 0; err = ensure_agent_connection (); if (err) return err; err = assuan_transact (agent_ctx, "SCD SERIALNO --all", NULL, NULL, NULL, NULL, NULL, NULL); return err; } struct keyinfo_parm { int require_card; gpg_error_t error; struct keyinfo *list; }; /* Callback function for agent_keyinfo_list. */ static gpg_error_t keyinfo_list_cb (void *opaque, const char *line) { gpg_error_t err = 0; struct keyinfo_parm *parm = opaque; const char *keyword = line; int keywordlen; struct keyinfo *keyinfo = NULL; for (keywordlen=0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 7 && !memcmp (keyword, "KEYINFO", keywordlen)) { const char *s; int n; struct keyinfo **l_p = &parm->list; /* It's going to append the information at the end. */ while ((*l_p)) l_p = &(*l_p)->next; keyinfo = calloc (1, sizeof *keyinfo); if (!keyinfo) goto alloc_error; for (n=0,s=line; hexdigitp (s); s++, n++) ; if (n != 40) goto parm_error; memcpy (keyinfo->grip, line, 40); keyinfo->grip[40] = 0; line = s; if (!*line) goto parm_error; while (spacep (line)) line++; if (*line++ != 'T') { if (parm->require_card) { /* It's not on card, skip the status line. */ free (keyinfo); return 0; } else goto parm_error; } if (!*line) goto parm_error; while (spacep (line)) line++; for (n=0,s=line; hexdigitp (s); s++, n++) ; if (!n) goto skip; keyinfo->serialno = malloc (n+1); if (!keyinfo->serialno) goto alloc_error; memcpy (keyinfo->serialno, line, n); keyinfo->serialno[n] = 0; line = s; skip: *l_p = keyinfo; } return err; alloc_error: free (keyinfo->serialno); free (keyinfo); if (!parm->error) parm->error = gpg_error_from_syserror (); return 0; parm_error: free (keyinfo); if (!parm->error) parm->error = gpg_error (GPG_ERR_ASS_PARAMETER); return 0; } void scute_agent_free_keyinfo (struct keyinfo *l) { struct keyinfo *l_next; for (; l; l = l_next) { l_next = l->next; free (l->serialno); free (l); } } gpg_error_t scute_agent_keyinfo_list (struct keyinfo **keyinfo_p) { gpg_error_t err; err = ensure_agent_connection (); if (!err) { struct keyinfo_parm parm; parm.require_card = 1; parm.error = 0; parm.list = NULL; err = assuan_transact (agent_ctx, "KEYINFO --list", NULL, NULL, /* No data call back */ NULL, NULL, /* No inquiry call back */ keyinfo_list_cb, &parm); if (!err && parm.error) err = parm.error; if (!err) *keyinfo_p = parm.list; else scute_agent_free_keyinfo (parm.list); } return err; } /* Return a new malloced string by unescaping the string S. Escaping is percent escaping and '+'/space mapping. A binary nul will silently be replaced by a 0xFF. Function returns NULL to indicate an out of memory status. */ static char * unescape_status_string (const unsigned char *src) { char *buffer; char *dst; buffer = malloc (strlen (src) + 1); if (!buffer) return NULL; dst = buffer; while (*src) { if (*src == '%' && src[1] && src[2]) { src++; *dst = xtoi_2 (src); if (*dst == '\0') *dst = '\xff'; dst++; src += 2; } else if (*src == '+') { *(dst++) = ' '; src++; } else *(dst++) = *(src++); } *dst = 0; return buffer; } /* We only support RSA signatures up to 4096 bits. */ #define MAX_SIGNATURE_BITS 4096 /* Enough space to hold a 4096 bit RSA signature in an S-expression. */ #define MAX_SIGNATURE_LEN 640 /* FIXME: magic value */ struct signature { unsigned char data[MAX_SIGNATURE_LEN]; int len; }; static gpg_error_t pksign_cb (void *opaque, const void *buffer, size_t length) { struct signature *sig = opaque; if (sig->len + length > MAX_SIGNATURE_LEN) { DEBUG (DBG_INFO, "maximum signature length exceeded"); return gpg_error (GPG_ERR_BAD_DATA); } memcpy (&sig->data[sig->len], buffer, length); sig->len += length; return 0; } +/* FIXME: Support ECC */ /* Parse the result of an pksign operation which is a s-expression in canonical form that looks like (7:sig-val(3:rsa(1:s:))). The raw result is stored in RESULT of size *LEN, and *LEN is adjusted to the actual size. */ static gpg_error_t pksign_parse_result (const struct signature *sig, unsigned char *result, unsigned int *len) { gpg_error_t err; const unsigned char *s = sig->data; size_t n; int depth; if (*s++ != '(') gpg_error (GPG_ERR_INV_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if (! smatch (&s, n, "sig-val")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s++ != '(') gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if (! smatch (&s, n, "rsa")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); if (*s++ != '(') gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); if (! smatch (&s, n, "s")) return gpg_error (GPG_ERR_UNKNOWN_SEXP); n = snext (&s); if (! n) return gpg_error (GPG_ERR_INV_SEXP); /* Remove a possible prepended zero byte. */ if (!*s && n > 1) { n -= 1; s += 1; } if (*len < (unsigned int) n) return gpg_error (GPG_ERR_INV_LENGTH); *len = (unsigned int) n; memcpy (result, s, n); s += n; depth = 3; err = sskip (&s, &depth); if (err) return err; if (s - sig->data != sig->len || depth != 0) return gpg_error (GPG_ERR_INV_SEXP); return 0; } /* Decodes the hash DATA of size LEN (if necessary). Returns a pointer to the raw hash data in R_DATA, the size in R_LEN, and the name of the hash function in R_HASH. Prior to TLSv1.2, the hash function was the concatenation of MD5 and SHA1 applied to the data respectively, and no encoding was applied. From TLSv1.2 on, the hash value is prefixed with an hash identifier and encoded using ASN1. FIXME: Reference. */ static gpg_error_t decode_hash (const unsigned char *data, int len, const unsigned char **r_data, size_t *r_len, const char **r_hash) { static unsigned char rmd160_prefix[15] = /* Object ID is 1.3.36.3.2.1 */ { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03, 0x02, 0x01, 0x05, 0x00, 0x04, 0x14 }; static unsigned char sha1_prefix[15] = /* (1.3.14.3.2.26) */ { 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14 }; static unsigned char sha224_prefix[19] = /* (2.16.840.1.101.3.4.2.4) */ { 0x30, 0x2D, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1C }; static unsigned char sha256_prefix[19] = /* (2.16.840.1.101.3.4.2.1) */ { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 }; static unsigned char sha384_prefix[19] = /* (2.16.840.1.101.3.4.2.2) */ { 0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30 }; static unsigned char sha512_prefix[19] = /* (2.16.840.1.101.3.4.2.3) */ { 0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40 }; #define HANDLE(hash,hashlen) \ if (len == sizeof hash ## _prefix + (hashlen) \ && !memcmp (data, hash ## _prefix, sizeof hash ## _prefix)) \ { \ *r_data = data + sizeof hash ## _prefix; \ *r_len = hashlen; \ *r_hash = #hash; \ } if (len == 36) { /* Prior to TLSv1.2, a combination of MD5 and SHA1 was used. */ *r_data = data; *r_len = 36; *r_hash = "tls-md5sha1"; } /* TLSv1.2 encodes the hash value using ASN1. */ else HANDLE (sha1, 20) else HANDLE (rmd160, 20) else HANDLE (sha224, 28) else HANDLE (sha256, 32) else HANDLE (sha384, 48) else HANDLE (sha512, 64) else return gpg_error (GPG_ERR_INV_ARG); #undef HANDLE return 0; } struct sethash_inq_parm_s { assuan_context_t ctx; const void *data; size_t datalen; }; /* This is the inquiry callback required by the SETHASH command. */ static gpg_error_t sethash_inq_cb (void *opaque, const char *line) { gpg_error_t err = 0; struct sethash_inq_parm_s *parm = opaque; if (has_leading_keyword (line, "TBSDATA")) { err = assuan_send_data (parm->ctx, parm->data, parm->datalen); } else err = default_inq_cb (opaque, line); return err; } +/* FIXME: Support ECC */ /* Call the agent to sign (DATA,LEN) using the key described by * HEXGRIP. Stores the signature in SIG_RESULT and its length at * SIG_LEN; SIGLEN must initially point to the allocated size of * SIG_RESULT. */ gpg_error_t scute_agent_sign (const char *hexgrip, CK_MECHANISM_TYPE mechtype, unsigned char *data, int len, unsigned char *sig_result, unsigned int *sig_len) { char cmd[150]; gpg_error_t err; const char *hash; const unsigned char *raw_data; size_t raw_len; #define MAX_DATA_LEN 64 /* Size of an SHA512 sum. */ unsigned char pretty_data[2 * MAX_DATA_LEN + 1]; int i; struct signature sig; int nopadding = (mechtype == CKM_RSA_X_509); sig.len = 0; if (sig_len == NULL) return gpg_error (GPG_ERR_INV_ARG); if (nopadding) { raw_data = data; raw_len = len; hash = NULL; } else { err = decode_hash (data, len, &raw_data, &raw_len, &hash); if (err) return err; } if (sig_result == NULL) { *sig_len = raw_len; return 0; } if (!hexgrip || !sig_result) return gpg_error (GPG_ERR_INV_ARG); snprintf (cmd, sizeof (cmd), "SIGKEY %s", hexgrip); err = ensure_agent_connection (); if (err) return err; err = assuan_transact (agent_ctx, cmd, NULL, NULL, default_inq_cb, NULL, NULL, NULL); err = check_broken_pipe (err); if (err) return err; if (nopadding) { struct sethash_inq_parm_s parm; parm.ctx = agent_ctx; parm.data = raw_data; parm.datalen = raw_len; snprintf (cmd, sizeof (cmd), "SETHASH %s --inquire", (raw_len && raw_data[raw_len -1] == 0xBC)? "--pss":""); err = assuan_transact (agent_ctx, cmd, NULL, NULL, sethash_inq_cb, &parm, NULL, NULL); } else { for (i = 0; i < raw_len; i++) snprintf (&pretty_data[2 * i], 3, "%02X", raw_data[i]); pretty_data[2 * raw_len] = '\0'; snprintf (cmd, sizeof (cmd), "SETHASH --hash=%s %s", hash, pretty_data); err = assuan_transact (agent_ctx, cmd, NULL, NULL, default_inq_cb, NULL, NULL, NULL); } err = check_broken_pipe (err); if (err) return err; err = assuan_transact (agent_ctx, "PKSIGN", pksign_cb, &sig, default_inq_cb, NULL, NULL, NULL); err = check_broken_pipe (err); if (err) return err; err = pksign_parse_result (&sig, sig_result, sig_len); return err; } - - struct pkdecrypt_parm_s { unsigned int len; unsigned char data[512]; assuan_context_t ctx; const unsigned char *ciphertext; size_t ciphertextlen; }; static gpg_error_t pkdecrypt_data_cb (void *opaque, const void *buffer, size_t length) { struct pkdecrypt_parm_s *parm = opaque; if (parm->len + length > sizeof parm->data) { DEBUG (DBG_INFO, "maximum decryption result length exceeded"); return gpg_error (GPG_ERR_BAD_DATA); } memcpy (parm->data + parm->len, buffer, length); parm->len += length; return 0; } /* Handle the inquiries from pkdecrypt. Note, we only send the data, * assuan_transact takes care of flushing and writing the "END". */ static gpg_error_t pkdecrypt_inq_cb (void *opaque, const char *line) { struct pkdecrypt_parm_s *parm = opaque; gpg_error_t err; const char *keyword = line; int keywordlen; for (keywordlen = 0; *line && !spacep (line); line++, keywordlen++) ; while (spacep (line)) line++; if (keywordlen == 10 && !memcmp (keyword, "CIPHERTEXT", 10)) err = assuan_send_data (parm->ctx, parm->ciphertext, parm->ciphertextlen); else err = default_inq_cb (NULL, line); return err; } /* Parse the result of a pkdecrypt operation which is an s-expression * in canonical form that looks like * (5:value:). * * The raw result is stored in RESULT which has a size of *R_LEN, and * *R_LEN is adjusted to the actual size. */ static gpg_error_t pkdecrypt_parse_result (struct pkdecrypt_parm_s *ctx, unsigned char *result, unsigned int *r_len) { char *buf = ctx->data; size_t len = ctx->len; char *endp, *raw; size_t n, rawlen; if (len < 13 || memcmp (buf, "(5:value", 8) ) return gpg_error (GPG_ERR_INV_SEXP); len -= 8; buf += 8; n = strtoul (buf, &endp, 10); if (!n || *endp != ':') return gpg_error (GPG_ERR_INV_SEXP); endp++; if ((endp-buf)+n > len) return gpg_error (GPG_ERR_INV_SEXP); /* Oops: Inconsistent S-Exp. */ /* Let (RAW,RAWLEN) describe the pkcs#1 block and remove that padding. */ raw = endp; rawlen = n; if (rawlen < 10) /* 0x00 + 0x02 + <1_random> + 0x00 + <16-session> */ return gpg_error (GPG_ERR_INV_SESSION_KEY); if (raw[0] || raw[1] != 2 ) /* Wrong block type version. */ return gpg_error (GPG_ERR_INV_SESSION_KEY); for (n=2; n < rawlen && raw[n]; n++) /* Skip the random bytes. */ ; if (n+1 >= rawlen || raw[n] ) return gpg_error (GPG_ERR_INV_SESSION_KEY); n++; /* Skip the zero byte */ if (*r_len < (rawlen - n)) return gpg_error (GPG_ERR_TOO_LARGE); memcpy (result, raw + n, rawlen - n); *r_len = rawlen - n; return 0; } /* Call the agent to decrypt (ENCDATA,ENCDATALEN) using the key * described by HEXGRIP. Stores the plaintext at R_PLAINDATA and its * length at R_PLAINDATALEN; R_PLAINDATALEN must initially point to * the allocated size of R_PLAINDATA and is updated to the actual used * size on return. */ gpg_error_t scute_agent_decrypt (const char *hexgrip, unsigned char *encdata, int encdatalen, unsigned char *r_plaindata, unsigned int *r_plaindatalen) { char cmd[150]; gpg_error_t err; struct pkdecrypt_parm_s pkdecrypt; char *s_data; size_t s_datalen; if (!hexgrip || !encdata || !encdatalen || !r_plaindatalen) return gpg_error (GPG_ERR_INV_ARG); if (!r_plaindata) { /* Fixme: We do not return the minimal required length but our * internal buffer size. */ pkdecrypt.len = *r_plaindatalen; *r_plaindatalen = sizeof pkdecrypt.data - 1; if (pkdecrypt.len > sizeof pkdecrypt.data - 1) return gpg_error (GPG_ERR_INV_LENGTH); return 0; } err = ensure_agent_connection (); if (err) return err; snprintf (cmd, sizeof (cmd), "SETKEY %s", hexgrip); err = assuan_transact (agent_ctx, cmd, NULL, NULL, default_inq_cb, NULL, NULL, NULL); err = check_broken_pipe (err); if (err) return err; /* Convert the input into an appropriate s-expression as expected by * gpg-agent which is: * * (enc-val * (flags pkcs1) * (rsa * (a VALUE))) * * Out of convenience we append a non-counted extra nul to the * created canonical s-expression. */ s_data = malloc (100 + encdatalen); if (!s_data) return gpg_error_from_syserror (); snprintf (s_data, 50, "(7:enc-val(5:flags5:pkcs1)(3:rsa(1:a%d:", encdatalen); s_datalen = strlen (s_data); memcpy (s_data + s_datalen, encdata, encdatalen); s_datalen += encdatalen; memcpy (s_data + s_datalen, ")))", 4); s_datalen += 3; pkdecrypt.len = 0; pkdecrypt.ctx = agent_ctx; pkdecrypt.ciphertext = s_data; pkdecrypt.ciphertextlen = s_datalen; err = assuan_transact (agent_ctx, "PKDECRYPT", pkdecrypt_data_cb, &pkdecrypt, pkdecrypt_inq_cb, &pkdecrypt, NULL, NULL); err = check_broken_pipe (err); if (!err) err = pkdecrypt_parse_result (&pkdecrypt, r_plaindata, r_plaindatalen); free (s_data); return err; } /* Determine if FPR is trusted. */ gpg_error_t scute_agent_is_trusted (const char *fpr, bool *is_trusted) { gpg_error_t err; bool trusted = false; char cmd[150]; err = ensure_agent_connection (); if (err) return err; snprintf (cmd, sizeof (cmd), "ISTRUSTED %s", fpr); err = assuan_transact (agent_ctx, cmd, NULL, NULL, default_inq_cb, NULL, NULL, NULL); err = check_broken_pipe (err); if (err && gpg_err_code (err) != GPG_ERR_NOT_TRUSTED) return err; else if (!err) trusted = true; *is_trusted = trusted; return 0; } #define GET_CERT_INIT_SIZE 2048 struct get_cert_s { unsigned char *cert_der; int cert_der_len; int cert_der_size; }; struct random_request { unsigned char *buffer; size_t len; }; gpg_error_t get_challenge_data_cb (void *opaque, const void *line, size_t len) { struct random_request *request = opaque; if (len != request->len) return gpg_error (GPG_ERR_INV_LENGTH); memcpy (request->buffer, line, len); return 0; } gpg_error_t scute_agent_get_random (unsigned char *data, size_t len) { char command[16]; gpg_error_t err; struct random_request request; err = ensure_agent_connection (); if (err) return err; snprintf (command, sizeof(command), "SCD RANDOM %zu", len); request.buffer = data; request.len = len; err = assuan_transact (agent_ctx, command, get_challenge_data_cb, &request, NULL, NULL, NULL, NULL); err = check_broken_pipe (err); return err; } void scute_agent_finalize (void) { if (!agent_ctx) { DEBUG (DBG_CRIT, "no GPG Agent connection established"); return; } DEBUG (DBG_INFO, "releasing agent context"); assuan_release (agent_ctx); agent_ctx = NULL; } diff --git a/src/cert-object.c b/src/cert-object.c index 7a24280..b2a5b06 100644 --- a/src/cert-object.c +++ b/src/cert-object.c @@ -1,773 +1,780 @@ /* cert-object.c - Convert a GPGSM certificate into a PKCS #11 object. * Copyright (C) 2006, 2007 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #if HAVE_CONFIG_H #include #endif #include #include #include #include #include #include #include "cryptoki.h" #include "support.h" #include "cert.h" #include "debug.h" #define atoi_1(p) (*(p) - '0' ) #define atoi_2(p) ((atoi_1(p) * 10) + atoi_1((p)+1)) #define atoi_4(p) ((atoi_2(p) * 100) + atoi_2((p)+2)) #if 0 /* Currently not used. */ static bool time_to_ck_date (time_t *atime, CK_DATE *ckdate) { struct tm broken_time; int nr; if (!*atime) return false; #ifdef HAVE_LOCALTIME_R if (!localtime_r (atime, &broken_time)) return false; #else { /* FIXME: This is not thread-safe, but it minimizes risk. */ struct tm *b_time = localtime (atime); if (!b_time) return false; memcpy (&broken_time, b_time, sizeof (*b_time)); } #endif /* We can only represent years until 9999. */ if (!(broken_time.tm_year >= 0 && broken_time.tm_year <= 8099 && broken_time.tm_mon >= 0 && broken_time.tm_mon <= 11 && broken_time.tm_mday >= 1 && broken_time.tm_mday <= 31)) { DEBUG (DBG_INFO, "unrepresentable time %i-%i-%i", broken_time.tm_year, broken_time.tm_mon, broken_time.tm_mday); return false; } #define LAST_DIGIT(d) (((d) % 10) + '0') nr = broken_time.tm_year + 1900; ckdate->year[3] = LAST_DIGIT (nr); nr = nr / 10; ckdate->year[2] = LAST_DIGIT (nr); nr = nr / 10; ckdate->year[1] = LAST_DIGIT (nr); nr = nr / 10; ckdate->year[0] = LAST_DIGIT (nr); nr = broken_time.tm_mon + 1; ckdate->month[1] = LAST_DIGIT (nr); nr = nr / 10; ckdate->month[0] = LAST_DIGIT (nr); nr = broken_time.tm_mday; ckdate->day[1] = LAST_DIGIT (nr); nr = nr / 10; ckdate->day[0] = LAST_DIGIT (nr); return true; } #endif /*0*/ static gpg_error_t asn1_get_len (unsigned char **asn1, int *asn1_len, int *rlen) { unsigned char *ptr = *asn1; int len = *asn1_len; int cnt; int result = 0; if (len < 1) { DEBUG (DBG_INFO, "unexpected end of certificate"); return gpg_error (GPG_ERR_GENERAL); } if (*ptr & 0x80) { cnt = *ptr & 0x7f; ptr++; len--; } else cnt = 1; /* We only support a limited number of length bytes. */ if (cnt > 2) { DEBUG (DBG_INFO, "unsupported length field"); return gpg_error (GPG_ERR_GENERAL); } if (len < cnt) { DEBUG (DBG_INFO, "unexpected end of certificate"); return gpg_error (GPG_ERR_GENERAL); } while (cnt--) { result = (result << 8) | *ptr; ptr++; len--; } *asn1 = ptr; *asn1_len = len; *rlen = result; return 0; } /* A path to an ASN.1 element that can be looked up with asn1_get_element. The last element in the list is returned (that one should have ENTER being false. */ struct asn1_path { unsigned char tag; /* True if we should enter the element, false if we should skip it. */ bool enter; }; static gpg_error_t asn1_get_element (unsigned char *cert, int cert_len, unsigned char **sub_start, int *sub_len, struct asn1_path *path, int path_size) { gpg_error_t err; unsigned char *prev_certp = NULL; unsigned char *certp = cert; int cert_left = cert_len; int len; int i; for (i = 0; i < path_size; i++) { prev_certp = certp; if (cert_left < 1) { DEBUG (DBG_INFO, "unexpected end of certificate"); return gpg_error (GPG_ERR_GENERAL); } if (*certp != path[i].tag) { DEBUG (DBG_INFO, "wrong element in lookup path"); return gpg_error (GPG_ERR_GENERAL); } certp++; cert_left--; err = asn1_get_len (&certp, &cert_left, &len); if (err) return err; if (!path[i].enter) { if (cert_left < len) { DEBUG (DBG_INFO, "unexpected end of certificate"); return gpg_error (GPG_ERR_GENERAL); } certp += len; cert_left -= len; } else { /* Special code to deal with ASN.1 data encapsulated in a bit string. */ if (path[i].tag == '\x03') { if (cert_left < 1) { DEBUG (DBG_INFO, "unexpected end of certificate"); return gpg_error (GPG_ERR_GENERAL); } if (*certp != '\x00') { DEBUG (DBG_INFO, "expected binary encapsulation missing"); return gpg_error (GPG_ERR_GENERAL); } certp++; cert_left--; } } } /* We found the subject. */ *sub_start = prev_certp; *sub_len = certp - prev_certp; return 0; } static gpg_error_t asn1_get_issuer (unsigned char *cert, int cert_len, unsigned char **sub_start, int *sub_len) { /* The path to the issuer entry in the DER file. This is Sequence->Sequence->Version,Serial,AlgID,Issuer. */ struct asn1_path path[] = { { '\x30', true }, { '\x30', true }, { '\xa0', false }, { '\x02', false }, { '\x30', false }, { '\x30', false } }; return asn1_get_element (cert, cert_len, sub_start, sub_len, path, DIM (path)); } static gpg_error_t asn1_get_subject (unsigned char *cert, int cert_len, unsigned char **sub_start, int *sub_len) { /* The path to the subject entry in the DER file. This is Sequence->Sequence->Version,Serial,AlgID,Issuer,Time,Subject. */ struct asn1_path path[] = { { '\x30', true }, { '\x30', true }, { '\xa0', false }, { '\x02', false }, { '\x30', false }, { '\x30', false }, { '\x30', false }, { '\x30', false } }; return asn1_get_element (cert, cert_len, sub_start, sub_len, path, DIM (path)); } static gpg_error_t asn1_get_serial (unsigned char *cert, int cert_len, unsigned char **sub_start, int *sub_len) { /* The path to the serial entry in the DER file. This is Sequence->Sequence->Version,Serial. */ struct asn1_path path[] = { { '\x30', true }, { '\x30', true }, { '\xa0', false }, { '\x02', false } }; return asn1_get_element (cert, cert_len, sub_start, sub_len, path, DIM (path)); } static gpg_error_t asn1_get_modulus (unsigned char *cert, int cert_len, unsigned char **sub_start, int *sub_len) { gpg_error_t err; int len; struct asn1_path path[] = { { '\x30', true }, { '\x30', true }, { '\xa0', false }, { '\x02', false }, { '\x30', false }, { '\x30', false }, { '\x30', false }, { '\x30', false }, { '\x30', true }, { '\x30', false }, { '\x03', true }, { '\x30', true }, { '\x02', false } }; /* The path to the modulus entry in the DER file. This is Sequence->Sequence->Version,Serial,AlgID,Issuer,Time,Subject, Sequence->Sequence,Bitstring->Sequence->Integer,Integer */ err = asn1_get_element (cert, cert_len, sub_start, sub_len, path, DIM (path)); if (err) return err; if (*sub_len < 1) { DEBUG (DBG_INFO, "modulus too short"); return gpg_error (GPG_ERR_GENERAL); } (*sub_start)++; (*sub_len)--; err = asn1_get_len (sub_start, sub_len, &len); if (err) return err; /* PKCS #11 expects an unsigned big integer. */ while (**sub_start == '\x00' && *sub_len > 0) { (*sub_start)++; (*sub_len)--; } return 0; } static gpg_error_t asn1_get_public_exp (unsigned char *cert, int cert_len, unsigned char **sub_start, int *sub_len) { gpg_error_t err; int len; /* The path to the public exp entry in the DER file. This is Sequence->Sequence->Version,Serial,AlgID,Issuer,Time,Subject, Sequence->Sequence,Bitstring->Sequence->Integer,Integer */ struct asn1_path path[] = { { '\x30', true }, { '\x30', true }, { '\xa0', false }, { '\x02', false }, { '\x30', false }, { '\x30', false }, { '\x30', false }, { '\x30', false }, { '\x30', true }, { '\x30', false }, { '\x03', true }, { '\x30', true }, { '\x02', false }, { '\x02', false } }; err = asn1_get_element (cert, cert_len, sub_start, sub_len, path, DIM (path)); if (err) return err; if (*sub_len < 1) { DEBUG (DBG_INFO, "public exponent too short"); return gpg_error (GPG_ERR_GENERAL); } (*sub_start)++; (*sub_len)--; err = asn1_get_len (sub_start, sub_len, &len); if (err) return err; /* PKCS #11 expects an unsigned big integer. */ while (**sub_start == '\x00' && *sub_len > 0) { (*sub_start)++; (*sub_len)--; } return 0; } static gpg_error_t attr_one (CK_ATTRIBUTE_PTR attr, CK_ULONG *attr_count, CK_ATTRIBUTE_TYPE type, CK_VOID_PTR val, CK_ULONG size) { CK_ULONG i = *attr_count; attr[i].type = type; attr[i].ulValueLen = size; attr[i].pValue = malloc (size); if (attr[i].pValue == NULL) { DEBUG (DBG_CRIT, "out of memory"); return gpg_error (GPG_ERR_ENOMEM); } memcpy (attr[i].pValue, val, size); (*attr_count)++; return 0; } static gpg_error_t attr_empty (CK_ATTRIBUTE_PTR attr, CK_ULONG *attr_count, CK_ATTRIBUTE_TYPE type) { CK_ULONG i = *attr_count; attr[i].type = type; attr[i].ulValueLen = 0; attr[i].pValue = NULL_PTR; (*attr_count)++; return 0; } void scute_attr_free (CK_ATTRIBUTE_PTR attr, CK_ULONG attr_count) { while (0 < attr_count--) free (attr[attr_count].pValue); } gpg_error_t scute_attr_cert (struct cert *cert, const char *grip, CK_ATTRIBUTE_PTR *attrp, CK_ULONG *attr_countp) { CK_RV err = 0; CK_ATTRIBUTE_PTR attr; CK_ULONG attr_count; unsigned char *subject_start; int subject_len; unsigned char *issuer_start; int issuer_len; unsigned char *serial_start; int serial_len; CK_OBJECT_CLASS obj_class = CKO_CERTIFICATE; CK_BBOOL obj_token = CK_TRUE; CK_BBOOL obj_private = CK_FALSE; CK_BBOOL obj_modifiable = CK_FALSE; CK_CERTIFICATE_TYPE obj_cert_type = CKC_X_509; CK_BBOOL obj_trusted = cert->is_trusted; CK_ULONG obj_cert_cat = 0; CK_BYTE obj_check_value[3] = { '\0', '\0', '\0' }; CK_DATE obj_start_date; CK_DATE obj_end_date; CK_ULONG obj_java_midp_sec_domain = 0; err = asn1_get_subject (cert->cert_der, cert->cert_der_len, &subject_start, &subject_len); if (err) { DEBUG (DBG_INFO, "rejecting certificate: could not get subject: %s", gpg_strerror (err)); return err; } err = asn1_get_issuer (cert->cert_der, cert->cert_der_len, &issuer_start, &issuer_len); if (err) { DEBUG (DBG_INFO, "rejecting certificate: could not get issuer: %s", gpg_strerror (err)); return err; } err = asn1_get_serial (cert->cert_der, cert->cert_der_len, &serial_start, &serial_len); if (err) { DEBUG (DBG_INFO, "rejecting certificate: could not get serial: %s", gpg_strerror (err)); return err; } #define NR_ATTR_CERT 20 attr = malloc (sizeof (CK_ATTRIBUTE) * NR_ATTR_CERT); attr_count = 0; if (!attr) { DEBUG (DBG_INFO, "out of memory"); return gpg_error (GPG_ERR_ENOMEM); } if (!err) err = attr_one (attr, &attr_count, CKA_CLASS, &obj_class, sizeof obj_class); if (!err) err = attr_one (attr, &attr_count, CKA_TOKEN, &obj_token, sizeof obj_token); if (!err) err = attr_one (attr, &attr_count, CKA_PRIVATE, &obj_private, sizeof obj_private); if (!err) err = attr_one (attr, &attr_count, CKA_MODIFIABLE, &obj_modifiable, sizeof obj_modifiable); if (!err) err = attr_one (attr, &attr_count, CKA_LABEL, "Scute", 5); if (!err) err = attr_one (attr, &attr_count, CKA_CERTIFICATE_TYPE, &obj_cert_type, sizeof obj_cert_type); if (!err) err = attr_one (attr, &attr_count, CKA_TRUSTED, &obj_trusted, sizeof obj_trusted); if (!err) err = attr_one (attr, &attr_count, CKA_CERTIFICATE_CATEGORY, &obj_cert_cat, sizeof obj_cert_cat); /* FIXME: Calculate check_value. */ if (!err) err = attr_one (attr, &attr_count, CKA_CHECK_VALUE, &obj_check_value, sizeof obj_check_value); #if 0 if (time_to_ck_date (&cert->timestamp, &obj_start_date)) { if (!err) err = attr_one (attr, &attr_count, CKA_START_DATE, &obj_start_date, sizeof obj_start_date); } if (time_to_ck_date (&cert->expires, &obj_end_date)) { if (!err) err = attr_one (attr, &attr_count, CKA_END_DATE, &obj_end_date, sizeof obj_end_date); } #else /* For now, we disable these fields. We can parse them from the certificate just as the other data. However, we would like to avoid parsing the certificates at all, let's see how much functionality we really need in the PKCS#11 token first. */ (void)obj_start_date; (void)obj_end_date; if (!err) err = attr_empty (attr, &attr_count, CKA_START_DATE); if (!err) err = attr_empty (attr, &attr_count, CKA_END_DATE); #endif /* Note: This attribute is mandatory. Without it, Firefox client authentication won't work. */ if (!err) err = attr_one (attr, &attr_count, CKA_SUBJECT, subject_start, subject_len); if (!err) err = attr_one (attr, &attr_count, CKA_ID, (void *)grip, strlen (grip)); if (!err) err = attr_one (attr, &attr_count, CKA_ISSUER, issuer_start, issuer_len); if (!err) err = attr_one (attr, &attr_count, CKA_SERIAL_NUMBER, serial_start, serial_len); if (!err) err = attr_one (attr, &attr_count, CKA_VALUE, cert->cert_der, cert->cert_der_len); if (!err) err = attr_empty (attr, &attr_count, CKA_URL); if (!err) err = attr_empty (attr, &attr_count, CKA_HASH_OF_SUBJECT_PUBLIC_KEY); if (!err) err = attr_empty (attr, &attr_count, CKA_HASH_OF_ISSUER_PUBLIC_KEY); if (!err) err = attr_one (attr, &attr_count, CKA_JAVA_MIDP_SECURITY_DOMAIN, &obj_java_midp_sec_domain, sizeof obj_java_midp_sec_domain); if (err) { DEBUG (DBG_INFO, "could not build certificate object: %s", gpg_strerror (err)); scute_attr_free (attr, attr_count); return err; } /* FIXME: Not completely safe. */ assert (NR_ATTR_CERT >= attr_count); *attrp = attr; *attr_countp = attr_count; return 0; } gpg_error_t scute_attr_prv (struct cert *cert, const char *grip, CK_ATTRIBUTE_PTR *attrp, CK_ULONG *attr_countp) { CK_RV err = 0; CK_ATTRIBUTE_PTR attr; CK_ULONG attr_count; unsigned char *subject_start; int subject_len; unsigned char *modulus_start; int modulus_len; unsigned char *public_exp_start; int public_exp_len; CK_OBJECT_CLASS obj_class = CKO_PRIVATE_KEY; CK_BBOOL obj_token = CK_TRUE; CK_BBOOL obj_private = CK_FALSE; CK_BBOOL obj_modifiable = CK_FALSE; CK_KEY_TYPE obj_key_type = CKK_RSA; CK_DATE obj_start_date; CK_DATE obj_end_date; CK_BBOOL obj_derive = CK_FALSE; CK_BBOOL obj_local = CK_FALSE; /* FIXME: Unknown. */ + /* FIXME: appropriate machanism should be chosen. */ + /* FIXME: CKM_EC_KEY_PAIR_GEN + CKM_EC_EDWARDS_KEY_PAIR_GEN + CKM_EC_MONTGOMERY_KEY_PAIR_GEN + */ CK_MECHANISM_TYPE obj_key_gen = CKM_RSA_PKCS_KEY_PAIR_GEN; CK_MECHANISM_TYPE obj_mechanisms[] = { CKM_RSA_PKCS }; CK_BBOOL obj_sensitive = CK_TRUE; CK_BBOOL obj_decrypt = CK_FALSE; /* Updated below. */ CK_BBOOL obj_sign = CK_FALSE; /* Updated below. */ CK_BBOOL obj_sign_recover = CK_FALSE; CK_BBOOL obj_unwrap = CK_FALSE; CK_BBOOL obj_extractable = CK_FALSE; CK_BBOOL obj_always_sensitive = CK_TRUE; CK_BBOOL obj_never_extractable = CK_TRUE; CK_BBOOL obj_wrap_with_trusted = CK_FALSE; CK_BBOOL obj_always_authenticate = CK_FALSE; obj_sign = CK_TRUE; err = asn1_get_subject (cert->cert_der, cert->cert_der_len, &subject_start, &subject_len); if (err) { DEBUG (DBG_INFO, "rejecting certificate: could not get subject: %s", gpg_strerror (err)); return err; } err = asn1_get_modulus (cert->cert_der, cert->cert_der_len, &modulus_start, &modulus_len); if (err) { DEBUG (DBG_INFO, "rejecting certificate: could not get modulus: %s", gpg_strerror (err)); return err; } err = asn1_get_public_exp (cert->cert_der, cert->cert_der_len, &public_exp_start, &public_exp_len); if (err) { DEBUG (DBG_INFO, "rejecting certificate: could not get public exp: %s", gpg_strerror (err)); return err; } #define NR_ATTR_PRV 27 attr = malloc (sizeof (CK_ATTRIBUTE) * NR_ATTR_PRV); attr_count = 0; if (!attr) { DEBUG (DBG_INFO, "out of core"); return gpg_error (GPG_ERR_ENOMEM); } if (!err) err = attr_one (attr, &attr_count, CKA_CLASS, &obj_class, sizeof obj_class); if (!err) err = attr_one (attr, &attr_count, CKA_TOKEN, &obj_token, sizeof obj_token); if (!err) err = attr_one (attr, &attr_count, CKA_PRIVATE, &obj_private, sizeof obj_private); if (!err) err = attr_one (attr, &attr_count, CKA_MODIFIABLE, &obj_modifiable, sizeof obj_modifiable); if (!err) err = attr_one (attr, &attr_count, CKA_LABEL, "Scute", 5); if (!err) err = attr_one (attr, &attr_count, CKA_KEY_TYPE, &obj_key_type, sizeof obj_key_type); if (!err) err = attr_one (attr, &attr_count, CKA_ID, (void *)grip, strlen (grip)); #if 0 /* For now, we disable these fields. We can parse them from the certificate just as the other data. However, we would like to avoid parsing the certificates at all, let's see how much functionality we really need in the PKCS#11 token first. */ /* This code currently only works for certificates retrieved through gpgsm. */ if (time_to_ck_date (&cert->timestamp, &obj_start_date)) { if (!err) err = attr_one (attr, &attr_count, CKA_START_DATE, &obj_start_date, sizeof obj_start_date); } if (time_to_ck_date (&cert->expires, &obj_end_date)) { if (!err) err = attr_one (attr, &attr_count, CKA_END_DATE, &obj_end_date, sizeof obj_end_date); } #else /* For now, we disable these fields. We can parse them from the certificate just as the other data. However, we would like to avoid parsing the certificates at all, let's see how much functionality we really need in the PKCS#11 token first. */ (void)obj_start_date; (void)obj_end_date; if (!err) err = attr_empty (attr, &attr_count, CKA_START_DATE); if (!err) err = attr_empty (attr, &attr_count, CKA_END_DATE); #endif if (!err) err = attr_one (attr, &attr_count, CKA_DERIVE, &obj_derive, sizeof obj_derive); if (!err) err = attr_one (attr, &attr_count, CKA_LOCAL, &obj_local, sizeof obj_local); if (!err) err = attr_one (attr, &attr_count, CKA_KEY_GEN_MECHANISM, &obj_key_gen, sizeof obj_key_gen); if (!err) err = attr_one (attr, &attr_count, CKA_ALLOWED_MECHANISMS, &obj_mechanisms, sizeof obj_mechanisms); if (!err) err = attr_one (attr, &attr_count, CKA_SUBJECT, subject_start, subject_len); if (!err) err = attr_one (attr, &attr_count, CKA_SENSITIVE, &obj_sensitive, sizeof obj_sensitive); if (!err) err = attr_one (attr, &attr_count, CKA_DECRYPT, &obj_decrypt, sizeof obj_decrypt); if (!err) err = attr_one (attr, &attr_count, CKA_SIGN, &obj_sign, sizeof obj_sign); if (!err) err = attr_one (attr, &attr_count, CKA_SIGN_RECOVER, &obj_sign_recover, sizeof obj_sign_recover); if (!err) err = attr_one (attr, &attr_count, CKA_UNWRAP, &obj_unwrap, sizeof obj_unwrap); if (!err) err = attr_one (attr, &attr_count, CKA_EXTRACTABLE, &obj_extractable, sizeof obj_extractable); if (!err) err = attr_one (attr, &attr_count, CKA_ALWAYS_SENSITIVE, &obj_always_sensitive, sizeof obj_always_sensitive); if (!err) err = attr_one (attr, &attr_count, CKA_NEVER_EXTRACTABLE, &obj_never_extractable, sizeof obj_never_extractable); if (!err) err = attr_one (attr, &attr_count, CKA_WRAP_WITH_TRUSTED, &obj_wrap_with_trusted, sizeof obj_wrap_with_trusted); if (!err) err = attr_empty (attr, &attr_count, CKA_UNWRAP_TEMPLATE); if (!err) err = attr_one (attr, &attr_count, CKA_ALWAYS_AUTHENTICATE, &obj_always_authenticate, sizeof obj_always_authenticate); + /* FIXME: appropriate objects should be provided. */ + /* FIXME: CKA_EC_POINT, CKA_EC_PARAMS */ if (!err) err = attr_one (attr, &attr_count, CKA_MODULUS, modulus_start, modulus_len); if (!err) err = attr_one (attr, &attr_count, CKA_PUBLIC_EXPONENT, public_exp_start, public_exp_len); if (err) { DEBUG (DBG_INFO, "could not build private certificate object: %s", gpg_strerror (err)); scute_attr_free (attr, attr_count); return err; } /* FIXME: Not completely safe. */ assert (NR_ATTR_PRV >= attr_count); *attrp = attr; *attr_countp = attr_count; return 0; } diff --git a/src/p11-signinit.c b/src/p11-signinit.c index 92cd928..5f3f0b3 100644 --- a/src/p11-signinit.c +++ b/src/p11-signinit.c @@ -1,63 +1,64 @@ /* p11-signinit.c - Cryptoki implementation. * Copyright (C) 2006 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #if HAVE_CONFIG_H #include #endif #include "cryptoki.h" #include "locking.h" #include "slots.h" /* Prepare a signature operation. HSESSION is the session's handle. * PMECHANISM describes the mechanism to be used. HKEY describes the * key to be used. After calling this function either C_Sign or * (C_SignUpdate, C_SignFinal) can be used to actually sign the data. * The preparation is valid until C_Sign or C_SignFinal. */ CK_RV CK_SPEC C_SignInit (CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey) { CK_RV err = CKR_OK; slot_iterator_t slot; session_iterator_t sid; if (pMechanism == NULL_PTR) return CKR_ARGUMENTS_BAD; if (hKey == CK_INVALID_HANDLE) return CKR_ARGUMENTS_BAD; + /* FIXME */ if (pMechanism->mechanism != CKM_RSA_PKCS && pMechanism->mechanism != CKM_RSA_X_509) return CKR_MECHANISM_INVALID; err = scute_global_lock (); if (err) return err; err = slots_lookup_session (hSession, &slot, &sid); if (!err) err = session_set_signing_key (slot, sid, hKey, pMechanism->mechanism); scute_global_unlock (); return err; } diff --git a/src/pkcs11.h b/src/pkcs11.h index c24bea0..311debf 100644 --- a/src/pkcs11.h +++ b/src/pkcs11.h @@ -1,1382 +1,1382 @@ /* pkcs11.h * Copyright 2006, 2007 g10 Code GmbH * Copyright 2006 Andreas Jellinghaus * * This file is free software; as a special exception the authors give * 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. * SPDX-License-Identifier: FSFULLR */ /* This file is a modified implementation of the PKCS #11 standard by * RSA Security Inc. It is mostly a drop-in replacement, with the * following change: * * This header file does not require any macro definitions by the user * (like CK_DEFINE_FUNCTION etc). In fact, it defines those macros * for you (if useful, some are missing, let me know if you need * more). * * There is an additional API available that does comply better to the * GNU coding standard. It can be switched on by defining * CRYPTOKI_GNU before including this header file. For this, the * following changes are made to the specification: * * All structure types are changed to a "struct ck_foo" where CK_FOO * is the type name in PKCS #11. * * All non-structure types are changed to ck_foo_t where CK_FOO is the * lowercase version of the type name in PKCS #11. The basic types * (CK_ULONG et al.) are removed without substitute. * * All members of structures are modified in the following way: Type * indication prefixes are removed, and underscore characters are * inserted before words. Then the result is lowercased. * * Note that function names are still in the original case, as they * need for ABI compatibility. * * CK_FALSE, CK_TRUE and NULL_PTR are removed without substitute. Use * . * * If CRYPTOKI_COMPAT is defined before including this header file, * then none of the API changes above take place, and the API is the * one defined by the PKCS #11 standard. * * * Please submit changes back to the Scute project with a request to * https://dev.gnupg.org, so that they can be picked up by other * projects from there as well. */ #ifndef PKCS11_H #define PKCS11_H 1 #if defined(__cplusplus) extern "C" { #endif /* The version of cryptoki we implement. The revision is changed with each modification of this file. If you do not use the "official" version of this file, please consider deleting the revision macro (you may use a macro with a different name to keep track of your versions). */ #define CRYPTOKI_VERSION_MAJOR 2 #define CRYPTOKI_VERSION_MINOR 20 #define CRYPTOKI_VERSION_REVISION 6 /* Compatibility interface is default, unless CRYPTOKI_GNU is given. */ #ifndef CRYPTOKI_GNU #ifndef CRYPTOKI_COMPAT #define CRYPTOKI_COMPAT 1 #endif #endif /* System dependencies. */ #if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32) /* There is a matching pop below. */ #pragma pack(push, cryptoki, 1) #ifdef CRYPTOKI_EXPORTS #define CK_SPEC __declspec(dllexport) #else #define CK_SPEC __declspec(dllimport) #endif #else #define CK_SPEC #endif #ifdef CRYPTOKI_COMPAT /* If we are in compatibility mode, switch all exposed names to the PKCS #11 variant. There are corresponding #undefs below. */ #define ck_flags_t CK_FLAGS #define ck_version _CK_VERSION #define ck_info _CK_INFO #define cryptoki_version cryptokiVersion #define manufacturer_id manufacturerID #define library_description libraryDescription #define library_version libraryVersion #define ck_notification_t CK_NOTIFICATION #define ck_slot_id_t CK_SLOT_ID #define ck_slot_info _CK_SLOT_INFO #define slot_description slotDescription #define hardware_version hardwareVersion #define firmware_version firmwareVersion #define ck_token_info _CK_TOKEN_INFO #define serial_number serialNumber #define max_session_count ulMaxSessionCount #define session_count ulSessionCount #define max_rw_session_count ulMaxRwSessionCount #define rw_session_count ulRwSessionCount #define max_pin_len ulMaxPinLen #define min_pin_len ulMinPinLen #define total_public_memory ulTotalPublicMemory #define free_public_memory ulFreePublicMemory #define total_private_memory ulTotalPrivateMemory #define free_private_memory ulFreePrivateMemory #define utc_time utcTime #define ck_session_handle_t CK_SESSION_HANDLE #define ck_user_type_t CK_USER_TYPE #define ck_state_t CK_STATE #define ck_session_info _CK_SESSION_INFO #define slot_id slotID #define device_error ulDeviceError #define ck_object_handle_t CK_OBJECT_HANDLE #define ck_object_class_t CK_OBJECT_CLASS #define ck_hw_feature_type_t CK_HW_FEATURE_TYPE #define ck_key_type_t CK_KEY_TYPE #define ck_certificate_type_t CK_CERTIFICATE_TYPE #define ck_attribute_type_t CK_ATTRIBUTE_TYPE #define ck_attribute _CK_ATTRIBUTE #define value pValue #define value_len ulValueLen #define ck_date _CK_DATE #define ck_mechanism_type_t CK_MECHANISM_TYPE #define ck_mechanism _CK_MECHANISM #define parameter pParameter #define parameter_len ulParameterLen #define ck_mechanism_info _CK_MECHANISM_INFO #define min_key_size ulMinKeySize #define max_key_size ulMaxKeySize #define ck_rv_t CK_RV #define ck_notify_t CK_NOTIFY #define ck_function_list _CK_FUNCTION_LIST #define ck_createmutex_t CK_CREATEMUTEX #define ck_destroymutex_t CK_DESTROYMUTEX #define ck_lockmutex_t CK_LOCKMUTEX #define ck_unlockmutex_t CK_UNLOCKMUTEX #define ck_c_initialize_args _CK_C_INITIALIZE_ARGS #define create_mutex CreateMutex #define destroy_mutex DestroyMutex #define lock_mutex LockMutex #define unlock_mutex UnlockMutex #define reserved pReserved #endif /* CRYPTOKI_COMPAT */ typedef unsigned long ck_flags_t; struct ck_version { unsigned char major; unsigned char minor; }; struct ck_info { struct ck_version cryptoki_version; unsigned char manufacturer_id[32]; ck_flags_t flags; unsigned char library_description[32]; struct ck_version library_version; }; typedef unsigned long ck_notification_t; #define CKN_SURRENDER (0UL) typedef unsigned long ck_slot_id_t; struct ck_slot_info { unsigned char slot_description[64]; unsigned char manufacturer_id[32]; ck_flags_t flags; struct ck_version hardware_version; struct ck_version firmware_version; }; #define CKF_TOKEN_PRESENT (1UL << 0) #define CKF_REMOVABLE_DEVICE (1UL << 1) #define CKF_HW_SLOT (1UL << 2) #define CKF_ARRAY_ATTRIBUTE (1UL << 30) struct ck_token_info { unsigned char label[32]; unsigned char manufacturer_id[32]; unsigned char model[16]; unsigned char serial_number[16]; ck_flags_t flags; unsigned long max_session_count; unsigned long session_count; unsigned long max_rw_session_count; unsigned long rw_session_count; unsigned long max_pin_len; unsigned long min_pin_len; unsigned long total_public_memory; unsigned long free_public_memory; unsigned long total_private_memory; unsigned long free_private_memory; struct ck_version hardware_version; struct ck_version firmware_version; unsigned char utc_time[16]; }; #define CKF_RNG (1UL << 0) #define CKF_WRITE_PROTECTED (1UL << 1) #define CKF_LOGIN_REQUIRED (1UL << 2) #define CKF_USER_PIN_INITIALIZED (1UL << 3) #define CKF_RESTORE_KEY_NOT_NEEDED (1UL << 5) #define CKF_CLOCK_ON_TOKEN (1UL << 6) #define CKF_PROTECTED_AUTHENTICATION_PATH (1UL << 8) #define CKF_DUAL_CRYPTO_OPERATIONS (1UL << 9) #define CKF_TOKEN_INITIALIZED (1UL << 10) #define CKF_SECONDARY_AUTHENTICATION (1UL << 11) #define CKF_USER_PIN_COUNT_LOW (1UL << 16) #define CKF_USER_PIN_FINAL_TRY (1UL << 17) #define CKF_USER_PIN_LOCKED (1UL << 18) #define CKF_USER_PIN_TO_BE_CHANGED (1UL << 19) #define CKF_SO_PIN_COUNT_LOW (1UL << 20) #define CKF_SO_PIN_FINAL_TRY (1UL << 21) #define CKF_SO_PIN_LOCKED (1UL << 22) #define CKF_SO_PIN_TO_BE_CHANGED (1UL << 23) #define CK_UNAVAILABLE_INFORMATION ((unsigned long) -1) #define CK_EFFECTIVELY_INFINITE (0UL) typedef unsigned long ck_session_handle_t; #define CK_INVALID_HANDLE (0UL) typedef unsigned long ck_user_type_t; #define CKU_SO (0UL) #define CKU_USER (1UL) #define CKU_CONTEXT_SPECIFIC (2UL) typedef unsigned long ck_state_t; #define CKS_RO_PUBLIC_SESSION (0UL) #define CKS_RO_USER_FUNCTIONS (1UL) #define CKS_RW_PUBLIC_SESSION (2UL) #define CKS_RW_USER_FUNCTIONS (3UL) #define CKS_RW_SO_FUNCTIONS (4UL) struct ck_session_info { ck_slot_id_t slot_id; ck_state_t state; ck_flags_t flags; unsigned long device_error; }; #define CKF_RW_SESSION (1UL << 1) #define CKF_SERIAL_SESSION (1UL << 2) typedef unsigned long ck_object_handle_t; typedef unsigned long ck_object_class_t; #define CKO_DATA (0UL) #define CKO_CERTIFICATE (1UL) #define CKO_PUBLIC_KEY (2UL) #define CKO_PRIVATE_KEY (3UL) #define CKO_SECRET_KEY (4UL) #define CKO_HW_FEATURE (5UL) #define CKO_DOMAIN_PARAMETERS (6UL) #define CKO_MECHANISM (7UL) #define CKO_VENDOR_DEFINED (1UL << 31) typedef unsigned long ck_hw_feature_type_t; #define CKH_MONOTONIC_COUNTER (1UL) #define CKH_CLOCK (2UL) #define CKH_USER_INTERFACE (3UL) #define CKH_VENDOR_DEFINED (1UL << 31) typedef unsigned long ck_key_type_t; #define CKK_RSA (0UL) #define CKK_DSA (1UL) #define CKK_DH (2UL) #define CKK_EC (3UL) #define CKK_X9_42_DH (4UL) #define CKK_KEA (5UL) #define CKK_GENERIC_SECRET (0x10UL) #define CKK_RC2 (0x11UL) #define CKK_RC4 (0x12UL) #define CKK_DES (0x13UL) #define CKK_DES2 (0x14UL) #define CKK_DES3 (0x15UL) #define CKK_CAST (0x16UL) #define CKK_CAST3 (0x17UL) #define CKK_CAST128 (0x18UL) #define CKK_RC5 (0x19UL) #define CKK_IDEA (0x1aUL) #define CKK_SKIPJACK (0x1bUL) #define CKK_BATON (0x1cUL) #define CKK_JUNIPER (0x1dUL) #define CKK_CDMF (0x1eUL) #define CKK_AES (0x1fUL) #define CKK_BLOWFISH (0x20UL) #define CKK_TWOFISH (0x21UL) #define CKK_GOSTR3410 (0x30UL) -#define CKK_EC_EDWARDS (0x40UL) -#define CKK_EC_MONTGOMERY (0x41UL) +#define CKK_EC_EDWARDS (0x40UL) +#define CKK_EC_MONTGOMERY (0x41UL) #define CKK_VENDOR_DEFINED (1UL << 31) typedef unsigned long ck_certificate_type_t; #define CKC_X_509 (0UL) #define CKC_X_509_ATTR_CERT (1UL) #define CKC_WTLS (2UL) #define CKC_VENDOR_DEFINED (1UL << 31) typedef unsigned long ck_attribute_type_t; #define CKA_CLASS (0UL) #define CKA_TOKEN (1UL) #define CKA_PRIVATE (2UL) #define CKA_LABEL (3UL) #define CKA_APPLICATION (0x10UL) #define CKA_VALUE (0x11UL) #define CKA_OBJECT_ID (0x12UL) #define CKA_CERTIFICATE_TYPE (0x80UL) #define CKA_ISSUER (0x81UL) #define CKA_SERIAL_NUMBER (0x82UL) #define CKA_AC_ISSUER (0x83UL) #define CKA_OWNER (0x84UL) #define CKA_ATTR_TYPES (0x85UL) #define CKA_TRUSTED (0x86UL) #define CKA_CERTIFICATE_CATEGORY (0x87UL) #define CKA_JAVA_MIDP_SECURITY_DOMAIN (0x88UL) #define CKA_URL (0x89UL) #define CKA_HASH_OF_SUBJECT_PUBLIC_KEY (0x8aUL) #define CKA_HASH_OF_ISSUER_PUBLIC_KEY (0x8bUL) #define CKA_CHECK_VALUE (0x90UL) #define CKA_KEY_TYPE (0x100UL) #define CKA_SUBJECT (0x101UL) #define CKA_ID (0x102UL) #define CKA_SENSITIVE (0x103UL) #define CKA_ENCRYPT (0x104UL) #define CKA_DECRYPT (0x105UL) #define CKA_WRAP (0x106UL) #define CKA_UNWRAP (0x107UL) #define CKA_SIGN (0x108UL) #define CKA_SIGN_RECOVER (0x109UL) #define CKA_VERIFY (0x10aUL) #define CKA_VERIFY_RECOVER (0x10bUL) #define CKA_DERIVE (0x10cUL) #define CKA_START_DATE (0x110UL) #define CKA_END_DATE (0x111UL) #define CKA_MODULUS (0x120UL) #define CKA_MODULUS_BITS (0x121UL) #define CKA_PUBLIC_EXPONENT (0x122UL) #define CKA_PRIVATE_EXPONENT (0x123UL) #define CKA_PRIME_1 (0x124UL) #define CKA_PRIME_2 (0x125UL) #define CKA_EXPONENT_1 (0x126UL) #define CKA_EXPONENT_2 (0x127UL) #define CKA_COEFFICIENT (0x128UL) #define CKA_PRIME (0x130UL) #define CKA_SUBPRIME (0x131UL) #define CKA_BASE (0x132UL) #define CKA_PRIME_BITS (0x133UL) #define CKA_SUB_PRIME_BITS (0x134UL) #define CKA_VALUE_BITS (0x160UL) #define CKA_VALUE_LEN (0x161UL) #define CKA_EXTRACTABLE (0x162UL) #define CKA_LOCAL (0x163UL) #define CKA_NEVER_EXTRACTABLE (0x164UL) #define CKA_ALWAYS_SENSITIVE (0x165UL) #define CKA_KEY_GEN_MECHANISM (0x166UL) #define CKA_MODIFIABLE (0x170UL) -#define CKA_ECDSA_PARAMS (0x180UL) #define CKA_EC_PARAMS (0x180UL) #define CKA_EC_POINT (0x181UL) #define CKA_SECONDARY_AUTH (0x200UL) #define CKA_AUTH_PIN_FLAGS (0x201UL) #define CKA_ALWAYS_AUTHENTICATE (0x202UL) #define CKA_WRAP_WITH_TRUSTED (0x210UL) #define CKA_GOSTR3410_PARAMS (0x250UL) #define CKA_GOSTR3411_PARAMS (0x251UL) #define CKA_GOST28147_PARAMS (0x252UL) #define CKA_HW_FEATURE_TYPE (0x300UL) #define CKA_RESET_ON_INIT (0x301UL) #define CKA_HAS_RESET (0x302UL) #define CKA_PIXEL_X (0x400UL) #define CKA_PIXEL_Y (0x401UL) #define CKA_RESOLUTION (0x402UL) #define CKA_CHAR_ROWS (0x403UL) #define CKA_CHAR_COLUMNS (0x404UL) #define CKA_COLOR (0x405UL) #define CKA_BITS_PER_PIXEL (0x406UL) #define CKA_CHAR_SETS (0x480UL) #define CKA_ENCODING_METHODS (0x481UL) #define CKA_MIME_TYPES (0x482UL) #define CKA_MECHANISM_TYPE (0x500UL) #define CKA_REQUIRED_CMS_ATTRIBUTES (0x501UL) #define CKA_DEFAULT_CMS_ATTRIBUTES (0x502UL) #define CKA_SUPPORTED_CMS_ATTRIBUTES (0x503UL) #define CKA_WRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x211UL) #define CKA_UNWRAP_TEMPLATE (CKF_ARRAY_ATTRIBUTE | 0x212UL) #define CKA_ALLOWED_MECHANISMS (CKF_ARRAY_ATTRIBUTE | 0x600UL) #define CKA_VENDOR_DEFINED (1UL << 31) struct ck_attribute { ck_attribute_type_t type; void *value; unsigned long value_len; }; struct ck_date { unsigned char year[4]; unsigned char month[2]; unsigned char day[2]; }; typedef unsigned long ck_mechanism_type_t; #define CKM_RSA_PKCS_KEY_PAIR_GEN (0UL) #define CKM_RSA_PKCS (1UL) #define CKM_RSA_9796 (2UL) #define CKM_RSA_X_509 (3UL) #define CKM_MD2_RSA_PKCS (4UL) #define CKM_MD5_RSA_PKCS (5UL) #define CKM_SHA1_RSA_PKCS (6UL) #define CKM_RIPEMD128_RSA_PKCS (7UL) #define CKM_RIPEMD160_RSA_PKCS (8UL) #define CKM_RSA_PKCS_OAEP (9UL) #define CKM_RSA_X9_31_KEY_PAIR_GEN (0xaUL) #define CKM_RSA_X9_31 (0xbUL) #define CKM_SHA1_RSA_X9_31 (0xcUL) #define CKM_RSA_PKCS_PSS (0xdUL) #define CKM_SHA1_RSA_PKCS_PSS (0xeUL) #define CKM_DSA_KEY_PAIR_GEN (0x10UL) #define CKM_DSA (0x11UL) #define CKM_DSA_SHA1 (0x12UL) #define CKM_DH_PKCS_KEY_PAIR_GEN (0x20UL) #define CKM_DH_PKCS_DERIVE (0x21UL) #define CKM_X9_42_DH_KEY_PAIR_GEN (0x30UL) #define CKM_X9_42_DH_DERIVE (0x31UL) #define CKM_X9_42_DH_HYBRID_DERIVE (0x32UL) #define CKM_X9_42_MQV_DERIVE (0x33UL) #define CKM_SHA256_RSA_PKCS (0x40UL) #define CKM_SHA384_RSA_PKCS (0x41UL) #define CKM_SHA512_RSA_PKCS (0x42UL) #define CKM_SHA256_RSA_PKCS_PSS (0x43UL) #define CKM_SHA384_RSA_PKCS_PSS (0x44UL) #define CKM_SHA512_RSA_PKCS_PSS (0x45UL) #define CKM_RC2_KEY_GEN (0x100UL) #define CKM_RC2_ECB (0x101UL) #define CKM_RC2_CBC (0x102UL) #define CKM_RC2_MAC (0x103UL) #define CKM_RC2_MAC_GENERAL (0x104UL) #define CKM_RC2_CBC_PAD (0x105UL) #define CKM_RC4_KEY_GEN (0x110UL) #define CKM_RC4 (0x111UL) #define CKM_DES_KEY_GEN (0x120UL) #define CKM_DES_ECB (0x121UL) #define CKM_DES_CBC (0x122UL) #define CKM_DES_MAC (0x123UL) #define CKM_DES_MAC_GENERAL (0x124UL) #define CKM_DES_CBC_PAD (0x125UL) #define CKM_DES2_KEY_GEN (0x130UL) #define CKM_DES3_KEY_GEN (0x131UL) #define CKM_DES3_ECB (0x132UL) #define CKM_DES3_CBC (0x133UL) #define CKM_DES3_MAC (0x134UL) #define CKM_DES3_MAC_GENERAL (0x135UL) #define CKM_DES3_CBC_PAD (0x136UL) #define CKM_CDMF_KEY_GEN (0x140UL) #define CKM_CDMF_ECB (0x141UL) #define CKM_CDMF_CBC (0x142UL) #define CKM_CDMF_MAC (0x143UL) #define CKM_CDMF_MAC_GENERAL (0x144UL) #define CKM_CDMF_CBC_PAD (0x145UL) #define CKM_MD2 (0x200UL) #define CKM_MD2_HMAC (0x201UL) #define CKM_MD2_HMAC_GENERAL (0x202UL) #define CKM_MD5 (0x210UL) #define CKM_MD5_HMAC (0x211UL) #define CKM_MD5_HMAC_GENERAL (0x212UL) #define CKM_SHA_1 (0x220UL) #define CKM_SHA_1_HMAC (0x221UL) #define CKM_SHA_1_HMAC_GENERAL (0x222UL) #define CKM_RIPEMD128 (0x230UL) #define CKM_RIPEMD128_HMAC (0x231UL) #define CKM_RIPEMD128_HMAC_GENERAL (0x232UL) #define CKM_RIPEMD160 (0x240UL) #define CKM_RIPEMD160_HMAC (0x241UL) #define CKM_RIPEMD160_HMAC_GENERAL (0x242UL) #define CKM_SHA256 (0x250UL) #define CKM_SHA256_HMAC (0x251UL) #define CKM_SHA256_HMAC_GENERAL (0x252UL) #define CKM_SHA384 (0x260UL) #define CKM_SHA384_HMAC (0x261UL) #define CKM_SHA384_HMAC_GENERAL (0x262UL) #define CKM_SHA512 (0x270UL) #define CKM_SHA512_HMAC (0x271UL) #define CKM_SHA512_HMAC_GENERAL (0x272UL) #define CKM_CAST_KEY_GEN (0x300UL) #define CKM_CAST_ECB (0x301UL) #define CKM_CAST_CBC (0x302UL) #define CKM_CAST_MAC (0x303UL) #define CKM_CAST_MAC_GENERAL (0x304UL) #define CKM_CAST_CBC_PAD (0x305UL) #define CKM_CAST3_KEY_GEN (0x310UL) #define CKM_CAST3_ECB (0x311UL) #define CKM_CAST3_CBC (0x312UL) #define CKM_CAST3_MAC (0x313UL) #define CKM_CAST3_MAC_GENERAL (0x314UL) #define CKM_CAST3_CBC_PAD (0x315UL) #define CKM_CAST5_KEY_GEN (0x320UL) #define CKM_CAST128_KEY_GEN (0x320UL) #define CKM_CAST5_ECB (0x321UL) #define CKM_CAST128_ECB (0x321UL) #define CKM_CAST5_CBC (0x322UL) #define CKM_CAST128_CBC (0x322UL) #define CKM_CAST5_MAC (0x323UL) #define CKM_CAST128_MAC (0x323UL) #define CKM_CAST5_MAC_GENERAL (0x324UL) #define CKM_CAST128_MAC_GENERAL (0x324UL) #define CKM_CAST5_CBC_PAD (0x325UL) #define CKM_CAST128_CBC_PAD (0x325UL) #define CKM_RC5_KEY_GEN (0x330UL) #define CKM_RC5_ECB (0x331UL) #define CKM_RC5_CBC (0x332UL) #define CKM_RC5_MAC (0x333UL) #define CKM_RC5_MAC_GENERAL (0x334UL) #define CKM_RC5_CBC_PAD (0x335UL) #define CKM_IDEA_KEY_GEN (0x340UL) #define CKM_IDEA_ECB (0x341UL) #define CKM_IDEA_CBC (0x342UL) #define CKM_IDEA_MAC (0x343UL) #define CKM_IDEA_MAC_GENERAL (0x344UL) #define CKM_IDEA_CBC_PAD (0x345UL) #define CKM_GENERIC_SECRET_KEY_GEN (0x350UL) #define CKM_CONCATENATE_BASE_AND_KEY (0x360UL) #define CKM_CONCATENATE_BASE_AND_DATA (0x362UL) #define CKM_CONCATENATE_DATA_AND_BASE (0x363UL) #define CKM_XOR_BASE_AND_DATA (0x364UL) #define CKM_EXTRACT_KEY_FROM_KEY (0x365UL) #define CKM_SSL3_PRE_MASTER_KEY_GEN (0x370UL) #define CKM_SSL3_MASTER_KEY_DERIVE (0x371UL) #define CKM_SSL3_KEY_AND_MAC_DERIVE (0x372UL) #define CKM_SSL3_MASTER_KEY_DERIVE_DH (0x373UL) #define CKM_TLS_PRE_MASTER_KEY_GEN (0x374UL) #define CKM_TLS_MASTER_KEY_DERIVE (0x375UL) #define CKM_TLS_KEY_AND_MAC_DERIVE (0x376UL) #define CKM_TLS_MASTER_KEY_DERIVE_DH (0x377UL) #define CKM_SSL3_MD5_MAC (0x380UL) #define CKM_SSL3_SHA1_MAC (0x381UL) #define CKM_MD5_KEY_DERIVATION (0x390UL) #define CKM_MD2_KEY_DERIVATION (0x391UL) #define CKM_SHA1_KEY_DERIVATION (0x392UL) #define CKM_PBE_MD2_DES_CBC (0x3a0UL) #define CKM_PBE_MD5_DES_CBC (0x3a1UL) #define CKM_PBE_MD5_CAST_CBC (0x3a2UL) #define CKM_PBE_MD5_CAST3_CBC (0x3a3UL) #define CKM_PBE_MD5_CAST5_CBC (0x3a4UL) #define CKM_PBE_MD5_CAST128_CBC (0x3a4UL) #define CKM_PBE_SHA1_CAST5_CBC (0x3a5UL) #define CKM_PBE_SHA1_CAST128_CBC (0x3a5UL) #define CKM_PBE_SHA1_RC4_128 (0x3a6UL) #define CKM_PBE_SHA1_RC4_40 (0x3a7UL) #define CKM_PBE_SHA1_DES3_EDE_CBC (0x3a8UL) #define CKM_PBE_SHA1_DES2_EDE_CBC (0x3a9UL) #define CKM_PBE_SHA1_RC2_128_CBC (0x3aaUL) #define CKM_PBE_SHA1_RC2_40_CBC (0x3abUL) #define CKM_PKCS5_PBKD2 (0x3b0UL) #define CKM_PBA_SHA1_WITH_SHA1_HMAC (0x3c0UL) #define CKM_KEY_WRAP_LYNKS (0x400UL) #define CKM_KEY_WRAP_SET_OAEP (0x401UL) #define CKM_SKIPJACK_KEY_GEN (0x1000UL) #define CKM_SKIPJACK_ECB64 (0x1001UL) #define CKM_SKIPJACK_CBC64 (0x1002UL) #define CKM_SKIPJACK_OFB64 (0x1003UL) #define CKM_SKIPJACK_CFB64 (0x1004UL) #define CKM_SKIPJACK_CFB32 (0x1005UL) #define CKM_SKIPJACK_CFB16 (0x1006UL) #define CKM_SKIPJACK_CFB8 (0x1007UL) #define CKM_SKIPJACK_WRAP (0x1008UL) #define CKM_SKIPJACK_PRIVATE_WRAP (0x1009UL) #define CKM_SKIPJACK_RELAYX (0x100aUL) #define CKM_KEA_KEY_PAIR_GEN (0x1010UL) #define CKM_KEA_KEY_DERIVE (0x1011UL) #define CKM_FORTEZZA_TIMESTAMP (0x1020UL) #define CKM_BATON_KEY_GEN (0x1030UL) #define CKM_BATON_ECB128 (0x1031UL) #define CKM_BATON_ECB96 (0x1032UL) #define CKM_BATON_CBC128 (0x1033UL) #define CKM_BATON_COUNTER (0x1034UL) #define CKM_BATON_SHUFFLE (0x1035UL) #define CKM_BATON_WRAP (0x1036UL) -#define CKM_ECDSA_KEY_PAIR_GEN (0x1040UL) #define CKM_EC_KEY_PAIR_GEN (0x1040UL) #define CKM_ECDSA (0x1041UL) #define CKM_ECDSA_SHA1 (0x1042UL) #define CKM_ECDSA_SHA256 (0x1044UL) #define CKM_ECDSA_SHA384 (0x1045UL) #define CKM_ECDSA_SHA512 (0x1046UL) #define CKM_ECDH1_DERIVE (0x1050UL) #define CKM_ECDH1_COFACTOR_DERIVE (0x1051UL) #define CKM_ECMQV_DERIVE (0x1052UL) +#define CKM_EC_EDWARDS_KEY_PAIR_GEN (0x1055UL) +#define CKM_EC_MONTGOMERY_KEY_PAIR_GEN (0x1056UL) #define CKM_EDDSA (0x1057UL) #define CKM_JUNIPER_KEY_GEN (0x1060UL) #define CKM_JUNIPER_ECB128 (0x1061UL) #define CKM_JUNIPER_CBC128 (0x1062UL) #define CKM_JUNIPER_COUNTER (0x1063UL) #define CKM_JUNIPER_SHUFFLE (0x1064UL) #define CKM_JUNIPER_WRAP (0x1065UL) #define CKM_FASTHASH (0x1070UL) #define CKM_AES_KEY_GEN (0x1080UL) #define CKM_AES_ECB (0x1081UL) #define CKM_AES_CBC (0x1082UL) #define CKM_AES_MAC (0x1083UL) #define CKM_AES_MAC_GENERAL (0x1084UL) #define CKM_AES_CBC_PAD (0x1085UL) #define CKM_GOSTR3410_KEY_PAIR_GEN (0x1200UL) #define CKM_GOSTR3410 (0x1201UL) #define CKM_GOSTR3410_WITH_GOSTR3411 (0x1202UL) #define CKM_GOSTR3411 (0x1210UL) #define CKM_DSA_PARAMETER_GEN (0x2000UL) #define CKM_DH_PKCS_PARAMETER_GEN (0x2001UL) #define CKM_X9_42_DH_PARAMETER_GEN (0x2002UL) #define CKM_VENDOR_DEFINED (1UL << 31) struct ck_mechanism { ck_mechanism_type_t mechanism; void *parameter; unsigned long parameter_len; }; struct ck_mechanism_info { unsigned long min_key_size; unsigned long max_key_size; ck_flags_t flags; }; #define CKF_HW (1UL << 0) #define CKF_ENCRYPT (1UL << 8) #define CKF_DECRYPT (1UL << 9) #define CKF_DIGEST (1UL << 10) #define CKF_SIGN (1UL << 11) #define CKF_SIGN_RECOVER (1UL << 12) #define CKF_VERIFY (1UL << 13) #define CKF_VERIFY_RECOVER (1UL << 14) #define CKF_GENERATE (1UL << 15) #define CKF_GENERATE_KEY_PAIR (1UL << 16) #define CKF_WRAP (1UL << 17) #define CKF_UNWRAP (1UL << 18) #define CKF_DERIVE (1UL << 19) #define CKF_EC_F_P (1UL << 20) #define CKF_EC_F_2M (1UL << 21) #define CKF_EC_PARAMETERS (1UL << 22) #define CKF_EC_OID (1UL << 23) #define CKF_EC_UNCOMPRESS (1UL << 24) #define CKF_EC_COMPRESS (1UL << 25) #define CKF_EC_CURVENAME (1UL << 26) #define CKF_EXTENSION (1UL << 31) /* Flags for C_WaitForSlotEvent. */ #define CKF_DONT_BLOCK (1UL) typedef unsigned long ck_rv_t; typedef ck_rv_t (*ck_notify_t) (ck_session_handle_t session, ck_notification_t event, void *application); /* Forward reference. */ struct ck_function_list; #define _CK_DECLARE_FUNCTION(name, args) \ typedef ck_rv_t (*CK_ ## name) args; \ ck_rv_t CK_SPEC name args _CK_DECLARE_FUNCTION (C_Initialize, (void *init_args)); _CK_DECLARE_FUNCTION (C_Finalize, (void *reserved)); _CK_DECLARE_FUNCTION (C_GetInfo, (struct ck_info *info)); _CK_DECLARE_FUNCTION (C_GetFunctionList, (struct ck_function_list **function_list)); _CK_DECLARE_FUNCTION (C_GetSlotList, (unsigned char token_present, ck_slot_id_t *slot_list, unsigned long *count)); _CK_DECLARE_FUNCTION (C_GetSlotInfo, (ck_slot_id_t slot_id, struct ck_slot_info *info)); _CK_DECLARE_FUNCTION (C_GetTokenInfo, (ck_slot_id_t slot_id, struct ck_token_info *info)); _CK_DECLARE_FUNCTION (C_WaitForSlotEvent, (ck_flags_t flags, ck_slot_id_t *slot, void *reserved)); _CK_DECLARE_FUNCTION (C_GetMechanismList, (ck_slot_id_t slot_id, ck_mechanism_type_t *mechanism_list, unsigned long *count)); _CK_DECLARE_FUNCTION (C_GetMechanismInfo, (ck_slot_id_t slot_id, ck_mechanism_type_t type, struct ck_mechanism_info *info)); _CK_DECLARE_FUNCTION (C_InitToken, (ck_slot_id_t slot_id, unsigned char *pin, unsigned long pin_len, unsigned char *label)); _CK_DECLARE_FUNCTION (C_InitPIN, (ck_session_handle_t session, unsigned char *pin, unsigned long pin_len)); _CK_DECLARE_FUNCTION (C_SetPIN, (ck_session_handle_t session, unsigned char *old_pin, unsigned long old_len, unsigned char *new_pin, unsigned long new_len)); _CK_DECLARE_FUNCTION (C_OpenSession, (ck_slot_id_t slot_id, ck_flags_t flags, void *application, ck_notify_t notify, ck_session_handle_t *session)); _CK_DECLARE_FUNCTION (C_CloseSession, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CloseAllSessions, (ck_slot_id_t slot_id)); _CK_DECLARE_FUNCTION (C_GetSessionInfo, (ck_session_handle_t session, struct ck_session_info *info)); _CK_DECLARE_FUNCTION (C_GetOperationState, (ck_session_handle_t session, unsigned char *operation_state, unsigned long *operation_state_len)); _CK_DECLARE_FUNCTION (C_SetOperationState, (ck_session_handle_t session, unsigned char *operation_state, unsigned long operation_state_len, ck_object_handle_t encryption_key, ck_object_handle_t authentiation_key)); _CK_DECLARE_FUNCTION (C_Login, (ck_session_handle_t session, ck_user_type_t user_type, unsigned char *pin, unsigned long pin_len)); _CK_DECLARE_FUNCTION (C_Logout, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CreateObject, (ck_session_handle_t session, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *object)); _CK_DECLARE_FUNCTION (C_CopyObject, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *new_object)); _CK_DECLARE_FUNCTION (C_DestroyObject, (ck_session_handle_t session, ck_object_handle_t object)); _CK_DECLARE_FUNCTION (C_GetObjectSize, (ck_session_handle_t session, ck_object_handle_t object, unsigned long *size)); _CK_DECLARE_FUNCTION (C_GetAttributeValue, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_SetAttributeValue, (ck_session_handle_t session, ck_object_handle_t object, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_FindObjectsInit, (ck_session_handle_t session, struct ck_attribute *templ, unsigned long count)); _CK_DECLARE_FUNCTION (C_FindObjects, (ck_session_handle_t session, ck_object_handle_t *object, unsigned long max_object_count, unsigned long *object_count)); _CK_DECLARE_FUNCTION (C_FindObjectsFinal, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_EncryptInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Encrypt, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *encrypted_data, unsigned long *encrypted_data_len)); _CK_DECLARE_FUNCTION (C_EncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_EncryptFinal, (ck_session_handle_t session, unsigned char *last_encrypted_part, unsigned long *last_encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Decrypt, (ck_session_handle_t session, unsigned char *encrypted_data, unsigned long encrypted_data_len, unsigned char *data, unsigned long *data_len)); _CK_DECLARE_FUNCTION (C_DecryptUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_DecryptFinal, (ck_session_handle_t session, unsigned char *last_part, unsigned long *last_part_len)); _CK_DECLARE_FUNCTION (C_DigestInit, (ck_session_handle_t session, struct ck_mechanism *mechanism)); _CK_DECLARE_FUNCTION (C_Digest, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *digest, unsigned long *digest_len)); _CK_DECLARE_FUNCTION (C_DigestUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_DigestKey, (ck_session_handle_t session, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_DigestFinal, (ck_session_handle_t session, unsigned char *digest, unsigned long *digest_len)); _CK_DECLARE_FUNCTION (C_SignInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Sign, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_SignUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_SignFinal, (ck_session_handle_t session, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_SignRecoverInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_SignRecover, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long *signature_len)); _CK_DECLARE_FUNCTION (C_VerifyInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_Verify, (ck_session_handle_t session, unsigned char *data, unsigned long data_len, unsigned char *signature, unsigned long signature_len)); _CK_DECLARE_FUNCTION (C_VerifyUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len)); _CK_DECLARE_FUNCTION (C_VerifyFinal, (ck_session_handle_t session, unsigned char *signature, unsigned long signature_len)); _CK_DECLARE_FUNCTION (C_VerifyRecoverInit, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t key)); _CK_DECLARE_FUNCTION (C_VerifyRecover, (ck_session_handle_t session, unsigned char *signature, unsigned long signature_len, unsigned char *data, unsigned long *data_len)); _CK_DECLARE_FUNCTION (C_DigestEncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptDigestUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_SignEncryptUpdate, (ck_session_handle_t session, unsigned char *part, unsigned long part_len, unsigned char *encrypted_part, unsigned long *encrypted_part_len)); _CK_DECLARE_FUNCTION (C_DecryptVerifyUpdate, (ck_session_handle_t session, unsigned char *encrypted_part, unsigned long encrypted_part_len, unsigned char *part, unsigned long *part_len)); _CK_DECLARE_FUNCTION (C_GenerateKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, struct ck_attribute *templ, unsigned long count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_GenerateKeyPair, (ck_session_handle_t session, struct ck_mechanism *mechanism, struct ck_attribute *public_key_template, unsigned long public_key_attribute_count, struct ck_attribute *private_key_template, unsigned long private_key_attribute_count, ck_object_handle_t *public_key, ck_object_handle_t *private_key)); _CK_DECLARE_FUNCTION (C_WrapKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t wrapping_key, ck_object_handle_t key, unsigned char *wrapped_key, unsigned long *wrapped_key_len)); _CK_DECLARE_FUNCTION (C_UnwrapKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t unwrapping_key, unsigned char *wrapped_key, unsigned long wrapped_key_len, struct ck_attribute *templ, unsigned long attribute_count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_DeriveKey, (ck_session_handle_t session, struct ck_mechanism *mechanism, ck_object_handle_t base_key, struct ck_attribute *templ, unsigned long attribute_count, ck_object_handle_t *key)); _CK_DECLARE_FUNCTION (C_SeedRandom, (ck_session_handle_t session, unsigned char *seed, unsigned long seed_len)); _CK_DECLARE_FUNCTION (C_GenerateRandom, (ck_session_handle_t session, unsigned char *random_data, unsigned long random_len)); _CK_DECLARE_FUNCTION (C_GetFunctionStatus, (ck_session_handle_t session)); _CK_DECLARE_FUNCTION (C_CancelFunction, (ck_session_handle_t session)); struct ck_function_list { struct ck_version version; CK_C_Initialize C_Initialize; CK_C_Finalize C_Finalize; CK_C_GetInfo C_GetInfo; CK_C_GetFunctionList C_GetFunctionList; CK_C_GetSlotList C_GetSlotList; CK_C_GetSlotInfo C_GetSlotInfo; CK_C_GetTokenInfo C_GetTokenInfo; CK_C_GetMechanismList C_GetMechanismList; CK_C_GetMechanismInfo C_GetMechanismInfo; CK_C_InitToken C_InitToken; CK_C_InitPIN C_InitPIN; CK_C_SetPIN C_SetPIN; CK_C_OpenSession C_OpenSession; CK_C_CloseSession C_CloseSession; CK_C_CloseAllSessions C_CloseAllSessions; CK_C_GetSessionInfo C_GetSessionInfo; CK_C_GetOperationState C_GetOperationState; CK_C_SetOperationState C_SetOperationState; CK_C_Login C_Login; CK_C_Logout C_Logout; CK_C_CreateObject C_CreateObject; CK_C_CopyObject C_CopyObject; CK_C_DestroyObject C_DestroyObject; CK_C_GetObjectSize C_GetObjectSize; CK_C_GetAttributeValue C_GetAttributeValue; CK_C_SetAttributeValue C_SetAttributeValue; CK_C_FindObjectsInit C_FindObjectsInit; CK_C_FindObjects C_FindObjects; CK_C_FindObjectsFinal C_FindObjectsFinal; CK_C_EncryptInit C_EncryptInit; CK_C_Encrypt C_Encrypt; CK_C_EncryptUpdate C_EncryptUpdate; CK_C_EncryptFinal C_EncryptFinal; CK_C_DecryptInit C_DecryptInit; CK_C_Decrypt C_Decrypt; CK_C_DecryptUpdate C_DecryptUpdate; CK_C_DecryptFinal C_DecryptFinal; CK_C_DigestInit C_DigestInit; CK_C_Digest C_Digest; CK_C_DigestUpdate C_DigestUpdate; CK_C_DigestKey C_DigestKey; CK_C_DigestFinal C_DigestFinal; CK_C_SignInit C_SignInit; CK_C_Sign C_Sign; CK_C_SignUpdate C_SignUpdate; CK_C_SignFinal C_SignFinal; CK_C_SignRecoverInit C_SignRecoverInit; CK_C_SignRecover C_SignRecover; CK_C_VerifyInit C_VerifyInit; CK_C_Verify C_Verify; CK_C_VerifyUpdate C_VerifyUpdate; CK_C_VerifyFinal C_VerifyFinal; CK_C_VerifyRecoverInit C_VerifyRecoverInit; CK_C_VerifyRecover C_VerifyRecover; CK_C_DigestEncryptUpdate C_DigestEncryptUpdate; CK_C_DecryptDigestUpdate C_DecryptDigestUpdate; CK_C_SignEncryptUpdate C_SignEncryptUpdate; CK_C_DecryptVerifyUpdate C_DecryptVerifyUpdate; CK_C_GenerateKey C_GenerateKey; CK_C_GenerateKeyPair C_GenerateKeyPair; CK_C_WrapKey C_WrapKey; CK_C_UnwrapKey C_UnwrapKey; CK_C_DeriveKey C_DeriveKey; CK_C_SeedRandom C_SeedRandom; CK_C_GenerateRandom C_GenerateRandom; CK_C_GetFunctionStatus C_GetFunctionStatus; CK_C_CancelFunction C_CancelFunction; CK_C_WaitForSlotEvent C_WaitForSlotEvent; }; typedef ck_rv_t (*ck_createmutex_t) (void **mutex); typedef ck_rv_t (*ck_destroymutex_t) (void *mutex); typedef ck_rv_t (*ck_lockmutex_t) (void *mutex); typedef ck_rv_t (*ck_unlockmutex_t) (void *mutex); struct ck_c_initialize_args { ck_createmutex_t create_mutex; ck_destroymutex_t destroy_mutex; ck_lockmutex_t lock_mutex; ck_unlockmutex_t unlock_mutex; ck_flags_t flags; void *reserved; }; #define CKF_LIBRARY_CANT_CREATE_OS_THREADS (1UL << 0) #define CKF_OS_LOCKING_OK (1UL << 1) #define CKR_OK (0UL) #define CKR_CANCEL (1UL) #define CKR_HOST_MEMORY (2UL) #define CKR_SLOT_ID_INVALID (3UL) #define CKR_GENERAL_ERROR (5UL) #define CKR_FUNCTION_FAILED (6UL) #define CKR_ARGUMENTS_BAD (7UL) #define CKR_NO_EVENT (8UL) #define CKR_NEED_TO_CREATE_THREADS (9UL) #define CKR_CANT_LOCK (0xaUL) #define CKR_ATTRIBUTE_READ_ONLY (0x10UL) #define CKR_ATTRIBUTE_SENSITIVE (0x11UL) #define CKR_ATTRIBUTE_TYPE_INVALID (0x12UL) #define CKR_ATTRIBUTE_VALUE_INVALID (0x13UL) #define CKR_DATA_INVALID (0x20UL) #define CKR_DATA_LEN_RANGE (0x21UL) #define CKR_DEVICE_ERROR (0x30UL) #define CKR_DEVICE_MEMORY (0x31UL) #define CKR_DEVICE_REMOVED (0x32UL) #define CKR_ENCRYPTED_DATA_INVALID (0x40UL) #define CKR_ENCRYPTED_DATA_LEN_RANGE (0x41UL) #define CKR_FUNCTION_CANCELED (0x50UL) #define CKR_FUNCTION_NOT_PARALLEL (0x51UL) #define CKR_FUNCTION_NOT_SUPPORTED (0x54UL) #define CKR_KEY_HANDLE_INVALID (0x60UL) #define CKR_KEY_SIZE_RANGE (0x62UL) #define CKR_KEY_TYPE_INCONSISTENT (0x63UL) #define CKR_KEY_NOT_NEEDED (0x64UL) #define CKR_KEY_CHANGED (0x65UL) #define CKR_KEY_NEEDED (0x66UL) #define CKR_KEY_INDIGESTIBLE (0x67UL) #define CKR_KEY_FUNCTION_NOT_PERMITTED (0x68UL) #define CKR_KEY_NOT_WRAPPABLE (0x69UL) #define CKR_KEY_UNEXTRACTABLE (0x6aUL) #define CKR_MECHANISM_INVALID (0x70UL) #define CKR_MECHANISM_PARAM_INVALID (0x71UL) #define CKR_OBJECT_HANDLE_INVALID (0x82UL) #define CKR_OPERATION_ACTIVE (0x90UL) #define CKR_OPERATION_NOT_INITIALIZED (0x91UL) #define CKR_PIN_INCORRECT (0xa0UL) #define CKR_PIN_INVALID (0xa1UL) #define CKR_PIN_LEN_RANGE (0xa2UL) #define CKR_PIN_EXPIRED (0xa3UL) #define CKR_PIN_LOCKED (0xa4UL) #define CKR_SESSION_CLOSED (0xb0UL) #define CKR_SESSION_COUNT (0xb1UL) #define CKR_SESSION_HANDLE_INVALID (0xb3UL) #define CKR_SESSION_PARALLEL_NOT_SUPPORTED (0xb4UL) #define CKR_SESSION_READ_ONLY (0xb5UL) #define CKR_SESSION_EXISTS (0xb6UL) #define CKR_SESSION_READ_ONLY_EXISTS (0xb7UL) #define CKR_SESSION_READ_WRITE_SO_EXISTS (0xb8UL) #define CKR_SIGNATURE_INVALID (0xc0UL) #define CKR_SIGNATURE_LEN_RANGE (0xc1UL) #define CKR_TEMPLATE_INCOMPLETE (0xd0UL) #define CKR_TEMPLATE_INCONSISTENT (0xd1UL) #define CKR_TOKEN_NOT_PRESENT (0xe0UL) #define CKR_TOKEN_NOT_RECOGNIZED (0xe1UL) #define CKR_TOKEN_WRITE_PROTECTED (0xe2UL) #define CKR_UNWRAPPING_KEY_HANDLE_INVALID (0xf0UL) #define CKR_UNWRAPPING_KEY_SIZE_RANGE (0xf1UL) #define CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT (0xf2UL) #define CKR_USER_ALREADY_LOGGED_IN (0x100UL) #define CKR_USER_NOT_LOGGED_IN (0x101UL) #define CKR_USER_PIN_NOT_INITIALIZED (0x102UL) #define CKR_USER_TYPE_INVALID (0x103UL) #define CKR_USER_ANOTHER_ALREADY_LOGGED_IN (0x104UL) #define CKR_USER_TOO_MANY_TYPES (0x105UL) #define CKR_WRAPPED_KEY_INVALID (0x110UL) #define CKR_WRAPPED_KEY_LEN_RANGE (0x112UL) #define CKR_WRAPPING_KEY_HANDLE_INVALID (0x113UL) #define CKR_WRAPPING_KEY_SIZE_RANGE (0x114UL) #define CKR_WRAPPING_KEY_TYPE_INCONSISTENT (0x115UL) #define CKR_RANDOM_SEED_NOT_SUPPORTED (0x120UL) #define CKR_RANDOM_NO_RNG (0x121UL) #define CKR_DOMAIN_PARAMS_INVALID (0x130UL) #define CKR_BUFFER_TOO_SMALL (0x150UL) #define CKR_SAVED_STATE_INVALID (0x160UL) #define CKR_INFORMATION_SENSITIVE (0x170UL) #define CKR_STATE_UNSAVEABLE (0x180UL) #define CKR_CRYPTOKI_NOT_INITIALIZED (0x190UL) #define CKR_CRYPTOKI_ALREADY_INITIALIZED (0x191UL) #define CKR_MUTEX_BAD (0x1a0UL) #define CKR_MUTEX_NOT_LOCKED (0x1a1UL) #define CKR_FUNCTION_REJECTED (0x200UL) #define CKR_VENDOR_DEFINED (1UL << 31) /* Compatibility layer. */ #ifdef CRYPTOKI_COMPAT #undef CK_DEFINE_FUNCTION #define CK_DEFINE_FUNCTION(retval, name) retval CK_SPEC name /* For NULL. */ #include typedef unsigned char CK_BYTE; typedef unsigned char CK_CHAR; typedef unsigned char CK_UTF8CHAR; typedef unsigned char CK_BBOOL; typedef unsigned long int CK_ULONG; typedef long int CK_LONG; typedef CK_BYTE *CK_BYTE_PTR; typedef CK_CHAR *CK_CHAR_PTR; typedef CK_UTF8CHAR *CK_UTF8CHAR_PTR; typedef CK_ULONG *CK_ULONG_PTR; typedef void *CK_VOID_PTR; typedef void **CK_VOID_PTR_PTR; #define CK_FALSE 0 #define CK_TRUE 1 #ifndef CK_DISABLE_TRUE_FALSE #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif #endif typedef struct ck_version CK_VERSION; typedef struct ck_version *CK_VERSION_PTR; typedef struct ck_info CK_INFO; typedef struct ck_info *CK_INFO_PTR; typedef ck_slot_id_t *CK_SLOT_ID_PTR; typedef struct ck_slot_info CK_SLOT_INFO; typedef struct ck_slot_info *CK_SLOT_INFO_PTR; typedef struct ck_token_info CK_TOKEN_INFO; typedef struct ck_token_info *CK_TOKEN_INFO_PTR; typedef ck_session_handle_t *CK_SESSION_HANDLE_PTR; typedef struct ck_session_info CK_SESSION_INFO; typedef struct ck_session_info *CK_SESSION_INFO_PTR; typedef ck_object_handle_t *CK_OBJECT_HANDLE_PTR; typedef ck_object_class_t *CK_OBJECT_CLASS_PTR; typedef struct ck_attribute CK_ATTRIBUTE; typedef struct ck_attribute *CK_ATTRIBUTE_PTR; typedef struct ck_date CK_DATE; typedef struct ck_date *CK_DATE_PTR; typedef ck_mechanism_type_t *CK_MECHANISM_TYPE_PTR; typedef struct ck_mechanism CK_MECHANISM; typedef struct ck_mechanism *CK_MECHANISM_PTR; typedef struct ck_mechanism_info CK_MECHANISM_INFO; typedef struct ck_mechanism_info *CK_MECHANISM_INFO_PTR; typedef struct ck_function_list CK_FUNCTION_LIST; typedef struct ck_function_list *CK_FUNCTION_LIST_PTR; typedef struct ck_function_list **CK_FUNCTION_LIST_PTR_PTR; typedef struct ck_c_initialize_args CK_C_INITIALIZE_ARGS; typedef struct ck_c_initialize_args *CK_C_INITIALIZE_ARGS_PTR; #define NULL_PTR NULL /* Delete the helper macros defined at the top of the file. */ #undef ck_flags_t #undef ck_version #undef ck_info #undef cryptoki_version #undef manufacturer_id #undef library_description #undef library_version #undef ck_notification_t #undef ck_slot_id_t #undef ck_slot_info #undef slot_description #undef hardware_version #undef firmware_version #undef ck_token_info #undef serial_number #undef max_session_count #undef session_count #undef max_rw_session_count #undef rw_session_count #undef max_pin_len #undef min_pin_len #undef total_public_memory #undef free_public_memory #undef total_private_memory #undef free_private_memory #undef utc_time #undef ck_session_handle_t #undef ck_user_type_t #undef ck_state_t #undef ck_session_info #undef slot_id #undef device_error #undef ck_object_handle_t #undef ck_object_class_t #undef ck_hw_feature_type_t #undef ck_key_type_t #undef ck_certificate_type_t #undef ck_attribute_type_t #undef ck_attribute #undef value #undef value_len #undef ck_date #undef ck_mechanism_type_t #undef ck_mechanism #undef parameter #undef parameter_len #undef ck_mechanism_info #undef min_key_size #undef max_key_size #undef ck_rv_t #undef ck_notify_t #undef ck_function_list #undef ck_createmutex_t #undef ck_destroymutex_t #undef ck_lockmutex_t #undef ck_unlockmutex_t #undef ck_c_initialize_args #undef create_mutex #undef destroy_mutex #undef lock_mutex #undef unlock_mutex #undef reserved #endif /* CRYPTOKI_COMPAT */ /* System dependencies. */ #if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32) #pragma pack(pop, cryptoki) #endif #if defined(__cplusplus) } #endif #endif /* PKCS11_H */ diff --git a/src/slots.c b/src/slots.c index 09a9a2e..a7241d6 100644 --- a/src/slots.c +++ b/src/slots.c @@ -1,1155 +1,1153 @@ /* slots.c - Slot management. * Copyright (C) 2006, 2019 g10 Code GmbH * * This file is part of Scute. * * Scute is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Scute 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, see . * SPDX-License-Identifier: LGPL-2.1-or-later */ #if HAVE_CONFIG_H #include #endif #include #include #include #include #include "cryptoki.h" #include "table.h" #include "error-mapping.h" #include "slots.h" #include "agent.h" #include "support.h" #include "gpgsm.h" #include "debug.h" /* A session is just a slot identifier with a per-slot session identifier. */ /* Must be power of two. */ #define SLOT_MAX (1 << 15) #define SESSION_SLOT_MASK (SLOT_MAX - 1) #define SESSION_SLOT_SHIFT 16 #define SESSION_MAX (1 << SESSION_SLOT_SHIFT) #define SESSION_ID_MASK (SESSION_MAX - 1) /* Get slot ID from session. */ #define SESSION_SLOT(session) \ ((session >> SESSION_SLOT_SHIFT) & SESSION_SLOT_MASK) /* Get session ID from session. */ #define SESSION_ID(session) (session & SESSION_ID_MASK) /* Because the slot is already 1-based, we can make the session 0-based. */ #define SESSION_BUILD_ID(slot, session) \ (((slot & SESSION_SLOT_MASK) << SESSION_SLOT_SHIFT) \ | (session & SESSION_ID_MASK)) /* We use one-based IDs. */ #define OBJECT_ID_TO_IDX(id) (id - 1) #define OBJECT_IDX_TO_ID(idx) (idx + 1) struct object { CK_ATTRIBUTE_PTR attributes; CK_ULONG attributes_count; }; /* A mechanism. */ struct mechanism { CK_MECHANISM_TYPE type; CK_MECHANISM_INFO info; }; /* We use one-based IDs. */ #define MECHANISM_ID_TO_IDX(id) (id - 1) #define MECHANISM_IDX_TO_ID(idx) (idx + 1) /* The session state. */ struct session { /* True iff read-write session. */ bool rw; /* The list of objects for the current search. */ object_iterator_t *search_result; /* The length of the list of objects for the current search. */ int search_result_len; /* The signing key. */ CK_OBJECT_HANDLE signing_key; /* The signing mechanism type. */ CK_MECHANISM_TYPE signing_mechanism_type; /* The decryption key. */ CK_OBJECT_HANDLE decryption_key; }; /* The slot status. */ typedef enum { SLOT_STATUS_USED = 0, SLOT_STATUS_DEAD = 1 } slot_status_t; struct slot { /* The slot status. Starts out as 0 (pristine). */ slot_status_t status; /* The slot login status. Starts out as 0 (public). */ slot_login_t login; /* True iff a token is present. */ bool token_present; /* The supported mechanisms. */ scute_table_t mechanisms; /* The sessions. */ scute_table_t sessions; /* The objects on the token. */ scute_table_t objects; /* The keygrip to the key in hex string. */ char grip[41]; /* The serial number. */ char serialno[33]; }; /* The slot table. */ static scute_table_t slot_table; /* Deallocator for mechanisms. */ static void mechanism_dealloc (void *data) { free (data); } /* Allocator for mechanisms. The hook must be a pointer to a CK_FLAGS that should be a combination of CKF_SIGN and/or CKF_DECRYPT. */ static gpg_error_t mechanism_alloc (void **data_r, void *hook) { struct mechanism *mechanism; - CK_FLAGS *flags = hook; + struct slot *slot = hook; mechanism = calloc (1, sizeof (*mechanism)); if (mechanism == NULL) return gpg_error_from_syserror (); - /* Set some default values. */ + /* Register the signing mechanism. */ + /* FIXME: examine slot->objects to setup the mechanism. */ + (void)slot; + mechanism->type = CKM_RSA_PKCS; mechanism->info.ulMinKeySize = 1024; mechanism->info.ulMaxKeySize = 4096; - mechanism->info.flags = CKF_HW | (*flags); + mechanism->info.flags = CKF_HW | CKF_SIGN; *data_r = mechanism; return 0; } static void object_dealloc (void *data) { struct object *obj = data; while (0 < obj->attributes_count--) free (obj->attributes[obj->attributes_count].pValue); free (obj->attributes); free (obj); } /* Allocator for objects. The hook is currently unused. */ static gpg_error_t object_alloc (void **data_r, void *hook) { struct object *object; (void) hook; object = calloc (1, sizeof (*object)); if (object == NULL) return gpg_error_from_syserror (); *data_r = object; return 0; } static void session_dealloc (void *data) { struct session *session = data; if (session->search_result) free (session->search_result); free (session); } /* Allocator for sessions. The hook is currently unused. */ static gpg_error_t session_alloc (void **data_r, void *hook) { struct session *session; (void) hook; session = calloc (1, sizeof (*session)); if (session == NULL) return gpg_error_from_syserror (); *data_r = session; return 0; } /* Deallocator for slots. */ static void slot_dealloc (void *data) { struct slot *slot = data; scute_table_destroy (slot->sessions); scute_table_destroy (slot->mechanisms); scute_table_destroy (slot->objects); free (slot); } /* Allocator for slots. The hook does not indicate anything at this point. */ static gpg_error_t slot_alloc (void **data_r, void *hook) { gpg_error_t err; struct slot *slot; - int idx; - CK_FLAGS flags; (void) hook; slot = calloc (1, sizeof (*slot)); if (slot == NULL) return gpg_error_from_syserror (); err = scute_table_create (&slot->mechanisms, mechanism_alloc, mechanism_dealloc); if (err) goto slot_alloc_out; - /* Register the signing mechanism. */ - flags = CKF_SIGN; - err = scute_table_alloc (slot->mechanisms, &idx, NULL, &flags); - if (err) - goto slot_alloc_out; - err = scute_table_create (&slot->sessions, session_alloc, session_dealloc); if (err) goto slot_alloc_out; err = scute_table_create (&slot->objects, object_alloc, object_dealloc); if (err) goto slot_alloc_out; slot->status = SLOT_STATUS_USED; slot->token_present = false; slot->login = SLOT_LOGIN_PUBLIC; *data_r = slot; slot_alloc_out: if (err) slot_dealloc (slot); return err; } static gpg_error_t add_object (void *hook, CK_ATTRIBUTE_PTR attrp, CK_ULONG attr_countp); static gpg_error_t slot_init (slot_iterator_t id); /* Initialize the slot list. */ CK_RV scute_slots_initialize (void) { gpg_error_t err; struct keyinfo *keyinfo = NULL; struct keyinfo *ki; err = scute_agent_serialno (); if (err) { if (gpg_err_code (err) != GPG_ERR_ENODEV) return scute_gpg_err_to_ck (err); } err = scute_agent_keyinfo_list (&keyinfo); if (err) return scute_gpg_err_to_ck (err); err = scute_table_create (&slot_table, slot_alloc, slot_dealloc); if (err) return err; for (ki = keyinfo; ki; ki = ki->next) { struct slot *slot; int slot_idx; err = scute_table_alloc (slot_table, &slot_idx, (void **)&slot, NULL); if (err) { scute_slots_finalize (); break; } else { memset (slot->serialno, 0, sizeof (slot->serialno)); if (ki->serialno) { int len; len = strlen (ki->serialno); if (len >= 32) memcpy (slot->serialno, &ki->serialno[len-32], 32); else memcpy (slot->serialno, ki->serialno, len); } memcpy (slot->grip, ki->grip, 41); err = scute_gpgsm_get_cert (slot->grip, add_object, slot); if (!err) err = slot_init (slot_idx); if (err) { scute_table_dealloc (slot_table, &slot_idx); err = 0; } } } scute_agent_free_keyinfo (keyinfo); return scute_gpg_err_to_ck (err); } void scute_slots_finalize (void) { if (!slot_table) return; /* This recursively releases all slots and any objects associated with them. */ scute_table_destroy (slot_table); slot_table = NULL; } /* Reset the slot SLOT after the token has been removed. */ static void slot_reset (slot_iterator_t id) { struct slot *slot = scute_table_data (slot_table, id); int oid; /* This also resets the login state. */ slot_close_all_sessions (id); oid = scute_table_first (slot->objects); while (!scute_table_last (slot->objects, oid)) scute_table_dealloc (slot->objects, &oid); assert (scute_table_used (slot->objects) == 0); slot->token_present = false; } static gpg_error_t add_object (void *hook, CK_ATTRIBUTE_PTR attrp, CK_ULONG attr_countp) { gpg_error_t err; struct slot *slot = hook; struct object *object; unsigned int oidx; void *objp; err = scute_table_alloc (slot->objects, &oidx, &objp, NULL); if (err) return err; object = objp; object->attributes = attrp; object->attributes_count = attr_countp; return 0; } /* Initialize the slot after a token has been inserted. */ static gpg_error_t slot_init (slot_iterator_t id) { gpg_error_t err = 0; struct slot *slot = scute_table_data (slot_table, id); + int idx; /* FIXME: Perform the rest of the initialization of the token. */ slot->token_present = true; + err = scute_table_alloc (slot->mechanisms, &idx, NULL, slot); + if (err) slot_reset (id); return err; } /* Begin iterating over the list of slots. */ CK_RV slots_iterate_first (slot_iterator_t *slot) { *slot = scute_table_first (slot_table); return CKR_OK; } /* Continue iterating over the list of slots. */ CK_RV slots_iterate_next (slot_iterator_t *slot) { *slot = scute_table_next (slot_table, *slot); return CKR_OK; } /* Return true iff the previous slot was the last one. */ bool slots_iterate_last (slot_iterator_t *slot) { return scute_table_last (slot_table, *slot); } /* Acquire the slot for the slot ID ID. */ CK_RV slots_lookup (CK_SLOT_ID id, slot_iterator_t *id_r) { struct slot *slot = scute_table_data (slot_table, id); if (slot == NULL) return CKR_SLOT_ID_INVALID; *id_r = id; return CKR_OK; } /* Return true iff a token is present in slot SLOT. */ bool slot_token_present (slot_iterator_t id) { struct slot *slot = scute_table_data (slot_table, id); return slot->token_present; } /* Return the token label. We use the dispserialno here too because * Firefox prints that value in the prompt ("Stored at:"). */ const char * slot_token_label (slot_iterator_t id) { struct slot *slot = scute_table_data (slot_table, id); return slot->serialno; } /* Get the manufacturer of the token. */ const char * slot_token_manufacturer (slot_iterator_t id) { /* FIXME */ (void)id; return "scdaemon"; } /* Get the application used on the token. */ const char * slot_token_application (slot_iterator_t id) { struct slot *slot = scute_table_data (slot_table, id); if (!slot) return "[ooops]"; /* slots_update() makes sure this is correct. */ /* FIXME */ return "gpg-agent"; } /* Get the LSB of serial number of the token. */ const char * slot_token_serial (slot_iterator_t id) { struct slot *slot = scute_table_data (slot_table, id); return &slot->serialno[16]; } /* Get the manufacturer of the token. */ void slot_token_version (slot_iterator_t id, CK_BYTE *hw_major, CK_BYTE *hw_minor, CK_BYTE *fw_major, CK_BYTE *fw_minor) { /* FIXME */ (void)id; *hw_major = 0; *hw_minor = 0; *fw_major = 0; *fw_minor = 0; } /* Get the maximum and minimum pin length. */ void slot_token_maxpinlen (slot_iterator_t id, CK_ULONG *max, CK_ULONG *min) { /* FIXME */ (void)id; *max = 31; /* FIXME: This is true at least for the user pin (CHV1 and CHV2). */ *min = 6; } /* Get the maximum and the actual pin count. */ void slot_token_pincount (slot_iterator_t id, int *max, int *len) { (void)id; *max = 3; /* FIXME */ *len = 1; } /* Return the ID of slot SLOT. */ CK_SLOT_ID slot_get_id (slot_iterator_t slot) { return slot; } /* Return true if the token supports the GET CHALLENGE operation. */ bool slot_token_has_rng (slot_iterator_t id) { struct slot *slot = scute_table_data (slot_table, id); (void)slot; /* FIXME */ return 1; } /* Mechanism management. */ /* Begin iterating over the list of mechanisms. */ CK_RV mechanisms_iterate_first (slot_iterator_t id, mechanism_iterator_t *mechanism) { struct slot *slot = scute_table_data (slot_table, id); *mechanism = scute_table_first (slot->mechanisms); return CKR_OK; } /* Continue iterating over the list of mechanisms. */ CK_RV mechanisms_iterate_next (slot_iterator_t id, mechanism_iterator_t *mechanism) { struct slot *slot = scute_table_data (slot_table, id); *mechanism = scute_table_next (slot->mechanisms, *mechanism); return CKR_OK; } /* Return true iff the previous slot was the last one. */ bool mechanisms_iterate_last (slot_iterator_t id, mechanism_iterator_t *mechanism) { struct slot *slot = scute_table_data (slot_table, id); return scute_table_last (slot->mechanisms, *mechanism); } /* Acquire the mechanism TYPE for the slot id ID. */ CK_RV mechanisms_lookup (slot_iterator_t id, mechanism_iterator_t *mid_r, CK_MECHANISM_TYPE type) { struct slot *slot = scute_table_data (slot_table, id); int mid = scute_table_first (slot->mechanisms); while (!scute_table_last (slot->mechanisms, mid)) { struct mechanism *mechanism = scute_table_data (slot->mechanisms, mid); if (mechanism->type == type) { *mid_r = mid; return CKR_OK; } mid = scute_table_next (slot->mechanisms, mid); } return CKR_MECHANISM_INVALID; } /* Return the type of mechanism MID in slot ID. */ CK_MECHANISM_TYPE mechanism_get_type (slot_iterator_t id, mechanism_iterator_t mid) { struct slot *slot = scute_table_data (slot_table, id); struct mechanism *mechanism = scute_table_data (slot->mechanisms, mid); return mechanism->type; } /* Return the info of mechanism MID. */ CK_MECHANISM_INFO_PTR mechanism_get_info (slot_iterator_t id, mechanism_iterator_t mid) { struct slot *slot = scute_table_data (slot_table, id); struct mechanism *mechanism = scute_table_data (slot->mechanisms, mid); return &mechanism->info; } /* Session management. */ static int active_sessions; /* Create a new session. */ CK_RV slot_create_session (slot_iterator_t id, session_iterator_t *session, bool rw) { int err; struct slot *slot = scute_table_data (slot_table, id); unsigned int tsid; void *rawp; struct session *session_p; assert (slot); if (scute_table_used (slot->sessions) == SESSION_MAX) return CKR_SESSION_COUNT; if (slot->login == SLOT_LOGIN_SO && !rw) return CKR_SESSION_READ_WRITE_SO_EXISTS; err = scute_table_alloc (slot->sessions, &tsid, &rawp, NULL); if (err) return scute_sys_to_ck (err); session_p = rawp; session_p->rw = rw; session_p->search_result = NULL; session_p->search_result_len = 0; session_p->signing_key = CK_INVALID_HANDLE; session_p->decryption_key = CK_INVALID_HANDLE; *session = SESSION_BUILD_ID (id, tsid); active_sessions++; return CKR_OK; } /* Look up session. */ CK_RV slots_lookup_session (CK_SESSION_HANDLE sid, slot_iterator_t *id, session_iterator_t *session_id) { CK_RV err; unsigned int idx = SESSION_SLOT (sid); unsigned session_idx = SESSION_ID (sid); struct slot *slot; /* Verify the slot. */ err = slots_lookup (SESSION_SLOT (sid), id); if (err) return err; *session_id = session_idx; /* Verify the session. */ slot = scute_table_data (slot_table, idx); if (!scute_table_data (slot->sessions, session_idx)) return CKR_SESSION_HANDLE_INVALID; return 0; } /* Close the session. */ CK_RV slot_close_session (slot_iterator_t id, session_iterator_t sid) { struct slot *slot = scute_table_data (slot_table, id); scute_table_dealloc (slot->sessions, &sid); /* At last session closed, return to public sessions. */ if (!scute_table_used (slot->sessions)) slot->login = SLOT_LOGIN_PUBLIC; active_sessions--; return CKR_OK; } /* Close all sessions. */ CK_RV slot_close_all_sessions (slot_iterator_t id) { struct slot *slot = scute_table_data (slot_table, id); int sid = scute_table_first (slot->sessions); while (!scute_table_last (slot->sessions, sid)) { slot_close_session (id, sid); sid = scute_table_next (slot->sessions, sid); } assert (scute_table_used (slot->sessions) == 0); return CKR_OK; } /* Get the RW flag from the session SID in slot ID. */ bool session_get_rw (slot_iterator_t id, session_iterator_t sid) { struct slot *slot = scute_table_data (slot_table, id); struct session *session = scute_table_data (slot->sessions, sid); return session->rw; } /* Get the login state from the slot ID. */ slot_login_t slot_get_login_status (slot_iterator_t id) { struct slot *slot = scute_table_data (slot_table, id); return slot->login; } /* Object management. */ /* Begin iterating over the list of objects. */ CK_RV objects_iterate_first (slot_iterator_t id, object_iterator_t *object) { struct slot *slot = scute_table_data (slot_table, id); *object = scute_table_first (slot->objects); return CKR_OK; } /* Continue iterating over the list of objects. */ CK_RV objects_iterate_next (slot_iterator_t id, object_iterator_t *object) { struct slot *slot = scute_table_data (slot_table, id); *object = scute_table_next (slot->objects, *object); return CKR_OK; } /* Return true iff the previous slot was the last one. */ bool objects_iterate_last (slot_iterator_t id, object_iterator_t *object) { struct slot *slot = scute_table_data (slot_table, id); return scute_table_last (slot->objects, *object); } /* Return the max. number of objects in the slot. May overcount somewhat. */ CK_RV slot_get_object_count (slot_iterator_t id, int *nr) { struct slot *slot = scute_table_data (slot_table, id); *nr = scute_table_used (slot->objects); return CKR_OK; } /* Get the object information for object OBJECT_ID in slot ID. */ CK_RV slot_get_object (slot_iterator_t id, object_iterator_t oid, CK_ATTRIBUTE_PTR *obj, CK_ULONG *obj_count) { struct slot *slot = scute_table_data (slot_table, id); struct object *object = scute_table_data (slot->objects, oid); if (!object) return CKR_OBJECT_HANDLE_INVALID; *obj = object->attributes; *obj_count = object->attributes_count; return 0; } /* Set the result of a search for session SID in slot ID to SEARCH_RESULT and SEARCH_RESULT_LEN. */ CK_RV session_set_search_result (slot_iterator_t id, session_iterator_t sid, object_iterator_t *search_result, int search_result_len) { struct slot *slot = scute_table_data (slot_table, id); struct session *session = scute_table_data (slot->sessions, sid); if (session->search_result && session->search_result != search_result) free (session->search_result); session->search_result = search_result; session->search_result_len = search_result_len; return 0; } /* Get the stored search result for the session SID in slot ID. */ CK_RV session_get_search_result (slot_iterator_t id, session_iterator_t sid, object_iterator_t **search_result, int *search_result_len) { struct slot *slot = scute_table_data (slot_table, id); struct session *session = scute_table_data (slot->sessions, sid); assert (search_result); assert (search_result_len); *search_result = session->search_result; *search_result_len = session->search_result_len; return 0; } /* Set the signing key for session SID in slot ID to KEY. This is the * core of C_SignInit. */ CK_RV session_set_signing_key (slot_iterator_t id, session_iterator_t sid, object_iterator_t key, CK_MECHANISM_TYPE mechanism_type) { struct slot *slot = scute_table_data (slot_table, id); struct session *session = scute_table_data (slot->sessions, sid); CK_RV err; CK_ATTRIBUTE_PTR attr; CK_ULONG attr_count; CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY; err = slot_get_object (id, key, &attr, &attr_count); if (err) return err; while (attr_count-- > 0) if (attr->type == CKA_CLASS) break; if (attr_count == (CK_ULONG) -1) return CKR_KEY_HANDLE_INVALID; if (attr->ulValueLen != sizeof (key_class) || memcmp (attr->pValue, &key_class, sizeof (key_class))) return CKR_KEY_HANDLE_INVALID; /* It's the private RSA key object. */ session->signing_key = key; session->signing_mechanism_type = mechanism_type; return 0; } /* The core of C_Sign - see there for a description. */ CK_RV session_sign (slot_iterator_t id, session_iterator_t sid, CK_BYTE_PTR pData, CK_ULONG ulDataLen, CK_BYTE_PTR pSignature, CK_ULONG_PTR pulSignatureLen) { struct slot *slot = scute_table_data (slot_table, id); struct session *session = scute_table_data (slot->sessions, sid); int rc; gpg_error_t err; CK_ATTRIBUTE_PTR attr; CK_ULONG attr_count; CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY; unsigned int sig_len; CK_BYTE key_id[100]; int i; if (!session->signing_key) return CKR_OPERATION_NOT_INITIALIZED; rc = slot_get_object (id, session->signing_key, &attr, &attr_count); if (rc) goto leave; if (attr_count == (CK_ULONG) -1) { rc = CKR_KEY_HANDLE_INVALID; goto leave; } if (attr->ulValueLen != sizeof (key_class) || memcmp (attr->pValue, &key_class, sizeof (key_class))) { rc = CKR_KEY_HANDLE_INVALID; goto leave; } /* Find the CKA_ID */ for (i = 0; i < attr_count; i++) if (attr[i].type == CKA_ID) break; if (i == attr_count) { rc = CKR_GENERAL_ERROR; goto leave; } if (attr[i].ulValueLen >= sizeof key_id - 1) { rc = CKR_GENERAL_ERROR; goto leave; } strncpy (key_id, attr[i].pValue, attr[i].ulValueLen); key_id[attr[i].ulValueLen] = 0; DEBUG (DBG_INFO, "Found CKA_ID '%s'", key_id); sig_len = *pulSignatureLen; err = scute_agent_sign (key_id, session->signing_mechanism_type, pData, ulDataLen, pSignature, &sig_len); /* Take care of error codes which are not mapped by default. */ if (gpg_err_code (err) == GPG_ERR_INV_LENGTH) rc = CKR_BUFFER_TOO_SMALL; else if (gpg_err_code (err) == GPG_ERR_INV_ARG) rc = CKR_ARGUMENTS_BAD; else rc = scute_gpg_err_to_ck (err); /* Return the length. */ if (rc == CKR_OK || rc == CKR_BUFFER_TOO_SMALL) *pulSignatureLen = sig_len; leave: if (rc != CKR_OK && rc != CKR_BUFFER_TOO_SMALL) session->signing_key = 0; return rc; } /* Prepare a decryption for slot with SLOTID and the session SID using * MECHANISM and KEY. This is the core of C_DecryptInit. */ CK_RV session_init_decrypt (slot_iterator_t slotid, session_iterator_t sid, CK_MECHANISM *mechanism, object_iterator_t key) { struct slot *slot; struct session *session; CK_RV rv; CK_ATTRIBUTE_PTR attr; CK_ULONG attr_count; CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY; if (mechanism->mechanism != CKM_RSA_PKCS) return CKR_MECHANISM_INVALID; slot = scute_table_data (slot_table, slotid); session = scute_table_data (slot->sessions, sid); rv = slot_get_object (slotid, key, &attr, &attr_count); if (rv) return rv; /* FIXME: What kind of strange loop is this? */ while (attr_count-- > 0) if (attr->type == CKA_CLASS) break; if (attr_count == (CK_ULONG) -1) return CKR_KEY_HANDLE_INVALID; if (attr->ulValueLen != sizeof (key_class) || memcmp (attr->pValue, &key_class, sizeof (key_class))) return CKR_KEY_HANDLE_INVALID; /* It's the private RSA key object. */ session->decryption_key = key; return 0; } /* The core of C_Decrypt - see there for a description. */ CK_RV session_decrypt (slot_iterator_t slotid, session_iterator_t sid, CK_BYTE *encdata, CK_ULONG encdatalen, CK_BYTE *r_plaindata, CK_ULONG *r_plaindatalen) { CK_RV rv; gpg_error_t err; struct slot *slot; struct session *session; CK_ATTRIBUTE_PTR attr; CK_ULONG attr_count; CK_OBJECT_CLASS key_class = CKO_PRIVATE_KEY; CK_BYTE key_id[100]; int i; unsigned int plaindatalen; slot = scute_table_data (slot_table, slotid); session = scute_table_data (slot->sessions, sid); if (!session->decryption_key) return CKR_OPERATION_NOT_INITIALIZED; rv = slot_get_object (slotid, session->decryption_key, &attr, &attr_count); if (rv) goto leave; if (attr_count == (CK_ULONG) -1) { rv = CKR_KEY_HANDLE_INVALID; goto leave; } if (attr->ulValueLen != sizeof (key_class) || memcmp (attr->pValue, &key_class, sizeof (key_class))) { rv = CKR_KEY_HANDLE_INVALID; goto leave; } /* Find the CKA_ID */ for (i = 0; i < attr_count; i++) if (attr[i].type == CKA_ID) break; if (i == attr_count) { rv = CKR_GENERAL_ERROR; goto leave; } if (attr[i].ulValueLen >= sizeof key_id - 1) { rv = CKR_GENERAL_ERROR; goto leave; } strncpy (key_id, attr[i].pValue, attr[i].ulValueLen); key_id[attr[i].ulValueLen] = 0; DEBUG (DBG_INFO, "Found CKA_ID '%s'", key_id); plaindatalen = *r_plaindatalen; err = scute_agent_decrypt (key_id, encdata, encdatalen, r_plaindata, &plaindatalen); DEBUG (DBG_INFO, "agent returned gpg error %d datalen=%u", err, plaindatalen); /* Take care of error codes which are not mapped by default. */ if (gpg_err_code (err) == GPG_ERR_INV_LENGTH) rv = CKR_BUFFER_TOO_SMALL; else if (gpg_err_code (err) == GPG_ERR_INV_ARG) rv = CKR_ARGUMENTS_BAD; else rv = scute_gpg_err_to_ck (err); /* Return the length. */ if (rv == CKR_OK || rv == CKR_BUFFER_TOO_SMALL) *r_plaindatalen = plaindatalen; leave: if (rv != CKR_BUFFER_TOO_SMALL) session->decryption_key = 0; DEBUG (DBG_INFO, "leaving decrypt with rv=%lu", rv); return rv; } CK_RV scute_slots_rescan_if_no_sessions (void) { if (active_sessions == 0) { scute_slots_finalize (); scute_slots_initialize (); } return CKR_OK; }