aboutsummaryrefslogtreecommitdiff
path: root/cmd/podman/sign.go
blob: 79bc3f02bdfbb7ce2f74566d2e2e3d898575800f (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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package main

import (
	"io/ioutil"
	"net/url"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"github.com/containers/image/signature"
	"github.com/containers/image/transports"
	"github.com/containers/image/transports/alltransports"
	"github.com/containers/libpod/cmd/podman/cliconfig"
	"github.com/containers/libpod/cmd/podman/libpodruntime"
	"github.com/containers/libpod/libpod/image"
	"github.com/containers/libpod/pkg/rootless"
	"github.com/containers/libpod/pkg/trust"
	"github.com/containers/libpod/pkg/util"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
)

var (
	signCommand     cliconfig.SignValues
	signDescription = "Create a signature file that can be used later to verify the image."
	_signCommand    = &cobra.Command{
		Use:   "sign [flags] IMAGE [IMAGE...]",
		Short: "Sign an image",
		Long:  signDescription,
		RunE: func(cmd *cobra.Command, args []string) error {
			signCommand.InputArgs = args
			signCommand.GlobalFlags = MainGlobalOpts
			signCommand.Remote = remoteclient
			return signCmd(&signCommand)
		},
		Example: `podman sign --sign-by mykey imageID
  podman sign --sign-by mykey --directory ./mykeydir imageID`,
	}
)

func init() {
	signCommand.Command = _signCommand
	signCommand.SetHelpTemplate(HelpTemplate())
	signCommand.SetUsageTemplate(UsageTemplate())
	flags := signCommand.Flags()
	flags.StringVarP(&signCommand.Directory, "directory", "d", "", "Define an alternate directory to store signatures")
	flags.StringVar(&signCommand.SignBy, "sign-by", "", "Name of the signing key")
	flags.StringVar(&signCommand.CertDir, "cert-dir", "", "`Pathname` of a directory containing TLS certificates and keys")
}

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

func signCmd(c *cliconfig.SignValues) error {
	args := c.InputArgs
	if len(args) < 1 {
		return errors.Errorf("at least one image name must be specified")
	}
	runtime, err := libpodruntime.GetRuntime(getContext(), &c.PodmanCommand)
	if err != nil {
		return errors.Wrapf(err, "could not create runtime")
	}
	defer runtime.DeferredShutdown(false)

	signby := c.SignBy
	if signby == "" {
		return errors.Errorf("please provide an identity")
	}

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

	sc := runtime.SystemContext()
	sc.DockerCertPath = c.CertDir

	dockerRegistryOptions := image.DockerRegistryOptions{
		DockerCertPath: c.CertDir,
	}

	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(sc)
	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(), sc)
		if err != nil {
			return errors.Wrapf(err, "error getting image source")
		}
		err = rawSource.Close()
		if err != nil {
			logrus.Errorf("unable to close new image source %q", err)
		}
		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
		rtc, err := runtime.GetConfig()
		if err != nil {
			return err
		}
		newImage, err := runtime.ImageRuntime().New(getContext(), signimage, rtc.SignaturePolicyPath, "", os.Stderr, &dockerRegistryOptions, image.SigningOptions{SignBy: signby}, nil, util.PullImageMissing)
		if err != nil {
			return errors.Wrapf(err, "error pulling image %s", signimage)
		}

		if rootless.IsRootless() {
			if sigStoreDir == "" {
				runtimeConfig, err := runtime.GetConfig()
				if err != nil {
					return err
				}

				sigStoreDir = filepath.Join(filepath.Dir(runtimeConfig.StorageConfig.GraphRoot), "sigstore")
			}
		} else {
			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, err := newImage.RepoDigests()
		if err != nil {
			return errors.Wrapf(err, "error calculating repo digests for %s", signimage)
		}
		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")
		}

		trimmedDigest := strings.TrimPrefix(repos[0], strings.Split(repos[0], "/")[0])
		sigStoreDir = filepath.Join(sigStoreDir, strings.Replace(trimmedDigest, ":", "=", 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(filepath.Join(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
}