File: keys.go

package info (click to toggle)
golang-github-smallstep-crypto 0.63.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,800 kB
  • sloc: sh: 66; makefile: 50
file content (242 lines) | stat: -rw-r--r-- 6,636 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
package nssdb

import (
	"context"
	"crypto/ecdh"
	"crypto/ecdsa"
	"crypto/elliptic"
	"encoding/asn1"
	"errors"
	"fmt"
	"math/big"

	"go.step.sm/crypto/internal/utils"
	"golang.org/x/crypto/cryptobyte"
)

// ASN.1 encoded OID for secp256r1 (1.2.840.10045.3.1.7), the only supported curve.
var ecParams = []byte{0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07}

func (obj Object) ToECPublicKey() (*ecdsa.PublicKey, error) {
	if err := obj.ValidateULong("CKA_CLASS", CKO_PUBLIC_KEY); err != nil {
		return nil, err
	}
	if err := obj.ValidateULong("CKA_KEY_TYPE", CKK_EC); err != nil {
		return nil, err
	}
	// TODO(areed) actually parse the params
	if err := obj.Validate("CKA_EC_PARAMS", ecParams); err != nil {
		return nil, err
	}

	ecPointASN1, ok := obj.Attributes["CKA_EC_POINT"]
	if !ok {
		return nil, errors.New("object is missing attribute CKA_EC_POINT")
	}
	var ecPoint []byte
	rest, err := asn1.Unmarshal(ecPointASN1, &ecPoint)
	if err != nil {
		return nil, fmt.Errorf("failed to decode CKA_EC_POINT: %w", err)
	} else if len(rest) > 0 {
		return nil, errors.New("failed to decode CKA_EC_POINT")
	}

	// TODO(areed) parse curve from CKA_EC_PARAMS
	pk, err := ecdh.P256().NewPublicKey(ecPoint)
	if err != nil {
		return nil, fmt.Errorf("parse CKA_EC_POINT: %w", err)
	}
	rawKey := pk.Bytes()

	return &ecdsa.PublicKey{
		Curve: elliptic.P256(),
		X:     big.NewInt(0).SetBytes(rawKey[1:33]),
		Y:     big.NewInt(0).SetBytes(rawKey[33:]),
	}, nil
}

func ecPubKeyToObject(pub *ecdsa.PublicKey, id []byte) (*Object, error) {
	uncompressedPoint := append(append([]byte{0x04}, pub.X.Bytes()...), pub.Y.Bytes()...)
	var b cryptobyte.Builder
	b.AddASN1OctetString(uncompressedPoint)
	ecPoint, err := b.Bytes()
	if err != nil {
		return nil, err
	}

	obj := &Object{
		ULongAttributes: map[string]uint32{
			"CKA_CLASS":    CKO_PUBLIC_KEY,
			"CKA_KEY_TYPE": CKK_EC,
		},
		Attributes: map[string][]byte{
			"CKA_EC_POINT":       ecPoint,
			"CKA_EC_PARAMS":      ecParams,
			"CKA_WRAP":           {0},
			"CKA_LOCAL":          {0},
			"CKA_MODIFIABLE":     {1},
			"CKA_SUBJECT":        {0xa5, 0, 0x5a},
			"CKA_START_DATE":     {0xa5, 0, 0x5a},
			"CKA_END_DATE":       {0xa5, 0, 0x5a},
			"CKA_TOKEN":          {1},
			"CKA_VERIFY":         {1},
			"CKA_VERIFY_RECOVER": {0},
			"CKA_PRIVATE":        {0},
			"CKA_ENCRYPT":        {0},
			"CKA_LABEL":          {0xa5, 0, 0x5a},
			"CKA_DERIVE":         {1},
		},
	}

	if len(id) > 0 {
		obj.Attributes["CKA_ID"] = id
	}

	return obj, nil
}

type certCN struct {
	OID        asn1.ObjectIdentifier
	CommonName string `asn1:"printable"`
}

type certCNUTF8 struct {
	OID        asn1.ObjectIdentifier
	CommonName string `asn1:"utf8"`
}

type privateKeySubject struct {
	List []any `asn1:"set"`
}

func ecPrivKeyToObject(priv *ecdsa.PrivateKey, name string, id []byte, certCNs ...string) (*Object, error) {
	pubKey, ok := priv.Public().(*ecdsa.PublicKey)
	if !ok {
		return nil, errors.New("failed to get ecdsa public key")
	}
	pubKeyBytes := append(append([]byte{0x04}, pubKey.X.Bytes()...), pubKey.Y.Bytes()...)

	obj := &Object{
		ULongAttributes: map[string]uint32{
			"CKA_CLASS":    CKO_PRIVATE_KEY,
			"CKA_KEY_TYPE": CKK_EC,
		},
		Attributes: map[string][]byte{
			"CKA_VALUE":             priv.D.Bytes(),
			"CKA_UNWRAP":            {0},
			"CKA_SIGN_RECOVER":      {1},
			"CKA_SENSITIVE":         {1},
			"CKA_DECRYPT":           {0},
			"CKA_DERIVE":            {1},
			"CKA_START_DATE":        {0xa5, 0, 0x5a},
			"CKA_END_DATE":          {0xa5, 0, 0x5a},
			"CKA_NEVER_EXTRACTABLE": {0},
			"CKA_EXTRACTABLE":       {1},
			"CKA_MODIFIABLE":        {1},
			"CKA_PRIVATE":           {1},
			"CKA_SIGN":              {1},
			"CKA_LOCAL":             {0},
			"CKA_EC_PARAMS":         ecParams,
			"CKA_NSS_DB":            pubKeyBytes,
			"CKA_TOKEN":             {1},
			"CKA_LABEL":             []byte(name),
			"CKA_ALWAYS_SENSITIVE":  {0},
		},
	}

	if len(certCNs) > 0 {
		sub := privateKeySubject{}
		for _, cn := range certCNs {
			if utils.IsPrintableString(cn, false, false) {
				sub.List = append(sub.List, certCN{
					OID:        asn1.ObjectIdentifier{2, 5, 4, 3},
					CommonName: cn,
				})
			} else {
				sub.List = append(sub.List, certCNUTF8{
					OID:        asn1.ObjectIdentifier{2, 5, 4, 3},
					CommonName: cn,
				})
			}
		}
		subASN1, err := asn1.Marshal(sub)
		if err != nil {
			return nil, fmt.Errorf("marshal CKA_SUBJECT: %w", err)
		}
		obj.Attributes["CKA_SUBJECT"] = subASN1
	}

	if len(id) > 0 {
		obj.Attributes["CKA_ID"] = id
	}

	return obj, nil
}

// AddPrivateKey adds a private key to the nssPrivate database and returns its id.
// The ckaID argument should come from the SubjectKeyID of the associated certificate.
// Keys with the same ckaID will be replaced.
// Only ecdsa keys with curve P-256 are supported.
func (db *NSSDB) AddPrivateKey(ctx context.Context, privKey *ecdsa.PrivateKey, name string, ckaID []byte, certCNs ...string) (uint32, error) {
	if privKey.Curve != elliptic.P256() {
		return 0, errors.New("unsupported curve")
	}

	if len(ckaID) > 0 {
		matches, err := db.findByAttr(ctx, CKO_PRIVATE_KEY, "CKA_ID", ckaID)
		if err != nil {
			return 0, fmt.Errorf("find cka id conflicts: %w", err)
		}
		for _, id := range matches {
			if err := db.DeleteObjectPrivate(ctx, id); err != nil {
				return 0, fmt.Errorf("delete conflicting private key %d: %w", id, err)
			}
		}
	}

	privKeyObj, err := ecPrivKeyToObject(privKey, name, ckaID, certCNs...)
	if err != nil {
		return 0, err
	}

	privKeyID, err := db.InsertPrivate(ctx, privKeyObj)
	if err != nil {
		return 0, err
	}

	return privKeyID, nil
}

// AddPublicKey adds a public key to the nssPublic database and returns its id.
// The ckaID argument should come from the SubjectKeyID of the associated certificate.
// Keys with the same ckaID will be replaced.
// Only ecdsa keys with curve P-256 are supported.
func (db *NSSDB) AddPublicKey(ctx context.Context, pubKey *ecdsa.PublicKey, ckaID []byte) (uint32, error) {
	if pubKey.Curve != elliptic.P256() {
		return 0, errors.New("unsupported curve")
	}

	if len(ckaID) > 0 {
		matches, err := db.findByAttr(ctx, CKO_PUBLIC_KEY, "CKA_ID", ckaID)
		if err != nil {
			return 0, fmt.Errorf("find cka id conflicts: %w", err)
		}
		for _, id := range matches {
			if err := db.DeleteObjectPublic(ctx, id); err != nil {
				return 0, fmt.Errorf("delete conflicting public key %d: %w", id, err)
			}
		}
	}

	pubKeyObj, err := ecPubKeyToObject(pubKey, ckaID)
	if err != nil {
		return 0, err
	}

	pubKeyID, err := db.InsertPublic(ctx, pubKeyObj)
	if err != nil {
		return 0, err
	}

	return pubKeyID, nil
}