aboutsummaryrefslogtreecommitdiff
path: root/cmd/podman/trust_set_show.go
blob: cd94382202bd7b795f8205b69d517390363fc592 (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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package main

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

	"github.com/containers/image/types"
	"github.com/containers/libpod/cmd/podman/cliconfig"
	"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/sirupsen/logrus"
	"github.com/spf13/cobra"
)

var (
	setTrustCommand     cliconfig.SetTrustValues
	showTrustCommand    cliconfig.ShowTrustValues
	setTrustDescription = "Set default trust policy or add a new trust policy for a registry"
	_setTrustCommand    = &cobra.Command{
		Use:     "set",
		Short:   "Set default trust policy or a new trust policy for a registry",
		Long:    setTrustDescription,
		Example: "default | REGISTRY[/REPOSITORY]",
		RunE: func(cmd *cobra.Command, args []string) error {
			setTrustCommand.InputArgs = args
			setTrustCommand.GlobalFlags = MainGlobalOpts
			return setTrustCmd(&setTrustCommand)
		},
	}

	showTrustDescription = "Display trust policy for the system"
	_showTrustCommand    = &cobra.Command{
		Use:   "show",
		Short: "Display trust policy for the system",
		Long:  showTrustDescription,
		RunE: func(cmd *cobra.Command, args []string) error {
			showTrustCommand.InputArgs = args
			showTrustCommand.GlobalFlags = MainGlobalOpts
			return showTrustCmd(&showTrustCommand)
		},
		Example: "",
	}
)

func init() {

	setTrustCommand.Command = _setTrustCommand
	showTrustCommand.Command = _showTrustCommand
	setFlags := setTrustCommand.Flags()
	setFlags.StringVar(&setTrustCommand.PolicyPath, "policypath", "", "")
	setFlags.MarkHidden("policypath")
	setFlags.StringSliceVarP(&setTrustCommand.PubKeysFile, "pubkeysfile", "f", []string{}, `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`)
	setFlags.StringVarP(&setTrustCommand.TrustType, "type", "t", "signedBy", "Trust type, accept values: signedBy(default), accept, reject")

	showFlags := showTrustCommand.Flags()
	showFlags.BoolVarP(&showTrustCommand.Json, "json", "j", false, "Output as json")
	showFlags.StringVar(&showTrustCommand.PolicyPath, "policypath", "", "")
	showFlags.BoolVar(&showTrustCommand.Raw, "raw", false, "Output raw policy file")
	showFlags.MarkHidden("policypath")
	showFlags.StringVar(&showTrustCommand.RegistryPath, "registrypath", "", "")
	showFlags.MarkHidden("registrypath")
}

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

	var (
		policyPath              string
		systemRegistriesDirPath string
		outjson                 interface{}
	)
	if c.Flag("policypath").Changed {
		policyPath = c.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.Flag("registrypath").Changed {
		systemRegistriesDirPath = c.RegistryPath
	} else {
		systemRegistriesDirPath = trust.RegistriesDirPath(runtime.SystemContext())
	}

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

	policyContentStruct, err := trust.GetPolicy(policyPath)
	if err != nil {
		return errors.Wrapf(err, "could not read trust policies")
	}

	if c.Json {
		policyJSON, err := getPolicyJSON(policyContentStruct, systemRegistriesDirPath)
		if err != nil {
			return errors.Wrapf(err, "could not show trust policies in JSON format")
		}
		outjson = policyJSON
		out := formats.JSONStruct{Output: outjson}
		return formats.Writer(out).Out()
	}

	showOutputMap, err := getPolicyShowOutput(policyContentStruct, systemRegistriesDirPath)
	if err != nil {
		return errors.Wrapf(err, "could not show trust policies")
	}
	out := formats.StdoutTemplateArray{Output: showOutputMap, Template: "{{.Repo}}\t{{.Trusttype}}\t{{.GPGid}}\t{{.Sigstore}}"}
	return formats.Writer(out).Out()
}

func setTrustCmd(c *cliconfig.SetTrustValues) error {
	runtime, err := libpodruntime.GetRuntime(&c.PodmanCommand)
	if err != nil {
		return errors.Wrapf(err, "could not create runtime")
	}
	var (
		policyPath          string
		policyContentStruct trust.PolicyContent
		newReposContent     []trust.RepoContent
	)
	args := c.InputArgs
	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.TrustType
	if !isValidTrustType(trusttype) {
		return errors.Errorf("invalid choice: %s (choose from 'accept', 'reject', 'signedBy')", trusttype)
	}
	if trusttype == "accept" {
		trusttype = "insecureAcceptAnything"
	}

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

	if c.Flag("policypath").Changed {
		policyPath = c.PolicyPath
	} else {
		policyPath = trust.DefaultPolicyPath(runtime.SystemContext())
	}
	_, err = os.Stat(policyPath)
	if !os.IsNotExist(err) {
		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 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 len(policyContentStruct.Default) == 0 {
			return errors.Errorf("Default trust policy must be set.")
		}
		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 sortShowOutputMapKey(m map[string]trust.ShowOutput) []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{})
}

func getPolicyJSON(policyContentStruct trust.PolicyContent, systemRegistriesDirPath string) (map[string]map[string]interface{}, error) {
	registryConfigs, err := trust.LoadAndMergeConfig(systemRegistriesDirPath)
	if err != nil {
		return nil, err
	}

	policyJSON := make(map[string]map[string]interface{})
	if len(policyContentStruct.Default) > 0 {
		policyJSON["* (default)"] = make(map[string]interface{})
		policyJSON["* (default)"]["type"] = policyContentStruct.Default[0].Type
	}
	for transname, transval := range policyContentStruct.Transports {
		for repo, repoval := range transval {
			policyJSON[repo] = make(map[string]interface{})
			policyJSON[repo]["type"] = repoval[0].Type
			policyJSON[repo]["transport"] = transname
			keyarr := []string{}
			uids := []string{}
			for _, repoele := range repoval {
				if len(repoele.KeyPath) > 0 {
					keyarr = append(keyarr, repoele.KeyPath)
					uids = append(uids, trust.GetGPGIdFromKeyPath(repoele.KeyPath)...)
				}
				if len(repoele.KeyData) > 0 {
					keyarr = append(keyarr, string(repoele.KeyData))
					uids = append(uids, trust.GetGPGIdFromKeyData(string(repoele.KeyData))...)
				}
			}
			policyJSON[repo]["keys"] = keyarr
			policyJSON[repo]["sigstore"] = ""
			registryNamespace := trust.HaveMatchRegistry(repo, registryConfigs)
			if registryNamespace != nil {
				policyJSON[repo]["sigstore"] = registryNamespace.SigStore
			}
		}
	}
	return policyJSON, nil
}

var typeDescription = map[string]string{"insecureAcceptAnything": "accept", "signedBy": "signed", "reject": "reject"}

func trustTypeDescription(trustType string) string {
	trustDescription, exist := typeDescription[trustType]
	if !exist {
		logrus.Warnf("invalid trust type %s", trustType)
	}
	return trustDescription
}

func getPolicyShowOutput(policyContentStruct trust.PolicyContent, systemRegistriesDirPath string) ([]interface{}, error) {
	var output []interface{}

	registryConfigs, err := trust.LoadAndMergeConfig(systemRegistriesDirPath)
	if err != nil {
		return nil, err
	}

	trustShowOutputMap := make(map[string]trust.ShowOutput)
	if len(policyContentStruct.Default) > 0 {
		defaultPolicyStruct := trust.ShowOutput{
			Repo:      "default",
			Trusttype: trustTypeDescription(policyContentStruct.Default[0].Type),
		}
		trustShowOutputMap["* (default)"] = defaultPolicyStruct
	}
	for _, transval := range policyContentStruct.Transports {
		for repo, repoval := range transval {
			tempTrustShowOutput := trust.ShowOutput{
				Repo:      repo,
				Trusttype: repoval[0].Type,
			}
			keyarr := []string{}
			uids := []string{}
			for _, repoele := range repoval {
				if len(repoele.KeyPath) > 0 {
					keyarr = append(keyarr, repoele.KeyPath)
					uids = append(uids, trust.GetGPGIdFromKeyPath(repoele.KeyPath)...)
				}
				if len(repoele.KeyData) > 0 {
					keyarr = append(keyarr, string(repoele.KeyData))
					uids = append(uids, trust.GetGPGIdFromKeyData(string(repoele.KeyData))...)
				}
			}
			tempTrustShowOutput.GPGid = strings.Join(uids, ", ")

			registryNamespace := trust.HaveMatchRegistry(repo, registryConfigs)
			if registryNamespace != nil {
				tempTrustShowOutput.Sigstore = registryNamespace.SigStore
			}
			trustShowOutputMap[repo] = tempTrustShowOutput
		}
	}

	sortedRepos := sortShowOutputMapKey(trustShowOutputMap)
	for _, reponame := range sortedRepos {
		showOutput, exists := trustShowOutputMap[reponame]
		if exists {
			output = append(output, interface{}(showOutput))
		}
	}
	return output, nil
}