aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--asn1.c441
-rw-r--r--asn1_internal.h38
-rwxr-xr-xcryptech_backup224
-rw-r--r--ecdsa.c191
-rw-r--r--hal.h28
-rw-r--r--hal_internal.h58
-rw-r--r--ks_flash.c4
-rw-r--r--ks_volatile.c9
-rw-r--r--libhal.py43
-rw-r--r--pkcs8.py324
-rw-r--r--rpc_api.c47
-rw-r--r--rpc_client.c105
-rw-r--r--rpc_client_daemon.c1
-rw-r--r--rpc_pkey.c494
-rw-r--r--rpc_server.c131
-rw-r--r--rsa.c54
-rw-r--r--tests/test-rpc_pkey.c36
-rw-r--r--unit-tests.py570
18 files changed, 2267 insertions, 531 deletions
diff --git a/asn1.c b/asn1.c
index bbb049f..73e34b6 100644
--- a/asn1.c
+++ b/asn1.c
@@ -52,9 +52,31 @@
#include <assert.h>
#include "hal.h"
-
+#include "hal_internal.h"
#include "asn1_internal.h"
+#define INIT_FP_INT {{{0}}}
+
+/*
+ * Algorithm OIDs used in SPKI and PKCS #8.
+ */
+
+const uint8_t hal_asn1_oid_rsaEncryption[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 };
+const size_t hal_asn1_oid_rsaEncryption_len = sizeof(hal_asn1_oid_rsaEncryption);
+
+const uint8_t hal_asn1_oid_ecPublicKey[] = { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01 };
+const size_t hal_asn1_oid_ecPublicKey_len = sizeof(hal_asn1_oid_ecPublicKey);
+
+#if KEK_LENGTH == (bitsToBytes(128))
+const uint8_t hal_asn1_oid_aesKeyWrap[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x08 };
+const size_t hal_asn1_oid_aesKeyWrap_len = sizeof(hal_asn1_oid_aesKeyWrap);
+#endif
+
+#if KEK_LENGTH == (bitsToBytes(256))
+const uint8_t hal_asn1_oid_aesKeyWrap[] = { 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x01, 0x30 };
+const size_t hal_asn1_oid_aesKeyWrap_len = sizeof(hal_asn1_oid_aesKeyWrap);
+#endif
+
/*
* Encode tag and length fields of an ASN.1 object.
*
@@ -153,7 +175,7 @@ hal_error_t hal_asn1_encode_integer(const fp_int * const bn,
}
/*
- * Encode a public key into an RFC 5280 SubjectPublicKeyInfo.
+ * Encode a public key into a X.509 SubjectPublicKeyInfo (RFC 5280).
*/
hal_error_t hal_asn1_encode_spki(const uint8_t * const alg_oid, const size_t alg_oid_len,
@@ -176,12 +198,14 @@ hal_error_t hal_asn1_encode_spki(const uint8_t * const alg_oid, const size_t a
(err = hal_asn1_encode_header(ASN1_BIT_STRING, 1 + pubkey_len, NULL, &hlen_bit, 0)) != HAL_OK)
return err;
- const size_t algid_len = hlen_alg + alg_oid_len + hlen_curve + curve_oid_len;
+ const size_t algid_len =
+ hlen_alg + alg_oid_len + hlen_curve + curve_oid_len;
if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, algid_len, NULL, &hlen_algid, 0)) != HAL_OK)
return err;
- const size_t vlen = hlen_algid + hlen_alg + alg_oid_len + hlen_curve + curve_oid_len + hlen_bit + 1 + pubkey_len;
+ const size_t vlen =
+ hlen_algid + hlen_alg + alg_oid_len + hlen_curve + curve_oid_len + hlen_bit + 1 + pubkey_len;
if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, vlen, NULL, &hlen_spki, 0)) != HAL_OK)
return err;
@@ -224,7 +248,6 @@ hal_error_t hal_asn1_encode_spki(const uint8_t * const alg_oid, const size_t a
return err;
d += hlen;
*d++ = 0x00;
-
d += pubkey_len; /* pubkey handled early, above. */
assert(d == der + hlen_spki + vlen);
@@ -234,6 +257,167 @@ hal_error_t hal_asn1_encode_spki(const uint8_t * const alg_oid, const size_t a
}
/*
+ * Encode a PKCS #8 PrivateKeyInfo (RFC 5208).
+ */
+
+hal_error_t hal_asn1_encode_pkcs8_privatekeyinfo(const uint8_t * const alg_oid, const size_t alg_oid_len,
+ const uint8_t * const curve_oid, const size_t curve_oid_len,
+ const uint8_t * const privkey, const size_t privkey_len,
+ uint8_t *der, size_t *der_len, const size_t der_max)
+{
+ if (alg_oid == NULL || alg_oid_len == 0 || privkey_len == 0 ||
+ (der != NULL && privkey == NULL) || (curve_oid == NULL && curve_oid_len != 0))
+ return HAL_ERROR_BAD_ARGUMENTS;
+
+ const uint8_t curve_oid_tag = curve_oid == NULL ? ASN1_NULL : ASN1_OBJECT_IDENTIFIER;
+
+ fp_int version[1] = INIT_FP_INT;
+
+ hal_error_t err;
+
+ size_t version_len, hlen, hlen_algid, hlen_alg, hlen_curve, hlen_oct;
+
+ if ((err = hal_asn1_encode_integer(version, NULL, &version_len, 0)) != HAL_OK ||
+ (err = hal_asn1_encode_header(ASN1_OBJECT_IDENTIFIER, alg_oid_len, NULL, &hlen_alg, 0)) != HAL_OK ||
+ (err = hal_asn1_encode_header(curve_oid_tag, curve_oid_len, NULL, &hlen_curve, 0)) != HAL_OK ||
+ (err = hal_asn1_encode_header(ASN1_OCTET_STRING, privkey_len, NULL, &hlen_oct, 0)) != HAL_OK)
+ return err;
+
+ const size_t algid_len =
+ hlen_alg + alg_oid_len + hlen_curve + curve_oid_len;
+
+ if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, algid_len, NULL, &hlen_algid, 0)) != HAL_OK)
+ return err;
+
+ const size_t vlen =
+ version_len + hlen_algid + hlen_alg + alg_oid_len + hlen_curve + curve_oid_len + hlen_oct + privkey_len;
+
+ if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, vlen, NULL, &hlen, 0)) != HAL_OK)
+ return err;
+
+ if (der_len != NULL)
+ *der_len = hlen + vlen;
+
+ if (der == NULL)
+ return HAL_OK;
+
+ uint8_t * const der_end = der + hlen + vlen;
+
+ /*
+ * Handle privkey early, in case it was staged into our output buffer.
+ */
+ if (der_end <= der + der_max)
+ memmove(der_end - privkey_len, privkey, privkey_len);
+
+ uint8_t *d = der;
+ memset(d, 0, hlen + vlen - privkey_len);
+
+ if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, vlen, d, &hlen, der + der_max - d)) != HAL_OK)
+ return err;
+ d += hlen;
+
+ if ((err = hal_asn1_encode_integer(version, d, NULL, der + der_max - d)) != HAL_OK)
+ return err;
+ d += version_len;
+
+ if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, algid_len, d, &hlen, der + der_max - d)) != HAL_OK)
+ return err;
+ d += hlen;
+
+ if ((err = hal_asn1_encode_header(ASN1_OBJECT_IDENTIFIER, alg_oid_len, d, &hlen, der + der_max - d)) != HAL_OK)
+ return err;
+ d += hlen;
+ memcpy(d, alg_oid, alg_oid_len);
+ d += alg_oid_len;
+
+ if ((err = hal_asn1_encode_header(curve_oid_tag, curve_oid_len, d, &hlen, der + der_max - d)) != HAL_OK)
+ return err;
+ d += hlen;
+ if (curve_oid != NULL)
+ memcpy(d, curve_oid, curve_oid_len);
+ d += curve_oid_len;
+
+ if ((err = hal_asn1_encode_header(ASN1_OCTET_STRING, privkey_len, d, &hlen, der + der_max - d)) != HAL_OK)
+ return err;
+ d += hlen;
+ d += privkey_len; /* privkey handled early, above. */
+
+ assert(d == der_end);
+ assert(d <= der + der_max);
+
+ return HAL_OK;
+}
+
+/*
+ * Encode a PKCS #8 EncryptedPrivateKeyInfo (RFC 5208).
+ */
+
+hal_error_t hal_asn1_encode_pkcs8_encryptedprivatekeyinfo(const uint8_t * const alg_oid, const size_t alg_oid_len,
+ const uint8_t * const data, const size_t data_len,
+ uint8_t *der, size_t *der_len, const size_t der_max)
+{
+ if (alg_oid == NULL || alg_oid_len == 0 || data_len == 0 || (der != NULL && data == NULL))
+ return HAL_ERROR_BAD_ARGUMENTS;
+
+ hal_error_t err;
+
+ size_t hlen, hlen_pkcs8, hlen_algid, hlen_alg, hlen_oct;
+
+ if ((err = hal_asn1_encode_header(ASN1_OBJECT_IDENTIFIER, alg_oid_len, NULL, &hlen_alg, 0)) != HAL_OK ||
+ (err = hal_asn1_encode_header(ASN1_OCTET_STRING, data_len, NULL, &hlen_oct, 0)) != HAL_OK)
+ return err;
+
+ const size_t algid_len = hlen_alg + alg_oid_len;
+
+ if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, algid_len, NULL, &hlen_algid, 0)) != HAL_OK)
+ return err;
+
+ const size_t vlen = hlen_algid + hlen_alg + alg_oid_len + hlen_oct + data_len;
+
+ if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, vlen, NULL, &hlen_pkcs8, 0)) != HAL_OK)
+ return err;
+
+ /*
+ * Handle data early, in case it was staged into our output buffer.
+ */
+ if (der != NULL && hlen_pkcs8 + vlen <= der_max)
+ memmove(der + hlen_pkcs8 + vlen - data_len, data, data_len);
+
+ err = hal_asn1_encode_header(ASN1_SEQUENCE, vlen, der, &hlen, der_max);
+
+ if (der_len != NULL)
+ *der_len = hlen + vlen;
+
+ if (der == NULL || err != HAL_OK)
+ return err;
+
+ uint8_t *d = der + hlen;
+ memset(d, 0, vlen - data_len);
+
+ if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, algid_len, d, &hlen, der + der_max - d)) != HAL_OK)
+ return err;
+ d += hlen;
+
+ if ((err = hal_asn1_encode_header(ASN1_OBJECT_IDENTIFIER, alg_oid_len, d, &hlen, der + der_max - d)) != HAL_OK)
+ return err;
+ d += hlen;
+ memcpy(d, alg_oid, alg_oid_len);
+ d += alg_oid_len;
+
+ if ((err = hal_asn1_encode_header(ASN1_OCTET_STRING, data_len, d, &hlen, der + der_max - d)) != HAL_OK)
+ return err;
+ d += hlen;
+
+ d += data_len; /* data handled early, above. */
+
+ assert(d == der + hlen_pkcs8 + vlen);
+ assert(d <= der + der_max);
+
+ return HAL_OK;
+}
+
+
+/*
* Parse tag and length of an ASN.1 object. Tag must match value
* specified by the caller. On success, sets hlen and vlen to lengths
* of header and value, respectively.
@@ -300,7 +484,7 @@ hal_error_t hal_asn1_decode_integer(fp_int *bn,
}
/*
- * Decode a public key from an RFC 5280 SubjectPublicKeyInfo.
+ * Decode a public key from a X.509 SubjectPublicKeyInfo (RFC 5280).
*/
hal_error_t hal_asn1_decode_spki(const uint8_t **alg_oid, size_t *alg_oid_len,
@@ -308,8 +492,7 @@ hal_error_t hal_asn1_decode_spki(const uint8_t **alg_oid, size_t *alg_oid_len,
const uint8_t **pubkey, size_t *pubkey_len,
const uint8_t *const der, const size_t der_len)
{
- if (alg_oid == NULL || alg_oid_len == NULL || curve_oid == NULL || curve_oid_len == NULL ||
- pubkey == NULL || pubkey_len == NULL || der == NULL)
+ if (der == NULL)
return HAL_ERROR_BAD_ARGUMENTS;
const uint8_t * const der_end = der + der_len;
@@ -322,6 +505,9 @@ hal_error_t hal_asn1_decode_spki(const uint8_t **alg_oid, size_t *alg_oid_len,
return err;
d += hlen;
+ if (hlen + vlen != der_len)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+
if ((err = hal_asn1_decode_header(ASN1_SEQUENCE, d, der_end - d, &hlen, &vlen)) != HAL_OK)
return err;
d += hlen;
@@ -333,12 +519,16 @@ hal_error_t hal_asn1_decode_spki(const uint8_t **alg_oid, size_t *alg_oid_len,
d += hlen;
if (vlen > algid_end - d)
return HAL_ERROR_ASN1_PARSE_FAILED;
- *alg_oid = d;
- *alg_oid_len = vlen;
+ if (alg_oid != NULL)
+ *alg_oid = d;
+ if (alg_oid_len != NULL)
+ *alg_oid_len = vlen;
d += vlen;
- *curve_oid = NULL;
- *curve_oid_len = 0;
+ if (curve_oid != NULL)
+ *curve_oid = NULL;
+ if (curve_oid_len != NULL)
+ *curve_oid_len = 0;
if (d < algid_end) {
switch (*d) {
@@ -349,8 +539,10 @@ hal_error_t hal_asn1_decode_spki(const uint8_t **alg_oid, size_t *alg_oid_len,
d += hlen;
if (vlen > algid_end - d)
return HAL_ERROR_ASN1_PARSE_FAILED;
- *curve_oid = d;
- *curve_oid_len = vlen;
+ if (curve_oid != NULL)
+ *curve_oid = d;
+ if (curve_oid_len != NULL)
+ *curve_oid_len = vlen;
d += vlen;
break;
@@ -374,8 +566,11 @@ hal_error_t hal_asn1_decode_spki(const uint8_t **alg_oid, size_t *alg_oid_len,
d += hlen;
if (vlen >= algid_end - d || vlen == 0 || *d != 0x00)
return HAL_ERROR_ASN1_PARSE_FAILED;
- *pubkey = ++d;
- *pubkey_len = --vlen;
+ ++d; --vlen;
+ if (pubkey != NULL)
+ *pubkey = d;
+ if (pubkey_len != NULL)
+ *pubkey_len = vlen;
d += vlen;
if (d != der_end)
@@ -385,6 +580,220 @@ hal_error_t hal_asn1_decode_spki(const uint8_t **alg_oid, size_t *alg_oid_len,
}
/*
+ * Decode a private key from a PKCS #8 PrivateKeyInfo (RFC 5208).
+ */
+
+hal_error_t hal_asn1_decode_pkcs8_privatekeyinfo(const uint8_t **alg_oid, size_t *alg_oid_len,
+ const uint8_t **curve_oid, size_t *curve_oid_len,
+ const uint8_t **privkey, size_t *privkey_len,
+ const uint8_t *const der, const size_t der_len)
+{
+ if (der == NULL)
+ return HAL_ERROR_BAD_ARGUMENTS;
+
+ const uint8_t * const der_end = der + der_len;
+ const uint8_t *d = der;
+
+ fp_int version[1] = INIT_FP_INT;
+ size_t hlen, vlen;
+ hal_error_t err;
+
+ if ((err = hal_asn1_decode_header(ASN1_SEQUENCE, d, der_end - d, &hlen, &vlen)) != HAL_OK)
+ return err;
+ d += hlen;
+
+ if (hlen + vlen != der_len)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+
+ if ((err = hal_asn1_decode_integer(version, d, &hlen, der_end - d)) != HAL_OK)
+ return err;
+ if (!fp_iszero(version))
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+ d += hlen;
+
+ if ((err = hal_asn1_decode_header(ASN1_SEQUENCE, d, der_end - d, &hlen, &vlen)) != HAL_OK)
+ return err;
+ d += hlen;
+
+ const uint8_t * const algid_end = d + vlen;
+
+ if ((err = hal_asn1_decode_header(ASN1_OBJECT_IDENTIFIER, d, algid_end - d, &hlen, &vlen)) != HAL_OK)
+ return err;
+ d += hlen;
+ if (vlen > algid_end - d)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+ if (alg_oid != NULL)
+ *alg_oid = d;
+ if (alg_oid_len != NULL)
+ *alg_oid_len = vlen;
+ d += vlen;
+
+ if (curve_oid != NULL)
+ *curve_oid = NULL;
+ if (curve_oid_len != NULL)
+ *curve_oid_len = 0;
+
+ if (d < algid_end) {
+ switch (*d) {
+
+ case ASN1_OBJECT_IDENTIFIER:
+ if ((err = hal_asn1_decode_header(ASN1_OBJECT_IDENTIFIER, d, algid_end - d, &hlen, &vlen)) != HAL_OK)
+ return err;
+ d += hlen;
+ if (vlen > algid_end - d)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+ if (curve_oid != NULL)
+ *curve_oid = d;
+ if (curve_oid_len != NULL)
+ *curve_oid_len = vlen;
+ d += vlen;
+ break;
+
+ case ASN1_NULL:
+ if ((err = hal_asn1_decode_header(ASN1_NULL, d, algid_end - d, &hlen, &vlen)) != HAL_OK)
+ return err;
+ d += hlen;
+ if (vlen == 0)
+ break;
+
+ default:
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+ }
+ }
+
+ if (d != algid_end)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+
+ if ((err = hal_asn1_decode_header(ASN1_OCTET_STRING, d, der_end - d, &hlen, &vlen)) != HAL_OK)
+ return err;
+ d += hlen;
+ if (vlen >= algid_end - d)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+ if (privkey != NULL)
+ *privkey = d;
+ if (privkey_len != NULL)
+ *privkey_len = vlen;
+ d += vlen;
+
+ if (d != der_end)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+
+ return HAL_OK;
+}
+
+/*
+ * Decode a private key from a PKCS #8 EncryptedPrivateKeyInfo (RFC 5208).
+ */
+
+hal_error_t hal_asn1_decode_pkcs8_encryptedprivatekeyinfo(const uint8_t **alg_oid, size_t *alg_oid_len,
+ const uint8_t **data, size_t *data_len,
+ const uint8_t *const der, const size_t der_len)
+{
+ if (alg_oid == NULL || alg_oid_len == NULL || data == NULL || data_len == NULL || der == NULL)
+ return HAL_ERROR_BAD_ARGUMENTS;
+
+ const uint8_t * const der_end = der + der_len;
+ const uint8_t *d = der;
+
+ size_t hlen, vlen;
+ hal_error_t err;
+
+ if ((err = hal_asn1_decode_header(ASN1_SEQUENCE, d, der_end - d, &hlen, &vlen)) != HAL_OK)
+ return err;
+ d += hlen;
+
+ if (hlen + vlen != der_len)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+
+ if ((err = hal_asn1_decode_header(ASN1_SEQUENCE, d, der_end - d, &hlen, &vlen)) != HAL_OK)
+ return err;
+ d += hlen;
+
+ const uint8_t * const algid_end = d + vlen;
+
+ if ((err = hal_asn1_decode_header(ASN1_OBJECT_IDENTIFIER, d, algid_end - d, &hlen, &vlen)) != HAL_OK)
+ return err;
+ d += hlen;
+ if (vlen > algid_end - d)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+ if (alg_oid != NULL)
+ *alg_oid = d;
+ if (alg_oid_len != NULL)
+ *alg_oid_len = vlen;
+ d += vlen;
+
+ if (d < algid_end) {
+ if ((err = hal_asn1_decode_header(ASN1_NULL, d, algid_end - d, &hlen, &vlen)) != HAL_OK)
+ return err;
+ d += hlen;
+ if (vlen != 0)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+ }
+
+ if (d != algid_end)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+
+ if ((err = hal_asn1_decode_header(ASN1_OCTET_STRING, d, der_end - d, &hlen, &vlen)) != HAL_OK)
+ return err;
+ d += hlen;
+ if (vlen >= algid_end - d)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+ if (data != NULL)
+ *data = d;
+ if (data_len != NULL)
+ *data_len = vlen;
+ d += vlen;
+
+ if (d != der_end)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+
+ return HAL_OK;
+}
+
+/*
+ * Attempt to guess what kind of key we're looking at.
+ */
+
+hal_error_t hal_asn1_guess_key_type(hal_key_type_t *type,
+ hal_curve_name_t *curve,
+ const uint8_t *const der, const size_t der_len)
+{
+ if (type == NULL || curve == NULL || der == NULL)
+ return HAL_ERROR_BAD_ARGUMENTS;
+
+ const uint8_t *alg_oid, *curve_oid;
+ size_t alg_oid_len, curve_oid_len;
+ hal_error_t err;
+ int public = 0;
+
+ err = hal_asn1_decode_pkcs8_privatekeyinfo(&alg_oid, &alg_oid_len, &curve_oid, &curve_oid_len, NULL, 0, der, der_len);
+
+ if (err == HAL_ERROR_ASN1_PARSE_FAILED &&
+ (err = hal_asn1_decode_spki(&alg_oid, &alg_oid_len, &curve_oid, &curve_oid_len, NULL, 0, der, der_len)) == HAL_OK)
+ public = 1;
+
+ if (err != HAL_OK)
+ return err;
+
+ if (alg_oid_len == hal_asn1_oid_rsaEncryption_len && memcmp(alg_oid, hal_asn1_oid_rsaEncryption, alg_oid_len) == 0) {
+ *type = public ? HAL_KEY_TYPE_RSA_PUBLIC : HAL_KEY_TYPE_RSA_PRIVATE;
+ *curve = HAL_CURVE_NONE;
+ return HAL_OK;
+ }
+
+ if (alg_oid_len == hal_asn1_oid_ecPublicKey_len && memcmp(alg_oid, hal_asn1_oid_ecPublicKey, alg_oid_len) == 0) {
+ *type = public ? HAL_KEY_TYPE_EC_PUBLIC : HAL_KEY_TYPE_EC_PRIVATE;
+ if ((err = hal_ecdsa_oid_to_curve(curve, curve_oid, curve_oid_len)) != HAL_OK)
+ *curve = HAL_CURVE_NONE;
+ return err;
+ }
+
+ *type = HAL_KEY_TYPE_NONE;
+ *curve = HAL_CURVE_NONE;
+ return HAL_ERROR_UNSUPPORTED_KEY;
+}
+
+/*
* Local variables:
* indent-tabs-mode: nil
* End:
diff --git a/asn1_internal.h b/asn1_internal.h
index 0b08b84..fe2f293 100644
--- a/asn1_internal.h
+++ b/asn1_internal.h
@@ -89,6 +89,23 @@ static inline uint8_t *unconst_uint8_t(const uint8_t * const arg)
return (uint8_t *) arg;
}
+/*
+ * OIDs.
+ */
+
+extern const uint8_t hal_asn1_oid_rsaEncryption[];
+extern const size_t hal_asn1_oid_rsaEncryption_len;
+
+extern const uint8_t hal_asn1_oid_ecPublicKey[];
+extern const size_t hal_asn1_oid_ecPublicKey_len;
+
+extern const uint8_t hal_asn1_oid_aesKeyWrap[];
+extern const size_t hal_asn1_oid_aesKeyWrap_len;
+
+/*
+ * Transcoding functions.
+ */
+
extern hal_error_t hal_asn1_encode_header(const uint8_t tag,
const size_t value_len,
uint8_t *der, size_t *der_len, const size_t der_max);
@@ -113,6 +130,27 @@ extern hal_error_t hal_asn1_decode_spki(const uint8_t **alg_oid, size_t *alg_o
const uint8_t **pubkey, size_t *pubkey_len,
const uint8_t *const der, const size_t der_len);
+extern hal_error_t hal_asn1_encode_pkcs8_privatekeyinfo(const uint8_t * const alg_oid, const size_t alg_oid_len,
+ const uint8_t * const curve_oid, const size_t curve_oid_len,
+ const uint8_t * const privkey, const size_t privkey_len,
+ uint8_t *der, size_t *der_len, const size_t der_max);
+
+extern hal_error_t hal_asn1_decode_pkcs8_privatekeyinfo(const uint8_t **alg_oid, size_t *alg_oid_len,
+ const uint8_t **curve_oid, size_t *curve_oid_len,
+ const uint8_t **privkey, size_t *privkey_len,
+ const uint8_t *const der, const size_t der_len);
+
+extern hal_error_t hal_asn1_encode_pkcs8_encryptedprivatekeyinfo(const uint8_t * const alg_oid, const size_t alg_oid_len,
+ const uint8_t * const data, const size_t data_len,
+ uint8_t *der, size_t *der_len, const size_t der_max);
+
+extern hal_error_t hal_asn1_decode_pkcs8_encryptedprivatekeyinfo(const uint8_t **alg_oid, size_t *alg_oid_len,
+ const uint8_t **data, size_t *data_len,
+ const uint8_t *const der, const size_t der_len);
+
+extern hal_error_t hal_asn1_guess_key_type(hal_key_type_t *type, hal_curve_name_t *curve,
+ const uint8_t *const der, const size_t der_len);
+
#endif /* _HAL_ASN1_INTERNAL_H_ */
/*
diff --git a/cryptech_backup b/cryptech_backup
new file mode 100755
index 0000000..7e465b8
--- /dev/null
+++ b/cryptech_backup
@@ -0,0 +1,224 @@
+#!/usr/bin/env python
+
+# KEY SOURCE KEY BACKUP
+#
+# Generate and export KEKEK:
+# hal_rpc_pkey_generate_rsa()
+# hal_rpc_pkey_get_public_key()
+#
+# Load KEKEK public <---------------- Export KEKEK public
+#
+# hal_rpc_pkey_load()
+# hal_rpc_pkey_export()
+#
+# Export PKCS #8 and KEK ----------> Load PKCS #8 and KEK, import key
+#
+# hal_rpc_pkey_import()
+
+import sys
+import json
+import uuid
+import atexit
+import getpass
+import argparse
+
+from libhal import *
+
+def main():
+
+ parser = argparse.ArgumentParser(
+ formatter_class = argparse.ArgumentDefaultsHelpFormatter,
+ description = __doc__)
+ subparsers = parser.add_subparsers(
+ title = "Commands (use \"--help\" after command name for help with individual commands)",
+ metavar = "")
+ parser.add_argument(
+ "-p", "--pin",
+ help = "wheel PIN")
+
+ subparser = defcmd(subparsers, cmd_setup)
+ group = subparser.add_mutually_exclusive_group()
+ group.add_argument(
+ "-n", "--new", action = "store_true",
+ help = "force creation of new KEKEK")
+ group.add_argument(
+ "-u", "--uuid",
+ help = "UUID of existing KEKEK to use")
+ subparser.add_argument(
+ "-k", "--keylen", type = int, default = 2048,
+ help = "length of new KEKEK if we need to create one")
+ subparser.add_argument(
+ "-o", "--output", type = argparse.FileType("w"), default = "-",
+ help = "output file")
+
+ subparser = defcmd(subparsers, cmd_export)
+ subparser.add_argument(
+ "-i", "--input", type = argparse.FileType("r"), default = "-",
+ help = "input file")
+ subparser.add_argument(
+ "-o", "--output", type = argparse.FileType("w"), default = "-",
+ help = "output file")
+
+ subparser = defcmd(subparsers, cmd_import)
+ subparser.add_argument(
+ "-i", "--input", type = argparse.FileType("r"), default = "-",
+ help = "input file")
+
+ args = parser.parse_args()
+
+ hsm = HSM()
+
+ try:
+ hsm.login(HAL_USER_WHEEL, args.pin or getpass.getpass("Wheel PIN: "))
+
+ except HALError as e:
+ sys.exit("Couldn't log into HSM: {}".format(e))
+
+ try:
+ sys.exit(args.func(args, hsm))
+
+ finally:
+ hsm.logout()
+
+
+def defcmd(subparsers, func):
+ assert func.__name__.startswith("cmd_")
+ subparser = subparsers.add_parser(func.__name__[4:],
+ description = func.__doc__,
+ help = func.__doc__.strip().splitlines()[0])
+ subparser.set_defaults(func = func)
+ return subparser
+
+
+def b64(bytes):
+ return bytes.encode("base64").splitlines()
+
+def b64join(lines):
+ return "".join(lines).decode("base64")
+
+
+def cmd_setup(args, hsm):
+ """
+ Set up backup HSM for subsequent import.
+ Generates an RSA keypair with appropriate usage settings
+ to use as a key-encryption-key-encryption-key (KEKEK), and
+ writes the KEKEK to a JSON file for transfer to primary HSM.
+ """
+
+ result = {}
+
+ uuids = []
+ if args.uuid:
+ uuids.append(args.uuid)
+ elif not args.new:
+ uuids.extend(hsm.pkey_match(
+ type = HAL_KEY_TYPE_RSA_PRIVATE,
+ mask = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT | HAL_KEY_FLAG_TOKEN,
+ flags = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT | HAL_KEY_FLAG_TOKEN))
+
+ for uuid in uuids:
+ with hsm.pkey_open(uuid) as kekek:
+ if kekek.key_type != HAL_KEY_TYPE_RSA_PRIVATE:
+ sys.stderr.write("Key {} is not an RSA private key\n".format(uuid))
+ elif (kekek.key_flags & HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT) == 0:
+ sys.stderr.write("Key {} does not allow key encipherment\n".format(uuid))
+ else:
+ result.update(kekek_uuid = str(kekek.uuid),
+ kekek_pubkey = b64(kekek.public_key))
+ break
+
+ if not result and not args.uuid:
+ with hsm.pkey_generate_rsa(
+ keylen = args.keylen,
+ flags = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT | HAL_KEY_FLAG_TOKEN) as kekek:
+ result.update(kekek_uuid = str(kekek.uuid),
+ kekek_pubkey = b64(kekek.public_key))
+ if not result:
+ sys.exit("Could not find suitable KEKEK")
+
+ result.update(comment = "KEKEK public key")
+ json.dump(result, args.output, indent = 4, sort_keys = True)
+
+
+def key_flag_names(flags):
+ names = dict(digitalsignature = HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE,
+ keyencipherment = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT,
+ dataencipherment = HAL_KEY_FLAG_USAGE_DATAENCIPHERMENT,
+ token = HAL_KEY_FLAG_TOKEN,
+ public = HAL_KEY_FLAG_PUBLIC,
+ exportable = HAL_KEY_FLAG_EXPORTABLE)
+ return ", ".join(sorted(k for k, v in names.iteritems() if (flags & v) != 0))
+
+
+def cmd_export(args, hsm):
+ """
+ Export encrypted keys from primary HSM.
+ Takes a JSON file containing KEKEK (generated by running this
+ script's "setup" command against the backup HSM), installs that
+ key on the primary HSM, and backs up keys encrypted to the KEKEK
+ by writing them to another JSON file for transfer to the backup HSM.
+ """
+
+ db = json.load(args.input)
+
+ result = []
+
+ kekek = None
+ try:
+ kekek = hsm.pkey_load(der = b64join(db["kekek_pubkey"]),
+ flags = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT)
+
+ for uuid in hsm.pkey_match(mask = HAL_KEY_FLAG_EXPORTABLE,
+ flags = HAL_KEY_FLAG_EXPORTABLE):
+ with hsm.pkey_open(uuid) as pkey:
+
+ if pkey.key_type in (HAL_KEY_TYPE_RSA_PRIVATE, HAL_KEY_TYPE_EC_PRIVATE):
+ pkcs8, kek = kekek.export_pkey(pkey)
+ result.append(dict(
+ comment = "Encrypted private key",
+ pkcs8 = b64(pkcs8),
+ kek = b64(kek),
+ uuid = str(pkey.uuid),
+ flags = pkey.key_flags))
+
+ elif pkey.key_type in (HAL_KEY_TYPE_RSA_PUBLIC, HAL_KEY_TYPE_EC_PUBLIC):
+ result.append(dict(
+ comment = "Public key",
+ spki = b64(pkey.public_key),
+ uuid = str(pkey.uuid),
+ flags = pkey.key_flags))
+
+ finally:
+ if kekek is not None:
+ kekek.delete()
+
+ db.update(comment = "Cryptech Alpha encrypted key backup",
+ keys = result)
+ json.dump(db, args.output, indent = 4, sort_keys = True)
+
+
+def cmd_import(args, hsm):
+ """
+ Import encrypted keys into backup HSM.
+ Takes a JSON file containing a key backup (generated by running
+ this script's "export" command against the primary HSM) and imports
+ keys into the backup HSM.
+ """
+
+ db = json.load(args.input)
+ with hsm.pkey_open(uuid.UUID(db["kekek_uuid"]).bytes) as kekek:
+ for k in db["keys"]:
+ pkcs8 = b64join(k.get("pkcs8", ""))
+ spki = b64join(k.get("spki", ""))
+ kek = b64join(k.get("kek", ""))
+ flags = k.get("flags", 0)
+ if pkcs8 and kek:
+ with kekek.import_pkey(pkcs8 = pkcs8, kek = kek, flags = flags) as pkey:
+ print "Imported {} as {}".format(k["uuid"], pkey.uuid)
+ elif spki:
+ with hsm.pkey_load(der = spki, flags = flags) as pkey:
+ print "Loaded {} as {}".format(k["uuid"], pkey.uuid)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/ecdsa.c b/ecdsa.c
index d654a78..27c4c2e 100644
--- a/ecdsa.c
+++ b/ecdsa.c
@@ -258,20 +258,21 @@ static const ecdsa_curve_t * const get_curve(const hal_curve_name_t curve)
}
}
-static inline const ecdsa_curve_t * oid_to_curve(hal_curve_name_t *curve_name,
- const uint8_t * const oid,
- const size_t oid_len)
+hal_error_t hal_ecdsa_oid_to_curve(hal_curve_name_t *curve_name,
+ const uint8_t * const oid,
+ const size_t oid_len)
{
- assert(curve_name != NULL && oid != NULL);
+ if (curve_name == NULL || oid == NULL)
+ return HAL_ERROR_BAD_ARGUMENTS;
- const ecdsa_curve_t *curve = NULL;
*curve_name = HAL_CURVE_NONE;
+ const ecdsa_curve_t *curve;
while ((curve = get_curve(++*curve_name)) != NULL)
if (oid_len == curve->oid_len && memcmp(oid, curve->oid, oid_len) == 0)
- return curve;
+ return HAL_OK;
- return NULL;
+ return HAL_ERROR_UNSUPPORTED_KEY;
}
/*
@@ -833,44 +834,6 @@ static hal_error_t verilog_point_pick_random(const verilog_ecdsa_driver_t * cons
#endif
-static inline hal_error_t verilog_p256_point_pick_random(fp_int *k, ec_point_t *P)
-{
-#if HAL_ECDSA_VERILOG_ECDSA256_MULTIPLIER
-
- static const verilog_ecdsa_driver_t p256_driver = {
- .name = ECDSA256_NAME,
- .bytes = ECDSA256_OPERAND_BITS / 8,
- .k_addr = ECDSA256_ADDR_K,
- .x_addr = ECDSA256_ADDR_X,
- .y_addr = ECDSA256_ADDR_Y
- };
-
- return verilog_point_pick_random(&p256_driver, k, P);
-
-#endif
-
- return HAL_ERROR_CORE_NOT_FOUND;
-}
-
-static inline hal_error_t verilog_p384_point_pick_random(fp_int *k, ec_point_t *P)
-{
-#if HAL_ECDSA_VERILOG_ECDSA384_MULTIPLIER
-
- static const verilog_ecdsa_driver_t p384_driver = {
- .name = ECDSA384_NAME,
- .bytes = ECDSA384_OPERAND_BITS / 8,
- .k_addr = ECDSA384_ADDR_K,
- .x_addr = ECDSA384_ADDR_X,
- .y_addr = ECDSA384_ADDR_Y
- };
-
- return verilog_point_pick_random(&p384_driver, k, P);
-
-#endif
-
- return HAL_ERROR_CORE_NOT_FOUND;
-}
-
/*
* Pick a random point on the curve, return random scalar and
* resulting point.
@@ -915,23 +878,39 @@ static hal_error_t point_pick_random(const ecdsa_curve_t * const curve,
memset(k_buf, 0, sizeof(k_buf));
-#if HAL_ECDSA_VERILOG_ECDSA256_MULTIPLIER || HAL_ECDSA_VERILOG_ECDSA384_MULTIPLIER
switch (curve->curve) {
- case HAL_CURVE_P256:
- if ((err = verilog_p256_point_pick_random(k, P)) != HAL_ERROR_CORE_NOT_FOUND)
+#if HAL_ECDSA_VERILOG_ECDSA256_MULTIPLIER
+ case HAL_CURVE_P256:;
+ static const verilog_ecdsa_driver_t p256_driver = {
+ .name = ECDSA256_NAME,
+ .bytes = ECDSA256_OPERAND_BITS / 8,
+ .k_addr = ECDSA256_ADDR_K,
+ .x_addr = ECDSA256_ADDR_X,
+ .y_addr = ECDSA256_ADDR_Y
+ };
+ if ((err = verilog_point_pick_random(&p256_driver, k, P)) != HAL_ERROR_CORE_NOT_FOUND)
return err;
- break;
+ break;
+#endif
- case HAL_CURVE_P384:
- if ((err = verilog_p384_point_pick_random(k, P)) != HAL_ERROR_CORE_NOT_FOUND)
+#if HAL_ECDSA_VERILOG_ECDSA384_MULTIPLIER
+ case HAL_CURVE_P384:;
+ static const verilog_ecdsa_driver_t p384_driver = {
+ .name = ECDSA384_NAME,
+ .bytes = ECDSA384_OPERAND_BITS / 8,
+ .k_addr = ECDSA384_ADDR_K,
+ .x_addr = ECDSA384_ADDR_X,
+ .y_addr = ECDSA384_ADDR_Y
+ };
+ if ((err = verilog_point_pick_random(&p384_driver, k, P)) != HAL_ERROR_CORE_NOT_FOUND)
return err;
- break;
+ break;
+#endif
default:
break;
}
-#endif
/*
* Calculate P = kG and return.
@@ -1287,7 +1266,11 @@ hal_error_t hal_ecdsa_key_from_ecpoint(hal_ecdsa_key_t **key_,
}
/*
- * Write private key in RFC 5915 ASN.1 DER format.
+ * Write private key in PKCS #8 PrivateKeyInfo DER format (RFC 5208).
+ * This is basically just the PKCS #8 wrapper around the ECPrivateKey
+ * format from RFC 5915, except that the OID naming the curve is in
+ * the privateKeyAlgorithm.parameters field in the PKCS #8 wrapper and
+ * is therefore omitted from the ECPrivateKey.
*
* This is hand-coded, and is approaching the limit where one should
* probably be using an ASN.1 compiler like asn1c instead.
@@ -1314,27 +1297,29 @@ hal_error_t hal_ecdsa_private_key_to_der(const hal_ecdsa_key_t * const key,
hal_error_t err;
- size_t version_len, hlen, hlen_oct, hlen_oid, hlen_exp0, hlen_bit, hlen_exp1;
+ size_t version_len, hlen, hlen_oct, hlen_bit, hlen_exp1;
if ((err = hal_asn1_encode_integer(version, NULL, &version_len, 0)) != HAL_OK ||
(err = hal_asn1_encode_header(ASN1_OCTET_STRING, q_len, NULL, &hlen_oct, 0)) != HAL_OK ||
- (err = hal_asn1_encode_header(ASN1_OBJECT_IDENTIFIER, curve->oid_len, NULL, &hlen_oid, 0)) != HAL_OK ||
- (err = hal_asn1_encode_header(ASN1_EXPLICIT_0, hlen_oid + curve->oid_len, NULL, &hlen_exp0, 0)) != HAL_OK ||
(err = hal_asn1_encode_header(ASN1_BIT_STRING, (q_len + 1) * 2, NULL, &hlen_bit, 0)) != HAL_OK ||
(err = hal_asn1_encode_header(ASN1_EXPLICIT_1, hlen_bit + (q_len + 1) * 2, NULL, &hlen_exp1, 0)) != HAL_OK)
return err;
- const size_t vlen = (version_len +
- hlen_oct + q_len +
- hlen_oid + hlen_exp0 + curve->oid_len +
- hlen_bit + hlen_exp1 + (q_len + 1) * 2);
+ const size_t vlen = version_len + hlen_oct + q_len + hlen_exp1 + hlen_bit + (q_len + 1) * 2;
- err = hal_asn1_encode_header(ASN1_SEQUENCE, vlen, der, &hlen, der_max);
+ if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, vlen, NULL, &hlen, 0)) != HAL_OK)
+ return err;
- if (der_len != NULL)
- *der_len = hlen + vlen;
+ if ((err = hal_asn1_encode_pkcs8_privatekeyinfo(hal_asn1_oid_ecPublicKey, hal_asn1_oid_ecPublicKey_len,
+ curve->oid, curve->oid_len,
+ NULL, hlen + vlen,
+ NULL, der_len, der_max)) != HAL_OK)
+ return err;
- if (der == NULL || err != HAL_OK)
+ if (der == NULL)
+ return HAL_OK;
+
+ if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, vlen, der, &hlen, der_max)) != HAL_OK)
return err;
uint8_t *d = der + hlen;
@@ -1350,15 +1335,6 @@ hal_error_t hal_ecdsa_private_key_to_der(const hal_ecdsa_key_t * const key,
fp_to_unsigned_bin(unconst_fp_int(key->d), d + q_len - d_len);
d += q_len;
- if ((err = hal_asn1_encode_header(ASN1_EXPLICIT_0, hlen_oid + curve->oid_len, d, &hlen, der + der_max - d)) != HAL_OK)
- return err;
- d += hlen;
- if ((err = hal_asn1_encode_header(ASN1_OBJECT_IDENTIFIER, curve->oid_len, d, &hlen, der + der_max - d)) != HAL_OK)
- return err;
- d += hlen;
- memcpy(d, curve->oid, curve->oid_len);
- d += curve->oid_len;
-
if ((err = hal_asn1_encode_header(ASN1_EXPLICIT_1, hlen_bit + (q_len + 1) * 2, d, &hlen, der + der_max - d)) != HAL_OK)
return err;
d += hlen;
@@ -1372,9 +1348,10 @@ hal_error_t hal_ecdsa_private_key_to_der(const hal_ecdsa_key_t * const key,
fp_to_unsigned_bin(unconst_fp_int(key->Q->y), d + q_len - Qy_len);
d += q_len;
- assert(d <= der + der_max);
-
- return HAL_OK;
+ return hal_asn1_encode_pkcs8_privatekeyinfo(hal_asn1_oid_ecPublicKey, hal_asn1_oid_ecPublicKey_len,
+ curve->oid, curve->oid_len,
+ der, d - der,
+ der, der_len, der_max);
}
/*
@@ -1389,7 +1366,7 @@ size_t hal_ecdsa_private_key_to_der_len(const hal_ecdsa_key_t * const key)
}
/*
- * Read private key in RFC 5915 ASN.1 DER format.
+ * Read private key in PKCS #8 PrivateKeyInfo DER format (RFC 5208, RFC 5915).
*
* This is hand-coded, and is approaching the limit where one should
* probably be using an ASN.1 compiler like asn1c instead.
@@ -1407,48 +1384,47 @@ hal_error_t hal_ecdsa_private_key_from_der(hal_ecdsa_key_t **key_,
memset(keybuf, 0, keybuf_len);
key->type = HAL_KEY_TYPE_EC_PRIVATE;
- size_t hlen, vlen;
+ size_t hlen, vlen, alg_oid_len, curve_oid_len, privkey_len;
+ const uint8_t *alg_oid, *curve_oid, *privkey;
hal_error_t err;
- if ((err = hal_asn1_decode_header(ASN1_SEQUENCE, der, der_len, &hlen, &vlen)) != HAL_OK)
+ if ((err = hal_asn1_decode_pkcs8_privatekeyinfo(&alg_oid, &alg_oid_len,
+ &curve_oid, &curve_oid_len,
+ &privkey, &privkey_len,
+ der, der_len)) != HAL_OK)
return err;
- const uint8_t * const der_end = der + hlen + vlen;
- const uint8_t *d = der + hlen;
- const ecdsa_curve_t *curve = NULL;
+ if (alg_oid_len != hal_asn1_oid_ecPublicKey_len ||
+ memcmp(alg_oid, hal_asn1_oid_ecPublicKey, alg_oid_len) != 0 ||
+ hal_ecdsa_oid_to_curve(&key->curve, curve_oid, curve_oid_len) != HAL_OK)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+
+ if ((err = hal_asn1_decode_header(ASN1_SEQUENCE, privkey, privkey_len, &hlen, &vlen)) != HAL_OK)
+ return err;
+
+ const uint8_t * const der_end = privkey + hlen + vlen;
+ const uint8_t *d = privkey + hlen;
fp_int version[1] = INIT_FP_INT;
if ((err = hal_asn1_decode_integer(version, d, &hlen, vlen)) != HAL_OK)
- goto fail;
+ return err;
if (fp_cmp_d(version, 1) != FP_EQ)
- lose(HAL_ERROR_ASN1_PARSE_FAILED);
+ return HAL_ERROR_ASN1_PARSE_FAILED;
d += hlen;
if ((err = hal_asn1_decode_header(ASN1_OCTET_STRING, d, der_end - d, &hlen, &vlen)) != HAL_OK)
- return err;
+ goto fail;
d += hlen;
fp_read_unsigned_bin(key->d, unconst_uint8_t(d), vlen);
d += vlen;
- if ((err = hal_asn1_decode_header(ASN1_EXPLICIT_0, d, der_end - d, &hlen, &vlen)) != HAL_OK)
- return err;
- d += hlen;
- if (vlen > der_end - d)
- lose(HAL_ERROR_ASN1_PARSE_FAILED);
- if ((err = hal_asn1_decode_header(ASN1_OBJECT_IDENTIFIER, d, vlen, &hlen, &vlen)) != HAL_OK)
- return err;
- d += hlen;
- if ((curve = oid_to_curve(&key->curve, d, vlen)) == NULL)
- lose(HAL_ERROR_ASN1_PARSE_FAILED);
- d += vlen;
-
if ((err = hal_asn1_decode_header(ASN1_EXPLICIT_1, d, der_end - d, &hlen, &vlen)) != HAL_OK)
- return err;
+ goto fail;
d += hlen;
if (vlen > der_end - d)
lose(HAL_ERROR_ASN1_PARSE_FAILED);
if ((err = hal_asn1_decode_header(ASN1_BIT_STRING, d, vlen, &hlen, &vlen)) != HAL_OK)
- return err;
+ goto fail;
d += hlen;
if (vlen < 4 || (vlen & 1) != 0 || *d++ != 0x00 || *d++ != 0x04)
lose(HAL_ERROR_ASN1_PARSE_FAILED);
@@ -1474,8 +1450,6 @@ hal_error_t hal_ecdsa_private_key_from_der(hal_ecdsa_key_t **key_,
* Write public key in SubjectPublicKeyInfo format, see RFCS 5280 and 5480.
*/
-static const uint8_t oid_ecPublicKey[] = { 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01 };
-
hal_error_t hal_ecdsa_public_key_to_der(const hal_ecdsa_key_t * const key,
uint8_t *der, size_t *der_len, const size_t der_max)
{
@@ -1508,7 +1482,7 @@ hal_error_t hal_ecdsa_public_key_to_der(const hal_ecdsa_key_t * const key,
assert(d < der + der_max);
}
- return hal_asn1_encode_spki(oid_ecPublicKey, sizeof(oid_ecPublicKey),
+ return hal_asn1_encode_spki(hal_asn1_oid_ecPublicKey, hal_asn1_oid_ecPublicKey_len,
curve->oid, curve->oid_len,
der, ecpoint_len,
der, der_len, der_max);
@@ -1543,18 +1517,19 @@ hal_error_t hal_ecdsa_public_key_from_der(hal_ecdsa_key_t **key_,
const uint8_t *alg_oid = NULL, *curve_oid = NULL, *pubkey = NULL;
size_t alg_oid_len, curve_oid_len, pubkey_len;
- const ecdsa_curve_t *curve;
hal_error_t err;
- if ((err = hal_asn1_decode_spki(&alg_oid, &alg_oid_len, &curve_oid, &curve_oid_len, &pubkey, &pubkey_len,
+ if ((err = hal_asn1_decode_spki(&alg_oid, &alg_oid_len, &curve_oid, &curve_oid_len,
+ &pubkey, &pubkey_len,
der, der_len)) != HAL_OK)
return err;
if (alg_oid == NULL || curve_oid == NULL || pubkey == NULL ||
- alg_oid_len != sizeof(oid_ecPublicKey) || memcmp(alg_oid, oid_ecPublicKey, alg_oid_len) != 0 ||
- (curve = oid_to_curve(&key->curve, curve_oid, curve_oid_len)) == NULL ||
+ alg_oid_len != hal_asn1_oid_ecPublicKey_len ||
+ memcmp(alg_oid, hal_asn1_oid_ecPublicKey, alg_oid_len) != 0 ||
+ hal_ecdsa_oid_to_curve(&key->curve, curve_oid, curve_oid_len) != HAL_OK ||
pubkey_len < 3 || (pubkey_len & 1) == 0 || pubkey[0] != 0x04 ||
- pubkey_len / 2 != fp_unsigned_bin_size(unconst_fp_int(curve->q)))
+ pubkey_len / 2 != fp_unsigned_bin_size(unconst_fp_int(get_curve(key->curve)->q)))
return HAL_ERROR_ASN1_PARSE_FAILED;
const uint8_t * const Qx = pubkey + 1;
diff --git a/hal.h b/hal.h
index 29b4dab..bfb727a 100644
--- a/hal.h
+++ b/hal.h
@@ -358,7 +358,7 @@ extern hal_error_t hal_aes_keywrap(hal_core_t *core,
extern hal_error_t hal_aes_keyunwrap(hal_core_t *core,
const uint8_t *kek, const size_t kek_length,
const uint8_t *ciphertext, const size_t ciphertext_length,
- unsigned char *plaintext, size_t *plaintext_length);
+ uint8_t *plaintext, size_t *plaintext_length);
extern size_t hal_aes_keywrap_ciphertext_length(const size_t plaintext_length);
@@ -505,6 +505,10 @@ extern const size_t hal_ecdsa_key_t_size;
extern void hal_ecdsa_set_debug(const int onoff);
+extern hal_error_t hal_ecdsa_oid_to_curve(hal_curve_name_t *curve,
+ const uint8_t * const oid,
+ const size_t oid_len);
+
extern hal_error_t hal_ecdsa_key_load_private(hal_ecdsa_key_t **key,
void *keybuf, const size_t keybuf_len,
const hal_curve_name_t curve,
@@ -725,6 +729,7 @@ typedef uint32_t hal_key_flags_t;
#define HAL_KEY_FLAG_USAGE_DATAENCIPHERMENT (1 << 2)
#define HAL_KEY_FLAG_TOKEN (1 << 3)
#define HAL_KEY_FLAG_PUBLIC (1 << 4)
+#define HAL_KEY_FLAG_EXPORTABLE (1 << 5)
/*
* hal_pkey_attribute_t.length would be size_t, except that we also
@@ -744,8 +749,6 @@ typedef struct {
extern hal_error_t hal_rpc_pkey_load(const hal_client_handle_t client,
const hal_session_handle_t session,
hal_pkey_handle_t *pkey,
- const hal_key_type_t type,
- const hal_curve_name_t curve,
hal_uuid_t *name,
const uint8_t * const der, const size_t der_len,
const hal_key_flags_t flags);
@@ -753,8 +756,7 @@ extern hal_error_t hal_rpc_pkey_load(const hal_client_handle_t client,
extern hal_error_t hal_rpc_pkey_open(const hal_client_handle_t client,
const hal_session_handle_t session,
hal_pkey_handle_t *pkey,
- const hal_uuid_t * const name,
- const hal_key_flags_t flags);
+ const hal_uuid_t * const name);
extern hal_error_t hal_rpc_pkey_generate_rsa(const hal_client_handle_t client,
const hal_session_handle_t session,
@@ -803,9 +805,11 @@ extern hal_error_t hal_rpc_pkey_match(const hal_client_handle_t client,
const hal_session_handle_t session,
const hal_key_type_t type,
const hal_curve_name_t curve,
+ const hal_key_flags_t mask,
const hal_key_flags_t flags,
const hal_pkey_attribute_t *attributes,
const unsigned attributes_len,
+ unsigned *state,
hal_uuid_t *result,
unsigned *result_len,
const unsigned result_max,
@@ -821,6 +825,20 @@ extern hal_error_t hal_rpc_pkey_get_attributes(const hal_pkey_handle_t pkey,
uint8_t *attributes_buffer,
const size_t attributes_buffer_len);
+extern hal_error_t hal_rpc_pkey_export(const hal_pkey_handle_t pkey,
+ const hal_pkey_handle_t kekek,
+ uint8_t *pkcs8, size_t *pkcs8_len, const size_t pkcs8_max,
+ uint8_t *kek, size_t *kek_len, const size_t kek_max);
+
+extern hal_error_t hal_rpc_pkey_import(const hal_client_handle_t client,
+ const hal_session_handle_t session,
+ hal_pkey_handle_t *pkey,
+ hal_uuid_t *name,
+ const hal_pkey_handle_t kekek,
+ const uint8_t * const pkcs8, const size_t pkcs8_len,
+ const uint8_t * const kek, const size_t kek_len,
+ const hal_key_flags_t flags);
+
extern hal_error_t hal_rpc_client_init(void);
extern hal_error_t hal_rpc_client_close(void);
diff --git a/hal_internal.h b/hal_internal.h
index 40a600c..1822781 100644
--- a/hal_internal.h
+++ b/hal_internal.h
@@ -192,8 +192,6 @@ typedef struct {
hal_error_t (*load)(const hal_client_handle_t client,
const hal_session_handle_t session,
hal_pkey_handle_t *pkey,
- const hal_key_type_t type,
- const hal_curve_name_t curve,
hal_uuid_t *name,
const uint8_t * const der, const size_t der_len,
const hal_key_flags_t flags);
@@ -201,8 +199,7 @@ typedef struct {
hal_error_t (*open)(const hal_client_handle_t client,
const hal_session_handle_t session,
hal_pkey_handle_t *pkey,
- const hal_uuid_t * const name,
- const hal_key_flags_t flags);
+ const hal_uuid_t * const name);
hal_error_t (*generate_rsa)(const hal_client_handle_t client,
const hal_session_handle_t session,
@@ -251,9 +248,11 @@ typedef struct {
const hal_session_handle_t session,
const hal_key_type_t type,
const hal_curve_name_t curve,
+ const hal_key_flags_t mask,
const hal_key_flags_t flags,
const hal_pkey_attribute_t *attributes,
const unsigned attributes_len,
+ unsigned *state,
hal_uuid_t *result,
unsigned *result_len,
const unsigned result_max,
@@ -269,6 +268,20 @@ typedef struct {
uint8_t *attributes_buffer,
const size_t attributes_buffer_len);
+ hal_error_t (*export)(const hal_pkey_handle_t pkey_handle,
+ const hal_pkey_handle_t kekek_handle,
+ uint8_t *pkcs8, size_t *pkcs8_len, const size_t pkcs8_max,
+ uint8_t *kek, size_t *kek_len, const size_t kek_max);
+
+ hal_error_t (*import)(const hal_client_handle_t client,
+ const hal_session_handle_t session,
+ hal_pkey_handle_t *pkey,
+ hal_uuid_t *name,
+ const hal_pkey_handle_t kekek_handle,
+ const uint8_t * const pkcs8, const size_t pkcs8_len,
+ const uint8_t * const kek, const size_t kek_len,
+ const hal_key_flags_t flags);
+
} hal_rpc_pkey_dispatch_t;
@@ -317,15 +330,16 @@ static inline hal_crc32_t hal_crc32_finalize(hal_crc32_t crc)
}
/*
- * Sizes for ASN.1-encoded keys, this may not be exact due to ASN.1
- * INTEGER encoding rules but should be good enough for buffer sizing:
+ * Sizes for PKCS #8 encoded private keys. This may not be exact due
+ * to ASN.1 INTEGER encoding rules, but should be good enough for
+ * buffer sizing.
*
- * 2048-bit RSA: 1194 bytes
- * 4096-bit RSA: 2351 bytes
- * 8192-bit RSA: 4655 bytes
- * EC P-256: 121 bytes
- * EC P-384: 167 bytes
- * EC P-521: 223 bytes
+ * 2048-bit RSA: 1219 bytes
+ * 4096-bit RSA: 2373 bytes
+ * 8192-bit RSA: 4679 bytes
+ * EC P-256: 138 bytes
+ * EC P-384: 185 bytes
+ * EC P-521: 240 bytes
*
* Plus we need a bit of AES-keywrap overhead, since we're storing the
* wrapped form (see hal_aes_keywrap_cyphertext_length()).
@@ -338,7 +352,7 @@ static inline hal_crc32_t hal_crc32_finalize(hal_crc32_t crc)
* moment we take the easy way out and cap this at 4096-bit RSA.
*/
-#define HAL_KS_WRAPPED_KEYSIZE ((2351 + 15) & ~7)
+#define HAL_KS_WRAPPED_KEYSIZE ((2373 + 15) & ~7)
/*
* PINs.
@@ -458,11 +472,11 @@ struct hal_ks_driver {
hal_error_t (*store)(hal_ks_t *ks,
hal_pkey_slot_t *slot,
- const uint8_t * const der, const size_t der_len);
+ const uint8_t * const der, const size_t der_len);
hal_error_t (*fetch)(hal_ks_t *ks,
hal_pkey_slot_t *slot,
- uint8_t *der, size_t *der_len, const size_t der_max);
+ uint8_t *der, size_t *der_len, const size_t der_max);
hal_error_t (*delete)(hal_ks_t *ks,
hal_pkey_slot_t *slot);
@@ -472,6 +486,7 @@ struct hal_ks_driver {
const hal_session_handle_t session,
const hal_key_type_t type,
const hal_curve_name_t curve,
+ const hal_key_flags_t mask,
const hal_key_flags_t flags,
const hal_pkey_attribute_t *attributes,
const unsigned attributes_len,
@@ -536,7 +551,7 @@ static inline hal_error_t hal_ks_shutdown(const hal_ks_driver_t * const driver)
}
static inline hal_error_t hal_ks_open(const hal_ks_driver_t * const driver,
- hal_ks_t **ks)
+ hal_ks_t **ks)
{
if (driver == NULL || ks == NULL)
return HAL_ERROR_BAD_ARGUMENTS;
@@ -601,6 +616,7 @@ static inline hal_error_t hal_ks_match(hal_ks_t *ks,
const hal_session_handle_t session,
const hal_key_type_t type,
const hal_curve_name_t curve,
+ const hal_key_flags_t mask,
const hal_key_flags_t flags,
const hal_pkey_attribute_t *attributes,
const unsigned attributes_len,
@@ -615,7 +631,7 @@ static inline hal_error_t hal_ks_match(hal_ks_t *ks,
if (ks->driver->match == NULL)
return HAL_ERROR_NOT_IMPLEMENTED;
- return ks->driver->match(ks, client, session, type, curve, flags, attributes, attributes_len,
+ return ks->driver->match(ks, client, session, type, curve, mask, flags, attributes, attributes_len,
result, result_len, result_max, previous_uuid);
}
@@ -862,6 +878,8 @@ typedef enum {
RPC_FUNC_PKEY_GET_KEY_CURVE,
RPC_FUNC_PKEY_SET_ATTRIBUTES,
RPC_FUNC_PKEY_GET_ATTRIBUTES,
+ RPC_FUNC_PKEY_EXPORT,
+ RPC_FUNC_PKEY_IMPORT,
} rpc_func_num_t;
#define RPC_VERSION 0x01010000 /* 1.1.0.0 */
@@ -897,7 +915,7 @@ typedef enum {
*/
#ifndef HAL_CLIENT_SERIAL_DEFAULT_DEVICE
-#define HAL_CLIENT_SERIAL_DEFAULT_DEVICE "/dev/ttyUSB0"
+#define HAL_CLIENT_SERIAL_DEFAULT_DEVICE "/dev/ttyUSB0"
#endif
#ifndef HAL_CLIENT_SERIAL_DEFAULT_SPEED
@@ -908,8 +926,8 @@ typedef enum {
* Names of environment variables for setting the above in RPC clients.
*/
-#define HAL_CLIENT_SERIAL_DEVICE_ENVVAR "CRYPTECH_RPC_CLIENT_SERIAL_DEVICE"
-#define HAL_CLIENT_SERIAL_SPEED_ENVVAR "CRYPTECH_RPC_CLIENT_SERIAL_SPEED"
+#define HAL_CLIENT_SERIAL_DEVICE_ENVVAR "CRYPTECH_RPC_CLIENT_SERIAL_DEVICE"
+#define HAL_CLIENT_SERIAL_SPEED_ENVVAR "CRYPTECH_RPC_CLIENT_SERIAL_SPEED"
#endif /* _HAL_INTERNAL_H_ */
diff --git a/ks_flash.c b/ks_flash.c
index 7a87d5c..b14e568 100644
--- a/ks_flash.c
+++ b/ks_flash.c
@@ -1239,6 +1239,7 @@ static hal_error_t ks_match(hal_ks_t *ks,
const hal_session_handle_t session,
const hal_key_type_t type,
const hal_curve_name_t curve,
+ const hal_key_flags_t mask,
const hal_key_flags_t flags,
const hal_pkey_attribute_t *attributes,
const unsigned attributes_len,
@@ -1284,7 +1285,8 @@ static hal_error_t ks_match(hal_ks_t *ks,
if (db.ksi.names[b].chunk == 0) {
memset(need_attr, 1, sizeof(need_attr));
possible = ((type == HAL_KEY_TYPE_NONE || type == block->key.type) &&
- (curve == HAL_CURVE_NONE || curve == block->key.curve));
+ (curve == HAL_CURVE_NONE || curve == block->key.curve) &&
+ ((flags ^ block->key.flags) & mask) == 0);
}
if (!possible)
diff --git a/ks_volatile.c b/ks_volatile.c
index 9762da3..6d65578 100644
--- a/ks_volatile.c
+++ b/ks_volatile.c
@@ -124,7 +124,10 @@ static inline int key_visible_to_session(const ks_t * const ksv,
const hal_session_handle_t session,
const ks_key_t * const k)
{
- return !ksv->per_session || client.handle == HAL_HANDLE_NONE || k->client.handle == client.handle;
+ return (!ksv->per_session ||
+ client.handle == HAL_HANDLE_NONE ||
+ k->client.handle == client.handle ||
+ hal_rpc_is_logged_in(client, HAL_USER_WHEEL) == HAL_OK);
}
static inline void *gnaw(uint8_t **mem, size_t *len, const size_t size)
@@ -385,6 +388,7 @@ static hal_error_t ks_match(hal_ks_t *ks,
hal_session_handle_t session,
const hal_key_type_t type,
const hal_curve_name_t curve,
+ const hal_key_flags_t mask,
const hal_key_flags_t flags,
const hal_pkey_attribute_t *attributes,
const unsigned attributes_len,
@@ -429,6 +433,9 @@ static hal_error_t ks_match(hal_ks_t *ks,
if (curve != HAL_CURVE_NONE && curve != ksv->db->keys[b].curve)
continue;
+ if (((flags ^ ksv->db->keys[b].flags) & mask) != 0)
+ continue;
+
if (!key_visible_to_session(ksv, client, session, &ksv->db->keys[b]))
continue;
diff --git a/libhal.py b/libhal.py
index 510827c..0c6b3f6 100644
--- a/libhal.py
+++ b/libhal.py
@@ -192,6 +192,8 @@ RPCFunc.define('''
RPC_FUNC_PKEY_GET_KEY_CURVE,
RPC_FUNC_PKEY_SET_ATTRIBUTES,
RPC_FUNC_PKEY_GET_ATTRIBUTES,
+ RPC_FUNC_PKEY_EXPORT,
+ RPC_FUNC_PKEY_IMPORT,
''')
class HALDigestAlgorithm(Enum): pass
@@ -240,6 +242,7 @@ HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT = (1 << 1)
HAL_KEY_FLAG_USAGE_DATAENCIPHERMENT = (1 << 2)
HAL_KEY_FLAG_TOKEN = (1 << 3)
HAL_KEY_FLAG_PUBLIC = (1 << 4)
+HAL_KEY_FLAG_EXPORTABLE = (1 << 5)
HAL_PKEY_ATTRIBUTE_NIL = (0xFFFFFFFF)
@@ -402,6 +405,11 @@ class PKey(Handle):
result.update(self.hsm.pkey_get_attributes(self, attrs.iterkeys(), sum(attrs.itervalues())))
return result
+ def export_pkey(self, pkey):
+ return self.hsm.pkey_export(pkey = pkey, kekek = self, pkcs8_max = 2560, kek_max = 512)
+
+ def import_pkey(self, pkcs8, kek, flags = 0):
+ return self.hsm.pkey_import(kekek = self, pkcs8 = pkcs8, kek = kek, flags = flags)
class HSM(object):
@@ -412,7 +420,8 @@ class HSM(object):
if status != 0:
raise HALError.table[status]()
- def __init__(self, sockname = os.getenv("CRYPTECH_RPC_CLIENT_SOCKET_NAME", "/tmp/.cryptech_muxd.rpc")):
+ def __init__(self, sockname = os.getenv("CRYPTECH_RPC_CLIENT_SOCKET_NAME",
+ "/tmp/.cryptech_muxd.rpc")):
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.socket.connect(sockname)
self.sockfile = self.socket.makefile("rb")
@@ -547,19 +556,19 @@ class HSM(object):
with self.rpc(RPC_FUNC_HASH_FINALIZE, handle, length) as r:
return r.unpack_bytes()
- def pkey_load(self, type, curve, der, flags = 0, client = 0, session = 0):
- with self.rpc(RPC_FUNC_PKEY_LOAD, session, type, curve, der, flags, client = client) as r:
+ def pkey_load(self, der, flags = 0, client = 0, session = 0):
+ with self.rpc(RPC_FUNC_PKEY_LOAD, session, der, flags, client = client) as r:
pkey = PKey(self, r.unpack_uint(), UUID(bytes = r.unpack_bytes()))
logger.debug("Loaded pkey %s", pkey.uuid)
return pkey
- def pkey_open(self, uuid, flags = 0, client = 0, session = 0):
- with self.rpc(RPC_FUNC_PKEY_OPEN, session, uuid, flags, client = client) as r:
+ def pkey_open(self, uuid, client = 0, session = 0):
+ with self.rpc(RPC_FUNC_PKEY_OPEN, session, uuid, client = client) as r:
pkey = PKey(self, r.unpack_uint(), uuid)
logger.debug("Opened pkey %s", pkey.uuid)
return pkey
- def pkey_generate_rsa(self, keylen, exponent = "\x01\x00\x01", flags = 0, client = 0, session = 0):
+ def pkey_generate_rsa(self, keylen, flags = 0, exponent = "\x01\x00\x01", client = 0, session = 0):
with self.rpc(RPC_FUNC_PKEY_GENERATE_RSA, session, keylen, exponent, flags, client = client) as r:
pkey = PKey(self, r.unpack_uint(), UUID(bytes = r.unpack_bytes()))
logger.debug("Generated RSA pkey %s", pkey.uuid)
@@ -623,13 +632,15 @@ class HSM(object):
with self.rpc(RPC_FUNC_PKEY_VERIFY, pkey, hash, data, signature):
return
- def pkey_match(self, type = 0, curve = 0, flags = 0, attributes = {},
- length = 64, client = 0, session = 0):
+ def pkey_match(self, type = 0, curve = 0, mask = 0, flags = 0,
+ attributes = {}, length = 64, client = 0, session = 0):
u = UUID(int = 0)
n = length
+ s = 0
while n == length:
- with self.rpc(RPC_FUNC_PKEY_MATCH, session, type, curve, flags,
- attributes, length, u, client = client) as r:
+ with self.rpc(RPC_FUNC_PKEY_MATCH, session, type, curve, mask, flags,
+ attributes, s, length, u, client = client) as r:
+ s = r.unpack_uint()
n = r.unpack_uint()
for i in xrange(n):
u = UUID(bytes = r.unpack_bytes())
@@ -649,3 +660,15 @@ class HSM(object):
return dict((r.unpack_uint(), r.unpack_bytes()) for i in xrange(n))
else:
return dict((r.unpack_uint(), r.unpack_uint()) for i in xrange(n))
+
+ def pkey_export(self, pkey, kekek, pkcs8_max = 2560, kek_max = 512):
+ with self.rpc(RPC_FUNC_PKEY_EXPORT, pkey, kekek, pkcs8_max, kek_max) as r:
+ pkcs8, kek = r.unpack_bytes(), r.unpack_bytes()
+ logger.debug("Exported pkey %s", pkey.uuid)
+ return pkcs8, kek
+
+ def pkey_import(self, kekek, pkcs8, kek, flags = 0, client = 0, session = 0):
+ with self.rpc(RPC_FUNC_PKEY_IMPORT, session, kekek, pkcs8, kek, flags, client = client) as r:
+ pkey = PKey(self, r.unpack_uint(), UUID(bytes = r.unpack_bytes()))
+ logger.debug("Imported pkey %s", pkey.uuid)
+ return pkey
diff --git a/pkcs8.py b/pkcs8.py
new file mode 100644
index 0000000..cd45ff6
--- /dev/null
+++ b/pkcs8.py
@@ -0,0 +1,324 @@
+# Temporary sandbox for Python PKCS #8 hacks, probably integrate into
+# test scripts, libhal.py, etc once have figured this out.
+#
+# Both PyCrpto and the Python ecdsa package have their own ASN.1, so
+# why are we using yet another package? Because it's easier to
+# understand, that's why. Perhaps once we've debugged this we'll
+# recode it using one of the other packages to reduce external
+# dependencies, but for now, pyasn1 wins on ease of debugging.
+#
+# Also see the "native" encode and decode routines in pyasn1, which
+# supposedly encode and decode to built-in Python data types instead
+# of the fancy types from the pyasn1 library. Might be simpler, but
+# whole new mess so defer for now.
+
+# RFC 5208: PKCS #8
+# RFC 2313: PKCS #1.5 [rsa.c]
+# RFC 5915: EC keys [ecdsa.c]
+
+from pyasn1.type.univ import Sequence, SetOf, Integer, OctetString, ObjectIdentifier, BitString, Any
+from pyasn1.type.namedtype import NamedTypes, NamedType, OptionalNamedType
+from pyasn1.type.namedval import NamedValues
+from pyasn1.type.tag import Tag, tagClassContext, tagFormatSimple, tagFormatConstructed
+from pyasn1.type.constraint import SingleValueConstraint
+from pyasn1.codec.der.encoder import encode as DER_Encode
+from pyasn1.codec.der.decoder import decode as DER_Decode
+
+from ecdsa import der as ECDSA_DER
+from ecdsa.util import oid_ecPublicKey, encoded_oid_ecPublicKey
+from ecdsa.keys import SigningKey
+from ecdsa.curves import find_curve
+
+class AlgorithmIdentifier(Sequence):
+ componentType = NamedTypes(
+ NamedType( "algorithm", ObjectIdentifier()),
+ OptionalNamedType( "parameters", Any()))
+
+class AttributeTypeAndValue(Sequence):
+ componentType = NamedTypes(
+ NamedType( "type", ObjectIdentifier()),
+ NamedType( "value", Any()))
+
+class Attribute(Sequence):
+ componentType = NamedTypes(
+ NamedType( "type", ObjectIdentifier()),
+ NamedType( "vals", SetOf(componentType = Any())))
+
+# RFC 5208
+
+class PrivateKeyInfo(Sequence):
+ componentType = NamedTypes(
+ NamedType( "version", Integer(namedValues = NamedValues(("v1", 0))) .subtype(subtypeSpec = Integer.subtypeSpec + SingleValueConstraint(0))),
+ NamedType( "privateKeyAlgorithm", AlgorithmIdentifier()),
+ NamedType( "privateKey", OctetString()),
+ OptionalNamedType( "attributes", SetOf(componentType = Attribute()) .subtype(implicitTag = Tag(tagClassContext, tagFormatConstructed, 0))))
+
+class EncryptedPrivateKeyInfo(Sequence):
+ componentType = NamedTypes(
+ NamedType( "encryptionAlgorithm", AlgorithmIdentifier()),
+ NamedType( "encryptedData", OctetString()))
+
+# RFC 2313
+
+class RSAPrivateKey(Sequence):
+ componentType = NamedTypes(
+ NamedType( "version", Integer() .subtype(subtypeSpec = Integer.subtypeSpec + SingleValueConstraint(0))),
+ NamedType( "n", Integer()),
+ NamedType( "e", Integer()),
+ NamedType( "d", Integer()),
+ NamedType( "p", Integer()),
+ NamedType( "q", Integer()),
+ NamedType( "dP", Integer()),
+ NamedType( "dQ", Integer()),
+ NamedType( "u", Integer()))
+
+# RFC 5915
+
+class ECPrivateKey(Sequence):
+ componentType = NamedTypes(
+ NamedType( "version", Integer(namedValues = NamedValues(("ecPrivkeyVer1", 1))) .subtype(subtypeSpec = Integer.subtypeSpec + SingleValueConstraint(1))),
+ NamedType( "privateKey", OctetString()),
+ OptionalNamedType( "parameters", ObjectIdentifier() .subtype(explicitTag = Tag(tagClassContext, tagFormatSimple, 0))),
+ OptionalNamedType( "publicKey", BitString() .subtype(explicitTag = Tag(tagClassContext, tagFormatSimple, 1))))
+
+# Test data, generated by OpenSSL
+
+der_test_keys = dict(
+
+ ec_rfc5915 = '''
+ MHcCAQEEIFWaZOsQxLwZmIK4YAuf1d8S9Pnznvzcl9TjiMpvXkCYoAoGC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tgVyb5xZ
+ 6mWD2VjiukkCgYEAvMuzUqufhjMM6v5aF7QghM39dUUJAhK2TzCjYHYzBeu9MmgP
+ HQ2B/gDETiojCZ0flPR6uQyYHmMrX+PXYwUOIfzvi0hbJF6ddYszBlTRQOhruoz8
+ OjoDe44tTOxtPzCL0zWmnlYkPpLuoEQPSgYnoVF/5BdAJlgqf35v+dBd8qUCgYAP
+ AW48SOTlw7hCC/g6N8L94irALyqNTo35Fb9yICLsRHWfr/o6wnB3M6kq+UYxSpQG
+ Xl6wu6jKY1ajhZzU9Xxo12amUcYG3fHQoH3LJTEi3142KLGWVzBfnYqhkinVe4Ep
+ sc6X3Iir1EZw+CkH5C7qPLc8xX64v+sackvKAjGLIQKBgDBIsu7EcoZzL6hmjW/F
+ JCVjaA6Smuor1XCMCHEa4aUl+1esv8ORvGwZq1bRsYDJD5U+K8+XxhiGzfg0IDW3
+ WkkpzNw1scQkU3nvHoC0JscUtYH3XBj3rIDrL8GB3jk+hevJCXv4Z04A/IRhjear
+ dHm9qjNOto+ucP7rWSkpUsn9
+ '''.decode("base64"))
+
+
+def decode_ecpoint(ecpoint):
+ return { "\x02": "compressed", "\x04": "uncompressed" }[ecpoint[0]], ecpoint[1:1+len(ecpoint)/2], ecpoint[1+len(ecpoint)/2:]
+
+def dumpasn1(der):
+ from subprocess import call
+ from tempfile import NamedTemporaryFile
+ with NamedTemporaryFile() as f:
+ f.write(der)
+ f.flush()
+ call(("dumpasn1", "-aop", f.name))
+
+if __name__ == "__main__":
+
+ show_manual_decode = False
+
+ ec_rfc5915 = DER_Decode(der_test_keys["ec_rfc5915"], ECPrivateKey() )[0]
+ ec_pkcs8 = DER_Decode(der_test_keys["ec_pkcs8"], PrivateKeyInfo())[0]
+ ec_pkcs8_privateKey = DER_Decode(str(ec_pkcs8["privateKey"]), ECPrivateKey() )[0]
+ rsa_rfc2313 = DER_Decode(der_test_keys["rsa_rfc2313"], RSAPrivateKey() )[0]
+ rsa_pkcs8 = DER_Decode(der_test_keys["rsa_pkcs8"], PrivateKeyInfo())[0]
+ rsa_pkcs8_privateKey = DER_Decode(str(rsa_pkcs8["privateKey"]), RSAPrivateKey() )[0]
+
+ print
+ print "EC RFC 5915"
+ print ec_rfc5915.prettyPrint()
+
+ if show_manual_decode:
+ print
+ compressed, Qx, Qy = decode_ecpoint(ec_rfc5915["publicKey"].asOctets())
+ print "version: ", ec_rfc5915["version"]
+ print "privateKey:", str(ec_rfc5915["privateKey"]).encode("hex")
+ print "parameters:", ec_rfc5915["parameters"]
+ print "publicKey: ", compressed
+ print " Qx: ", Qx.encode("hex")
+ print " Qy: ", Qy.encode("hex")
+
+ # This works, and lets .prettyPrint() display the ANY content properly,
+ # but it breaks some of the key hackery we do after all this display stuff.
+ #ec_pkcs8["privateKeyAlgorithm"]["parameters"] = DER_Decode(ec_pkcs8["privateKeyAlgorithm"]["parameters"])[0]
+
+ print
+ print "EC PKCS #8"
+ print ec_pkcs8.prettyPrint()
+ print ec_pkcs8_privateKey.prettyPrint()
+
+ if show_manual_decode:
+ print
+ compressed, Qx, Qy = decode_ecpoint(ec_pkcs8_privateKey["publicKey"].asOctets())
+ print "version: ", ec_pkcs8["version"]
+ print "privateKeyAlgorithm:", ec_pkcs8["privateKeyAlgorithm"][0]
+ print " ", DER_Decode(ec_pkcs8["privateKeyAlgorithm"]["parameters"])[0]
+ print "privateKey:"
+ print " version: ", ec_pkcs8_privateKey["version"]
+ print " privateKey:", str(ec_pkcs8_privateKey["privateKey"]).encode("hex")
+ print " parameters:", ec_pkcs8_privateKey["parameters"]
+ print " publicKey: ", compressed
+ print " Qx: ", Qx.encode("hex")
+ print " Qy: ", Qy.encode("hex")
+
+ print
+ print "RSA RFC 2313"
+ print rsa_rfc2313.prettyPrint()
+
+ if show_manual_decode:
+ print
+ print "version:", rsa_rfc2313["version"]
+ print " n:", rsa_rfc2313["n"]
+ print " e:", rsa_rfc2313["e"]
+ print " d:", rsa_rfc2313["d"]
+ print " p:", rsa_rfc2313["p"]
+ print " q:", rsa_rfc2313["q"]
+ print " dP:", rsa_rfc2313["dP"]
+ print " dQ:", rsa_rfc2313["dQ"]
+ print " u:", rsa_rfc2313["u"]
+
+ #rsa_pkcs8["privateKeyAlgorithm"]["parameters"] = DER_Decode(rsa_pkcs8["privateKeyAlgorithm"]["parameters"])[0]
+
+ print
+ print "RSA PKCS #8"
+ print rsa_pkcs8.prettyPrint()
+ print rsa_pkcs8_privateKey.prettyPrint()
+
+ if show_manual_decode:
+ print
+ print "version: ", rsa_pkcs8["version"]
+ print "privateKeyAlgorithm:", rsa_pkcs8["privateKeyAlgorithm"][0]
+ print "privateKey:"
+ print " version:", rsa_pkcs8_privateKey["version"]
+ print " n:", rsa_pkcs8_privateKey["n"]
+ print " e:", rsa_pkcs8_privateKey["e"]
+ print " d:", rsa_pkcs8_privateKey["d"]
+ print " p:", rsa_pkcs8_privateKey["p"]
+ print " q:", rsa_pkcs8_privateKey["q"]
+ print " dP:", rsa_pkcs8_privateKey["dP"]
+ print " dQ:", rsa_pkcs8_privateKey["dQ"]
+ print " u:", rsa_pkcs8_privateKey["u"]
+
+ # Generate PKCS #8 from ECPrivateKey and check against static data
+ p8 = PrivateKeyInfo()
+ ec = ECPrivateKey()
+ ec["version"] = ec_rfc5915["version"]
+ ec["privateKey"] = ec_rfc5915["privateKey"]
+ ec["publicKey"] = ec_rfc5915["publicKey"]
+ p8["version"] = 0
+ p8["privateKeyAlgorithm"] = AlgorithmIdentifier()
+ p8["privateKeyAlgorithm"]["algorithm"] = "1.2.840.10045.2.1"
+ p8["privateKeyAlgorithm"]["parameters"] = ObjectIdentifier(ec_rfc5915["parameters"])
+ p8["privateKey"] = DER_Encode(ec)
+ der = DER_Encode(p8)
+ #print; dumpasn1(der)
+ #print; dumpasn1(der_test_keys["ec_pkcs8"])
+ print; print "Reencoded PKCS #8 {} static data".format("matches" if der == der_test_keys["ec_pkcs8"] else "doesn't match")
+
+ # Try doing same thing with ecdsa package ASN.1 utilities.
+ sk = SigningKey.from_der(der_test_keys["ec_rfc5915"])
+ vk = ECDSA_DER.encode_bitstring("\x00\x04" + sk.get_verifying_key().to_string())
+ ec = ECDSA_DER.encode_sequence(ECDSA_DER.encode_integer(1),
+ ECDSA_DER.encode_octet_string(sk.to_string()),
+ ECDSA_DER.encode_constructed(1, vk))
+ p8 = ECDSA_DER.encode_sequence(ECDSA_DER.encode_integer(0),
+ ECDSA_DER.encode_sequence(encoded_oid_ecPublicKey,
+ sk.curve.encoded_oid),
+ ECDSA_DER.encode_octet_string(ec))
+ print; print "ECDSA-library PKCS #8 encoding {} pyasn1 PKCS #8 encoding".format("matches" if p8 == der_test_keys["ec_pkcs8"] else "doesn't match")
+
+ # Generate ECPrivateKey from PKCS #8 and check against static data
+ ec = ECPrivateKey()
+ ec["version"] = ec_pkcs8_privateKey["version"]
+ ec["privateKey"] = ec_pkcs8_privateKey["privateKey"]
+ ec["parameters"] = str(DER_Decode(ec_pkcs8["privateKeyAlgorithm"]["parameters"])[0])
+ ec["publicKey"] = ec_pkcs8_privateKey["publicKey"]
+ der = DER_Encode(ec)
+ #print; dumpasn1(der)
+ #print; dumpasn1(der_test_keys["ec_rfc5915"])
+ print; print "Reencoded PKCS #8 {} static data".format("matches" if der == der_test_keys["ec_rfc5915"] else "doesn't match")
+
+ # Paranoia: Make sure we really can load the RFC 5915 we just generated.
+ sk = SigningKey.from_der(der)
+ print; print "ECDSA Python library parse of reencoded PKCS #8 data: {!r}".format(sk)
+
+ # Same thing with ecdsa package ASN.1 utilities.
+ car, cdr = ECDSA_DER.remove_sequence(der_test_keys["ec_pkcs8"])
+ assert cdr == ""
+ version, cdr = ECDSA_DER.remove_integer(car)
+ assert version == 0
+ car, ec = ECDSA_DER.remove_sequence(cdr)
+ oid, cdr = ECDSA_DER.remove_object(car)
+ assert oid == oid_ecPublicKey
+ oid, cdr = ECDSA_DER.remove_object(cdr)
+ curve = find_curve(oid)
+ assert cdr == ""
+ car, cdr = ECDSA_DER.remove_octet_string(ec)
+ assert cdr == ""
+ car, cdr = ECDSA_DER.remove_sequence(car)
+ assert cdr == ""
+ version, cdr = ECDSA_DER.remove_integer(car)
+ assert version == 1
+ privkey, cdr = ECDSA_DER.remove_octet_string(cdr)
+ tag, car, cdr = ECDSA_DER.remove_constructed(cdr)
+ assert tag == 1
+ assert cdr == ""
+ pubkey, cdr = ECDSA_DER.remove_bitstring(car)
+ assert cdr == ""
+ assert pubkey[:2] == "\x00\x04"
+ sk = SigningKey.from_string(privkey, curve)
+ print; print "ECDSA-library PKCS #8 decoding {} pyasn1 PKCS #8 decoding".format(
+ "matches" if der == sk.to_der() else "doesn't match")
diff --git a/rpc_api.c b/rpc_api.c
index 6ffd7a0..1a2d268 100644
--- a/rpc_api.c
+++ b/rpc_api.c
@@ -75,7 +75,9 @@ static inline int check_pkey_flags(const hal_key_flags_t flags)
return (flags &~ (HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE |
HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT |
HAL_KEY_FLAG_USAGE_DATAENCIPHERMENT |
- HAL_KEY_FLAG_TOKEN)) == 0;
+ HAL_KEY_FLAG_TOKEN |
+ HAL_KEY_FLAG_PUBLIC |
+ HAL_KEY_FLAG_EXPORTABLE)) == 0;
}
static inline int check_pkey_type_curve_flags(const hal_key_type_t type,
@@ -216,26 +218,23 @@ hal_error_t hal_rpc_hash_finalize(const hal_hash_handle_t hash,
hal_error_t hal_rpc_pkey_load(const hal_client_handle_t client,
const hal_session_handle_t session,
hal_pkey_handle_t *pkey,
- const hal_key_type_t type,
- const hal_curve_name_t curve,
hal_uuid_t *name,
const uint8_t * const der, const size_t der_len,
const hal_key_flags_t flags)
{
- if (pkey == NULL || name == NULL || der == NULL || der_len == 0 || !check_pkey_type_curve_flags(type, curve, flags))
+ if (pkey == NULL || name == NULL || der == NULL || der_len == 0 || !check_pkey_flags(flags))
return HAL_ERROR_BAD_ARGUMENTS;
- return hal_rpc_pkey_dispatch->load(client, session, pkey, type, curve, name, der, der_len, flags);
+ return hal_rpc_pkey_dispatch->load(client, session, pkey, name, der, der_len, flags);
}
hal_error_t hal_rpc_pkey_open(const hal_client_handle_t client,
const hal_session_handle_t session,
hal_pkey_handle_t *pkey,
- const hal_uuid_t * const name,
- const hal_key_flags_t flags)
+ const hal_uuid_t * const name)
{
if (pkey == NULL || name == NULL)
return HAL_ERROR_BAD_ARGUMENTS;
- return hal_rpc_pkey_dispatch->open(client, session, pkey, name, flags);
+ return hal_rpc_pkey_dispatch->open(client, session, pkey, name);
}
hal_error_t hal_rpc_pkey_generate_rsa(const hal_client_handle_t client,
@@ -338,16 +337,18 @@ hal_error_t hal_rpc_pkey_match(const hal_client_handle_t client,
const hal_session_handle_t session,
const hal_key_type_t type,
const hal_curve_name_t curve,
+ const hal_key_flags_t mask,
const hal_key_flags_t flags,
const hal_pkey_attribute_t *attributes,
const unsigned attributes_len,
+ unsigned *state,
hal_uuid_t *result,
unsigned *result_len,
const unsigned result_max,
const hal_uuid_t * const previous_uuid)
{
if ((attributes == NULL && attributes_len > 0) || previous_uuid == NULL ||
- result == NULL || result_len == NULL || result_max == 0)
+ state == NULL || result == NULL || result_len == NULL || result_max == 0)
return HAL_ERROR_BAD_ARGUMENTS;
if (attributes != NULL)
@@ -355,9 +356,9 @@ hal_error_t hal_rpc_pkey_match(const hal_client_handle_t client,
if (attributes[i].value == NULL)
return HAL_ERROR_BAD_ARGUMENTS;
- return hal_rpc_pkey_dispatch->match(client, session, type, curve, flags,
+ return hal_rpc_pkey_dispatch->match(client, session, type, curve, mask, flags,
attributes, attributes_len,
- result, result_len, result_max, previous_uuid);
+ state, result, result_len, result_max, previous_uuid);
}
hal_error_t hal_rpc_pkey_set_attributes(const hal_pkey_handle_t pkey,
@@ -381,6 +382,30 @@ hal_error_t hal_rpc_pkey_get_attributes(const hal_pkey_handle_t pkey,
attributes_buffer, attributes_buffer_len);
}
+hal_error_t hal_rpc_pkey_export(const hal_pkey_handle_t pkey,
+ const hal_pkey_handle_t kekek,
+ uint8_t *pkcs8, size_t *pkcs8_len, const size_t pkcs8_max,
+ uint8_t *kek, size_t *kek_len, const size_t kek_max)
+{
+ if (pkcs8 == NULL || pkcs8_len == NULL || kek == NULL || kek_len == NULL || kek_max <= KEK_LENGTH)
+ return HAL_ERROR_BAD_ARGUMENTS;
+ return hal_rpc_pkey_dispatch->export(pkey, kekek, pkcs8, pkcs8_len, pkcs8_max, kek, kek_len, kek_max);
+}
+
+hal_error_t hal_rpc_pkey_import(const hal_client_handle_t client,
+ const hal_session_handle_t session,
+ hal_pkey_handle_t *pkey,
+ hal_uuid_t *name,
+ const hal_pkey_handle_t kekek,
+ const uint8_t * const pkcs8, const size_t pkcs8_len,
+ const uint8_t * const kek, const size_t kek_len,
+ const hal_key_flags_t flags)
+{
+ if (pkey == NULL || name == NULL || pkcs8 == NULL || kek == NULL || kek_len <= 2)
+ return HAL_ERROR_BAD_ARGUMENTS;
+ return hal_rpc_pkey_dispatch->import(client, session, pkey, name, kekek, pkcs8, pkcs8_len, kek, kek_len, flags);
+}
+
/*
* Local variables:
* indent-tabs-mode: nil
diff --git a/rpc_client.c b/rpc_client.c
index 4adf247..aad9edf 100644
--- a/rpc_client.c
+++ b/rpc_client.c
@@ -420,13 +420,11 @@ static hal_error_t hash_finalize(const hal_hash_handle_t hash,
static hal_error_t pkey_remote_load(const hal_client_handle_t client,
const hal_session_handle_t session,
hal_pkey_handle_t *pkey,
- const hal_key_type_t type,
- const hal_curve_name_t curve,
hal_uuid_t *name,
const uint8_t * const der, const size_t der_len,
const hal_key_flags_t flags)
{
- uint8_t outbuf[nargs(7) + pad(der_len)], *optr = outbuf, *olimit = outbuf + sizeof(outbuf);
+ uint8_t outbuf[nargs(5) + pad(der_len)], *optr = outbuf, *olimit = outbuf + sizeof(outbuf);
uint8_t inbuf[nargs(5) + pad(sizeof(name->uuid))];
const uint8_t *iptr = inbuf, *ilimit = inbuf + sizeof(inbuf);
uint32_t name_len = sizeof(name->uuid);
@@ -435,8 +433,6 @@ static hal_error_t pkey_remote_load(const hal_client_handle_t client,
check(hal_xdr_encode_int(&optr, olimit, RPC_FUNC_PKEY_LOAD));
check(hal_xdr_encode_int(&optr, olimit, client.handle));
check(hal_xdr_encode_int(&optr, olimit, session.handle));
- check(hal_xdr_encode_int(&optr, olimit, type));
- check(hal_xdr_encode_int(&optr, olimit, curve));
check(hal_xdr_encode_buffer(&optr, olimit, der, der_len));
check(hal_xdr_encode_int(&optr, olimit, flags));
check(hal_rpc_send(outbuf, optr - outbuf));
@@ -458,10 +454,9 @@ static hal_error_t pkey_remote_load(const hal_client_handle_t client,
static hal_error_t pkey_remote_open(const hal_client_handle_t client,
const hal_session_handle_t session,
hal_pkey_handle_t *pkey,
- const hal_uuid_t * const name,
- const hal_key_flags_t flags)
+ const hal_uuid_t * const name)
{
- uint8_t outbuf[nargs(5) + pad(sizeof(name->uuid))], *optr = outbuf, *olimit = outbuf + sizeof(outbuf);
+ uint8_t outbuf[nargs(4) + pad(sizeof(name->uuid))], *optr = outbuf, *olimit = outbuf + sizeof(outbuf);
uint8_t inbuf[nargs(4)];
const uint8_t *iptr = inbuf, *ilimit = inbuf + sizeof(inbuf);
hal_error_t rpc_ret;
@@ -470,7 +465,6 @@ static hal_error_t pkey_remote_open(const hal_client_handle_t client,
check(hal_xdr_encode_int(&optr, olimit, client.handle));
check(hal_xdr_encode_int(&optr, olimit, session.handle));
check(hal_xdr_encode_buffer(&optr, olimit, name->uuid, sizeof(name->uuid)));
- check(hal_xdr_encode_int(&optr, olimit, flags));
check(hal_rpc_send(outbuf, optr - outbuf));
check(read_matching_packet(RPC_FUNC_PKEY_OPEN, inbuf, sizeof(inbuf), &iptr, &ilimit));
@@ -776,9 +770,11 @@ static hal_error_t pkey_remote_match(const hal_client_handle_t client,
const hal_session_handle_t session,
const hal_key_type_t type,
const hal_curve_name_t curve,
+ const hal_key_flags_t mask,
const hal_key_flags_t flags,
const hal_pkey_attribute_t *attributes,
const unsigned attributes_len,
+ unsigned *state,
hal_uuid_t *result,
unsigned *result_len,
const unsigned result_max,
@@ -789,9 +785,9 @@ static hal_error_t pkey_remote_match(const hal_client_handle_t client,
for (int i = 0; i < attributes_len; i++)
attributes_buffer_len += pad(attributes[i].length);
- uint8_t outbuf[nargs(9 + attributes_len * 2) + attributes_buffer_len + pad(sizeof(hal_uuid_t))];
+ uint8_t outbuf[nargs(11 + attributes_len * 2) + attributes_buffer_len + pad(sizeof(hal_uuid_t))];
uint8_t *optr = outbuf, *olimit = outbuf + sizeof(outbuf);
- uint8_t inbuf[nargs(4) + pad(result_max * sizeof(hal_uuid_t))];
+ uint8_t inbuf[nargs(5) + pad(result_max * sizeof(hal_uuid_t))];
const uint8_t *iptr = inbuf, *ilimit = inbuf + sizeof(inbuf);
hal_error_t rpc_ret;
@@ -800,6 +796,7 @@ static hal_error_t pkey_remote_match(const hal_client_handle_t client,
check(hal_xdr_encode_int(&optr, olimit, session.handle));
check(hal_xdr_encode_int(&optr, olimit, type));
check(hal_xdr_encode_int(&optr, olimit, curve));
+ check(hal_xdr_encode_int(&optr, olimit, mask));
check(hal_xdr_encode_int(&optr, olimit, flags));
check(hal_xdr_encode_int(&optr, olimit, attributes_len));
if (attributes != NULL) {
@@ -808,6 +805,7 @@ static hal_error_t pkey_remote_match(const hal_client_handle_t client,
check(hal_xdr_encode_buffer(&optr, olimit, attributes[i].value, attributes[i].length));
}
}
+ check(hal_xdr_encode_int(&optr, olimit, *state));
check(hal_xdr_encode_int(&optr, olimit, result_max));
check(hal_xdr_encode_buffer(&optr, olimit, previous_uuid->uuid, sizeof(previous_uuid->uuid)));
check(hal_rpc_send(outbuf, optr - outbuf));
@@ -816,8 +814,10 @@ static hal_error_t pkey_remote_match(const hal_client_handle_t client,
check(hal_xdr_decode_int(&iptr, ilimit, &rpc_ret));
if (rpc_ret == HAL_OK) {
- uint32_t array_len;
+ uint32_t array_len, ustate;
*result_len = 0;
+ check(hal_xdr_decode_int(&iptr, ilimit, &ustate));
+ *state = ustate;
check(hal_xdr_decode_int(&iptr, ilimit, &array_len));
for (int i = 0; i < array_len; ++i) {
uint32_t uuid_len = sizeof(result[i].uuid);
@@ -915,6 +915,78 @@ static hal_error_t pkey_remote_get_attributes(const hal_pkey_handle_t pkey,
return rpc_ret;
}
+static hal_error_t pkey_remote_export(const hal_pkey_handle_t pkey,
+ const hal_pkey_handle_t kekek,
+ uint8_t *pkcs8, size_t *pkcs8_len, const size_t pkcs8_max,
+ uint8_t *kek, size_t *kek_len, const size_t kek_max)
+{
+ uint8_t outbuf[nargs(6)], *optr = outbuf, *olimit = outbuf + sizeof(outbuf);
+ uint8_t inbuf[nargs(5) + pad(pkcs8_max) + pad(kek_max)];
+ const uint8_t *iptr = inbuf, *ilimit = inbuf + sizeof(inbuf);
+ hal_client_handle_t dummy_client = {0};
+ hal_error_t rpc_ret;
+
+ check(hal_xdr_encode_int(&optr, olimit, RPC_FUNC_PKEY_EXPORT));
+ check(hal_xdr_encode_int(&optr, olimit, dummy_client.handle));
+ check(hal_xdr_encode_int(&optr, olimit, pkey.handle));
+ check(hal_xdr_encode_int(&optr, olimit, kekek.handle));
+ check(hal_xdr_encode_int(&optr, olimit, pkcs8_max));
+ check(hal_xdr_encode_int(&optr, olimit, kek_max));
+ check(hal_rpc_send(outbuf, optr - outbuf));
+
+ check(read_matching_packet(RPC_FUNC_PKEY_EXPORT, inbuf, sizeof(inbuf), &iptr, &ilimit));
+
+ check(hal_xdr_decode_int(&iptr, ilimit, &rpc_ret));
+ if (rpc_ret == HAL_OK) {
+ uint32_t len;
+ len = pkcs8_max;
+ check(hal_xdr_decode_buffer(&iptr, ilimit, pkcs8, &len));
+ *pkcs8_len = (size_t) len;
+ len = kek_max;
+ check(hal_xdr_decode_buffer(&iptr, ilimit, kek, &len));
+ *kek_len = (size_t) len;
+ }
+ return rpc_ret;
+}
+
+static hal_error_t pkey_remote_import(const hal_client_handle_t client,
+ const hal_session_handle_t session,
+ hal_pkey_handle_t *pkey,
+ hal_uuid_t *name,
+ const hal_pkey_handle_t kekek,
+ const uint8_t * const pkcs8, const size_t pkcs8_len,
+ const uint8_t * const kek, const size_t kek_len,
+ const hal_key_flags_t flags)
+{
+ uint8_t outbuf[nargs(7) + pad(pkcs8_len) + pad(kek_len)], *optr = outbuf, *olimit = outbuf + sizeof(outbuf);
+ uint8_t inbuf[nargs(5) + pad(sizeof(name->uuid))];
+ const uint8_t *iptr = inbuf, *ilimit = inbuf + sizeof(inbuf);
+ uint32_t name_len = sizeof(name->uuid);
+ hal_error_t rpc_ret;
+
+ check(hal_xdr_encode_int(&optr, olimit, RPC_FUNC_PKEY_IMPORT));
+ check(hal_xdr_encode_int(&optr, olimit, client.handle));
+ check(hal_xdr_encode_int(&optr, olimit, session.handle));
+ check(hal_xdr_encode_int(&optr, olimit, kekek.handle));
+ check(hal_xdr_encode_buffer(&optr, olimit, pkcs8, pkcs8_len));
+ check(hal_xdr_encode_buffer(&optr, olimit, kek, kek_len));
+ check(hal_xdr_encode_int(&optr, olimit, flags));
+ check(hal_rpc_send(outbuf, optr - outbuf));
+
+ check(read_matching_packet(RPC_FUNC_PKEY_IMPORT, inbuf, sizeof(inbuf), &iptr, &ilimit));
+
+ check(hal_xdr_decode_int(&iptr, ilimit, &rpc_ret));
+
+ if (rpc_ret == HAL_OK) {
+ check(hal_xdr_decode_int(&iptr, ilimit, &pkey->handle));
+ check(hal_xdr_decode_buffer(&iptr, ilimit, name->uuid, &name_len));
+ if (name_len != sizeof(name->uuid))
+ return HAL_ERROR_KEY_NAME_TOO_LONG;
+ }
+
+ return rpc_ret;
+}
+
#if RPC_CLIENT == RPC_CLIENT_MIXED
/*
@@ -1043,7 +1115,9 @@ const hal_rpc_pkey_dispatch_t hal_rpc_remote_pkey_dispatch = {
.verify = pkey_remote_verify,
.match = pkey_remote_match,
.set_attributes = pkey_remote_set_attributes,
- .get_attributes = pkey_remote_get_attributes
+ .get_attributes = pkey_remote_get_attributes,
+ .export = pkey_remote_export,
+ .import = pkey_remote_import
};
#if RPC_CLIENT == RPC_CLIENT_MIXED
@@ -1063,7 +1137,9 @@ const hal_rpc_pkey_dispatch_t hal_rpc_mixed_pkey_dispatch = {
.verify = pkey_mixed_verify,
.match = pkey_remote_match,
.set_attributes = pkey_remote_set_attributes,
- .get_attributes = pkey_remote_get_attributes
+ .get_attributes = pkey_remote_get_attributes,
+ .export = pkey_remote_export,
+ .import = pkey_remote_import
};
#endif /* RPC_CLIENT == RPC_CLIENT_MIXED */
@@ -1100,7 +1176,6 @@ hal_error_t hal_rpc_client_close(void)
#endif
}
-
/*
* Local variables:
* indent-tabs-mode: nil
diff --git a/rpc_client_daemon.c b/rpc_client_daemon.c
index 7ff3f21..1c506eb 100644
--- a/rpc_client_daemon.c
+++ b/rpc_client_daemon.c
@@ -40,6 +40,7 @@
#include "hal.h"
#include "hal_internal.h"
+#include "slip_internal.h"
static int sock = -1;
diff --git a/rpc_pkey.c b/rpc_pkey.c
index 48072ce..e0d9bdc 100644
--- a/rpc_pkey.c
+++ b/rpc_pkey.c
@@ -38,6 +38,7 @@
#include "hal.h"
#include "hal_internal.h"
+#include "asn1_internal.h"
#ifndef HAL_STATIC_PKEY_STATE_BLOCKS
#define HAL_STATIC_PKEY_STATE_BLOCKS 0
@@ -56,7 +57,10 @@ static hal_pkey_slot_t pkey_slot[HAL_STATIC_PKEY_STATE_BLOCKS];
*
* The high order bit of the pkey handle is left free for
* HAL_PKEY_HANDLE_TOKEN_FLAG, which is used by the mixed-mode
- * handlers to route calls to the appropriate destination.
+ * handlers to route calls to the appropriate destination. In most
+ * cases this flag is set here, but pkey_local_open() also sets it
+ * directly, so that we can present a unified UUID namespace
+ * regardless of which keystore holds a particular key.
*/
static inline hal_pkey_slot_t *alloc_slot(const hal_key_flags_t flags)
@@ -117,10 +121,10 @@ static inline hal_pkey_slot_t *find_handle(const hal_pkey_handle_t handle)
*
* That's almost the rule that PKCS #11 follows for so-called
* "private" objects (CKA_PRIVATE = CK_TRUE), but PKCS #11 has a more
- * model which not only allows wider visibility to "public" objects
- * (CKA_PRIVATE = CK_FALSE) but also allows write access to "public
- * session" (CKA_PRIVATE = CK_FALSE, CKA_TOKEN = CK_FALSE) objects
- * regardless of login state.
+ * complex model which not only allows wider visibility to "public"
+ * objects (CKA_PRIVATE = CK_FALSE) but also allows write access to
+ * "public session" (CKA_PRIVATE = CK_FALSE, CKA_TOKEN = CK_FALSE)
+ * objects regardless of login state.
*
* PKCS #11 also has a concept of read-only sessions, which we don't
* bother to implement at all on the HSM, since the PIN is required to
@@ -173,29 +177,55 @@ static inline hal_error_t check_writable(const hal_client_handle_t client,
}
/*
+ * PKCS #1.5 encryption requires non-zero random bytes, which is a bit
+ * messy if done in place, so make it a separate function for readability.
+ */
+
+static inline hal_error_t get_nonzero_random(uint8_t *buffer, size_t n)
+{
+ assert(buffer != NULL);
+
+ uint32_t word = 0;
+ hal_error_t err;
+
+ while (n > 0) {
+
+ while ((word & 0xFF) == 0)
+ if ((word & ~0xFF) != 0)
+ word >>= 8;
+ else if ((err = hal_get_random(NULL, &word, sizeof(word))) != HAL_OK)
+ return err;
+
+ *buffer++ = word & 0xFF;
+ word >>= 8;
+ n--;
+ }
+
+ return HAL_OK;
+}
+
+/*
* Pad an octet string with PKCS #1.5 padding for use with RSA.
*
- * For the moment, this only handles type 01 encryption blocks, thus
- * is only suitable for use with signature and verification. If and
- * when we add support for encryption and decryption, this function
- * should be extended to take an argument specifying the block type
- * and include support for generating type 02 encryption blocks.
- * Other than the block type code, the only difference is the padding
- * value: for type 01 it's constant (0xFF), for type 02 it should be
- * non-zero random bytes from the CSPRNG.
+ * This handles type 01 and type 02 encryption blocks. The formats
+ * are identical, except that the padding string is constant 0xFF
+ * bytes for type 01 and non-zero random bytes for type 02.
*
* We use memmove() instead of memcpy() so that the caller can
* construct the data to be padded in the same buffer.
*/
static hal_error_t pkcs1_5_pad(const uint8_t * const data, const size_t data_len,
- uint8_t *block, const size_t block_len)
+ uint8_t *block, const size_t block_len,
+ const uint8_t type)
{
- assert(data != NULL && block != NULL);
+ assert(data != NULL && block != NULL && (type == 0x01 || type == 0x02));
+
+ hal_error_t err;
/*
* Congregation will now please turn to RFC 2313 8.1 as we
- * construct a PKCS #1.5 type 01 encryption block.
+ * construct a PKCS #1.5 type 01 or type 02 encryption block.
*/
if (data_len > block_len - 11)
@@ -204,10 +234,20 @@ static hal_error_t pkcs1_5_pad(const uint8_t * const data, const size_t data_len
memmove(block + block_len - data_len, data, data_len);
block[0] = 0x00;
- block[1] = 0x01;
+ block[1] = type;
+
+ switch (type) {
+
+ case 0x01: /* Signature */
+ memset(block + 2, 0xFF, block_len - 3 - data_len);
+ break;
+
+ case 0x02: /* Encryption */
+ if ((err = get_nonzero_random(block + 2, block_len - 3 - data_len)) != HAL_OK)
+ return err;
+ break;
- /* This is where we'd use non-zero random bytes if constructing a type 02 block. */
- memset(block + 2, 0xFF, block_len - 3 - data_len);
+ }
block[block_len - data_len - 1] = 0x00;
@@ -227,6 +267,44 @@ static inline hal_error_t ks_open_from_flags(hal_ks_t **ks, const hal_key_flags_
}
/*
+ * Fetch a key from a driver.
+ */
+
+static inline hal_error_t ks_fetch_from_driver(const hal_ks_driver_t * const driver,
+ hal_pkey_slot_t *slot,
+ uint8_t *der, size_t *der_len, const size_t der_max)
+{
+ hal_ks_t *ks = NULL;
+ hal_error_t err;
+
+ if ((err = hal_ks_open(driver, &ks)) != HAL_OK)
+ return err;
+
+ if ((err = hal_ks_fetch(ks, slot, der, der_len, der_max)) == HAL_OK)
+ err = hal_ks_close(ks);
+ else
+ (void) hal_ks_close(ks);
+
+ return err;
+}
+
+/*
+ * Same thing but from key flag in slot object rather than explict driver.
+ */
+
+static inline hal_error_t ks_fetch_from_flags(hal_pkey_slot_t *slot,
+ uint8_t *der, size_t *der_len, const size_t der_max)
+{
+ assert(slot != NULL);
+
+ return ks_fetch_from_driver((slot->flags & HAL_KEY_FLAG_TOKEN) == 0
+ ? hal_ks_volatile_driver
+ : hal_ks_token_driver,
+ slot, der, der_len, der_max);
+}
+
+
+/*
* Receive key from application, generate a name (UUID), store it, and
* return a key handle and the name.
*/
@@ -234,21 +312,24 @@ static inline hal_error_t ks_open_from_flags(hal_ks_t **ks, const hal_key_flags_
static hal_error_t pkey_local_load(const hal_client_handle_t client,
const hal_session_handle_t session,
hal_pkey_handle_t *pkey,
- const hal_key_type_t type,
- const hal_curve_name_t curve,
hal_uuid_t *name,
const uint8_t * const der, const size_t der_len,
const hal_key_flags_t flags)
{
- assert(pkey != NULL && name != NULL);
+ assert(pkey != NULL && name != NULL && der != NULL);
+ hal_curve_name_t curve;
hal_pkey_slot_t *slot;
+ hal_key_type_t type;
hal_ks_t *ks = NULL;
hal_error_t err;
if ((err = check_writable(client, flags)) != HAL_OK)
return err;
+ if ((err = hal_asn1_guess_key_type(&type, &curve, der, der_len)) != HAL_OK)
+ return err;
+
if ((slot = alloc_slot(flags)) == NULL)
return HAL_ERROR_NO_KEY_SLOTS_AVAILABLE;
@@ -284,38 +365,38 @@ static hal_error_t pkey_local_load(const hal_client_handle_t client,
static hal_error_t pkey_local_open(const hal_client_handle_t client,
const hal_session_handle_t session,
hal_pkey_handle_t *pkey,
- const hal_uuid_t * const name,
- const hal_key_flags_t flags)
+ const hal_uuid_t * const name)
{
assert(pkey != NULL && name != NULL);
hal_pkey_slot_t *slot;
- hal_ks_t *ks = NULL;
hal_error_t err;
- if ((err = check_readable(client, flags)) != HAL_OK)
+ if ((err = check_readable(client, 0)) != HAL_OK)
return err;
- if ((slot = alloc_slot(flags)) == NULL)
+ if ((slot = alloc_slot(0)) == NULL)
return HAL_ERROR_NO_KEY_SLOTS_AVAILABLE;
slot->name = *name;
slot->client_handle = client;
slot->session_handle = session;
- if ((err = ks_open_from_flags(&ks, flags)) == HAL_OK &&
- (err = hal_ks_fetch(ks, slot, NULL, NULL, 0)) == HAL_OK)
- err = hal_ks_close(ks);
- else if (ks != NULL)
- (void) hal_ks_close(ks);
+ if ((err = ks_fetch_from_driver(hal_ks_token_driver, slot, NULL, NULL, 0)) == HAL_OK)
+ slot->pkey_handle.handle |= HAL_PKEY_HANDLE_TOKEN_FLAG;
- if (err != HAL_OK) {
- slot->type = HAL_KEY_TYPE_NONE;
- return err;
- }
+ else if (err == HAL_ERROR_KEY_NOT_FOUND)
+ err = ks_fetch_from_driver(hal_ks_volatile_driver, slot, NULL, NULL, 0);
+
+ if (err != HAL_OK)
+ goto fail;
*pkey = slot->pkey_handle;
return HAL_OK;
+
+ fail:
+ memset(slot, 0, sizeof(*slot));
+ return err;
}
/*
@@ -568,16 +649,9 @@ static size_t pkey_local_get_public_key_len(const hal_pkey_handle_t pkey)
hal_ecdsa_key_t *ecdsa_key = NULL;
uint8_t der[HAL_KS_WRAPPED_KEYSIZE];
size_t der_len;
- hal_ks_t *ks = NULL;
hal_error_t err;
- if ((err = ks_open_from_flags(&ks, slot->flags)) == HAL_OK &&
- (err = hal_ks_fetch(ks, slot, der, &der_len, sizeof(der))) == HAL_OK)
- err = hal_ks_close(ks);
- else if (ks != NULL)
- (void) hal_ks_close(ks);
-
- if (err == HAL_OK) {
+ if ((err = ks_fetch_from_flags(slot, der, &der_len, sizeof(der))) == HAL_OK) {
switch (slot->type) {
case HAL_KEY_TYPE_RSA_PUBLIC:
@@ -618,21 +692,15 @@ static hal_error_t pkey_local_get_public_key(const hal_pkey_handle_t pkey,
if (slot == NULL)
return HAL_ERROR_KEY_NOT_FOUND;
- uint8_t keybuf[hal_rsa_key_t_size > hal_ecdsa_key_t_size ? hal_rsa_key_t_size : hal_ecdsa_key_t_size];
+ uint8_t keybuf[hal_rsa_key_t_size > hal_ecdsa_key_t_size
+ ? hal_rsa_key_t_size : hal_ecdsa_key_t_size];
hal_rsa_key_t *rsa_key = NULL;
hal_ecdsa_key_t *ecdsa_key = NULL;
uint8_t buf[HAL_KS_WRAPPED_KEYSIZE];
size_t buf_len;
- hal_ks_t *ks = NULL;
hal_error_t err;
- if ((err = ks_open_from_flags(&ks, slot->flags)) == HAL_OK &&
- (err = hal_ks_fetch(ks, slot, buf, &buf_len, sizeof(buf))) == HAL_OK)
- err = hal_ks_close(ks);
- else if (ks != NULL)
- (void) hal_ks_close(ks);
-
- if (err == HAL_OK) {
+ if ((err = ks_fetch_from_flags(slot, buf, &buf_len, sizeof(buf))) == HAL_OK) {
switch (slot->type) {
case HAL_KEY_TYPE_RSA_PUBLIC:
@@ -699,7 +767,7 @@ static hal_error_t pkey_local_sign_rsa(uint8_t *keybuf, const size_t keybuf_len,
input = signature;
}
- if ((err = pkcs1_5_pad(input, input_len, signature, *signature_len)) != HAL_OK ||
+ if ((err = pkcs1_5_pad(input, input_len, signature, *signature_len, 0x01)) != HAL_OK ||
(err = hal_rsa_decrypt(NULL, key, signature, *signature_len, signature, *signature_len)) != HAL_OK)
return err;
@@ -770,20 +838,18 @@ static hal_error_t pkey_local_sign(const hal_pkey_handle_t pkey,
return HAL_ERROR_UNSUPPORTED_KEY;
}
- uint8_t keybuf[hal_rsa_key_t_size > hal_ecdsa_key_t_size ? hal_rsa_key_t_size : hal_ecdsa_key_t_size];
+ if ((slot->flags & HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE) == 0)
+ return HAL_ERROR_FORBIDDEN;
+
+ uint8_t keybuf[hal_rsa_key_t_size > hal_ecdsa_key_t_size
+ ? hal_rsa_key_t_size : hal_ecdsa_key_t_size];
uint8_t der[HAL_KS_WRAPPED_KEYSIZE];
size_t der_len;
- hal_ks_t *ks = NULL;
hal_error_t err;
- if ((err = ks_open_from_flags(&ks, slot->flags)) == HAL_OK &&
- (err = hal_ks_fetch(ks, slot, der, &der_len, sizeof(der))) == HAL_OK)
- err = hal_ks_close(ks);
- else if (ks != NULL)
- (void) hal_ks_close(ks);
-
- if (err == HAL_OK)
- err = signer(keybuf, sizeof(keybuf), der, der_len, hash, input, input_len, signature, signature_len, signature_max);
+ if ((err = ks_fetch_from_flags(slot, der, &der_len, sizeof(der))) == HAL_OK)
+ err = signer(keybuf, sizeof(keybuf), der, der_len, hash, input, input_len,
+ signature, signature_len, signature_max);
memset(keybuf, 0, sizeof(keybuf));
memset(der, 0, sizeof(der));
@@ -831,7 +897,7 @@ static hal_error_t pkey_local_verify_rsa(uint8_t *keybuf, const size_t keybuf_le
input = expected;
}
- if ((err = pkcs1_5_pad(input, input_len, expected, sizeof(expected))) != HAL_OK ||
+ if ((err = pkcs1_5_pad(input, input_len, expected, sizeof(expected), 0x01)) != HAL_OK ||
(err = hal_rsa_encrypt(NULL, key, signature, signature_len, received, sizeof(received))) != HAL_OK)
return err;
@@ -918,20 +984,18 @@ static hal_error_t pkey_local_verify(const hal_pkey_handle_t pkey,
return HAL_ERROR_UNSUPPORTED_KEY;
}
- uint8_t keybuf[hal_rsa_key_t_size > hal_ecdsa_key_t_size ? hal_rsa_key_t_size : hal_ecdsa_key_t_size];
+ if ((slot->flags & HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE) == 0)
+ return HAL_ERROR_FORBIDDEN;
+
+ uint8_t keybuf[hal_rsa_key_t_size > hal_ecdsa_key_t_size
+ ? hal_rsa_key_t_size : hal_ecdsa_key_t_size];
uint8_t der[HAL_KS_WRAPPED_KEYSIZE];
size_t der_len;
- hal_ks_t *ks = NULL;
hal_error_t err;
- if ((err = ks_open_from_flags(&ks, slot->flags)) == HAL_OK &&
- (err = hal_ks_fetch(ks, slot, der, &der_len, sizeof(der))) == HAL_OK)
- err = hal_ks_close(ks);
- else if (ks != NULL)
- (void) hal_ks_close(ks);
-
- if (err == HAL_OK)
- err = verifier(keybuf, sizeof(keybuf), slot->type, der, der_len, hash, input, input_len, signature, signature_len);
+ if ((err = ks_fetch_from_flags(slot, der, &der_len, sizeof(der))) == HAL_OK)
+ err = verifier(keybuf, sizeof(keybuf), slot->type, der, der_len, hash,
+ input, input_len, signature, signature_len);
memset(keybuf, 0, sizeof(keybuf));
memset(der, 0, sizeof(der));
@@ -939,40 +1003,111 @@ static hal_error_t pkey_local_verify(const hal_pkey_handle_t pkey,
return err;
}
+static inline hal_error_t match_one_keystore(const hal_ks_driver_t * const driver,
+ const hal_client_handle_t client,
+ const hal_session_handle_t session,
+ const hal_key_type_t type,
+ const hal_curve_name_t curve,
+ const hal_key_flags_t mask,
+ const hal_key_flags_t flags,
+ const hal_pkey_attribute_t *attributes,
+ const unsigned attributes_len,
+ hal_uuid_t **result,
+ unsigned *result_len,
+ const unsigned result_max,
+ const hal_uuid_t * const previous_uuid)
+{
+ hal_ks_t *ks = NULL;
+ hal_error_t err;
+ unsigned len;
+
+ if ((err = hal_ks_open(driver, &ks)) != HAL_OK)
+ return err;
+
+ if ((err = hal_ks_match(ks, client, session, type, curve,
+ mask, flags, attributes, attributes_len,
+ *result, &len, result_max - *result_len,
+ previous_uuid)) != HAL_OK) {
+ (void) hal_ks_close(ks);
+ return err;
+ }
+
+ if ((err = hal_ks_close(ks)) != HAL_OK)
+ return err;
+
+ *result += len;
+ *result_len += len;
+
+ return HAL_OK;
+}
+
+typedef enum {
+ MATCH_STATE_START,
+ MATCH_STATE_TOKEN,
+ MATCH_STATE_VOLATILE,
+ MATCH_STATE_DONE
+} match_state_t;
+
static hal_error_t pkey_local_match(const hal_client_handle_t client,
const hal_session_handle_t session,
const hal_key_type_t type,
const hal_curve_name_t curve,
+ const hal_key_flags_t mask,
const hal_key_flags_t flags,
const hal_pkey_attribute_t *attributes,
const unsigned attributes_len,
+ unsigned *state,
hal_uuid_t *result,
unsigned *result_len,
const unsigned result_max,
const hal_uuid_t * const previous_uuid)
{
- hal_ks_t *ks = NULL;
+ assert(state != NULL && result_len != NULL);
+
+ static const hal_uuid_t uuid_zero[1] = {{{0}}};
+ const hal_uuid_t *prev = previous_uuid;
hal_error_t err;
- err = check_readable(client, flags);
+ *result_len = 0;
- if (err == HAL_ERROR_FORBIDDEN) {
- assert(result_len != NULL);
- *result_len = 0;
+ if ((err = check_readable(client, flags)) == HAL_ERROR_FORBIDDEN)
return HAL_OK;
- }
-
- if (err != HAL_OK)
+ else if (err != HAL_OK)
return err;
- if ((err = ks_open_from_flags(&ks, flags)) == HAL_OK &&
- (err = hal_ks_match(ks, client, session, type, curve, flags, attributes, attributes_len,
- result, result_len, result_max, previous_uuid)) == HAL_OK)
- err = hal_ks_close(ks);
- else if (ks != NULL)
- (void) hal_ks_close(ks);
+ switch ((match_state_t) *state) {
- return err;
+ case MATCH_STATE_START:
+ prev = uuid_zero;
+ ++*state;
+
+ case MATCH_STATE_TOKEN:
+ if (((mask & HAL_KEY_FLAG_TOKEN) == 0 || (mask & flags & HAL_KEY_FLAG_TOKEN) != 0) &&
+ (err = match_one_keystore(hal_ks_token_driver, client, session, type, curve,
+ mask, flags, attributes, attributes_len,
+ &result, result_len, result_max - *result_len, prev)) != HAL_OK)
+ return err;
+ if (*result_len == result_max)
+ return HAL_OK;
+ prev = uuid_zero;
+ ++*state;
+
+ case MATCH_STATE_VOLATILE:
+ if (((mask & HAL_KEY_FLAG_TOKEN) == 0 || (mask & flags & HAL_KEY_FLAG_TOKEN) == 0) &&
+ (err = match_one_keystore(hal_ks_volatile_driver, client, session, type, curve,
+ mask, flags, attributes, attributes_len,
+ &result, result_len, result_max - *result_len, prev)) != HAL_OK)
+ return err;
+ if (*result_len == result_max)
+ return HAL_OK;
+ ++*state;
+
+ case MATCH_STATE_DONE:
+ return HAL_OK;
+
+ default:
+ return HAL_ERROR_BAD_ARGUMENTS;
+ }
}
static hal_error_t pkey_local_set_attributes(const hal_pkey_handle_t pkey,
@@ -1023,6 +1158,181 @@ static hal_error_t pkey_local_get_attributes(const hal_pkey_handle_t pkey,
return err;
}
+static hal_error_t pkey_local_export(const hal_pkey_handle_t pkey_handle,
+ const hal_pkey_handle_t kekek_handle,
+ uint8_t *pkcs8, size_t *pkcs8_len, const size_t pkcs8_max,
+ uint8_t *kek, size_t *kek_len, const size_t kek_max)
+{
+ assert(pkcs8 != NULL && pkcs8_len != NULL && kek != NULL && kek_len != NULL && kek_max > KEK_LENGTH);
+
+ uint8_t rsabuf[hal_rsa_key_t_size];
+ hal_rsa_key_t *rsa = NULL;
+ hal_error_t err;
+ size_t len;
+
+ hal_pkey_slot_t * const pkey = find_handle(pkey_handle);
+ hal_pkey_slot_t * const kekek = find_handle(kekek_handle);
+
+ if (pkey == NULL || kekek == NULL)
+ return HAL_ERROR_KEY_NOT_FOUND;
+
+ if ((pkey->flags & HAL_KEY_FLAG_EXPORTABLE) == 0)
+ return HAL_ERROR_FORBIDDEN;
+
+ if ((kekek->flags & HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT) == 0)
+ return HAL_ERROR_FORBIDDEN;
+
+ if (kekek->type != HAL_KEY_TYPE_RSA_PRIVATE && kekek->type != HAL_KEY_TYPE_RSA_PUBLIC)
+ return HAL_ERROR_UNSUPPORTED_KEY;
+
+ if (pkcs8_max < HAL_KS_WRAPPED_KEYSIZE)
+ return HAL_ERROR_RESULT_TOO_LONG;
+
+ if ((err = ks_fetch_from_flags(kekek, pkcs8, &len, pkcs8_max)) != HAL_OK)
+ goto fail;
+
+ switch (kekek->type) {
+ case HAL_KEY_TYPE_RSA_PRIVATE:
+ err = hal_rsa_private_key_from_der(&rsa, rsabuf, sizeof(rsabuf), pkcs8, len);
+ break;
+ case HAL_KEY_TYPE_RSA_PUBLIC:
+ err = hal_rsa_public_key_from_der(&rsa, rsabuf, sizeof(rsabuf), pkcs8, len);
+ break;
+ default:
+ err = HAL_ERROR_IMPOSSIBLE;
+ }
+ if (err != HAL_OK)
+ goto fail;
+
+ if ((err = hal_rsa_key_get_modulus(rsa, NULL, kek_len, 0)) != HAL_OK)
+ goto fail;
+
+ if (*kek_len > kek_max) {
+ err = HAL_ERROR_RESULT_TOO_LONG;
+ goto fail;
+ }
+
+ if ((err = ks_fetch_from_flags(pkey, pkcs8, &len, pkcs8_max)) != HAL_OK)
+ goto fail;
+
+ if ((err = hal_get_random(NULL, kek, KEK_LENGTH)) != HAL_OK)
+ goto fail;
+
+ *pkcs8_len = pkcs8_max;
+ if ((err = hal_aes_keywrap(NULL, kek, KEK_LENGTH, pkcs8, len, pkcs8, pkcs8_len)) != HAL_OK)
+ goto fail;
+
+ if ((err = hal_asn1_encode_pkcs8_encryptedprivatekeyinfo(hal_asn1_oid_aesKeyWrap,
+ hal_asn1_oid_aesKeyWrap_len,
+ pkcs8, *pkcs8_len,
+ pkcs8, pkcs8_len, pkcs8_max)) != HAL_OK)
+ goto fail;
+
+ if ((err = pkcs1_5_pad(kek, KEK_LENGTH, kek, *kek_len, 0x02)) != HAL_OK)
+ goto fail;
+
+ if ((err = hal_rsa_encrypt(NULL, rsa, kek, *kek_len, kek, *kek_len)) != HAL_OK)
+ goto fail;
+
+ if ((err = hal_asn1_encode_pkcs8_encryptedprivatekeyinfo(hal_asn1_oid_rsaEncryption,
+ hal_asn1_oid_rsaEncryption_len,
+ kek, *kek_len,
+ kek, kek_len, kek_max)) != HAL_OK)
+ goto fail;
+
+ memset(rsabuf, 0, sizeof(rsabuf));
+ return HAL_OK;
+
+ fail:
+ memset(pkcs8, 0, pkcs8_max);
+ memset(kek, 0, kek_max);
+ memset(rsabuf, 0, sizeof(rsabuf));
+ *pkcs8_len = *kek_len = 0;
+ return err;
+}
+
+static hal_error_t pkey_local_import(const hal_client_handle_t client,
+ const hal_session_handle_t session,
+ hal_pkey_handle_t *pkey,
+ hal_uuid_t *name,
+ const hal_pkey_handle_t kekek_handle,
+ const uint8_t * const pkcs8, const size_t pkcs8_len,
+ const uint8_t * const kek_, const size_t kek_len,
+ const hal_key_flags_t flags)
+{
+ assert(pkey != NULL && name != NULL && pkcs8 != NULL && kek_ != NULL && kek_len > 2);
+
+ uint8_t kek[KEK_LENGTH], rsabuf[hal_rsa_key_t_size], der[HAL_KS_WRAPPED_KEYSIZE], *d;
+ size_t der_len, oid_len, data_len;
+ const uint8_t *oid, *data;
+ hal_rsa_key_t *rsa = NULL;
+ hal_error_t err;
+
+ hal_pkey_slot_t * const kekek = find_handle(kekek_handle);
+
+ if (kekek == NULL)
+ return HAL_ERROR_KEY_NOT_FOUND;
+
+ if ((kekek->flags & HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT) == 0)
+ return HAL_ERROR_FORBIDDEN;
+
+ if (kekek->type != HAL_KEY_TYPE_RSA_PRIVATE)
+ return HAL_ERROR_UNSUPPORTED_KEY;
+
+ if ((err = ks_fetch_from_flags(kekek, der, &der_len, sizeof(der))) != HAL_OK)
+ goto fail;
+
+ if ((err = hal_rsa_private_key_from_der(&rsa, rsabuf, sizeof(rsabuf), der, der_len)) != HAL_OK)
+ goto fail;
+
+ if ((err = hal_asn1_decode_pkcs8_encryptedprivatekeyinfo(&oid, &oid_len, &data, &data_len,
+ kek_, kek_len)) != HAL_OK)
+ goto fail;
+
+ if (oid_len != hal_asn1_oid_rsaEncryption_len ||
+ memcmp(oid, hal_asn1_oid_rsaEncryption, oid_len) != 0 ||
+ data_len > sizeof(der) ||
+ data_len < 2) {
+ err = HAL_ERROR_ASN1_PARSE_FAILED;
+ goto fail;
+ }
+
+ if ((err = hal_rsa_decrypt(NULL, rsa, data, data_len, der, data_len)) != HAL_OK)
+ goto fail;
+
+ if ((err = hal_get_random(NULL, kek, sizeof(kek))) != HAL_OK)
+ goto fail;
+
+ d = memchr(der + 2, 0x00, data_len - 2);
+
+ if (der[0] == 0x00 && der[1] == 0x02 && d != NULL && d - der > 10 &&
+ der + data_len == d + 1 + KEK_LENGTH)
+ memcpy(kek, d + 1, sizeof(kek));
+
+ if ((err = hal_asn1_decode_pkcs8_encryptedprivatekeyinfo(&oid, &oid_len, &data, &data_len,
+ pkcs8, pkcs8_len)) != HAL_OK)
+ goto fail;
+
+ if (oid_len != hal_asn1_oid_aesKeyWrap_len ||
+ memcmp(oid, hal_asn1_oid_aesKeyWrap, oid_len) != 0 ||
+ data_len > sizeof(der)) {
+ err = HAL_ERROR_ASN1_PARSE_FAILED;
+ goto fail;
+ }
+
+ der_len = sizeof(der);
+ if ((err = hal_aes_keyunwrap(NULL, kek, sizeof(kek), data, data_len, der, &der_len)) != HAL_OK)
+ goto fail;
+
+ err = hal_rpc_pkey_load(client, session, pkey, name, der, der_len, flags);
+
+ fail:
+ memset(rsabuf, 0, sizeof(rsabuf));
+ memset(kek, 0, sizeof(kek));
+ memset(der, 0, sizeof(der));
+ return err;
+}
+
const hal_rpc_pkey_dispatch_t hal_rpc_local_pkey_dispatch = {
.load = pkey_local_load,
.open = pkey_local_open,
@@ -1039,7 +1349,9 @@ const hal_rpc_pkey_dispatch_t hal_rpc_local_pkey_dispatch = {
.verify = pkey_local_verify,
.match = pkey_local_match,
.set_attributes = pkey_local_set_attributes,
- .get_attributes = pkey_local_get_attributes
+ .get_attributes = pkey_local_get_attributes,
+ .export = pkey_local_export,
+ .import = pkey_local_import
};
/*
diff --git a/rpc_server.c b/rpc_server.c
index a21679a..d946b06 100644
--- a/rpc_server.c
+++ b/rpc_server.c
@@ -322,30 +322,28 @@ static hal_error_t pkey_load(const uint8_t **iptr, const uint8_t * const ilimit,
hal_client_handle_t client;
hal_session_handle_t session;
hal_pkey_handle_t pkey;
- uint32_t type;
- uint32_t curve;
hal_uuid_t name;
const uint8_t *der;
uint32_t der_len;
hal_key_flags_t flags;
hal_error_t ret;
+ uint8_t *optr_orig = *optr;
check(hal_xdr_decode_int(iptr, ilimit, &client.handle));
check(hal_xdr_decode_int(iptr, ilimit, &session.handle));
- check(hal_xdr_decode_int(iptr, ilimit, &type));
- check(hal_xdr_decode_int(iptr, ilimit, &curve));
check(hal_xdr_decode_buffer_in_place(iptr, ilimit, &der, &der_len));
check(hal_xdr_decode_int(iptr, ilimit, &flags));
- /* call the local function */
- ret = hal_rpc_pkey_load(client, session, &pkey, type, curve, &name, der, der_len, flags);
+ ret = hal_rpc_pkey_load(client, session, &pkey, &name, der, der_len, flags);
- if (ret == HAL_OK) {
- uint8_t *optr_orig = *optr;
- if ((ret = hal_xdr_encode_int(optr, olimit, pkey.handle)) != HAL_OK ||
- (ret = hal_xdr_encode_buffer(optr, olimit, name.uuid, sizeof(name.uuid))) != HAL_OK)
- *optr = optr_orig;
- }
+ if (ret == HAL_OK)
+ ret = hal_xdr_encode_int(optr, olimit, pkey.handle);
+
+ if (ret == HAL_OK)
+ ret = hal_xdr_encode_buffer(optr, olimit, name.uuid, sizeof(name.uuid));
+
+ if (ret != HAL_OK)
+ *optr = optr_orig;
return ret;
}
@@ -358,19 +356,17 @@ static hal_error_t pkey_open(const uint8_t **iptr, const uint8_t * const ilimit,
hal_pkey_handle_t pkey;
const uint8_t *name_ptr;
uint32_t name_len;
- hal_key_flags_t flags;
hal_error_t ret;
check(hal_xdr_decode_int(iptr, ilimit, &client.handle));
check(hal_xdr_decode_int(iptr, ilimit, &session.handle));
check(hal_xdr_decode_buffer_in_place(iptr, ilimit, &name_ptr, &name_len));
- check(hal_xdr_decode_int(iptr, ilimit, &flags));
if (name_len != sizeof(hal_uuid_t))
return HAL_ERROR_KEY_NAME_TOO_LONG;
/* call the local function */
- ret = hal_rpc_pkey_open(client, session, &pkey, (const hal_uuid_t *) name_ptr, flags);
+ ret = hal_rpc_pkey_open(client, session, &pkey, (const hal_uuid_t *) name_ptr);
if (ret == HAL_OK)
check(hal_xdr_encode_int(optr, olimit, pkey.handle));
@@ -645,15 +641,17 @@ static hal_error_t pkey_match(const uint8_t **iptr, const uint8_t * const ilimit
{
hal_client_handle_t client;
hal_session_handle_t session;
- uint32_t type, curve, attributes_len, result_max, previous_uuid_len;
+ uint32_t type, curve, attributes_len, state, result_max, previous_uuid_len;
const uint8_t *previous_uuid_ptr;
- hal_key_flags_t flags;
+ hal_key_flags_t mask, flags;
+ uint8_t *optr_orig = *optr;
hal_error_t ret;
check(hal_xdr_decode_int(iptr, ilimit, &client.handle));
check(hal_xdr_decode_int(iptr, ilimit, &session.handle));
check(hal_xdr_decode_int(iptr, ilimit, &type));
check(hal_xdr_decode_int(iptr, ilimit, &curve));
+ check(hal_xdr_decode_int(iptr, ilimit, &mask));
check(hal_xdr_decode_int(iptr, ilimit, &flags));
check(hal_xdr_decode_int(iptr, ilimit, &attributes_len));
@@ -669,6 +667,7 @@ static hal_error_t pkey_match(const uint8_t **iptr, const uint8_t * const ilimit
a->length = value_len;
}
+ check(hal_xdr_decode_int(iptr, ilimit, &state));
check(hal_xdr_decode_int(iptr, ilimit, &result_max));
check(hal_xdr_decode_buffer_in_place(iptr, ilimit, &previous_uuid_ptr, &previous_uuid_len));
@@ -678,22 +677,24 @@ static hal_error_t pkey_match(const uint8_t **iptr, const uint8_t * const ilimit
const hal_uuid_t * const previous_uuid = (const void *) previous_uuid_ptr;
hal_uuid_t result[result_max];
- unsigned result_len;
+ unsigned result_len, ustate = state;
- ret = hal_rpc_pkey_match(client, session, type, curve, flags,
+ ret = hal_rpc_pkey_match(client, session, type, curve, mask, flags,
attributes, attributes_len,
- result, &result_len, result_max,
+ &ustate, result, &result_len, result_max,
previous_uuid);
- if (ret == HAL_OK) {
- uint8_t *optr_orig = *optr;
+ if (ret == HAL_OK)
+ ret = hal_xdr_encode_int(optr, olimit, ustate);
+
+ if (ret == HAL_OK)
ret = hal_xdr_encode_int(optr, olimit, result_len);
- for (int i = 0; ret == HAL_OK && i < result_len; ++i)
- ret = hal_xdr_encode_buffer(optr, olimit, result[i].uuid,
- sizeof(result[i].uuid));
- if (ret != HAL_OK)
- *optr = optr_orig;
- }
+
+ for (int i = 0; ret == HAL_OK && i < result_len; ++i)
+ ret = hal_xdr_encode_buffer(optr, olimit, result[i].uuid,
+ sizeof(result[i].uuid));
+ if (ret != HAL_OK)
+ *optr = optr_orig;
return ret;
}
@@ -782,6 +783,74 @@ static hal_error_t pkey_get_attributes(const uint8_t **iptr, const uint8_t * con
return ret;
}
+static hal_error_t pkey_export(const uint8_t **iptr, const uint8_t * const ilimit,
+ uint8_t **optr, const uint8_t * const olimit)
+{
+ hal_client_handle_t client;
+ hal_pkey_handle_t pkey;
+ hal_pkey_handle_t kekek;
+ size_t pkcs8_len, kek_len;
+ uint32_t pkcs8_max, kek_max;
+ uint8_t *optr_orig = *optr;
+ hal_error_t ret;
+
+ check(hal_xdr_decode_int(iptr, ilimit, &client.handle));
+ check(hal_xdr_decode_int(iptr, ilimit, &pkey.handle));
+ check(hal_xdr_decode_int(iptr, ilimit, &kekek.handle));
+ check(hal_xdr_decode_int(iptr, ilimit, &pkcs8_max));
+ check(hal_xdr_decode_int(iptr, ilimit, &kek_max));
+
+ uint8_t pkcs8[pkcs8_max], kek[kek_max];
+
+ ret = hal_rpc_pkey_export(pkey, kekek, pkcs8, &pkcs8_len, sizeof(pkcs8), kek, &kek_len, sizeof(kek));
+
+ if (ret == HAL_OK)
+ ret = hal_xdr_encode_buffer(optr, olimit, pkcs8, pkcs8_len);
+
+ if (ret == HAL_OK)
+ ret = hal_xdr_encode_buffer(optr, olimit, kek, kek_len);
+
+ if (ret != HAL_OK)
+ *optr = optr_orig;
+
+ return ret;
+}
+
+static hal_error_t pkey_import(const uint8_t **iptr, const uint8_t * const ilimit,
+ uint8_t **optr, const uint8_t * const olimit)
+{
+ hal_client_handle_t client;
+ hal_session_handle_t session;
+ hal_pkey_handle_t pkey;
+ hal_pkey_handle_t kekek;
+ hal_uuid_t name;
+ const uint8_t *pkcs8, *kek;
+ uint32_t pkcs8_len, kek_len;
+ uint8_t *optr_orig = *optr;
+ hal_key_flags_t flags;
+ hal_error_t ret;
+
+ check(hal_xdr_decode_int(iptr, ilimit, &client.handle));
+ check(hal_xdr_decode_int(iptr, ilimit, &session.handle));
+ check(hal_xdr_decode_int(iptr, ilimit, &kekek.handle));
+ check(hal_xdr_decode_buffer_in_place(iptr, ilimit, &pkcs8, &pkcs8_len));
+ check(hal_xdr_decode_buffer_in_place(iptr, ilimit, &kek, &kek_len));
+ check(hal_xdr_decode_int(iptr, ilimit, &flags));
+
+ ret = hal_rpc_pkey_import(client, session, &pkey, &name, kekek, pkcs8, pkcs8_len, kek, kek_len, flags);
+
+ if (ret == HAL_OK)
+ ret = hal_xdr_encode_int(optr, olimit, pkey.handle);
+
+ if (ret == HAL_OK)
+ ret = hal_xdr_encode_buffer(optr, olimit, name.uuid, sizeof(name.uuid));
+
+ if (ret != HAL_OK)
+ *optr = optr_orig;
+
+ return ret;
+}
+
hal_error_t hal_rpc_server_dispatch(const uint8_t * const ibuf, const size_t ilen,
uint8_t * const obuf, size_t * const olen)
@@ -888,6 +957,12 @@ hal_error_t hal_rpc_server_dispatch(const uint8_t * const ibuf, const size_t ile
case RPC_FUNC_PKEY_GET_ATTRIBUTES:
handler = pkey_get_attributes;
break;
+ case RPC_FUNC_PKEY_EXPORT:
+ handler = pkey_export;
+ break;
+ case RPC_FUNC_PKEY_IMPORT:
+ handler = pkey_import;
+ break;
}
if (handler)
diff --git a/rsa.c b/rsa.c
index e24b5eb..3cea42c 100644
--- a/rsa.c
+++ b/rsa.c
@@ -673,7 +673,7 @@ hal_error_t hal_rsa_key_gen(const hal_core_t *core,
/*
* Just enough ASN.1 to read and write PKCS #1.5 RSAPrivateKey syntax
- * (RFC 2313 section 7.2).
+ * (RFC 2313 section 7.2) wrapped in a PKCS #8 PrivateKeyInfo (RFC 5208).
*
* RSAPrivateKey fields in the required order.
*/
@@ -709,15 +709,12 @@ hal_error_t hal_rsa_private_key_to_der(const hal_rsa_key_t * const key,
RSAPrivateKey_fields;
#undef _
- /*
- * Encode header.
- */
-
- if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, vlen, der, &hlen, der_max)) != HAL_OK)
+ if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, vlen, NULL, &hlen, 0)) != HAL_OK)
return err;
- if (der_len != NULL)
- *der_len = hlen + vlen;
+ if ((err = hal_asn1_encode_pkcs8_privatekeyinfo(hal_asn1_oid_rsaEncryption, hal_asn1_oid_rsaEncryption_len,
+ NULL, 0, NULL, hlen + vlen, NULL, der_len, der_max)) != HAL_OK)
+ return err;
if (der == NULL)
return HAL_OK;
@@ -726,13 +723,18 @@ hal_error_t hal_rsa_private_key_to_der(const hal_rsa_key_t * const key,
* Encode data.
*/
- der += hlen;
+ if ((err = hal_asn1_encode_header(ASN1_SEQUENCE, vlen, der, &hlen, der_max)) != HAL_OK)
+ return err;
-#define _(x) { size_t n; if ((err = hal_asn1_encode_integer(x, der, &n, vlen)) != HAL_OK) return err; der += n; vlen -= n; }
+ uint8_t *d = der + hlen;
+ memset(d, 0, vlen);
+
+#define _(x) { size_t n; if ((err = hal_asn1_encode_integer(x, d, &n, vlen)) != HAL_OK) return err; d += n; vlen -= n; }
RSAPrivateKey_fields;
#undef _
- return HAL_OK;
+ return hal_asn1_encode_pkcs8_privatekeyinfo(hal_asn1_oid_rsaEncryption, hal_asn1_oid_rsaEncryption_len,
+ NULL, 0, der, d - der, der, der_len, der_max);
}
size_t hal_rsa_private_key_to_der_len(const hal_rsa_key_t * const key)
@@ -754,21 +756,33 @@ hal_error_t hal_rsa_private_key_from_der(hal_rsa_key_t **key_,
key->type = HAL_KEY_TYPE_RSA_PRIVATE;
- hal_error_t err = HAL_OK;
- size_t hlen, vlen;
+ size_t hlen, vlen, alg_oid_len, curve_oid_len, privkey_len;
+ const uint8_t *alg_oid, *curve_oid, *privkey;
+ hal_error_t err;
- if ((err = hal_asn1_decode_header(ASN1_SEQUENCE, der, der_len, &hlen, &vlen)) != HAL_OK)
+ if ((err = hal_asn1_decode_pkcs8_privatekeyinfo(&alg_oid, &alg_oid_len,
+ &curve_oid, &curve_oid_len,
+ &privkey, &privkey_len,
+ der, der_len)) != HAL_OK)
return err;
- der += hlen;
+ if (alg_oid_len != hal_asn1_oid_rsaEncryption_len ||
+ memcmp(alg_oid, hal_asn1_oid_rsaEncryption, alg_oid_len) != 0 ||
+ curve_oid_len != 0)
+ return HAL_ERROR_ASN1_PARSE_FAILED;
+
+ if ((err = hal_asn1_decode_header(ASN1_SEQUENCE, privkey, privkey_len, &hlen, &vlen)) != HAL_OK)
+ return err;
+
+ const uint8_t *d = privkey + hlen;
fp_int version[1] = INIT_FP_INT;
-#define _(x) { size_t i; if ((err = hal_asn1_decode_integer(x, der, &i, vlen)) != HAL_OK) return err; der += i; vlen -= i; }
+#define _(x) { size_t n; if ((err = hal_asn1_decode_integer(x, d, &n, vlen)) != HAL_OK) return err; d += n; vlen -= n; }
RSAPrivateKey_fields;
#undef _
- if (fp_cmp_d(version, 0) != FP_EQ)
+ if (d != privkey + privkey_len || !fp_iszero(version))
return HAL_ERROR_ASN1_PARSE_FAILED;
*key_ = key;
@@ -780,8 +794,6 @@ hal_error_t hal_rsa_private_key_from_der(hal_rsa_key_t **key_,
* ASN.1 public keys in SubjectPublicKeyInfo form, see RFCs 2313, 4055, and 5280.
*/
-static const uint8_t oid_rsaEncryption[] = { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 };
-
hal_error_t hal_rsa_public_key_to_der(const hal_rsa_key_t * const key,
uint8_t *der, size_t *der_len, const size_t der_max)
{
@@ -810,7 +822,7 @@ hal_error_t hal_rsa_public_key_to_der(const hal_rsa_key_t * const key,
return err;
}
- return hal_asn1_encode_spki(oid_rsaEncryption, sizeof(oid_rsaEncryption),
+ return hal_asn1_encode_spki(hal_asn1_oid_rsaEncryption, hal_asn1_oid_rsaEncryption_len,
NULL, 0, der, hlen + vlen,
der, der_len, der_max);
@@ -843,7 +855,7 @@ hal_error_t hal_rsa_public_key_from_der(hal_rsa_key_t **key_,
return err;
if (null != NULL || null_len != 0 || alg_oid == NULL ||
- alg_oid_len != sizeof(oid_rsaEncryption) || memcmp(alg_oid, oid_rsaEncryption, alg_oid_len) != 0)
+ alg_oid_len != hal_asn1_oid_rsaEncryption_len || memcmp(alg_oid, hal_asn1_oid_rsaEncryption, alg_oid_len) != 0)
return HAL_ERROR_ASN1_PARSE_FAILED;
size_t len, hlen, vlen;
diff --git a/tests/test-rpc_pkey.c b/tests/test-rpc_pkey.c
index c07a318..1f00fb8 100644
--- a/tests/test-rpc_pkey.c
+++ b/tests/test-rpc_pkey.c
@@ -98,25 +98,27 @@ static int test_attributes(const hal_pkey_handle_t pkey,
const hal_client_handle_t client = {HAL_HANDLE_NONE};
const hal_session_handle_t session = {HAL_HANDLE_NONE};
hal_uuid_t result[10], previous_uuid = {{0}};
- unsigned result_len;
+ unsigned result_len, state;
- if ((err = hal_rpc_pkey_match(client, session, HAL_KEY_TYPE_NONE, HAL_CURVE_NONE, flags, NULL, 0,
- result, &result_len, sizeof(result)/sizeof(*result),
+ state = 0;
+ if ((err = hal_rpc_pkey_match(client, session, HAL_KEY_TYPE_NONE, HAL_CURVE_NONE, 0, 0, NULL, 0,
+ &state, result, &result_len, sizeof(result)/sizeof(*result),
&previous_uuid)) != HAL_OK)
lose("Unrestricted match() failed: %s\n", hal_error_string(err));
if (result_len == 0)
lose("Unrestricted match found no results\n");
+ state = 0;
for (const size_t *size = sizes; *size; size++) {
uint8_t buf[*size];
memset(buf, 0x55, sizeof(buf));
snprintf((char *) buf, sizeof(buf), format, (unsigned long) *size);
hal_pkey_attribute_t attribute[1] = {{ *size, sizeof(buf), buf }};
- if ((err = hal_rpc_pkey_match(client, session, HAL_KEY_TYPE_NONE, HAL_CURVE_NONE, flags,
+ if ((err = hal_rpc_pkey_match(client, session, HAL_KEY_TYPE_NONE, HAL_CURVE_NONE, 0, 0,
attribute, sizeof(attribute)/sizeof(*attribute),
- result, &result_len, sizeof(result)/sizeof(*result),
+ &state, result, &result_len, sizeof(result)/sizeof(*result),
&previous_uuid)) != HAL_OK)
lose("Restricted match() for attribute %lu failed: %s\n",
(unsigned long) *size, hal_error_string(err));
@@ -177,8 +179,8 @@ static int test_rsa_testvec(const rsa_tc_t * const tc, hal_key_flags_t flags)
assert(len == sizeof(private_der));
- if ((err = hal_rpc_pkey_load(client, session, &private_key, HAL_KEY_TYPE_RSA_PRIVATE, HAL_CURVE_NONE,
- &private_name, private_der, sizeof(private_der), flags)) != HAL_OK)
+ if ((err = hal_rpc_pkey_load(client, session, &private_key, &private_name,
+ private_der, sizeof(private_der), flags)) != HAL_OK)
lose("Could not load private key into RPC: %s\n", hal_error_string(err));
if ((err = hal_rsa_public_key_to_der(tc_key, public_der, &len, sizeof(public_der))) != HAL_OK)
@@ -186,8 +188,8 @@ static int test_rsa_testvec(const rsa_tc_t * const tc, hal_key_flags_t flags)
assert(len == sizeof(public_der));
- if ((err = hal_rpc_pkey_load(client, session, &public_key, HAL_KEY_TYPE_RSA_PUBLIC, HAL_CURVE_NONE,
- &public_name, public_der, sizeof(public_der), flags)) != HAL_OK)
+ if ((err = hal_rpc_pkey_load(client, session, &public_key, &public_name,
+ public_der, sizeof(public_der), flags)) != HAL_OK)
lose("Could not load public key into RPC: %s\n", hal_error_string(err));
uint8_t sig[tc->s.len];
@@ -271,8 +273,8 @@ static int test_ecdsa_testvec(const ecdsa_tc_t * const tc, hal_key_flags_t flags
assert(len == sizeof(private_der));
- if ((err = hal_rpc_pkey_load(client, session, &private_key, HAL_KEY_TYPE_EC_PRIVATE, tc->curve,
- &private_name, private_der, sizeof(private_der), flags)) != HAL_OK)
+ if ((err = hal_rpc_pkey_load(client, session, &private_key, &private_name,
+ private_der, sizeof(private_der), flags)) != HAL_OK)
lose("Could not load private key into RPC: %s\n", hal_error_string(err));
if ((err = hal_ecdsa_public_key_to_der(tc_key, public_der, &len, sizeof(public_der))) != HAL_OK)
@@ -280,8 +282,8 @@ static int test_ecdsa_testvec(const ecdsa_tc_t * const tc, hal_key_flags_t flags
assert(len == sizeof(public_der));
- if ((err = hal_rpc_pkey_load(client, session, &public_key, HAL_KEY_TYPE_EC_PUBLIC, tc->curve,
- &public_name, public_der, sizeof(public_der), flags)) != HAL_OK)
+ if ((err = hal_rpc_pkey_load(client, session, &public_key, &public_name,
+ public_der, sizeof(public_der), flags)) != HAL_OK)
lose("Could not load public key into RPC: %s\n", hal_error_string(err));
if ((err = hal_rpc_pkey_verify(public_key, hal_hash_handle_none,
@@ -353,8 +355,8 @@ static int test_rsa_generate(const rsa_tc_t * const tc, hal_key_flags_t flags)
assert(len == sizeof(public_der));
- if ((err = hal_rpc_pkey_load(client, session, &public_key, HAL_KEY_TYPE_RSA_PUBLIC, HAL_CURVE_NONE,
- &public_name, public_der, sizeof(public_der), flags)) != HAL_OK)
+ if ((err = hal_rpc_pkey_load(client, session, &public_key, &public_name,
+ public_der, sizeof(public_der), flags)) != HAL_OK)
lose("Could not load public key into RPC: %s\n", hal_error_string(err));
uint8_t sig[tc->s.len];
@@ -429,8 +431,8 @@ static int test_ecdsa_generate(const ecdsa_tc_t * const tc, hal_key_flags_t flag
assert(len == sizeof(public_der));
- if ((err = hal_rpc_pkey_load(client, session, &public_key, HAL_KEY_TYPE_EC_PUBLIC, tc->curve,
- &public_name, public_der, sizeof(public_der), flags)) != HAL_OK)
+ if ((err = hal_rpc_pkey_load(client, session, &public_key, &public_name,
+ public_der, sizeof(public_der), flags)) != HAL_OK)
lose("Could not load public key into RPC: %s\n", hal_error_string(err));
uint8_t sig[tc->sig_len + 4];
diff --git a/unit-tests.py b/unit-tests.py
index 4fd91e6..295bf40 100644
--- a/unit-tests.py
+++ b/unit-tests.py
@@ -42,26 +42,34 @@ import datetime
import logging
import sys
+from struct import pack, unpack
+
from libhal import *
try:
- from Crypto.Util.number import inverse
- from Crypto.PublicKey import RSA
- from Crypto.Signature import PKCS1_v1_5
- from Crypto.Hash.SHA256 import SHA256Hash as SHA256
- from Crypto.Hash.SHA384 import SHA384Hash as SHA384
- from Crypto.Hash.SHA512 import SHA512Hash as SHA512
+ from Crypto.Util.number import inverse
+ from Crypto.PublicKey import RSA
+ from Crypto.Cipher import AES
+ from Crypto.Cipher.PKCS1_v1_5 import PKCS115_Cipher
+ from Crypto.Signature.PKCS1_v1_5 import PKCS115_SigScheme
+ from Crypto.Hash.SHA256 import SHA256Hash as SHA256
+ from Crypto.Hash.SHA384 import SHA384Hash as SHA384
+ from Crypto.Hash.SHA512 import SHA512Hash as SHA512
pycrypto_loaded = True
except ImportError:
pycrypto_loaded = False
try:
- from ecdsa.keys import SigningKey as ECDSA_SigningKey, VerifyingKey as ECDSA_VerifyingKey
- from ecdsa.ellipticcurve import Point
- from ecdsa.curves import NIST256p, NIST384p, NIST521p
+ from ecdsa import der as ECDSA_DER
+ from ecdsa.keys import SigningKey as ECDSA_SigningKey
+ from ecdsa.keys import VerifyingKey as ECDSA_VerifyingKey
+ from ecdsa.ellipticcurve import Point
+ from ecdsa.curves import NIST256p, NIST384p, NIST521p
+ from ecdsa.curves import find_curve as ECDSA_find_curve
+ from ecdsa.util import oid_ecPublicKey
if not pycrypto_loaded:
- from hashlib import sha256 as SHA256, sha384 as SHA384, sha512 as SHA512
+ from hashlib import sha256 as SHA256, sha384 as SHA384, sha512 as SHA512
ecdsa_loaded = True
except ImportError:
ecdsa_loaded = False
@@ -256,16 +264,16 @@ class TestPKeyGen(TestCaseLoggedIn):
k2.verify(signature = sig, data = data)
def gen_sign_verify_rsa(self, hashalg, keylen):
- k1 = hsm.pkey_generate_rsa(keylen)
+ k1 = hsm.pkey_generate_rsa(keylen, HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k1.delete)
- k2 = hsm.pkey_load(HAL_KEY_TYPE_RSA_PUBLIC, HAL_CURVE_NONE, k1.public_key)
+ k2 = hsm.pkey_load(k1.public_key, HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k2.delete)
self.sign_verify(hashalg, k1, k2)
def gen_sign_verify_ecdsa(self, hashalg, curve):
- k1 = hsm.pkey_generate_ec(curve)
+ k1 = hsm.pkey_generate_ec(curve, HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k1.delete)
- k2 = hsm.pkey_load(HAL_KEY_TYPE_EC_PUBLIC, curve, k1.public_key)
+ k2 = hsm.pkey_load(k1.public_key, HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k2.delete)
self.sign_verify(hashalg, k1, k2)
@@ -278,7 +286,7 @@ class TestPKeyGen(TestCaseLoggedIn):
def test_gen_sign_verify_ecdsa_p521_sha512(self):
self.gen_sign_verify_ecdsa(HAL_DIGEST_ALGORITHM_SHA512, HAL_CURVE_P521)
- def test_gen_sign_verify_rsa_1024_p256_sha256(self):
+ def test_gen_sign_verify_rsa_1024_sha256(self):
self.gen_sign_verify_rsa(HAL_DIGEST_ALGORITHM_SHA256, 1024)
@unittest.skipUnless(args.all_tests, "Slow")
@@ -299,20 +307,20 @@ class TestPKeyHashing(TestCaseLoggedIn):
"""
def load_sign_verify_rsa(self, alg, keylen, method):
- k1 = hsm.pkey_load(HAL_KEY_TYPE_RSA_PRIVATE, HAL_CURVE_NONE,
- PreloadedKey.db[HAL_KEY_TYPE_RSA_PRIVATE, keylen].der)
+ k1 = hsm.pkey_load(PreloadedKey.db[HAL_KEY_TYPE_RSA_PRIVATE, keylen].der,
+ HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k1.delete)
- k2 = hsm.pkey_load(HAL_KEY_TYPE_RSA_PUBLIC, HAL_CURVE_NONE,
- PreloadedKey.db[HAL_KEY_TYPE_RSA_PUBLIC, keylen].der)
+ k2 = hsm.pkey_load(PreloadedKey.db[HAL_KEY_TYPE_RSA_PUBLIC, keylen].der,
+ HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k2.delete)
method(alg, k1, k2)
def load_sign_verify_ecdsa(self, alg, curve, method):
- k1 = hsm.pkey_load(HAL_KEY_TYPE_EC_PRIVATE, curve,
- PreloadedKey.db[HAL_KEY_TYPE_EC_PRIVATE, curve].der)
+ k1 = hsm.pkey_load(PreloadedKey.db[HAL_KEY_TYPE_EC_PRIVATE, curve].der,
+ HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k1.delete)
- k2 = hsm.pkey_load(HAL_KEY_TYPE_EC_PUBLIC, curve,
- PreloadedKey.db[HAL_KEY_TYPE_EC_PUBLIC, curve].der)
+ k2 = hsm.pkey_load(PreloadedKey.db[HAL_KEY_TYPE_EC_PUBLIC, curve].der,
+ HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k2.delete)
method(alg, k1, k2)
@@ -482,9 +490,9 @@ class TestPKeyRSAInterop(TestCaseLoggedIn):
hamster = "Your mother was a hamster"
sk = PreloadedKey.db[HAL_KEY_TYPE_RSA_PRIVATE, keylen]
vk = PreloadedKey.db[HAL_KEY_TYPE_RSA_PUBLIC, keylen]
- k1 = hsm.pkey_load(HAL_KEY_TYPE_RSA_PRIVATE, HAL_CURVE_NONE, sk.der)
+ k1 = hsm.pkey_load(sk.der, HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k1.delete)
- k2 = hsm.pkey_load(HAL_KEY_TYPE_RSA_PUBLIC, HAL_CURVE_NONE, vk.der)
+ k2 = hsm.pkey_load(vk.der, HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k2.delete)
sig1 = k1.sign(hash = self.h(alg, hamster))
sig2 = sk.sign(hamster, pyhash)
@@ -517,9 +525,9 @@ class TestPKeyECDSAInterop(TestCaseLoggedIn):
hamster = "Your mother was a hamster"
sk = PreloadedKey.db[HAL_KEY_TYPE_EC_PRIVATE, curve]
vk = PreloadedKey.db[HAL_KEY_TYPE_EC_PUBLIC, curve]
- k1 = hsm.pkey_load(HAL_KEY_TYPE_EC_PRIVATE, curve, sk.der)
+ k1 = hsm.pkey_load(sk.der, HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k1.delete)
- k2 = hsm.pkey_load(HAL_KEY_TYPE_EC_PUBLIC, curve, vk.der)
+ k2 = hsm.pkey_load(vk.der, HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k2.delete)
sig1 = k1.sign(hash = self.h(alg, hamster))
sig2 = sk.sign(hamster, pyhash)
@@ -542,43 +550,54 @@ class TestPKeyMatch(TestCaseLoggedIn):
Tests involving PKey list and match functions.
"""
+ @staticmethod
+ def key_flag_names(flags):
+ names = dict(digitalsignature = HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE,
+ keyencipherment = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT,
+ dataencipherment = HAL_KEY_FLAG_USAGE_DATAENCIPHERMENT,
+ token = HAL_KEY_FLAG_TOKEN,
+ public = HAL_KEY_FLAG_PUBLIC,
+ exportable = HAL_KEY_FLAG_EXPORTABLE)
+ return ", ".join(sorted(k for k, v in names.iteritems() if (flags & v) != 0))
+
def load_keys(self, flags):
uuids = set()
for obj in PreloadedKey.db.itervalues():
- with hsm.pkey_load(obj.keytype, obj.curve, obj.der, flags) as k:
- self.addCleanup(lambda uuid: hsm.pkey_open(uuid, flags = flags).delete(), k.uuid)
+ with hsm.pkey_load(obj.der, flags) as k:
+ self.addCleanup(lambda uuid: hsm.pkey_open(uuid).delete(), k.uuid)
uuids.add(k.uuid)
+ #print k.uuid, k.key_type, k.key_curve, self.key_flag_names(k.key_flags)
k.set_attributes(dict((i, a) for i, a in enumerate((str(obj.keytype), str(obj.fn2)))))
return uuids
- def match(self, flags, **kwargs):
- uuids = kwargs.pop("uuids", None)
- kwargs.update(flags = flags)
+ def match(self, uuids, **kwargs):
n = 0
for uuid in hsm.pkey_match(**kwargs):
- if uuids is None or uuid in uuids:
- with hsm.pkey_open(uuid, flags) as k:
+ if uuid in uuids:
+ with hsm.pkey_open(uuid) as k:
n += 1
yield n, k
- def ks_match(self, flags):
+ def ks_match(self, mask, flags):
tags = []
uuids = set()
for i in xrange(2):
- uuids |= self.load_keys(flags)
+ uuids |= self.load_keys(flags if mask else HAL_KEY_FLAG_TOKEN * i)
tags.extend(PreloadedKey.db)
self.assertEqual(len(tags), len(uuids))
- self.assertEqual(uuids, set(k.uuid for n, k in self.match(flags = flags, uuids = uuids)))
+ self.assertEqual(uuids, set(k.uuid for n, k in self.match(mask = mask,
+ flags = flags,
+ uuids = uuids)))
for keytype in set(HALKeyType.index.itervalues()) - {HAL_KEY_TYPE_NONE}:
- for n, k in self.match(flags = flags, uuids = uuids, type = keytype):
+ for n, k in self.match(mask = mask, flags = flags, uuids = uuids, type = keytype):
self.assertEqual(k.key_type, keytype)
self.assertEqual(k.get_attributes({0}).pop(0), str(keytype))
self.assertEqual(n, sum(1 for t1, t2 in tags if t1 == keytype))
for curve in set(HALCurve.index.itervalues()) - {HAL_CURVE_NONE}:
- for n, k in self.match(flags = flags, uuids = uuids, curve = curve):
+ for n, k in self.match(mask = mask, flags = flags, uuids = uuids, curve = curve):
self.assertEqual(k.key_curve, curve)
self.assertEqual(k.get_attributes({1}).pop(1), str(curve))
self.assertIn(k.key_type, (HAL_KEY_TYPE_EC_PUBLIC,
@@ -586,7 +605,7 @@ class TestPKeyMatch(TestCaseLoggedIn):
self.assertEqual(n, sum(1 for t1, t2 in tags if t2 == curve))
for keylen in set(kl for kt, kl in tags if not isinstance(kl, Enum)):
- for n, k in self.match(flags = flags, uuids = uuids,
+ for n, k in self.match(mask = mask, flags = flags, uuids = uuids,
attributes = {1 : str(keylen)}):
self.assertEqual(keylen, int(k.get_attributes({1}).pop(1)))
self.assertIn(k.key_type, (HAL_KEY_TYPE_RSA_PUBLIC,
@@ -594,17 +613,20 @@ class TestPKeyMatch(TestCaseLoggedIn):
self.assertEqual(n, sum(1 for t1, t2 in tags
if not isinstance(t2, Enum) and t2 == keylen))
- for n, k in self.match(flags = flags, uuids = uuids,
+ for n, k in self.match(mask = mask, flags = flags, uuids = uuids,
type = HAL_KEY_TYPE_RSA_PUBLIC, attributes = {1 : "2048"}):
self.assertEqual(k.key_type, HAL_KEY_TYPE_RSA_PUBLIC)
self.assertEqual(n, sum(1 for t1, t2 in tags
if t1 == HAL_KEY_TYPE_RSA_PUBLIC and t2 == 2048))
def test_ks_match_token(self):
- self.ks_match(HAL_KEY_FLAG_TOKEN)
+ self.ks_match(mask = HAL_KEY_FLAG_TOKEN, flags = HAL_KEY_FLAG_TOKEN)
def test_ks_match_volatile(self):
- self.ks_match(0)
+ self.ks_match(mask = HAL_KEY_FLAG_TOKEN, flags = 0)
+
+ def test_ks_match_all(self):
+ self.ks_match(mask = 0, flags = 0)
class TestPKeyAttribute(TestCaseLoggedIn):
@@ -616,9 +638,9 @@ class TestPKeyAttribute(TestCaseLoggedIn):
pinwheel = Pinwheel()
for i in xrange(n_keys):
for obj in PreloadedKey.db.itervalues():
- with hsm.pkey_load(obj.keytype, obj.curve, obj.der, flags) as k:
+ with hsm.pkey_load(obj.der, flags) as k:
pinwheel()
- self.addCleanup(lambda uuid: hsm.pkey_open(uuid, flags = flags).delete(), k.uuid)
+ self.addCleanup(lambda uuid: hsm.pkey_open(uuid).delete(), k.uuid)
k.set_attributes(dict((j, "Attribute {}{}".format(j, "*" * n_fill))
for j in xrange(n_attrs)))
pinwheel()
@@ -644,7 +666,7 @@ class TestPKeyAttributeP11(TestCaseLoggedIn):
def setUp(self):
der = PreloadedKey.db[HAL_KEY_TYPE_EC_PRIVATE, HAL_CURVE_P256].der
- self.k = hsm.pkey_load(HAL_KEY_TYPE_EC_PRIVATE, HAL_CURVE_P256, der, HAL_KEY_FLAG_TOKEN)
+ self.k = hsm.pkey_load(der, HAL_KEY_FLAG_TOKEN)
self.addCleanup(self.k.delete)
super(TestPKeyAttributeP11, self).setUp()
@@ -709,7 +731,7 @@ class TestPKeyAttributeWriteSpeedToken(TestCaseLoggedIn):
def setUp(self):
der = PreloadedKey.db[HAL_KEY_TYPE_EC_PRIVATE, HAL_CURVE_P256].der
- self.k = hsm.pkey_load(HAL_KEY_TYPE_EC_PRIVATE, HAL_CURVE_P256, der, HAL_KEY_FLAG_TOKEN)
+ self.k = hsm.pkey_load(der, HAL_KEY_FLAG_TOKEN)
self.addCleanup(self.k.delete)
super(TestPKeyAttributeWriteSpeedToken, self).setUp()
@@ -734,7 +756,7 @@ class TestPKeyAttributeWriteSpeedVolatile(TestCaseLoggedIn):
def setUp(self):
der = PreloadedKey.db[HAL_KEY_TYPE_EC_PRIVATE, HAL_CURVE_P256].der
- self.k = hsm.pkey_load(HAL_KEY_TYPE_EC_PRIVATE, HAL_CURVE_P256, der, 0)
+ self.k = hsm.pkey_load(der, 0)
self.addCleanup(self.k.delete)
super(TestPKeyAttributeWriteSpeedVolatile, self).setUp()
@@ -759,7 +781,7 @@ class TestPKeyAttributeReadSpeedToken(TestCaseLoggedIn):
def setUp(self):
der = PreloadedKey.db[HAL_KEY_TYPE_EC_PRIVATE, HAL_CURVE_P256].der
- self.k = hsm.pkey_load(HAL_KEY_TYPE_EC_PRIVATE, HAL_CURVE_P256, der, HAL_KEY_FLAG_TOKEN)
+ self.k = hsm.pkey_load(der, HAL_KEY_FLAG_TOKEN)
self.addCleanup(self.k.delete)
self.k.set_attributes(dict((i, "Attribute {}".format(i))
for i in xrange(12)))
@@ -791,7 +813,7 @@ class TestPKeyAttributeReadSpeedVolatile(TestCaseLoggedIn):
def setUp(self):
der = PreloadedKey.db[HAL_KEY_TYPE_EC_PRIVATE, HAL_CURVE_P256].der
- self.k = hsm.pkey_load(HAL_KEY_TYPE_EC_PRIVATE, HAL_CURVE_P256, der, 0)
+ self.k = hsm.pkey_load(der, 0)
self.addCleanup(self.k.delete)
self.k.set_attributes(dict((i, "Attribute {}".format(i))
for i in xrange(12)))
@@ -822,10 +844,10 @@ class TestPkeyECDSAVerificationNIST(TestCaseLoggedIn):
ECDSA verification tests based on Suite B Implementer's Guide to FIPS 186-3.
"""
- def verify(self, Qx, Qy, H, r, s, hal_curve, py_curve, py_hash):
+ def verify(self, Qx, Qy, H, r, s, py_curve, py_hash):
Q = ECDSA_VerifyingKey.from_public_point(Point(py_curve.curve, Qx, Qy),
py_curve, py_hash).to_der()
- k = hsm.pkey_load(HAL_KEY_TYPE_EC_PUBLIC, hal_curve, Q)
+ k = hsm.pkey_load(Q, HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
self.addCleanup(k.delete)
k.verify(signature = (r + s).decode("hex"), data = H.decode("hex"))
@@ -836,7 +858,6 @@ class TestPkeyECDSAVerificationNIST(TestCaseLoggedIn):
H = "7c3e883ddc8bd688f96eac5e9324222c8f30f9d6bb59e9c5f020bd39ba2b8377",
r = "7214bc9647160bbd39ff2f80533f5dc6ddd70ddf86bb815661e805d5d4e6f27c",
s = "7d1ff961980f961bdaa3233b6209f4013317d3e3f9e1493592dbeaa1af2bc367",
- hal_curve = HAL_CURVE_P256,
py_curve = NIST256p,
py_hash = SHA256)
@@ -847,21 +868,170 @@ class TestPkeyECDSAVerificationNIST(TestCaseLoggedIn):
H = "b9210c9d7e20897ab86597266a9d5077e8db1b06f7220ed6ee75bd8b45db37891f8ba5550304004159f4453dc5b3f5a1",
r = "a0c27ec893092dea1e1bd2ccfed3cf945c8134ed0c9f81311a0f4a05942db8dbed8dd59f267471d5462aa14fe72de856",
s = "20ab3f45b74f10b6e11f96a2c8eb694d206b9dda86d3c7e331c26b22c987b7537726577667adadf168ebbe803794a402",
- hal_curve = HAL_CURVE_P384,
py_curve = NIST384p,
py_hash = SHA384)
-# Entire classes of tests still missing:
-#
-# * pkey attribute functions
-#
-# * pkey list and match functions
-#
-# * token vs session key tests
-#
-# Preloaded keys should suffice for all of these.
+@unittest.skipUnless(pycrypto_loaded, "Requires Python Crypto package")
+class TestPKeyBackup(TestCaseLoggedIn):
+
+ oid_rsaEncryption = "\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01"
+ oid_aesKeyWrap = "\x60\x86\x48\x01\x65\x03\x04\x01\x30"
+
+ @staticmethod
+ def parse_EncryptedPrivateKeyInfo(der, oid):
+ from Crypto.Util.asn1 import DerObject, DerSequence, DerOctetString, DerObjectId
+ encryptedPrivateKeyInfo = DerSequence()
+ encryptedPrivateKeyInfo.decode(der)
+ encryptionAlgorithm = DerSequence()
+ encryptionAlgorithm.decode(encryptedPrivateKeyInfo[0])
+ algorithm = DerObjectId()
+ algorithm.decode(encryptionAlgorithm[0])
+ encryptedData = DerOctetString()
+ encryptedData.decode(encryptedPrivateKeyInfo[1])
+ if algorithm.payload != oid:
+ raise ValueError
+ return encryptedData.payload
+
+ @staticmethod
+ def encode_EncryptedPrivateKeyInfo(der, oid):
+ from Crypto.Util.asn1 import DerSequence, DerOctetString
+ return DerSequence([
+ DerSequence([chr(0x06) + chr(len(oid)) + oid]).encode(),
+ DerOctetString(der).encode()
+ ]).encode()
+
+ @staticmethod
+ def make_kek():
+ import Crypto.Random
+ return Crypto.Random.new().read(256/8)
+
+ def sig_check(self, pkey, der):
+ from Crypto.Util.asn1 import DerSequence, DerNull, DerOctetString
+ p115 = PKCS115_SigScheme(RSA.importKey(der))
+ hash = SHA256("Your mother was a hamster")
+ data = DerSequence([
+ DerSequence([hash.oid, DerNull().encode()]).encode(),
+ DerOctetString(hash.digest()).encode()
+ ]).encode()
+ sig1 = p115.sign(hash)
+ sig2 = pkey.sign(data = data)
+ self.assertEqual(sig1, sig2)
+ p115.verify(hash, sig1)
+ p115.verify(hash, sig2)
+ pkey.verify(signature = sig1, data = data)
+ pkey.verify(signature = sig2, data = data)
+
+ def test_export(self):
+ kekek = hsm.pkey_load(
+ flags = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT,
+ der = PreloadedKey.db[HAL_KEY_TYPE_RSA_PUBLIC, 1024].der)
+ self.addCleanup(kekek.delete)
+ pkey = hsm.pkey_generate_rsa(
+ keylen= 1024,
+ flags = HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE | HAL_KEY_FLAG_EXPORTABLE)
+ self.addCleanup(pkey.delete)
+ pkcs8_der, kek_der = kekek.export_pkey(pkey)
+ kek = PKCS115_Cipher(PreloadedKey.db[HAL_KEY_TYPE_RSA_PRIVATE, 1024].obj).decrypt(
+ self.parse_EncryptedPrivateKeyInfo(kek_der, self.oid_rsaEncryption),
+ self.make_kek())
+ der = AESKeyWrapWithPadding(kek).unwrap(
+ self.parse_EncryptedPrivateKeyInfo(pkcs8_der, self.oid_aesKeyWrap))
+ self.sig_check(pkey, der)
+
+ def test_import(self):
+ kekek = hsm.pkey_generate_rsa(
+ keylen= 1024,
+ flags = HAL_KEY_FLAG_USAGE_KEYENCIPHERMENT)
+ self.addCleanup(kekek.delete)
+ kek = self.make_kek()
+ der = PreloadedKey.db[HAL_KEY_TYPE_RSA_PRIVATE, 1024].der
+ pkey = kekek.import_pkey(
+ pkcs8 = self.encode_EncryptedPrivateKeyInfo(
+ AESKeyWrapWithPadding(kek).wrap(der),
+ self.oid_aesKeyWrap),
+ kek = self.encode_EncryptedPrivateKeyInfo(
+ PKCS115_Cipher(RSA.importKey(kekek.public_key)).encrypt(kek),
+ self.oid_rsaEncryption),
+ flags = HAL_KEY_FLAG_USAGE_DIGITALSIGNATURE)
+ self.addCleanup(pkey.delete)
+ self.sig_check(pkey, der)
+
+
+class AESKeyWrapWithPadding(object):
+ """
+ Implementation of AES Key Wrap With Padding from RFC 5649.
+ """
+
+ class UnwrapError(Exception):
+ "Something went wrong during unwrap."
+ def __init__(self, key):
+ self.ctx = AES.new(key, AES.MODE_ECB)
+
+ def _encrypt(self, b1, b2):
+ aes_block = self.ctx.encrypt(b1 + b2)
+ return aes_block[:8], aes_block[8:]
+
+ def _decrypt(self, b1, b2):
+ aes_block = self.ctx.decrypt(b1 + b2)
+ return aes_block[:8], aes_block[8:]
+
+ @staticmethod
+ def _start_stop(start, stop): # Syntactic sugar
+ step = -1 if start > stop else 1
+ return xrange(start, stop + step, step)
+
+ def wrap(self, Q):
+ "RFC 5649 section 4.1."
+ m = len(Q) # Plaintext length
+ if m % 8 != 0: # Pad Q if needed
+ Q += "\x00" * (8 - (m % 8))
+ R = [pack(">LL", 0xa65959a6, m)] # Magic MSB(32,A), build LSB(32,A)
+ R.extend(Q[i : i + 8] # Append Q
+ for i in xrange(0, len(Q), 8))
+ n = len(R) - 1
+ if n == 1:
+ R[0], R[1] = self._encrypt(R[0], R[1])
+ else:
+ # RFC 3394 section 2.2.1
+ for j in self._start_stop(0, 5):
+ for i in self._start_stop(1, n):
+ R[0], R[i] = self._encrypt(R[0], R[i])
+ W0, W1 = unpack(">LL", R[0])
+ W1 ^= n * j + i
+ R[0] = pack(">LL", W0, W1)
+ assert len(R) == (n + 1) and all(len(r) == 8 for r in R)
+ return "".join(R)
+
+ def unwrap(self, C):
+ "RFC 5649 section 4.2."
+ if len(C) % 8 != 0:
+ raise self.UnwrapError("Ciphertext length {} is not an integral number of blocks"
+ .format(len(C)))
+ n = (len(C) / 8) - 1
+ R = [C[i : i + 8] for i in xrange(0, len(C), 8)]
+ if n == 1:
+ R[0], R[1] = self._decrypt(R[0], R[1])
+ else:
+ # RFC 3394 section 2.2.2 steps (1), (2), and part of (3)
+ for j in self._start_stop(5, 0):
+ for i in self._start_stop(n, 1):
+ W0, W1 = unpack(">LL", R[0])
+ W1 ^= n * j + i
+ R[0] = pack(">LL", W0, W1)
+ R[0], R[i] = self._decrypt(R[0], R[i])
+ magic, m = unpack(">LL", R[0])
+ if magic != 0xa65959a6:
+ raise self.UnwrapError("Magic value in AIV should have been 0xa65959a6, was 0x{:02x}"
+ .format(magic))
+ if m <= 8 * (n - 1) or m > 8 * n:
+ raise self.UnwrapError("Length encoded in AIV out of range: m {}, n {}".format(m, n))
+ R = "".join(R[1:])
+ assert len(R) == 8 * n
+ if any(r != "\x00" for r in R[m:]):
+ raise self.UnwrapError("Nonzero trailing bytes {}".format(R[m:].encode("hex")))
+ return R[:m]
class Pinwheel(object):
@@ -889,13 +1059,10 @@ class Pinwheel(object):
class PreloadedKey(object):
"""
Keys for preload tests, here at the end because they're large.
- For the moment, we use PKCS #1.5 format for RSA and secg format
- for ECDSA, because those are the formats that everything
- (including our own ASN.1 code) supports. Arguably, we should be
- using PKCS #8 to get a single, consistent, self-identifying
- private key format, but we're not there yet and it's not
- particularly urgent given widespread availablity of conversion
- tools (eg, "openssl pkcs8").
+ These are now in PKCS #8 format, which gives us a single,
+ consistent, self-identifying private key format. See tools
+ like "openssl pkcs8" if you need to convert from some other format
+ (eg, PKCS #1 or secg).
"""
db = {}
@@ -916,23 +1083,48 @@ class PreloadedRSAKey(PreloadedKey):
if pycrypto_loaded:
k1 = RSA.importKey(pem)
k2 = k1.publickey()
- cls(HAL_KEY_TYPE_RSA_PRIVATE, keylen, k1, k1.exportKey("DER"), keylen = keylen)
- cls(HAL_KEY_TYPE_RSA_PUBLIC, keylen, k2, k2.exportKey("DER"), keylen = keylen)
+ cls(HAL_KEY_TYPE_RSA_PRIVATE, keylen,
+ k1, k1.exportKey(format = "DER", pkcs = 8), keylen = keylen)
+ cls(HAL_KEY_TYPE_RSA_PUBLIC, keylen,
+ k2, k2.exportKey(format = "DER" ), keylen = keylen)
def sign(self, text, hash):
- return PKCS1_v1_5.PKCS115_SigScheme(self.obj).sign(hash(text))
+ return PKCS115_SigScheme(self.obj).sign(hash(text))
def verify(self, text, hash, signature):
- return PKCS1_v1_5.PKCS115_SigScheme(self.obj).verify(hash(text), signature)
+ return PKCS115_SigScheme(self.obj).verify(hash(text), signature)
class PreloadedECKey(PreloadedKey):
+ @staticmethod
+ def _check(condition):
+ if not condition:
+ raise ECDSA_DER.UnexpectedDER()
+
@classmethod
def importKey(cls, curve, pem):
if ecdsa_loaded:
- k1 = ECDSA_SigningKey.from_pem(pem)
+ der = ECDSA_DER.unpem(pem)
+ car, cdr = ECDSA_DER.remove_sequence(der)
+ cls._check(cdr == "")
+ version, cdr = ECDSA_DER.remove_integer(car)
+ cls._check(version == 0)
+ algid, pkinfo = ECDSA_DER.remove_sequence(cdr)
+ oid, cdr = ECDSA_DER.remove_object(algid)
+ cls._check(oid == oid_ecPublicKey)
+ oid, cdr = ECDSA_DER.remove_object(cdr)
+ sk_curve = ECDSA_find_curve(oid)
+ cls._check(cdr == "")
+ car, cdr = ECDSA_DER.remove_octet_string(pkinfo)
+ cls._check(cdr == "")
+ car, cdr = ECDSA_DER.remove_sequence(car)
+ cls._check(cdr == "")
+ version, cdr = ECDSA_DER.remove_integer(car)
+ cls._check(version == 1)
+ privkey, cdr = ECDSA_DER.remove_octet_string(cdr)
+ k1 = ECDSA_SigningKey.from_string(privkey, sk_curve)
k2 = k1.get_verifying_key()
- cls(HAL_KEY_TYPE_EC_PRIVATE, curve, k1, k1.to_der(), curve = curve)
+ cls(HAL_KEY_TYPE_EC_PRIVATE, curve, k1, der, curve = curve)
cls(HAL_KEY_TYPE_EC_PUBLIC, curve, k2, k2.to_der(), curve = curve)
def sign(self, text, hash):
@@ -944,137 +1136,141 @@ class PreloadedECKey(PreloadedKey):
# openssl genrsa 1024
PreloadedRSAKey.importKey(1024, '''\
------BEGIN RSA PRIVATE KEY-----
-MIICXQIBAAKBgQC95QlDOvlQhdCe/a7eIoX9SGPVfXfA8/62ilnF+NcwLrhxkr2R
-4EVQB65+9AbxqM8Hqol6fhZzmDs48cl2tOFGJpE8iMhiFm4i6SGl2RXYaG0xi+lJ
-FrXXCLFQovIEMuukBE129wra1xIB72tYR14lu8REX+Mhpbuz44M1jlCrlQIDAQAB
-AoGAeU928l8bZIiH9PnlG318kYkMVhd4SGjXQK/zl9hXSC2goNV4i1d1kCHIJMwq
-H3mTALe+aeVg3GnU85Tq+g2llzogoyXl8q902KbvImrM/XSbsue9/oj0OSgw+jKB
-faFzX6FxAtNV5pmU9QiwauBIl/3yPCF9ifim5zg+pWCqLaECQQD59Z/R6TrTHxp6
-w2vH4CJyP5KORcf+eMa50SAriMVBXsJzsBiLLVxKIZfWbQn9gytJqJZKmIHezZQm
-dyam84fpAkEAwnvSF27RhxLXE037+t7k5MZti6BfNTeUBrwffteepL6qax9HK+h9
-IQZ1vfNIqjZm8i7kQQyy4L8tRnk8mjZmzQJBAIUwfXWTilW+yBRMFx1M7+3itAv9
-YODWqEWRCkxIN5tqi8CrP5jBleCmX8rRFTaxcxpvq42aD/GRp3SLntvs/ikCQCSg
-GOKc1gyv+Z0DFK8cBtMmoz6mRwfInbHe/7dtd8zis0lVLJwSPm5Xvxi0ljyn3h9B
-wW6Wq6Ezn50j+8u27wkCQQCcIFE01BDAdtFHtTJ3aaEM9IdMCYrcJ0I/Y0NTE2M6
-lsTSiPyQjc4dQQJxFduvWHLx28bx+l7FTav7FaKntCJo
------END RSA PRIVATE KEY-----
+-----BEGIN PRIVATE KEY-----
+MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL3lCUM6+VCF0J79
+rt4ihf1IY9V9d8Dz/raKWcX41zAuuHGSvZHgRVAHrn70BvGozweqiXp+FnOYOzjx
+yXa04UYmkTyIyGIWbiLpIaXZF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ey -name prime256v1 | openssl ec
PreloadedECKey.importKey(HAL_CURVE_P256, '''\
------BEGIN EC PRIVATE KEY-----
-MHcCAQEEIPBrVhD1iFF2e8wPkPf4N1038iR8xPgku/CVOT8lcSztoAoGCCqGSM49
-AwEHoUQDQgAE3mB5BmN5Fa4fV74LsDWIpBUxktPqYGJ6WOBrjPs1HWkNU7JHO3qY
-9yy+CXFSPb89GWQgb5wLtNPn4QYMj+KRTA==
------END EC PRIVATE KEY-----
+-----BEGIN PRIVATE KEY-----
+MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg8GtWEPWIUXZ7zA+Q
+9/g3XTfyJHzE+CS78JU5PyVxLO2hRANCAATeYHkGY3kVrh9XvguwNYikFTGS0+pg
+YnpY4GuM+zUdaQ1Tskc7epj3LL4JcVI9vz0ZZCBvnAu00+fhBgyP4pFM
+-----END PRIVATE KEY-----
''')
# openssl ecparam -genkey -name secp384r1 | openssl ec
PreloadedECKey.importKey(HAL_CURVE_P384, '''\
------BEGIN EC PRIVATE KEY-----
-MIGkAgEBBDCVGo35Hbrf3Iys7mWRIm5yjg+6vPIgzbp2jCbDyszBo+wTxmQambG4
-g8yocp4wM6+gBwYFK4EEACKhZANiAATYwa+M8T8jsNHKmMZTvPPflUIfrjuZZo1D
-3kkkmN4r6cTNctjaeRdAfD0X40l4yPnGIP9ParuKVVl1y0TdQ7BS3g/Gj/LP33HD
-ESP8gFDIKFCWSDX0uhmy+HsGsPwgNoY=
------END EC PRIVATE KEY-----
+-----BEGIN PRIVATE KEY-----
+MIG2AgEAMBAGByqGSM49AgEGBSuBBAAiBIGeMIGbAgEBBDCVGo35Hbrf3Iys7mWR
+Im5yjg+6vPIgzbp2jCbDyszBo+wTxmQambG4g8yocp4wM6+hZANiAATYwa+M8T8j
+sNHKmMZTvPPflUIfrjuZZo1D3kkkmN4r6cTNctjaeRdAfD0X40l4yPnGIP9ParuK
+VVl1y0TdQ7BS3g/Gj/LP33HDESP8gFDIKFCWSDX0uhmy+HsGsPwgNoY=
+-----END PRIVATE KEY-----
''')
# openssl ecparam -genkey -name secp521r1 | openssl ec
PreloadedECKey.importKey(HAL_CURVE_P521, '''\
------BEGIN EC PRIVATE KEY-----
-MIHcAgEBBEIBtf+LKhJNQEJRFQ2cGQPcviwfp9IKSnD5EFTqAPtv7/+t2FtmdHHP
-/fWIlZ7jcC5N9dWy6bKGu3+FqwgZAYLpsqigBwYFK4EEACOhgYkDgYYABADdfcUe
-P0oAZQ5308v5ijcg4hePvhvVi+QKcrwmE9kirXCFoYN1tzPmXZmw8lNJenrbwaNz
-opJR84LBHnomGPogAQGF0aRk0jE8w1j1oMfrrzV6vCWnkh7pyzsDnrLU1HrkWeqw
-ihzwMzYJgFzToDH+fCh7nrBFZZZ9P9gPYMlSM5UMeA==
------END EC PRIVATE KEY-----
+-----BEGIN PRIVATE KEY-----
+MIHuAgEAMBAGByqGSM49AgEGBSuBBAAjBIHWMIHTAgEBBEIBtf+LKhJNQEJRFQ2c
+GQPcviwfp9IKSnD5EFTqAPtv7/+t2FtmdHHP/fWIlZ7jcC5N9dWy6bKGu3+FqwgZ
+AYLpsqihgYkDgYYABADdfcUeP0oAZQ5308v5ijcg4hePvhvVi+QKcrwmE9kirXCF
+oYN1tzPmXZmw8lNJenrbwaNzopJR84LBHnomGPogAQGF0aRk0jE8w1j1oMfrrzV6
+vCWnkh7pyzsDnrLU1HrkWeqwihzwMzYJgFzToDH+fCh7nrBFZZZ9P9gPYMlSM5UM
+eA==
+-----END PRIVATE KEY-----
''')