File: truststore_freebsd.go

package info (click to toggle)
golang-github-smallstep-truststore 0.12.1-2
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 188 kB
  • sloc: makefile: 30; sh: 21
file content (102 lines) | stat: -rw-r--r-- 2,368 bytes parent folder | download | duplicates (2)
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
package truststore

import (
	"bytes"
	"crypto/x509"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strings"
)

var (
	// NSSProfile is the path of the Firefox profiles.
	NSSProfile = os.Getenv("HOME") + "/.mozilla/firefox/*"

	// CertutilInstallHelp is the command to add NSS support.
	CertutilInstallHelp = ""

	// SystemTrustFilename is the format used to name the root certificates.
	SystemTrustFilename string

	// SystemTrustCommand is the command used to update the system truststore.
	SystemTrustCommand []string
)

func init() {
	if !pathExists("/usr/local/etc/ssl/certs") {
		err := os.Mkdir("/usr/local/etc/ssl/certs", 0755)
		if err != nil {
			SystemTrustCommand = nil
			debug(err.Error())
			return
		}
	}
	SystemTrustCommand = []string{"certctl", "rehash"}
	SystemTrustFilename = "/usr/local/etc/ssl/certs/%s.crt"
}

func pathExists(path string) bool {
	_, err := os.Stat(path)
	return err == nil
}

func systemTrustFilename(cert *x509.Certificate) string {
	return fmt.Sprintf(SystemTrustFilename, strings.Replace(uniqueName(cert), " ", "_", -1))
}

func installPlatform(filename string, cert *x509.Certificate) error {
	if SystemTrustCommand == nil {
		return ErrNotSupported
	}

	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return err
	}

	cmd := CommandWithSudo("tee", systemTrustFilename(cert))
	cmd.Stdin = bytes.NewReader(data)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return NewCmdError(err, cmd, out)
	}

	cmd = CommandWithSudo(SystemTrustCommand...)
	out, err = cmd.CombinedOutput()
	if err != nil {
		return NewCmdError(err, cmd, out)
	}

	debug("certificate installed properly in FreeBSD trusts")
	return nil
}

func uninstallPlatform(filename string, cert *x509.Certificate) error {
	if SystemTrustCommand == nil {
		return ErrNotSupported
	}

	cmd := CommandWithSudo("rm", "-f", systemTrustFilename(cert))
	out, err := cmd.CombinedOutput()
	if err != nil {
		return NewCmdError(err, cmd, out)
	}

	cmd = CommandWithSudo(SystemTrustCommand...)
	out, err = cmd.CombinedOutput()
	if err != nil {
		return NewCmdError(err, cmd, out)
	}

	debug("certificate uninstalled properly from FreeBSD trusts")
	return nil
}

func CommandWithSudo(cmd ...string) *exec.Cmd {
	if _, err := exec.LookPath("sudo"); err != nil {
		return exec.Command(cmd[0], cmd[1:]...)
	}
	return exec.Command("sudo", append([]string{"--"}, cmd...)...)
}