summaryrefslogtreecommitdiff
path: root/cmd/podman/trust.go
blob: 863f36d09e7540b552b19fca64fe8fb403d4aac0 (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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"sort"

	"github.com/containers/image/types"
	"github.com/containers/libpod/cmd/podman/formats"
	"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/urfave/cli"
)

var (
	setTrustFlags = []cli.Flag{
		cli.StringFlag{
			Name:  "type, t",
			Usage: "Trust type, accept values: signedBy(default), accept, reject.",
			Value: "signedBy",
		},
		cli.StringSliceFlag{
			Name: "pubkeysfile, f",
			Usage: `Path of installed public key(s) to trust for TARGET.
	Absolute path to keys is added to policy.json. May
	used multiple times to define multiple public keys.
	File(s) must exist before using this command.`,
		},
		cli.StringFlag{
			Name:   "policypath",
			Hidden: true,
		},
	}
	showTrustFlags = []cli.Flag{
		cli.BoolFlag{
			Name:  "raw",
			Usage: "Output raw policy file",
		},
		cli.BoolFlag{
			Name:  "json, j",
			Usage: "Output as json",
		},
		cli.StringFlag{
			Name:   "policypath",
			Hidden: true,
		},
		cli.StringFlag{
			Name:   "registrypath",
			Hidden: true,
		},
	}

	setTrustDescription = "Set default trust policy or add a new trust policy for a registry"
	setTrustCommand     = cli.Command{
		Name:         "set",
		Usage:        "Set default trust policy or a new trust policy for a registry",
		Description:  setTrustDescription,
		Flags:        sortFlags(setTrustFlags),
		ArgsUsage:    "default | REGISTRY[/REPOSITORY]",
		Action:       setTrustCmd,
		OnUsageError: usageErrorHandler,
	}

	showTrustDescription = "Display trust policy for the system"
	showTrustCommand     = cli.Command{
		Name:                   "show",
		Usage:                  "Display trust policy for the system",
		Description:            showTrustDescription,
		Flags:                  sortFlags(showTrustFlags),
		Action:                 showTrustCmd,
		ArgsUsage:              "",
		UseShortOptionHandling: true,
		OnUsageError:           usageErrorHandler,
	}

	trustSubCommands = []cli.Command{
		setTrustCommand,
		showTrustCommand,
	}

	trustDescription = fmt.Sprintf(`Manages the trust policy of the host system. (%s)
	 Trust policy describes a registry scope that must be signed by public keys.`, getDefaultPolicyPath())
	trustCommand = cli.Command{
		Name:         "trust",
		Usage:        "Manage container image trust policy",
		Description:  trustDescription,
		ArgsUsage:    "{set,show} ...",
		Subcommands:  trustSubCommands,
		OnUsageError: usageErrorHandler,
	}
)

func showTrustCmd(c *cli.Context) error {
	runtime, err := libpodruntime.GetRuntime(c)
	if err != nil {
		return errors.Wrapf(err, "could not create runtime")
	}

	var (
		policyPath              string
		systemRegistriesDirPath string
	)
	if c.IsSet("policypath") {
		policyPath = c.String("policypath")
	} else {
		policyPath = trust.DefaultPolicyPath(runtime.SystemContext())
	}
	policyContent, err := ioutil.ReadFile(policyPath)
	if err != nil {
		return errors.Wrapf(err, "unable to read %s", policyPath)
	}
	if c.IsSet("registrypath") {
		systemRegistriesDirPath = c.String("registrypath")
	} else {
		systemRegistriesDirPath = trust.RegistriesDirPath(runtime.SystemContext())
	}

	if c.Bool("raw") {
		_, err := os.Stdout.Write(policyContent)
		if err != nil {
			return errors.Wrap(err, "could not read trust policies")
		}
		return nil
	}

	var policyContentStruct trust.PolicyContent
	if err := json.Unmarshal(policyContent, &policyContentStruct); err != nil {
		return errors.Errorf("could not read trust policies")
	}
	policyJSON, showOutputMap, err := trust.GetPolicy(policyContentStruct, systemRegistriesDirPath)
	if err != nil {
		return errors.Wrapf(err, "error reading registry config file")
	}
	if c.Bool("json") {
		var outjson interface{}
		outjson = policyJSON
		out := formats.JSONStruct{Output: outjson}
		return formats.Writer(out).Out()
	}

	sortedRepos := sortPolicyJSONKey(policyJSON)
	var output []interface{}
	for _, reponame := range sortedRepos {
		showOutput, exists := showOutputMap[reponame]
		if exists {
			output = append(output, interface{}(showOutput))
		}
	}
	out := formats.StdoutTemplateArray{Output: output, Template: "{{.Repo}}\t{{.Trusttype}}\t{{.GPGid}}\t{{.Sigstore}}"}
	return formats.Writer(out).Out()
}

func setTrustCmd(c *cli.Context) error {
	runtime, err := libpodruntime.GetRuntime(c)
	if err != nil {
		return errors.Wrapf(err, "could not create runtime")
	}

	args := c.Args()
	if len(args) != 1 {
		return errors.Errorf("default or a registry name must be specified")
	}
	valid, err := image.IsValidImageURI(args[0])
	if err != nil || !valid {
		return errors.Wrapf(err, "invalid image uri %s", args[0])
	}

	trusttype := c.String("type")
	if !isValidTrustType(trusttype) {
		return errors.Errorf("invalid choice: %s (choose from 'accept', 'reject', 'signedBy')", trusttype)
	}
	if trusttype == "accept" {
		trusttype = "insecureAcceptAnything"
	}

	pubkeysfile := c.StringSlice("pubkeysfile")
	if len(pubkeysfile) == 0 && trusttype == "signedBy" {
		return errors.Errorf("At least one public key must be defined for type 'signedBy'")
	}

	var policyPath string
	if c.IsSet("policypath") {
		policyPath = c.String("policypath")
	} else {
		policyPath = trust.DefaultPolicyPath(runtime.SystemContext())
	}
	var policyContentStruct trust.PolicyContent
	policyFileExists := false
	_, err = os.Stat(policyPath)
	if !os.IsNotExist(err) {
		policyFileExists = true
		policyContent, err := ioutil.ReadFile(policyPath)
		if err != nil {
			return errors.Wrapf(err, "unable to read %s", policyPath)
		}
		if err := json.Unmarshal(policyContent, &policyContentStruct); err != nil {
			return errors.Errorf("could not read trust policies")
		}
		if args[0] != "default" && len(policyContentStruct.Default) == 0 {
			return errors.Errorf("Default trust policy must be set.")
		}
	}
	var newReposContent []trust.RepoContent
	if len(pubkeysfile) != 0 {
		for _, filepath := range pubkeysfile {
			newReposContent = append(newReposContent, trust.RepoContent{Type: trusttype, KeyType: "GPGKeys", KeyPath: filepath})
		}
	} else {
		newReposContent = append(newReposContent, trust.RepoContent{Type: trusttype})
	}
	if args[0] == "default" {
		policyContentStruct.Default = newReposContent
	} else {
		if policyFileExists == false && len(policyContentStruct.Default) == 0 {
			return errors.Errorf("Default trust policy must be set to create the policy file.")
		}
		registryExists := false
		for transport, transportval := range policyContentStruct.Transports {
			_, registryExists = transportval[args[0]]
			if registryExists {
				policyContentStruct.Transports[transport][args[0]] = newReposContent
				break
			}
		}
		if !registryExists {
			if policyContentStruct.Transports == nil {
				policyContentStruct.Transports = make(map[string]trust.RepoMap)
			}
			if policyContentStruct.Transports["docker"] == nil {
				policyContentStruct.Transports["docker"] = make(map[string][]trust.RepoContent)
			}
			policyContentStruct.Transports["docker"][args[0]] = append(policyContentStruct.Transports["docker"][args[0]], newReposContent...)
		}
	}

	data, err := json.MarshalIndent(policyContentStruct, "", "    ")
	if err != nil {
		return errors.Wrapf(err, "error setting trust policy")
	}
	err = ioutil.WriteFile(policyPath, data, 0644)
	if err != nil {
		return errors.Wrapf(err, "error setting trust policy")
	}
	return nil
}

func sortPolicyJSONKey(m map[string]map[string]interface{}) []string {
	keys := make([]string, len(m))
	i := 0
	for k := range m {
		keys[i] = k
		i++
	}
	sort.Strings(keys)
	return keys
}

func isValidTrustType(t string) bool {
	if t == "accept" || t == "insecureAcceptAnything" || t == "reject" || t == "signedBy" {
		return true
	}
	return false
}

func getDefaultPolicyPath() string {
	return trust.DefaultPolicyPath(&types.SystemContext{})
}