PK: support for opaque keys

Add a new key pair object type: MBEDTLS_PK_OPAQUE, intended for
implementations of asymmetric cryptography operations that call an
external cryptographic module.

External cryptographic module engines must implement the API described
by a mbedtls_pk_info_t structure and, usually, a custom setup function.

Document the fields of the mbedtls_pk_info_t structure and the
requirements on a PK engine. Also document non-obvious aspects of the
behavior of the pk interface functions on opaque keys.

Change the interface of check_pair_func to take a pointer to a full
mbedtls_pk_context as its pub argument, and not just the data part of
the context. This is necessary because when prv is opaque, pub may
legitimately be of a different type (typically prv would be opaque and
pub would be transparent).
diff --git a/include/mbedtls/error.h b/include/mbedtls/error.h
index 4eb7b78..301b73d 100644
--- a/include/mbedtls/error.h
+++ b/include/mbedtls/error.h
@@ -74,7 +74,7 @@
  * X509      2   20
  * PKCS5     2   4 (Started from top)
  * DHM       3   9
- * PK        3   14 (Started from top)
+ * PK        3   17 (Started from top)
  * RSA       4   10
  * ECP       4   8 (Started from top)
  * MD        5   4
diff --git a/include/mbedtls/pk.h b/include/mbedtls/pk.h
index 92f43ac..0fd5ec8 100644
--- a/include/mbedtls/pk.h
+++ b/include/mbedtls/pk.h
@@ -3,7 +3,7 @@
  *
  * \brief Public Key cryptography abstraction layer
  *
- *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
+ *  Copyright (C) 2006-2017, ARM Limited, All Rights Reserved
  *  SPDX-License-Identifier: Apache-2.0
  *
  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
@@ -66,6 +66,9 @@
 #define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00  /**< Elliptic curve is unsupported (only NIST curves are supported). */
 #define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980  /**< Unavailable feature, e.g. RSA disabled for RSA key. */
 #define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH    -0x3900  /**< The signature is valid but its length is less than expected. */
+#define MBEDTLS_ERR_PK_INVALID_SIGNATURE   -0x3880  /**< Invalid signature */
+#define MBEDTLS_ERR_PK_BUFFER_TOO_SMALL    -0x3800  /**< Output buffer too small */
+#define MBEDTLS_ERR_PK_NOT_PERMITTED       -0x3780  /**< Operation not permitted */
 
 /**@}*/
 
@@ -87,6 +90,10 @@
     MBEDTLS_PK_ECDSA,           /**< ECC key pair with ECDSA context */
     MBEDTLS_PK_RSA_ALT,         /**< RSA (alternative implementation) */
     MBEDTLS_PK_RSASSA_PSS,      /**< RSA key pair; same context as MBEDTLS_PK_RSA, but used to represent keys with the algorithm identifier id-RSASSA-PSS */
+    /** Opaque key pair (cryptographic material held in an external module).
+     * This may be an RSA or ECC key or a key of an unrecognized type. Call
+     * \c mbedtls_pk_can_do() to check whether a key is of a recognized type. */
+    MBEDTLS_PK_OPAQUE,
 } mbedtls_pk_type_t;
 
 /**
@@ -216,6 +223,12 @@
  *                  MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input,
  *                  MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure.
  *
+ * \note            Engines that implement of opaque keys may offer an
+ *                  alternative setup function that take engine-dependent
+ *                  parameters. If such a function exists, call it
+ *                  instead of mbedtls_pk_setup. The implementation-specific
+ *                  setup function should call mbedtls_pk_setup internally.
+ *
  * \note            For contexts holding an RSA-alt key pair, use
  *                  \c mbedtls_pk_setup_rsa_alt() instead.
  */
@@ -448,7 +461,13 @@
  *                    is ill-formed.
  *                  * MBEDTLS_ERR_PK_TYPE_MISMATCH if the contexts cannot
  *                    represent keys of the same type.
+ *                  * MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if it is impossible
+ *                    to determine whether the keys match. This is guaranteed
+ *                    not to happen if \c prv is a transparent key pair.
  *                  * Or a type-specific error code.
+ *
+ * \note            Opaque key types may not implement this function.
+ *                  An opaque \c pub never matches a transparent \c prv.
  */
 int mbedtls_pk_check_pair( const mbedtls_pk_context *pub, const mbedtls_pk_context *prv );
 
@@ -481,6 +500,12 @@
  * \param ctx       Context to use
  *
  * \return          Type on success, or MBEDTLS_PK_NONE
+ *
+ * \note            This function returns the type of the key pair object. The
+ *                  type encodes the representation of the object as well as
+ *                  the operations that it can be used for. To test whether
+ *                  the object represents a key of a recognized type such
+ *                  as RSA or ECDSA, call \c mbedtls_pk_can_do().
  */
 mbedtls_pk_type_t mbedtls_pk_get_type( const mbedtls_pk_context *ctx );
 
diff --git a/include/mbedtls/pk_info.h b/include/mbedtls/pk_info.h
index fe2dbdf..a90e489 100644
--- a/include/mbedtls/pk_info.h
+++ b/include/mbedtls/pk_info.h
@@ -32,58 +32,196 @@
 
 #include "pk.h"
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Methods that opaque key pair objects must implement.
+ *
+ * Engines that interface with external cryptographic processors must
+ * implement this interface. Platform-specific hardware accelerators
+ * that can be used for all keys of a given type should use alternative
+ * ("xxx_alt") interfaces instead. This interface allows using different
+ * engines for each key.
+ *
+ * An engine for asymmetric cryptography must implement the interface
+ * described in this structure. The interface for the engine may be
+ * exposed in one of two ways:
+ *
+ * - Declare the mbedtls_pk_info_t structure and instruct users to call
+ *   mbedtls_pk_setup with that structure.
+ * - Keep the mbedtls_pk_info_t structure hidden and declare a function
+ *   to call instead of mbedtls_pk_setup. This function should have an
+ *   interface of the form
+ *    `int mbedtls_pk_setup_myengine(mbedtls_pk_context *, ...)`
+ *   where the extra parameters depend on the engine, e.g. handles to keys
+ *   stored in an external cryptographic module.
+ *
+ * Unless otherwise indicated, functions returning int must return an
+ * Mbed TLS status code, either 0 for success or a negative value to indicate
+ * an error. It is recommended to use the MBEDTLS_ERR_PK_XXX error codes
+ * defined in pk.h.
+ *
+ * Some methods are optional; this is clearly indicated in their description.
+ * If a method is optional, then an opaque key implementation may put NULL
+ * in the corresponding field. The corresponding function in pk.h will
+ * return MBEDTLS_ERR_PK_TYPE_MISMATCH in this case.
+ *
+ * \note If you are using the PK interface to perform operations on
+ * keys, call the functions in pk.h. The interface in this file should only
+ * be used by implementers of opaque key engines.
+ */
 struct mbedtls_pk_info_t
 {
-    /** Key pair type with indication of supported algorithms */
+    /** Key pair type.
+     *
+     * mbedtls_pk_get_type() returns this value.
+     *
+     * For transparent keys, this contains an indication of supported
+     * algorithms. For opaque keys, this is \c MBEDTLS_PK_OPAQUE. */
     mbedtls_pk_type_t type;
 
-    /** Type name */
+    /** Type name.
+     *
+     * mbedtls_pk_get_name() returns this value. It must be a
+     * null-terminated string.
+     *
+     * For transparent keys, this reflects the key type. For opaque keys,
+     * this reflects the cryptographic module driver. */
     const char *name;
 
-    /** Get key size in bits */
+    /** Get key size in bits.
+     *
+     * mbedtls_pk_get_bitlen() returns this value.
+     *
+     * This function cannot fail. */
     size_t (*get_bitlen)( const void *ctx );
 
-    /** Tell if the context implements this type (e.g. ECKEY can do ECDSA) */
+    /** Tell if the context implements this type (e.g.\ ECKEY can do ECDSA).
+     *
+     * mbedtls_pk_can_do() calls this function.
+     *
+     * This function is only based on the key type. It does not take any
+     * usage restrictions into account. */
     int (*can_do)( const void * ctx, mbedtls_pk_type_t type );
 
-    /** Verify signature */
+    /** Verify signature
+     *
+     * mbedtls_pk_verify() calls this function.
+     *
+     * Opaque implementations may omit this method if they do not support
+     * signature verification. */
     int (*verify_func)( void *ctx, mbedtls_md_type_t md_alg,
                         const unsigned char *hash, size_t hash_len,
                         const unsigned char *sig, size_t sig_len );
 
-    /** Make signature */
+    /** Make signature
+     *
+     * mbedtls_pk_sign() calls this function.
+     *
+     * Assume that the buffer \c sig has room for
+     * \c signature_size_func(ctx) bytes.
+     *
+     * The arguments \c f_rng and \c p_rng are provided in case the
+     * algorithm requires randomization. Implementations are not
+     * required to use it if they have their own random source. If \c
+     * f_rng is null, the implementation should operate if it can, and
+     * return #MBEDTLS_ERR_PK_BAD_INPUT_DATA otherwise.
+     *
+     * Opaque implementations may omit this method if they do not support
+     * signature. */
     int (*sign_func)( void *ctx, mbedtls_md_type_t md_alg,
                       const unsigned char *hash, size_t hash_len,
                       unsigned char *sig, size_t *sig_len,
                       int (*f_rng)(void *, unsigned char *, size_t),
                       void *p_rng );
 
-    /** Decrypt message */
+    /** Decrypt message
+     *
+     * mbedtls_pk_decrypt() calls this function.
+     *
+     * The arguments \c f_rng and \c p_rng are provided in case the
+     * algorithm requires randomization. Implementations are not
+     * required to use it if they have their own random source. If \c
+     * f_rng is null, the implementation should operate if it can, and
+     * return #MBEDTLS_ERR_PK_BAD_INPUT_DATA otherwise.
+     *
+     * Opaque implementations may omit this method if they do not support
+     * decryption. */
     int (*decrypt_func)( void *ctx, const unsigned char *input, size_t ilen,
                          unsigned char *output, size_t *olen, size_t osize,
                          int (*f_rng)(void *, unsigned char *, size_t),
                          void *p_rng );
 
-    /** Encrypt message */
+    /** Encrypt message
+     *
+     * mbedtls_pk_decrypt() calls this function.
+     *
+     * The arguments \c f_rng and \c p_rng are provided in case the
+     * algorithm requires randomization. Implementations are not
+     * required to use it if they have their own random source. If \c
+     * f_rng is null, the implementation should operate if it can, and
+     * return #MBEDTLS_ERR_PK_BAD_INPUT_DATA otherwise.
+     *
+     * Opaque implementations may omit this method if they do not support
+     * encryption. */
     int (*encrypt_func)( void *ctx, const unsigned char *input, size_t ilen,
                          unsigned char *output, size_t *olen, size_t osize,
                          int (*f_rng)(void *, unsigned char *, size_t),
                          void *p_rng );
 
-    /** Check public-private key pair */
-    int (*check_pair_func)( const void *pub, const void *prv );
+    /** Check public-private key pair
+     *
+     * mbedtls_pk_check_pair() calls this function on the private key pair
+     * object \c prv. The other argument \c pub may be of any type, but it
+     * is guaranteed to be initialized.
+     *
+     * Opaque implementations may omit this method. */
+    int (*check_pair_func)( const mbedtls_pk_context *pub, const void *prv );
 
-    /** Allocate a new context */
+    /** Allocate a new context
+     *
+     * mbedtls_pk_setup() calls this function.
+     *
+     * If this function returns NULL, the allocation is considered to
+     * have failed and the the object remains uninitialized.
+     *
+     * Opaque implementations may omit this method. In this case,
+     * mbedtls_pk_setup will set the \c pk_ctx field of the mbedtls_pk_context
+     * object to NULL, and it is up to an engine-specific setup function to
+     * initialize the \c pk_ctx field. This is useful if the size of the
+     * memory depends on extra parameters passed to the engine-specific setup
+     * function. */
     void * (*ctx_alloc_func)( void );
 
-    /** Free the given context */
+    /** Free the given context
+     *
+     * mbedtls_pk_free() calls this function. It must free the data allocated
+     * by \b ctx_alloc_func as well as any other resource that belongs to
+     * the object.
+     * */
     void (*ctx_free_func)( void *ctx );
 
-    /** Interface with the debug module */
+    /** Interface with the debug module
+     *
+     * mbedtls_pk_debug() calls this function.
+     *
+     * Opaque implementations may omit this method. */
     void (*debug_func)( const void *ctx, mbedtls_pk_debug_item *items );
 
-    /** Signature size */
+    /** Signature size
+     *
+     * mbedtls_pk_signature_size() returns this value.
+     *
+     * Opaque implementations may omit this method. In this case, the value
+     * returned by \c get_bitlen (rounded up to a whole number of bytes)
+     * is used instead. */
     size_t (*signature_size_func)( const void *ctx );
 };
 
+#ifdef __cplusplus
+}
+#endif
+
 #endif /* MBEDTLS_PK_INFO_H */