File: cert.go

package info (click to toggle)
lxd 5.0.2%2Bgit20231211.1364ae4-9
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 25,632 kB
  • sloc: sh: 14,272; ansic: 3,112; python: 432; makefile: 265; ruby: 51; sql: 50; javascript: 9; lisp: 6
file content (59 lines) | stat: -rw-r--r-- 1,352 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
package config

import (
	"fmt"
	"io"
	"os"

	"github.com/canonical/lxd/shared"
)

// HasClientCertificate will return true if a client certificate has already been generated.
func (c *Config) HasClientCertificate() bool {
	certf := c.ConfigPath("client.crt")
	keyf := c.ConfigPath("client.key")
	if !shared.PathExists(certf) || !shared.PathExists(keyf) {
		return false
	}

	return true
}

// GenerateClientCertificate will generate the needed client.crt and client.key if needed.
func (c *Config) GenerateClientCertificate() error {
	if c.HasClientCertificate() {
		return nil
	}

	certf := c.ConfigPath("client.crt")
	keyf := c.ConfigPath("client.key")

	return shared.FindOrGenCert(certf, keyf, true, false)
}

// CopyGlobalCert will copy global (system-wide) certificate to the user config path.
func (c *Config) CopyGlobalCert(src string, dst string) error {
	oldPath := c.GlobalConfigPath("servercerts", fmt.Sprintf("%s.crt", src))
	newPath := c.ConfigPath("servercerts", fmt.Sprintf("%s.crt", dst))
	sourceFile, err := os.Open(oldPath)
	if err != nil {
		return err
	}

	defer func() { _ = sourceFile.Close() }()

	// Create new file
	newFile, err := os.Create(newPath)
	if err != nil {
		return err
	}

	defer func() { _ = newFile.Close() }()

	_, err = io.Copy(newFile, sourceFile)
	if err != nil {
		return err
	}

	return newFile.Close()
}