Debian Codegraph @

cmd/nebula-cert/ca.go

raw
1 package main
2
3 import (
4 "crypto/ecdsa"
5 "crypto/elliptic"
6 "crypto/rand"
7 "flag"
8 "fmt"
9 "io"
10 "math"
11 "net/netip"
12 "os"
13 "strings"
14 "time"
15
16 "github.com/skip2/go-qrcode"
17 "github.com/slackhq/nebula/cert"
18 "github.com/slackhq/nebula/pkclient"
19 "golang.org/x/crypto/ed25519"
20 )
21
22 type caFlags struct {
23 set *flag.FlagSet
24 name *string
25 duration *time.Duration
26 outKeyPath *string
27 outCertPath *string
28 outQRPath *string
29 groups *string
30 networks *string
31 unsafeNetworks *string
32 argonMemory *uint
33 argonIterations *uint
34 argonParallelism *uint
35 encryption *bool
36 version *uint
37
38 curve *string
39 p11url *string
40
41 // Deprecated options
42 ips *string
43 subnets *string
44 }
45
46 func newCaFlags() *caFlags {
47 cf := caFlags{set: flag.NewFlagSet("ca", flag.ContinueOnError)}
48 cf.set.Usage = func() {}
49 cf.name = cf.set.String("name", "", "Required: name of the certificate authority")
50 cf.version = cf.set.Uint("version", uint(cert.Version2), "Optional: version of the certificate format to use")
51 cf.duration = cf.set.Duration("duration", time.Duration(time.Hour*8760), "Optional: amount of time the certificate should be valid for. Valid time units are seconds: \"s\", minutes: \"m\", hours: \"h\"")
52 cf.outKeyPath = cf.set.String("out-key", "ca.key", "Optional: path to write the private key to")
53 cf.outCertPath = cf.set.String("out-crt", "ca.crt", "Optional: path to write the certificate to")
54 cf.outQRPath = cf.set.String("out-qr", "", "Optional: output a qr code image (png) of the certificate")
55 cf.groups = cf.set.String("groups", "", "Optional: comma separated list of groups. This will limit which groups subordinate certs can use")
56 cf.networks = cf.set.String("networks", "", "Optional: comma separated list of ip address and network in CIDR notation. This will limit which ip addresses and networks subordinate certs can use in networks")
57 cf.unsafeNetworks = cf.set.String("unsafe-networks", "", "Optional: comma separated list of ip address and network in CIDR notation. This will limit which ip addresses and networks subordinate certs can use in unsafe networks")
58 cf.argonMemory = cf.set.Uint("argon-memory", 2*1024*1024, "Optional: Argon2 memory parameter (in KiB) used for encrypted private key passphrase")
59 cf.argonParallelism = cf.set.Uint("argon-parallelism", 4, "Optional: Argon2 parallelism parameter used for encrypted private key passphrase")
60 cf.argonIterations = cf.set.Uint("argon-iterations", 1, "Optional: Argon2 iterations parameter used for encrypted private key passphrase")
61 cf.encryption = cf.set.Bool("encrypt", false, "Optional: prompt for passphrase and write out-key in an encrypted format")
62 cf.curve = cf.set.String("curve", "25519", "EdDSA/ECDSA Curve (25519, P256)")
63 cf.p11url = p11Flag(cf.set)
64
65 cf.ips = cf.set.String("ips", "", "Deprecated, see -networks")
66 cf.subnets = cf.set.String("subnets", "", "Deprecated, see -unsafe-networks")
67 return &cf
68 }
69
70 func parseArgonParameters(memory uint, parallelism uint, iterations uint) (*cert.Argon2Parameters, error) {
71 if memory <= 0 || memory > math.MaxUint32 {
72 return nil, newHelpErrorf("-argon-memory must be be greater than 0 and no more than %d KiB", uint32(math.MaxUint32))
73 }
74 if parallelism <= 0 || parallelism > math.MaxUint8 {
75 return nil, newHelpErrorf("-argon-parallelism must be be greater than 0 and no more than %d", math.MaxUint8)
76 }
77 if iterations <= 0 || iterations > math.MaxUint32 {
78 return nil, newHelpErrorf("-argon-iterations must be be greater than 0 and no more than %d", uint32(math.MaxUint32))
79 }
80
81 return cert.NewArgon2Parameters(uint32(memory), uint8(parallelism), uint32(iterations)), nil
82 }
83
84 func ca(args []string, out io.Writer, errOut io.Writer, pr PasswordReader) error {
85 cf := newCaFlags()
86 err := cf.set.Parse(args)
87 if err != nil {
88 return err
89 }
90
91 isP11 := len(*cf.p11url) > 0
92
93 if err := mustFlagString("name", cf.name); err != nil {
94 return err
95 }
96 if !isP11 {
97 if err = mustFlagString("out-key", cf.outKeyPath); err != nil {
98 return err
99 }
100 } else {
101 // out-key is meaningless under PKCS#11 because the private key never
102 // leaves the HSM; reject it so we never silently accept or claim a
103 // stdout slot for it.
104 outKeySet := false
105 cf.set.Visit(func(f *flag.Flag) {
106 if f.Name == "out-key" {
107 outKeySet = true
108 }
109 })
110 if outKeySet {
111 return newHelpErrorf("cannot set -out-key with -pkcs11")
112 }
113 }
114 if err := mustFlagString("out-crt", cf.outCertPath); err != nil {
115 return err
116 }
117 var kdfParams *cert.Argon2Parameters
118 if !isP11 && *cf.encryption {
119 if kdfParams, err = parseArgonParameters(*cf.argonMemory, *cf.argonParallelism, *cf.argonIterations); err != nil {
120 return err
121 }
122 }
123
124 if *cf.duration <= 0 {
125 return &helpError{"-duration must be greater than 0"}
126 }
127
128 var groups []string
129 if *cf.groups != "" {
130 for _, rg := range strings.Split(*cf.groups, ",") {
131 g := strings.TrimSpace(rg)
132 if g != "" {
133 groups = append(groups, g)
134 }
135 }
136 }
137
138 version := cert.Version(*cf.version)
139 if version != cert.Version1 && version != cert.Version2 {
140 return newHelpErrorf("-version must be either %v or %v", cert.Version1, cert.Version2)
141 }
142
143 var networks []netip.Prefix
144 if *cf.networks == "" && *cf.ips != "" {
145 // Pull up deprecated -ips flag if needed
146 *cf.networks = *cf.ips
147 }
148
149 if *cf.networks != "" {
150 for _, rs := range strings.Split(*cf.networks, ",") {
151 rs := strings.Trim(rs, " ")
152 if rs != "" {
153 n, err := netip.ParsePrefix(rs)
154 if err != nil {
155 return newHelpErrorf("invalid -networks definition: %s", rs)
156 }
157 if version == cert.Version1 && !n.Addr().Is4() {
158 return newHelpErrorf("invalid -networks definition: v1 certificates can only be ipv4, have %s", rs)
159 }
160 networks = append(networks, n)
161 }
162 }
163 }
164
165 var unsafeNetworks []netip.Prefix
166 if *cf.unsafeNetworks == "" && *cf.subnets != "" {
167 // Pull up deprecated -subnets flag if needed
168 *cf.unsafeNetworks = *cf.subnets
169 }
170
171 if *cf.unsafeNetworks != "" {
172 for _, rs := range strings.Split(*cf.unsafeNetworks, ",") {
173 rs := strings.Trim(rs, " ")
174 if rs != "" {
175 n, err := netip.ParsePrefix(rs)
176 if err != nil {
177 return newHelpErrorf("invalid -unsafe-networks definition: %s", rs)
178 }
179 if version == cert.Version1 && !n.Addr().Is4() {
180 return newHelpErrorf("invalid -unsafe-networks definition: v1 certificates can only be ipv4, have %s", rs)
181 }
182 unsafeNetworks = append(unsafeNetworks, n)
183 }
184 }
185 }
186
187 var claims ioClaims
188 if err := reserveOutputs(&claims,
189 "out-key", *cf.outKeyPath,
190 "out-crt", *cf.outCertPath,
191 "out-qr", *cf.outQRPath,
192 ); err != nil {
193 return err
194 }
195
196 var passphrase []byte
197 if !isP11 && *cf.encryption {
198 passphrase = []byte(os.Getenv("NEBULA_CA_PASSPHRASE"))
199 if len(passphrase) == 0 {
200 for i := 0; i < 5; i++ {
201 errOut.Write([]byte("Enter passphrase: "))
202 passphrase, err = pr.ReadPassword()
203
204 if err == ErrNoTerminal {
205 return fmt.Errorf("out-key must be encrypted interactively")
206 } else if err != nil {
207 return fmt.Errorf("error reading passphrase: %s", err)
208 }
209
210 if len(passphrase) > 0 {
211 break
212 }
213 }
214
215 if len(passphrase) == 0 {
216 return fmt.Errorf("no passphrase specified, remove -encrypt flag to write out-key in plaintext")
217 }
218 }
219 }
220
221 var curve cert.Curve
222 var pub, rawPriv []byte
223 var p11Client *pkclient.PKClient
224
225 if isP11 {
226 switch *cf.curve {
227 case "P256":
228 curve = cert.Curve_P256
229 default:
230 return fmt.Errorf("invalid curve for PKCS#11: %s", *cf.curve)
231 }
232
233 p11Client, err = pkclient.FromUrl(*cf.p11url)
234 if err != nil {
235 return fmt.Errorf("error while creating PKCS#11 client: %w", err)
236 }
237 defer func(client *pkclient.PKClient) {
238 _ = client.Close()
239 }(p11Client)
240 pub, err = p11Client.GetPubKey()
241 if err != nil {
242 return fmt.Errorf("error while getting public key with PKCS#11: %w", err)
243 }
244 } else {
245 switch *cf.curve {
246 case "25519", "X25519", "Curve25519", "CURVE25519":
247 curve = cert.Curve_CURVE25519
248 pub, rawPriv, err = ed25519.GenerateKey(rand.Reader)
249 if err != nil {
250 return fmt.Errorf("error while generating ed25519 keys: %s", err)
251 }
252 case "P256":
253 var key *ecdsa.PrivateKey
254 curve = cert.Curve_P256
255 key, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
256 if err != nil {
257 return fmt.Errorf("error while generating ecdsa keys: %s", err)
258 }
259
260 // ecdh.PrivateKey lets us get at the encoded bytes, even though
261 // we aren't using ECDH here.
262 eKey, err := key.ECDH()
263 if err != nil {
264 return fmt.Errorf("error while converting ecdsa key: %s", err)
265 }
266 rawPriv = eKey.Bytes()
267 pub = eKey.PublicKey().Bytes()
268 default:
269 return fmt.Errorf("invalid curve: %s", *cf.curve)
270 }
271 }
272
273 t := &cert.TBSCertificate{
274 Version: version,
275 Name: *cf.name,
276 Groups: groups,
277 Networks: networks,
278 UnsafeNetworks: unsafeNetworks,
279 NotBefore: time.Now(),
280 NotAfter: time.Now().Add(*cf.duration),
281 PublicKey: pub,
282 IsCA: true,
283 Curve: curve,
284 }
285
286 if !isP11 && !isStdio(*cf.outKeyPath) {
287 if _, err := os.Stat(*cf.outKeyPath); err == nil {
288 return fmt.Errorf("refusing to overwrite existing CA key: %s", *cf.outKeyPath)
289 }
290 }
291
292 if !isStdio(*cf.outCertPath) {
293 if _, err := os.Stat(*cf.outCertPath); err == nil {
294 return fmt.Errorf("refusing to overwrite existing CA cert: %s", *cf.outCertPath)
295 }
296 }
297
298 var c cert.Certificate
299 var b []byte
300
301 if isP11 {
302 c, err = t.SignWith(nil, curve, p11Client.SignASN1)
303 if err != nil {
304 return fmt.Errorf("error while signing with PKCS#11: %w", err)
305 }
306 } else {
307 c, err = t.Sign(nil, curve, rawPriv)
308 if err != nil {
309 return fmt.Errorf("error while signing: %s", err)
310 }
311
312 if *cf.encryption {
313 b, err = cert.EncryptAndMarshalSigningPrivateKey(curve, rawPriv, passphrase, kdfParams)
314 if err != nil {
315 return fmt.Errorf("error while encrypting out-key: %s", err)
316 }
317 } else {
318 b = cert.MarshalSigningPrivateKeyToPEM(curve, rawPriv)
319 }
320
321 err = writeOutput(*cf.outKeyPath, b, 0600, out)
322 if err != nil {
323 return fmt.Errorf("error while writing out-key: %s", err)
324 }
325 }
326
327 b, err = c.MarshalPEM()
328 if err != nil {
329 return fmt.Errorf("error while marshalling certificate: %s", err)
330 }
331
332 err = writeOutput(*cf.outCertPath, b, 0600, out)
333 if err != nil {
334 return fmt.Errorf("error while writing out-crt: %s", err)
335 }
336
337 if *cf.outQRPath != "" {
338 b, err = qrcode.Encode(string(b), qrcode.Medium, -5)
339 if err != nil {
340 return fmt.Errorf("error while generating qr code: %s", err)
341 }
342
343 err = writeOutput(*cf.outQRPath, b, 0600, out)
344 if err != nil {
345 return fmt.Errorf("error while writing out-qr: %s", err)
346 }
347 }
348
349 return nil
350 }
351
352 func caSummary() string {
353 return "ca <flags>: create a self signed certificate authority"
354 }
355
356 func caHelp(out io.Writer) {
357 cf := newCaFlags()
358 out.Write([]byte("Usage of " + os.Args[0] + " " + caSummary() + "\n"))
359 out.Write([]byte(stdioHelpText))
360 cf.set.SetOutput(out)
361 cf.set.PrintDefaults()
362 }