Debian Codegraph @

noiseutil/pkcs11.go

raw
1 package noiseutil
2
3 import (
4 "crypto/ecdh"
5 "fmt"
6 "strings"
7
8 "github.com/slackhq/nebula/pkclient"
9
10 "github.com/flynn/noise"
11 )
12
13 // DHP256PKCS11 is the NIST P-256 ECDH function
14 var DHP256PKCS11 noise.DHFunc = newNISTP11Curve("P256", ecdh.P256(), 32)
15
16 type nistP11Curve struct {
17 nistCurve
18 }
19
20 func newNISTP11Curve(name string, curve ecdh.Curve, byteLen int) nistP11Curve {
21 return nistP11Curve{
22 newNISTCurve(name, curve, byteLen),
23 }
24 }
25
26 func (c nistP11Curve) DH(privkey, pubkey []byte) ([]byte, error) {
27 //for this function "privkey" is actually a pkcs11 URI
28 pkStr := string(privkey)
29
30 //to set up a handshake, we need to also do non-pkcs11-DH. Handle that here.
31 if !strings.HasPrefix(pkStr, "pkcs11:") {
32 return DHP256.DH(privkey, pubkey)
33 }
34 ecdhPubKey, err := c.curve.NewPublicKey(pubkey)
35 if err != nil {
36 return nil, fmt.Errorf("unable to unmarshal pubkey: %w", err)
37 }
38
39 //this is not the most performant way to do this (a long-lived client would be better)
40 //but, it works, and helps avoid problems with stale sessions and HSMs used by multiple users.
41 client, err := pkclient.FromUrl(pkStr)
42 if err != nil {
43 return nil, err
44 }
45 defer func(client *pkclient.PKClient) {
46 _ = client.Close()
47 }(client)
48
49 return client.DeriveNoise(ecdhPubKey.Bytes())
50 }