Files

444 lines
14 KiB
Go

package crypto11
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"fmt"
"io"
"strings"
"github.com/cockroachdb/errors"
pkcs11 "github.com/miekg/pkcs11"
)
// KeyPurpose declares the purpose for keys
type KeyPurpose int
const (
// Undefined purpose of key
Undefined KeyPurpose = 0
// Signing specifies the purpose of key to be used in signing/verification operations
Signing KeyPurpose = 1
// Encryption specifies the purpose of key to be used in encryption/decryption operations
Encryption KeyPurpose = 2
)
// Identify returns the ID and label for a PKCS#11 object.
//
// Either of these values may be used to retrieve the key for later use.
// The object's Handle is used as given; IdentifyKey, given a private key of
// this package, also recovers from a handle invalidated by a logout.
func (lib *PKCS11Lib) Identify(object *PKCS11Object) (keyID, label string, err error) {
return lib.identify(object, nil)
}
// identify is Identify with the key's identity for handle refreshes.
func (lib *PKCS11Lib) identify(object *PKCS11Object, ref *objectRef) (keyID, label string, err error) {
var a []*pkcs11.Attribute
if err = lib.withKey(object, ref, func(session pkcs11.SessionHandle, handle pkcs11.ObjectHandle) error {
// a fresh template per attempt: a failed call returns none
a, err = lib.Ctx.GetAttributeValue(session, handle, []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_ID, nil),
pkcs11.NewAttribute(pkcs11.CKA_LABEL, nil),
})
return err
}); err != nil {
return "", "", errors.WithStack(err)
}
return string(a[0].Value), string(a[1].Value), nil
}
// Find a key object. For asymmetric keys this only finds one half so
// callers will call it twice.
func (lib *PKCS11Lib) findKey(session pkcs11.SessionHandle, keyID, label string, keyclass uint, keytype uint) (pkcs11.ObjectHandle, error) {
var err error
var handles []pkcs11.ObjectHandle
template := []*pkcs11.Attribute{}
if keyclass != ^uint(0) {
template = append(template, pkcs11.NewAttribute(pkcs11.CKA_CLASS, keyclass))
}
if keytype != ^uint(0) {
template = append(template, pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, keytype))
}
if keyID != "" {
template = append(template, pkcs11.NewAttribute(pkcs11.CKA_ID, []byte(keyID)))
}
if label != "" {
template = append(template, pkcs11.NewAttribute(pkcs11.CKA_LABEL, []byte(label)))
}
if err = lib.Ctx.FindObjectsInit(session, template); err != nil {
return 0, errors.WithStack(err)
}
defer func() {
_ = lib.Ctx.FindObjectsFinal(session)
}()
if handles, _, err = lib.Ctx.FindObjects(session, 1); err != nil {
return 0, errors.WithStack(err)
}
if len(handles) == 0 {
return 0, errors.WithStack(errKeyNotFound)
}
return handles[0], nil
}
// findObjectsBatchSize is the maximum number of handles requested from a
// single C_FindObjects call.
const findObjectsBatchSize = 100
// findAllObjects drains the C_FindObjects cursor opened by FindObjectsInit.
// PKCS#11 allows a call to return fewer than the requested maximum while
// more objects remain, so enumeration continues until an empty batch is
// returned; tokens holding more than findObjectsBatchSize matching objects
// are therefore not truncated.
func (lib *PKCS11Lib) findAllObjects(session pkcs11.SessionHandle) ([]pkcs11.ObjectHandle, error) {
var all []pkcs11.ObjectHandle
for {
handles, _, err := lib.Ctx.FindObjects(session, findObjectsBatchSize)
if err != nil {
return nil, errors.WithStack(err)
}
if len(handles) == 0 {
return all, nil
}
all = append(all, handles...)
}
}
// ListKeys returns key objects on the slot matching the key class and type.
// session is owned by the caller; after Close it returns errClosed.
func (lib *PKCS11Lib) ListKeys(session pkcs11.SessionHandle, keyclass uint, keytype uint) ([]pkcs11.ObjectHandle, error) {
if err := lib.enter(); err != nil {
return nil, err
}
defer lib.exit()
return lib.listKeys(session, keyclass, keytype)
}
func (lib *PKCS11Lib) listKeys(session pkcs11.SessionHandle, keyclass uint, keytype uint) ([]pkcs11.ObjectHandle, error) {
var err error
var handles []pkcs11.ObjectHandle
template := []*pkcs11.Attribute{}
if keyclass != ^uint(0) {
template = append(template, pkcs11.NewAttribute(pkcs11.CKA_CLASS, keyclass))
}
if keytype != ^uint(0) {
template = append(template, pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, keytype))
}
if err = lib.Ctx.FindObjectsInit(session, template); err != nil {
return nil, errors.WithStack(err)
}
defer func() {
_ = lib.Ctx.FindObjectsFinal(session)
}()
if handles, err = lib.findAllObjects(session); err != nil {
return nil, err
}
return handles, nil
}
// FindKeys returns key objects on the slot matching label and key type.
// session is owned by the caller; after Close it returns errClosed.
func (lib *PKCS11Lib) FindKeys(session pkcs11.SessionHandle, keylabel string, keyclass uint, keytype uint) ([]pkcs11.ObjectHandle, error) {
if err := lib.enter(); err != nil {
return nil, err
}
defer lib.exit()
return lib.findKeys(session, keylabel, keyclass, keytype)
}
func (lib *PKCS11Lib) findKeys(session pkcs11.SessionHandle, keylabel string, keyclass uint, keytype uint) ([]pkcs11.ObjectHandle, error) {
var err error
var handles []pkcs11.ObjectHandle
template := []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_LABEL, []byte(keylabel)),
}
if keyclass != ^uint(0) {
template = append(template, pkcs11.NewAttribute(pkcs11.CKA_CLASS, keyclass))
}
if keytype != ^uint(0) {
template = append(template, pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, keytype))
}
if err = lib.Ctx.FindObjectsInit(session, template); err != nil {
return nil, errors.WithStack(err)
}
defer func() {
_ = lib.Ctx.FindObjectsFinal(session)
}()
if handles, err = lib.findAllObjects(session); err != nil {
return nil, err
}
return handles, nil
}
// FindKeyPair retrieves a previously created asymmetric key.
//
// Either (but not both) of id and label may be nil, in which case they are ignored.
func (lib *PKCS11Lib) FindKeyPair(keyID, label string) (crypto.PrivateKey, error) {
return lib.FindKeyPairOnSlot(lib.Slot.id, keyID, label)
}
// FindKeyPairOnSlot retrieves a previously created asymmetric key, using a specified slot.
//
// Either (but not both) of id and label may be nil, in which case they are ignored.
func (lib *PKCS11Lib) FindKeyPairOnSlot(slot uint, keyID, label string) (crypto.PrivateKey, error) {
var err error
var k crypto.PrivateKey
err = lib.withSession(slot, func(session pkcs11.SessionHandle) error {
k, err = lib.findKeyPairOnSession(session, slot, keyID, label)
return err
})
return k, err
}
// FindKeyPairOnSession retrieves a previously created asymmetric key, using a specified session.
//
// Either (but not both) of id and label may be nil, in which case they are ignored.
// session is owned by the caller; after Close it returns errClosed.
func (lib *PKCS11Lib) FindKeyPairOnSession(session pkcs11.SessionHandle, slot uint, keyID, label string) (crypto.PrivateKey, error) {
if err := lib.enter(); err != nil {
return nil, err
}
defer lib.exit()
return lib.findKeyPairOnSession(session, slot, keyID, label)
}
func (lib *PKCS11Lib) findKeyPairOnSession(session pkcs11.SessionHandle, slot uint, keyID, label string) (crypto.PrivateKey, error) {
var err error
var privHandle, pubHandle pkcs11.ObjectHandle
var pub crypto.PublicKey
if privHandle, err = lib.findKey(session, keyID, label, pkcs11.CKO_PRIVATE_KEY, ^uint(0)); err != nil {
return nil, errors.WithStack(err)
}
attributes := []*pkcs11.Attribute{
pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, 0),
}
if attributes, err = lib.Ctx.GetAttributeValue(session, privHandle, attributes); err != nil {
return nil, errors.WithStack(err)
}
keyType, err := bytesToUlong(attributes[0].Value)
if err != nil {
return nil, errors.WithMessage(err, "CKA_KEY_TYPE")
}
if pubHandle, err = lib.findKey(session, keyID, label, pkcs11.CKO_PUBLIC_KEY, keyType); err != nil {
return nil, errors.WithStack(err)
}
// the CKA_ID is known when the key was found by id; otherwise it is read
var id []byte
if keyID != "" {
id = []byte(keyID)
}
obj, ref, err := lib.newPrivateKeyObject(session, privHandle, slot, id)
if err != nil {
return nil, err
}
switch keyType {
case pkcs11.CKK_RSA:
if pub, err = lib.exportRSAPublicKey(session, pubHandle); err != nil {
return nil, errors.WithMessage(err, "exportRSAPublicKey")
}
return &PKCS11PrivateKeyRSA{key: &PKCS11PrivateKey{obj, pub}, lib: lib, ref: ref}, nil
case pkcs11.CKK_EC:
if pub, err = lib.exportECDSAPublicKey(session, pubHandle); err != nil {
return nil, errors.WithMessage(err, "exportECDSAPublicKey")
}
return &PKCS11PrivateKeyECDSA{key: &PKCS11PrivateKey{obj, pub}, lib: lib, ref: ref}, nil
default:
return nil, errors.WithMessagef(errUnsupportedKeyType, "key type: %v", keyType)
}
}
// ConvertToPublic converts a private key interface to crypto.PublicKey type
func ConvertToPublic(priv crypto.PrivateKey) (crypto.PublicKey, error) {
switch t := priv.(type) {
case *rsa.PrivateKey:
return t.Public(), nil
case *ecdsa.PrivateKey:
return t.Public(), nil
case *PKCS11PrivateKeyRSA:
return t.Public(), nil
case *PKCS11PrivateKeyECDSA:
return t.Public(), nil
case *privateKeyGen:
// keys returned by GenerateRSAKey/GenerateECDSAKey wrap the PKCS#11 key
return ConvertToPublic(t.PrivateKey)
}
return nil, errors.WithStack(errUnsupportedKeyType)
}
// GetKey returns private key handle
func (lib *PKCS11Lib) GetKey(keyID string) (crypto.PrivateKey, error) {
key, err := lib.FindKeyPair(keyID, "")
if err != nil {
return nil, errors.WithMessagef(err, "unable to find key %q", keyID)
}
return key, err
}
// exportKeyAdmitted is a test hook that runs in ExportKey once the operation
// holds its session, before the key lookup.
var exportKeyAdmitted = func() {}
// ExportKey returns PKCS#11 URI for specified key ID.
// It does not return key bytes.
func (lib *PKCS11Lib) ExportKey(keyID string) (string, []byte, error) {
// the lookup and the token info read are one operation, so a Close
// that starts in between waits for both instead of rejecting the lookup
var ti pkcs11.TokenInfo
err := lib.withSession(lib.Slot.id, func(session pkcs11.SessionHandle) error {
exportKeyAdmitted()
// ensure that key exists
if _, err := lib.findKeyPairOnSession(session, lib.Slot.id, keyID, ""); err != nil {
return errors.WithMessagef(err, "unable to find key %q", keyID)
}
var err error
if ti, err = lib.Ctx.GetTokenInfo(lib.Slot.id); err != nil {
return errors.WithMessage(err, "token info")
}
return nil
})
if err != nil {
return "", nil, err
}
uri := fmt.Sprintf("pkcs11:manufacturer=%s;model=%s;serial=%s;token=%s;id=%s;type=private",
lib.Config.Manufacturer(),
lib.Config.Model(),
strings.TrimSpace(ti.SerialNumber),
strings.TrimSpace(ti.Label),
strings.TrimSpace(keyID),
)
return uri, nil, nil
}
// KeyIdentifier interface provides key ID and label
type KeyIdentifier interface {
KeyID() string
Label() string
}
// PrivateKeyGen contains a reference to a loaded PKCS#11 private key object.
type privateKeyGen struct {
id string
label string
*PKCS11PrivateKey
crypto.PrivateKey
}
func (p *privateKeyGen) KeyID() string {
return p.id
}
func (p *privateKeyGen) Label() string {
return p.label
}
func (p *privateKeyGen) Public() crypto.PublicKey {
return p.PubKey
}
func (p *privateKeyGen) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
if signer, ok := p.PrivateKey.(crypto.Signer); ok {
b, err := signer.Sign(rand, digest, opts)
if err != nil {
return nil, errors.WithStack(err)
}
return b, nil
}
return nil, errors.WithStack(errUnsupportedKeyType)
}
// Decrypt decrypts ciphertext with priv.
// If opts is nil or of type *PKCS1v15DecryptOptions then PKCS#1 v1.5 decryption is performed.
// Otherwise opts must have type *OAEPOptions and OAEP decryption is done.
func (p *privateKeyGen) Decrypt(rand io.Reader, ciphertext []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) {
if decrypter, ok := p.PrivateKey.(crypto.Decrypter); ok {
b, err := decrypter.Decrypt(rand, ciphertext, opts)
if err != nil {
return nil, errors.WithStack(err)
}
return b, nil
}
return nil, errors.WithStack(errUnsupportedKeyType)
}
// GenerateRSAKey generates RSA key pair
func (lib *PKCS11Lib) GenerateRSAKey(label string, bits int, purpose int) (crypto.PrivateKey, error) {
keypurpose := KeyPurpose(purpose)
priv, err := lib.GenerateRSAKeyPairWithLabel(label, bits, keypurpose)
if err != nil {
return nil, errors.WithStack(err)
}
id, l, err := lib.identify(&priv.key.PKCS11Object, priv.ref)
if err != nil {
return nil, errors.WithStack(err)
}
k := &privateKeyGen{
id: string(id),
label: string(l),
PKCS11PrivateKey: priv.key,
PrivateKey: priv,
}
return k, nil
}
// GenerateECDSAKey generates ECDSA key pair
func (lib *PKCS11Lib) GenerateECDSAKey(label string, curve elliptic.Curve) (crypto.PrivateKey, error) {
priv, err := lib.GenerateECDSAKeyPairWithLabel(label, curve)
if err != nil {
return nil, errors.WithStack(err)
}
id, l, err := lib.identify(&priv.key.PKCS11Object, priv.ref)
if err != nil {
return nil, errors.WithStack(err)
}
k := &privateKeyGen{
id: string(id),
label: string(l),
PKCS11PrivateKey: priv.key,
PrivateKey: priv,
}
return k, nil
}
// IdentifyKey returns the ID and label for a private key.
func (lib *PKCS11Lib) IdentifyKey(priv crypto.PrivateKey) (keyID, label string, err error) {
if ki, ok := priv.(KeyIdentifier); ok {
return ki.KeyID(), ki.Label(), nil
}
var (
p11o *PKCS11Object
ref *objectRef
)
switch t := priv.(type) {
case *PKCS11PrivateKeyRSA:
p11o, ref = &t.key.PKCS11Object, t.ref
case *PKCS11PrivateKeyECDSA:
p11o, ref = &t.key.PKCS11Object, t.ref
default:
return "", "", errors.WithStack(errUnsupportedKeyType)
}
id, l, err := lib.identify(p11o, ref)
if err != nil {
return "", "", errors.WithStack(err)
}
keyID = string(id)
label = string(l)
return
}