| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package p11token |
| 18 | |
| 19 | import ( |
| 20 | "crypto" |
| 21 | "crypto/ecdsa" |
| 22 | "crypto/rand" |
| 23 | "crypto/rsa" |
| 24 | "crypto/x509" |
| 25 | "encoding/hex" |
| 26 | "errors" |
| 27 | "fmt" |
| 28 | "io" |
| 29 | |
| 30 | "github.com/miekg/pkcs11" |
| 31 | |
| 32 | "github.com/sassoftware/relic/v7/token" |
| 33 | ) |
| 34 | |
| 35 | // Common attributes for new public keys |
| 36 | var newPublicKeyAttrs = []*pkcs11.Attribute{ |
| 37 | pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PUBLIC_KEY), |
| 38 | pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true), |
| 39 | pkcs11.NewAttribute(pkcs11.CKA_PRIVATE, false), |
| 40 | pkcs11.NewAttribute(pkcs11.CKA_VERIFY, true), |
| 41 | } |
| 42 | |
| 43 | // Common attributes for new private keys |
| 44 | var newPrivateKeyAttrs = []*pkcs11.Attribute{ |
| 45 | pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_PRIVATE_KEY), |
| 46 | pkcs11.NewAttribute(pkcs11.CKA_TOKEN, true), |
| 47 | pkcs11.NewAttribute(pkcs11.CKA_PRIVATE, true), |
| 48 | pkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, true), |
| 49 | pkcs11.NewAttribute(pkcs11.CKA_EXTRACTABLE, false), |
| 50 | pkcs11.NewAttribute(pkcs11.CKA_SIGN, true), |
| 51 | } |
| 52 | |
| 53 | // Import a PKCS#8 encoded key using a random 3DES key and the Unwrap function. |
| 54 | // For some HSMs this is the only way to import keys. |
| 55 | func (tok *Token) importPkcs8(pk8 []byte, attrs []*pkcs11.Attribute) (err error) { |
| 56 | // Generate a temporary 3DES key |
| 57 | genMech := []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_DES3_KEY_GEN, nil)} |
| 58 | wrapKey, err := tok.ctx.GenerateKey(tok.sh, genMech, []*pkcs11.Attribute{ |
| 59 | pkcs11.NewAttribute(pkcs11.CKA_TOKEN, false), |
| 60 | pkcs11.NewAttribute(pkcs11.CKA_ENCRYPT, true), |
| 61 | pkcs11.NewAttribute(pkcs11.CKA_UNWRAP, true), |
| 62 | }) |
| 63 | if err != nil { |
| 64 | return err |
| 65 | } |
| 66 | defer func() { |
| 67 | err2 := tok.ctx.DestroyObject(tok.sh, wrapKey) |
| 68 | if err2 != nil && err == nil { |
| 69 | err = fmt.Errorf("destroying temporary key: %w", err2) |
| 70 | } |
| 71 | }() |
| 72 | // Encrypt key |
| 73 | iv := make([]byte, 8) |
| 74 | if _, err := io.ReadFull(rand.Reader, iv); err != nil { |
| 75 | return err |
| 76 | } |
| 77 | encMech := []*pkcs11.Mechanism{pkcs11.NewMechanism(pkcs11.CKM_DES3_CBC_PAD, iv)} |
| 78 | if err := tok.ctx.EncryptInit(tok.sh, encMech, wrapKey); err != nil { |
| 79 | return err |
| 80 | } |
| 81 | wrapped, err := tok.ctx.Encrypt(tok.sh, pk8) |
| 82 | if err != nil { |
| 83 | return err |
| 84 | } |
| 85 | // Unwrap key into token |
| 86 | if _, err := tok.ctx.UnwrapKey(tok.sh, encMech, wrapKey, wrapped, attrs); err != nil { |
| 87 | return err |
| 88 | } |
| 89 | return nil |
| 90 | } |
| 91 | |
| 92 | // Import an RSA or ECDSA private key into the token |
| 93 | func (tok *Token) Import(keyName string, privKey crypto.PrivateKey) (token.Key, error) { |
| 94 | keyConf, err := tok.config.GetKey(keyName) |
| 95 | if err != nil { |
| 96 | return nil, err |
| 97 | } |
| 98 | if keyConf.Label == "" { |
| 99 | return nil, errors.New("Key attribute 'label' must be defined in order to create an object") |
| 100 | } |
| 101 | keyID := makeKeyID() |
| 102 | if keyID == nil { |
| 103 | return nil, errors.New("failed to make key ID") |
| 104 | } |
| 105 | var pubTypeAttrs, privTypeAttrs []*pkcs11.Attribute |
| 106 | var keyType uint |
| 107 | switch priv := privKey.(type) { |
| 108 | case *rsa.PrivateKey: |
| 109 | keyType = pkcs11.CKK_RSA |
| 110 | pubTypeAttrs, privTypeAttrs, err = rsaImportAttrs(priv) |
| 111 | case *ecdsa.PrivateKey: |
| 112 | keyType = pkcs11.CKK_ECDSA |
| 113 | pubTypeAttrs, privTypeAttrs, err = ecdsaImportAttrs(priv) |
| 114 | default: |
| 115 | return nil, errors.New("Unsupported key type") |
| 116 | } |
| 117 | if err != nil { |
| 118 | return nil, err |
| 119 | } |
| 120 | commonAttrs := []*pkcs11.Attribute{ |
| 121 | pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, keyType), |
| 122 | pkcs11.NewAttribute(pkcs11.CKA_ID, keyID), |
| 123 | pkcs11.NewAttribute(pkcs11.CKA_LABEL, keyConf.Label), |
| 124 | } |
| 125 | pubAttrs := attrConcat(commonAttrs, newPublicKeyAttrs, pubTypeAttrs) |
| 126 | privAttrsSensitive := attrConcat(commonAttrs, newPrivateKeyAttrs, privTypeAttrs) |
| 127 | pubHandle, err := tok.ctx.CreateObject(tok.sh, pubAttrs) |
| 128 | if err != nil { |
| 129 | return nil, err |
| 130 | } |
| 131 | _, err = tok.ctx.CreateObject(tok.sh, privAttrsSensitive) |
| 132 | if err2, ok := err.(pkcs11.Error); ok && err2 == pkcs11.CKR_TEMPLATE_INCONSISTENT { |
| 133 | // Some HSMs don't seem to allow importing private keys directly so use |
| 134 | // key wrapping to sneak it in. Exclude the "sensitive" attrs since |
| 135 | // only the flags, label etc. are useful for Unwrap |
| 136 | privAttrsUnwrap := attrConcat(commonAttrs, newPrivateKeyAttrs) |
| 137 | var pk8 []byte |
| 138 | pk8, err = x509.MarshalPKCS8PrivateKey(privKey) |
| 139 | if err == nil { |
| 140 | err = tok.importPkcs8(pk8, privAttrsUnwrap) |
| 141 | } |
| 142 | } |
| 143 | if err != nil { |
| 144 | _ = tok.ctx.DestroyObject(tok.sh, pubHandle) |
| 145 | return nil, err |
| 146 | } |
| 147 | keyConf.ID = hex.EncodeToString(keyID) |
| 148 | return tok.getKey(keyConf, keyName) |
| 149 | } |
| 150 | |
| 151 | // Generate an RSA or ECDSA key in the token |
| 152 | func (tok *Token) Generate(keyName string, keyType token.KeyType, bits uint) (token.Key, error) { |
| 153 | tok.mutex.Lock() |
| 154 | defer tok.mutex.Unlock() |
| 155 | keyConf, err := tok.config.GetKey(keyName) |
| 156 | if err != nil { |
| 157 | return nil, err |
| 158 | } |
| 159 | if keyConf.Label == "" { |
| 160 | return nil, errors.New("Key attribute 'label' must be defined in order to create an object") |
| 161 | } |
| 162 | keyID := makeKeyID() |
| 163 | if keyID == nil { |
| 164 | return nil, errors.New("failed to make key ID") |
| 165 | } |
| 166 | var pubTypeAttrs []*pkcs11.Attribute |
| 167 | var mech *pkcs11.Mechanism |
| 168 | switch keyType { |
| 169 | case token.KeyTypeRsa: |
| 170 | pubTypeAttrs, mech, err = rsaGenerateAttrs(bits) |
| 171 | case token.KeyTypeEcdsa: |
| 172 | pubTypeAttrs, mech, err = ecdsaGenerateAttrs(bits) |
| 173 | default: |
| 174 | return nil, errors.New("Unsupported key type") |
| 175 | } |
| 176 | if err != nil { |
| 177 | return nil, err |
| 178 | } |
| 179 | commonAttrs := []*pkcs11.Attribute{ |
| 180 | pkcs11.NewAttribute(pkcs11.CKA_ID, keyID), |
| 181 | pkcs11.NewAttribute(pkcs11.CKA_LABEL, keyConf.Label), |
| 182 | } |
| 183 | pubAttrs := attrConcat(commonAttrs, newPublicKeyAttrs, pubTypeAttrs) |
| 184 | privAttrs := attrConcat(commonAttrs, newPrivateKeyAttrs) |
| 185 | if _, _, err := tok.ctx.GenerateKeyPair(tok.sh, []*pkcs11.Mechanism{mech}, pubAttrs, privAttrs); err != nil { |
| 186 | if err2, ok := err.(pkcs11.Error); ok && err2 == pkcs11.CKR_MECHANISM_INVALID && mech.Mechanism == pkcs11.CKM_RSA_X9_31_KEY_PAIR_GEN { |
| 187 | mech.Mechanism = pkcs11.CKM_RSA_PKCS_KEY_PAIR_GEN |
| 188 | if _, _, err := tok.ctx.GenerateKeyPair(tok.sh, []*pkcs11.Mechanism{mech}, pubAttrs, privAttrs); err != nil { |
| 189 | return nil, err |
| 190 | } |
| 191 | } else { |
| 192 | return nil, err |
| 193 | } |
| 194 | } |
| 195 | keyConf.ID = hex.EncodeToString(keyID) |
| 196 | return tok.getKey(keyConf, keyName) |
| 197 | } |
| 198 | |
| 199 | func attrConcat(attrSets ...[]*pkcs11.Attribute) []*pkcs11.Attribute { |
| 200 | ret := make([]*pkcs11.Attribute, 0) |
| 201 | for _, attrs := range attrSets { |
| 202 | ret = append(ret, attrs...) |
| 203 | } |
| 204 | return ret |
| 205 | } |