summaryrefslogtreecommitdiff
path: root/cmd/podman/sign.go
blob: 790b6031de90eacc89766e33562fb7e804a6d569 (plain)
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package main

import (
	"fmt"
	"io/ioutil"
	"net/url"
	"os"
	"strconv"
	"strings"

	"github.com/containers/image/signature"
	"github.com/containers/image/transports"
	"github.com/containers/image/transports/alltransports"
	"github.com/containers/libpod/cmd/podman/libpodruntime"
	"github.com/containers/libpod/libpod/image"
	"github.com/containers/libpod/pkg/trust"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli"
)

var (
	signFlags = []cli.Flag{
		cli.StringFlag{
			Name:  "sign-by",
			Usage: "Name of the signing key",
		},
		cli.StringFlag{
			Name:  "directory, d",
			Usage: "Define an alternate directory to store signatures",
		},
	}

	signDescription = "Create a signature file that can be used later to verify the image"
	signCommand     = cli.Command{
		Name:         "sign",
		Usage:        "Sign an image",
		Description:  signDescription,
		Flags:        sortFlags(signFlags),
		Action:       signCmd,
		ArgsUsage:    "IMAGE-NAME [IMAGE-NAME ...]",
		OnUsageError: usageErrorHandler,
	}
)

// SignatureStoreDir defines default directory to store signatures
const SignatureStoreDir = "/var/lib/containers/sigstore"

func signCmd(c *cli.Context) error {
	args := c.Args()
	if len(args) < 1 {
		return errors.Errorf("at least one image name must be specified")
	}
	runtime, err := libpodruntime.GetRuntime(c)
	if err != nil {
		return errors.Wrapf(err, "could not create runtime")
	}
	defer runtime.Shutdown(false)

	signby := c.String("sign-by")
	if signby == "" {
		return errors.Errorf("You must provide an identity")
	}

	var sigStoreDir string
	if c.IsSet("directory") {
		sigStoreDir = c.String("directory")
		if _, err := os.Stat(sigStoreDir); err != nil {
			return errors.Wrapf(err, "invalid directory %s", sigStoreDir)
		}
	}

	mech, err := signature.NewGPGSigningMechanism()
	if err != nil {
		return errors.Wrap(err, "Error initializing GPG")
	}
	defer mech.Close()
	if err := mech.SupportsSigning(); err != nil {
		return errors.Wrap(err, "Signing is not supported")
	}

	systemRegistriesDirPath := trust.RegistriesDirPath(runtime.SystemContext())
	registryConfigs, err := trust.LoadAndMergeConfig(systemRegistriesDirPath)
	if err != nil {
		return errors.Wrapf(err, "error reading registry configuration")
	}

	for _, signimage := range args {
		srcRef, err := alltransports.ParseImageName(signimage)
		if err != nil {
			return errors.Wrapf(err, "error parsing image name")
		}
		rawSource, err := srcRef.NewImageSource(getContext(), runtime.SystemContext())
		if err != nil {
			return errors.Wrapf(err, "error getting image source")
		}
		manifest, _, err := rawSource.GetManifest(getContext(), nil)
		if err != nil {
			return errors.Wrapf(err, "error getting manifest")
		}
		dockerReference := rawSource.Reference().DockerReference()
		if dockerReference == nil {
			return errors.Errorf("Cannot determine canonical Docker reference for destination %s", transports.ImageName(rawSource.Reference()))
		}

		// create the signstore file
		newImage, err := runtime.ImageRuntime().New(getContext(), signimage, runtime.GetConfig().SignaturePolicyPath, "", os.Stderr, nil, image.SigningOptions{SignBy: signby}, false)
		if err != nil {
			return errors.Wrapf(err, "error pulling image %s", signimage)
		}

		registryInfo := trust.HaveMatchRegistry(rawSource.Reference().DockerReference().String(), registryConfigs)
		if registryInfo != nil {
			if sigStoreDir == "" {
				sigStoreDir = registryInfo.SigStoreStaging
				if sigStoreDir == "" {
					sigStoreDir = registryInfo.SigStore
				}
			}
			sigStoreDir, err = isValidSigStoreDir(sigStoreDir)
			if err != nil {
				return errors.Wrapf(err, "invalid signature storage %s", sigStoreDir)
			}
		}
		if sigStoreDir == "" {
			sigStoreDir = SignatureStoreDir
		}

		repos := newImage.RepoDigests()
		if len(repos) == 0 {
			logrus.Errorf("no repodigests associated with the image %s", signimage)
			continue
		}

		// create signature
		newSig, err := signature.SignDockerManifest(manifest, dockerReference.String(), mech, signby)
		if err != nil {
			return errors.Wrapf(err, "error creating new signature")
		}

		sigStoreDir = fmt.Sprintf("%s/%s", sigStoreDir, strings.Replace(repos[0][strings.Index(repos[0], "/")+1:len(repos[0])], ":", "=", 1))
		if err := os.MkdirAll(sigStoreDir, 0751); err != nil {
			// The directory is allowed to exist
			if !os.IsExist(err) {
				logrus.Errorf("error creating directory %s: %s", sigStoreDir, err)
				continue
			}
		}
		sigFilename, err := getSigFilename(sigStoreDir)
		if err != nil {
			logrus.Errorf("error creating sigstore file: %v", err)
			continue
		}
		err = ioutil.WriteFile(sigStoreDir+"/"+sigFilename, newSig, 0644)
		if err != nil {
			logrus.Errorf("error storing signature for %s", rawSource.Reference().DockerReference().String())
			continue
		}
	}
	return nil
}

func getSigFilename(sigStoreDirPath string) (string, error) {
	sigFileSuffix := 1
	sigFiles, err := ioutil.ReadDir(sigStoreDirPath)
	if err != nil {
		return "", err
	}
	sigFilenames := make(map[string]bool)
	for _, file := range sigFiles {
		sigFilenames[file.Name()] = true
	}
	for {
		sigFilename := "signature-" + strconv.Itoa(sigFileSuffix)
		if _, exists := sigFilenames[sigFilename]; !exists {
			return sigFilename, nil
		}
		sigFileSuffix++
	}
}

func isValidSigStoreDir(sigStoreDir string) (string, error) {
	writeURIs := map[string]bool{"file": true}
	url, err := url.Parse(sigStoreDir)
	if err != nil {
		return sigStoreDir, errors.Wrapf(err, "invalid directory %s", sigStoreDir)
	}
	_, exists := writeURIs[url.Scheme]
	if !exists {
		return sigStoreDir, errors.Errorf("Writing to %s is not supported. Use a supported scheme", sigStoreDir)
	}
	sigStoreDir = url.Path
	return sigStoreDir, nil
}