| 1 |
//go:build cgo && pkcs11 |
| 2 |
|
| 3 |
package pkclient |
| 4 |
|
| 5 |
import ( |
| 6 |
"encoding/asn1" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"log" |
| 10 |
"math/big" |
| 11 |
|
| 12 |
"github.com/miekg/pkcs11" |
| 13 |
"github.com/miekg/pkcs11/p11" |
| 14 |
) |
| 15 |
|
| 16 |
type PKClient struct { |
| 17 |
module p11.Module |
| 18 |
session p11.Session |
| 19 |
id []byte |
| 20 |
label []byte |
| 21 |
privKeyObj p11.Object |
| 22 |
pubKeyObj p11.Object |
| 23 |
} |
| 24 |
|
| 25 |
type ecdsaSignature struct { |
| 26 |
R, S *big.Int |
| 27 |
} |
| 28 |
|
| 29 |
// New tries to open a session with the HSM, select the slot and login to it |
| 30 |
func New(hsmPath string, slotId uint, pin string, id string, label string) (*PKClient, error) { |
| 31 |
module, err := p11.OpenModule(hsmPath) |
| 32 |
if err != nil { |
| 33 |
return nil, fmt.Errorf("failed to load module library: %s", hsmPath) |
| 34 |
} |
| 35 |
|
| 36 |
slots, err := module.Slots() |
| 37 |
if err != nil { |
| 38 |
module.Destroy() |
| 39 |
return nil, err |
| 40 |
} |
| 41 |
|
| 42 |
// Try to open a session on the slot |
| 43 |
slotIdx := 0 |
| 44 |
for i, slot := range slots { |
| 45 |
if slot.ID() == slotId { |
| 46 |
slotIdx = i |
| 47 |
break |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
client := &PKClient{ |
| 52 |
module: module, |
| 53 |
id: []byte(id), |
| 54 |
label: []byte(label), |
| 55 |
} |
| 56 |
|
| 57 |
client.session, err = slots[slotIdx].OpenWriteSession() |
| 58 |
if err != nil { |
| 59 |
module.Destroy() |
| 60 |
return nil, fmt.Errorf("failed to open session on slot %d", slotId) |
| 61 |
} |
| 62 |
|
| 63 |
if len(pin) != 0 { |
| 64 |
err = client.session.Login(pin) |
| 65 |
if err != nil { |
| 66 |
// ignore "already logged in" |
| 67 |
if !errors.Is(err, pkcs11.Error(256)) { |
| 68 |
_ = client.session.Close() |
| 69 |
return nil, fmt.Errorf("unable to login. error: %w", err) |
| 70 |
} |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
// Make sure the hsm has a private key for deriving |
| 75 |
client.privKeyObj, err = client.findDeriveKey(client.id, client.label, true) |
| 76 |
if err != nil { |
| 77 |
_ = client.Close() //log out, close session, destroy module |
| 78 |
return nil, fmt.Errorf("failed to find private key for deriving: %w", err) |
| 79 |
} |
| 80 |
|
| 81 |
return client, nil |
| 82 |
} |
| 83 |
|
| 84 |
// Close cleans up properly and logs out |
| 85 |
func (c *PKClient) Close() error { |
| 86 |
var err error = nil |
| 87 |
if c.session != nil { |
| 88 |
_ = c.session.Logout() //if logout fails, we still want to close |
| 89 |
err = c.session.Close() |
| 90 |
} |
| 91 |
|
| 92 |
c.module.Destroy() |
| 93 |
return err |
| 94 |
} |
| 95 |
|
| 96 |
// Try to find a suitable key on the hsm for key derivation |
| 97 |
// parameter GET_PUB_KEY sets the search pattern for a public or private key |
| 98 |
func (c *PKClient) findDeriveKey(id []byte, label []byte, private bool) (key p11.Object, err error) { |
| 99 |
keyClass := pkcs11.CKO_PRIVATE_KEY |
| 100 |
if !private { |
| 101 |
keyClass = pkcs11.CKO_PUBLIC_KEY |
| 102 |
} |
| 103 |
keyAttrs := []*pkcs11.Attribute{ |
| 104 |
//todo, not all HSMs seem to report this, even if its true: pkcs11.NewAttribute(pkcs11.CKA_DERIVE, true), |
| 105 |
pkcs11.NewAttribute(pkcs11.CKA_CLASS, keyClass), |
| 106 |
} |
| 107 |
|
| 108 |
if id != nil && len(id) != 0 { |
| 109 |
keyAttrs = append(keyAttrs, pkcs11.NewAttribute(pkcs11.CKA_ID, id)) |
| 110 |
} |
| 111 |
if label != nil && len(label) != 0 { |
| 112 |
keyAttrs = append(keyAttrs, pkcs11.NewAttribute(pkcs11.CKA_LABEL, label)) |
| 113 |
} |
| 114 |
|
| 115 |
return c.session.FindObject(keyAttrs) |
| 116 |
} |
| 117 |
|
| 118 |
func (c *PKClient) listDeriveKeys(id []byte, label []byte, private bool) { |
| 119 |
keyClass := pkcs11.CKO_PRIVATE_KEY |
| 120 |
if !private { |
| 121 |
keyClass = pkcs11.CKO_PUBLIC_KEY |
| 122 |
} |
| 123 |
keyAttrs := []*pkcs11.Attribute{ |
| 124 |
pkcs11.NewAttribute(pkcs11.CKA_CLASS, keyClass), |
| 125 |
} |
| 126 |
|
| 127 |
if id != nil && len(id) != 0 { |
| 128 |
keyAttrs = append(keyAttrs, pkcs11.NewAttribute(pkcs11.CKA_ID, id)) |
| 129 |
} |
| 130 |
if label != nil && len(label) != 0 { |
| 131 |
keyAttrs = append(keyAttrs, pkcs11.NewAttribute(pkcs11.CKA_LABEL, label)) |
| 132 |
} |
| 133 |
|
| 134 |
objects, err := c.session.FindObjects(keyAttrs) |
| 135 |
if err != nil { |
| 136 |
return |
| 137 |
} |
| 138 |
|
| 139 |
for _, obj := range objects { |
| 140 |
l, err := obj.Label() |
| 141 |
log.Printf("%s, %v", l, err) |
| 142 |
a, err := obj.Attribute(pkcs11.CKA_DERIVE) |
| 143 |
log.Printf("DERIVE: %s %v, %v", l, a, err) |
| 144 |
} |
| 145 |
} |
| 146 |
|
| 147 |
// SignASN1 signs some data. Returns the ASN.1 encoded signature. |
| 148 |
func (c *PKClient) SignASN1(data []byte) ([]byte, error) { |
| 149 |
mech := pkcs11.NewMechanism(pkcs11.CKM_ECDSA_SHA256, nil) |
| 150 |
sk := p11.PrivateKey(c.privKeyObj) |
| 151 |
rawSig, err := sk.Sign(*mech, data) |
| 152 |
if err != nil { |
| 153 |
return nil, err |
| 154 |
} |
| 155 |
|
| 156 |
// PKCS #11 Mechanisms v2.30: |
| 157 |
// "The signature octets correspond to the concatenation of the ECDSA values r and s, |
| 158 |
// both represented as an octet string of equal length of at most nLen with the most |
| 159 |
// significant byte first. If r and s have different octet length, the shorter of both |
| 160 |
// must be padded with leading zero octets such that both have the same octet length. |
| 161 |
// Loosely spoken, the first half of the signature is r and the second half is s." |
| 162 |
r := new(big.Int).SetBytes(rawSig[:len(rawSig)/2]) |
| 163 |
s := new(big.Int).SetBytes(rawSig[len(rawSig)/2:]) |
| 164 |
return asn1.Marshal(ecdsaSignature{r, s}) |
| 165 |
} |
| 166 |
|
| 167 |
// DeriveNoise derives a shared secret using the input public key against the private key that was found during setup. |
| 168 |
// Returns a fixed 32 byte array. |
| 169 |
func (c *PKClient) DeriveNoise(peerPubKey []byte) ([]byte, error) { |
| 170 |
// Before we call derive, we need to have an array of attributes which specify the type of |
| 171 |
// key to be returned, in our case, it's the shared secret key, produced via deriving |
| 172 |
// This template pulled from OpenSC pkclient-tool.c line 4038 |
| 173 |
attrTemplate := []*pkcs11.Attribute{ |
| 174 |
pkcs11.NewAttribute(pkcs11.CKA_TOKEN, false), |
| 175 |
pkcs11.NewAttribute(pkcs11.CKA_CLASS, pkcs11.CKO_SECRET_KEY), |
| 176 |
pkcs11.NewAttribute(pkcs11.CKA_KEY_TYPE, pkcs11.CKK_GENERIC_SECRET), |
| 177 |
pkcs11.NewAttribute(pkcs11.CKA_SENSITIVE, false), |
| 178 |
pkcs11.NewAttribute(pkcs11.CKA_EXTRACTABLE, true), |
| 179 |
pkcs11.NewAttribute(pkcs11.CKA_ENCRYPT, true), |
| 180 |
pkcs11.NewAttribute(pkcs11.CKA_DECRYPT, true), |
| 181 |
pkcs11.NewAttribute(pkcs11.CKA_WRAP, true), |
| 182 |
pkcs11.NewAttribute(pkcs11.CKA_UNWRAP, true), |
| 183 |
pkcs11.NewAttribute(pkcs11.CKA_VALUE_LEN, NoiseKeySize), |
| 184 |
} |
| 185 |
|
| 186 |
// Set up the parameters which include the peer's public key |
| 187 |
ecdhParams := pkcs11.NewECDH1DeriveParams(pkcs11.CKD_NULL, nil, peerPubKey) |
| 188 |
mech := pkcs11.NewMechanism(pkcs11.CKM_ECDH1_DERIVE, ecdhParams) |
| 189 |
sk := p11.PrivateKey(c.privKeyObj) |
| 190 |
|
| 191 |
tmpKey, err := sk.Derive(*mech, attrTemplate) |
| 192 |
if err != nil { |
| 193 |
return nil, err |
| 194 |
} |
| 195 |
if tmpKey == nil || len(tmpKey) == 0 { |
| 196 |
return nil, fmt.Errorf("got an empty secret key") |
| 197 |
} |
| 198 |
secret := make([]byte, NoiseKeySize) |
| 199 |
copy(secret[:], tmpKey[:NoiseKeySize]) |
| 200 |
return secret, nil |
| 201 |
} |
| 202 |
|
| 203 |
func (c *PKClient) GetPubKey() ([]byte, error) { |
| 204 |
d, err := c.privKeyObj.Attribute(pkcs11.CKA_PUBLIC_KEY_INFO) |
| 205 |
if err != nil { |
| 206 |
return nil, err |
| 207 |
} |
| 208 |
if d != nil && len(d) > 0 { |
| 209 |
return formatPubkeyFromPublicKeyInfoAttr(d) |
| 210 |
} |
| 211 |
c.pubKeyObj, err = c.findDeriveKey(c.id, c.label, false) |
| 212 |
if err != nil { |
| 213 |
return nil, fmt.Errorf("pkcs11 module gave us a nil CKA_PUBLIC_KEY_INFO, and looking up the public key also failed: %w", err) |
| 214 |
} |
| 215 |
d, err = c.pubKeyObj.Attribute(pkcs11.CKA_EC_POINT) |
| 216 |
if err != nil { |
| 217 |
return nil, fmt.Errorf("pkcs11 module gave us a nil CKA_PUBLIC_KEY_INFO, and reading CKA_EC_POINT also failed: %w", err) |
| 218 |
} |
| 219 |
if d == nil || len(d) < 1 { |
| 220 |
return nil, fmt.Errorf("pkcs11 module gave us a nil or empty CKA_EC_POINT") |
| 221 |
} |
| 222 |
switch len(d) { |
| 223 |
case 65: //length of 0x04 + len(X) + len(Y) |
| 224 |
return d, nil |
| 225 |
case 67: //as above, DER-encoded IIRC? |
| 226 |
return d[2:], nil |
| 227 |
default: |
| 228 |
return nil, fmt.Errorf("unknown public key length: %d", len(d)) |
| 229 |
} |
| 230 |
} |