File: print.go

package info (click to toggle)
nebula 1.6.1%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,376 kB
  • sloc: makefile: 149; sh: 100; python: 16
file content (108 lines) | stat: -rw-r--r-- 2,314 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
package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"

	"github.com/skip2/go-qrcode"
	"github.com/slackhq/nebula/cert"
)

type printFlags struct {
	set       *flag.FlagSet
	json      *bool
	outQRPath *string
	path      *string
}

func newPrintFlags() *printFlags {
	pf := printFlags{set: flag.NewFlagSet("print", flag.ContinueOnError)}
	pf.set.Usage = func() {}
	pf.json = pf.set.Bool("json", false, "Optional: outputs certificates in json format")
	pf.outQRPath = pf.set.String("out-qr", "", "Optional: output a qr code image (png) of the certificate")
	pf.path = pf.set.String("path", "", "Required: path to the certificate")

	return &pf
}

func printCert(args []string, out io.Writer, errOut io.Writer) error {
	pf := newPrintFlags()
	err := pf.set.Parse(args)
	if err != nil {
		return err
	}

	if err := mustFlagString("path", pf.path); err != nil {
		return err
	}

	rawCert, err := ioutil.ReadFile(*pf.path)
	if err != nil {
		return fmt.Errorf("unable to read cert; %s", err)
	}

	var c *cert.NebulaCertificate
	var qrBytes []byte
	part := 0

	for {
		c, rawCert, err = cert.UnmarshalNebulaCertificateFromPEM(rawCert)
		if err != nil {
			return fmt.Errorf("error while unmarshaling cert: %s", err)
		}

		if *pf.json {
			b, _ := json.Marshal(c)
			out.Write(b)
			out.Write([]byte("\n"))

		} else {
			out.Write([]byte(c.String()))
			out.Write([]byte("\n"))
		}

		if *pf.outQRPath != "" {
			b, err := c.MarshalToPEM()
			if err != nil {
				return fmt.Errorf("error while marshalling cert to PEM: %s", err)
			}
			qrBytes = append(qrBytes, b...)
		}

		if rawCert == nil || len(rawCert) == 0 || strings.TrimSpace(string(rawCert)) == "" {
			break
		}

		part++
	}

	if *pf.outQRPath != "" {
		b, err := qrcode.Encode(string(qrBytes), qrcode.Medium, -5)
		if err != nil {
			return fmt.Errorf("error while generating qr code: %s", err)
		}

		err = ioutil.WriteFile(*pf.outQRPath, b, 0600)
		if err != nil {
			return fmt.Errorf("error while writing out-qr: %s", err)
		}
	}

	return nil
}

func printSummary() string {
	return "print <flags>: prints details about a certificate"
}

func printHelp(out io.Writer) {
	pf := newPrintFlags()
	out.Write([]byte("Usage of " + os.Args[0] + " " + printSummary() + "\n"))
	pf.set.SetOutput(out)
	pf.set.PrintDefaults()
}