Debian Codegraph @

verifier/trustpolicy/trustpolicy.go

raw
1 // Copyright The Notary Project Authors.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package trustpolicy provides functionalities for trust policy document
15 // and trust policy statements.
16 package trustpolicy
17
18 import (
19 "encoding/json"
20 "errors"
21 "fmt"
22 "io/fs"
23 "os"
24 "strings"
25
26 "github.com/notaryproject/notation-go/dir"
27 "github.com/notaryproject/notation-go/internal/file"
28 "github.com/notaryproject/notation-go/internal/pkix"
29 "github.com/notaryproject/notation-go/internal/slices"
30 "github.com/notaryproject/notation-go/internal/trustpolicy"
31 "github.com/notaryproject/notation-go/verifier/truststore"
32 )
33
34 // trustPolicyLink is a tutorial link for creating Notation's trust policy.
35 const trustPolicyLink = "https://notaryproject.dev/docs/quickstart/#create-a-trust-policy"
36
37 // ValidationType is an enum for signature verification types such as Integrity,
38 // Authenticity, etc.
39 type ValidationType string
40
41 // ValidationAction is an enum for signature verification actions such as
42 // Enforced, Logged, Skipped.
43 type ValidationAction string
44
45 // VerificationLevel encapsulates the signature verification preset and its
46 // actions for each verification type
47 type VerificationLevel struct {
48 Name string
49 Enforcement map[ValidationType]ValidationAction
50 }
51
52 const (
53 TypeIntegrity ValidationType = "integrity"
54 TypeAuthenticity ValidationType = "authenticity"
55 TypeAuthenticTimestamp ValidationType = "authenticTimestamp"
56 TypeExpiry ValidationType = "expiry"
57 TypeRevocation ValidationType = "revocation"
58 )
59
60 const (
61 ActionEnforce ValidationAction = "enforce"
62 ActionLog ValidationAction = "log"
63 ActionSkip ValidationAction = "skip"
64 )
65
66 // TimestampOption is an enum for timestamp verifiction options such as Always,
67 // AfterCertExpiry.
68 type TimestampOption string
69
70 const (
71 // OptionAlways denotes always perform timestamp verification
72 OptionAlways TimestampOption = "always"
73
74 // OptionAfterCertExpiry denotes perform timestamp verification only if
75 // the signing certificate chain has expired
76 OptionAfterCertExpiry TimestampOption = "afterCertExpiry"
77 )
78
79 var (
80 LevelStrict = &VerificationLevel{
81 Name: "strict",
82 Enforcement: map[ValidationType]ValidationAction{
83 TypeIntegrity: ActionEnforce,
84 TypeAuthenticity: ActionEnforce,
85 TypeAuthenticTimestamp: ActionEnforce,
86 TypeExpiry: ActionEnforce,
87 TypeRevocation: ActionEnforce,
88 },
89 }
90
91 LevelPermissive = &VerificationLevel{
92 Name: "permissive",
93 Enforcement: map[ValidationType]ValidationAction{
94 TypeIntegrity: ActionEnforce,
95 TypeAuthenticity: ActionEnforce,
96 TypeAuthenticTimestamp: ActionLog,
97 TypeExpiry: ActionLog,
98 TypeRevocation: ActionLog,
99 },
100 }
101
102 LevelAudit = &VerificationLevel{
103 Name: "audit",
104 Enforcement: map[ValidationType]ValidationAction{
105 TypeIntegrity: ActionEnforce,
106 TypeAuthenticity: ActionLog,
107 TypeAuthenticTimestamp: ActionLog,
108 TypeExpiry: ActionLog,
109 TypeRevocation: ActionLog,
110 },
111 }
112
113 LevelSkip = &VerificationLevel{
114 Name: "skip",
115 Enforcement: map[ValidationType]ValidationAction{
116 TypeIntegrity: ActionSkip,
117 TypeAuthenticity: ActionSkip,
118 TypeAuthenticTimestamp: ActionSkip,
119 TypeExpiry: ActionSkip,
120 TypeRevocation: ActionSkip,
121 },
122 }
123 )
124
125 var (
126 ValidationTypes = []ValidationType{
127 TypeIntegrity,
128 TypeAuthenticity,
129 TypeAuthenticTimestamp,
130 TypeExpiry,
131 TypeRevocation,
132 }
133
134 ValidationActions = []ValidationAction{
135 ActionEnforce,
136 ActionLog,
137 ActionSkip,
138 }
139
140 VerificationLevels = []*VerificationLevel{
141 LevelStrict,
142 LevelPermissive,
143 LevelAudit,
144 LevelSkip,
145 }
146 )
147
148 // SignatureVerification represents verification configuration in a trust policy
149 type SignatureVerification struct {
150 VerificationLevel string `json:"level"`
151 Override map[ValidationType]ValidationAction `json:"override,omitempty"`
152 VerifyTimestamp TimestampOption `json:"verifyTimestamp,omitempty"`
153 }
154
155 type errPolicyNotExist struct{}
156
157 func (e errPolicyNotExist) Error() string {
158 return fmt.Sprintf("trust policy is not present. To create a trust policy, see: %s", trustPolicyLink)
159 }
160
161 // GetVerificationLevel returns VerificationLevel struct for the given
162 // SignatureVerification struct throws error if SignatureVerification is invalid
163 func (signatureVerification *SignatureVerification) GetVerificationLevel() (*VerificationLevel, error) {
164 if signatureVerification.VerificationLevel == "" {
165 return nil, errors.New("signature verification level is empty or missing in the trust policy statement")
166 }
167
168 var baseLevel *VerificationLevel
169 for _, l := range VerificationLevels {
170 if l.Name == signatureVerification.VerificationLevel {
171 baseLevel = l
172 }
173 }
174 if baseLevel == nil {
175 return nil, fmt.Errorf("invalid signature verification level %q", signatureVerification.VerificationLevel)
176 }
177
178 if len(signatureVerification.Override) == 0 {
179 // nothing to override, return the base verification level
180 return baseLevel, nil
181 }
182
183 if baseLevel == LevelSkip {
184 return nil, fmt.Errorf("signature verification level %q can't be used to customize signature verification", baseLevel.Name)
185 }
186
187 customVerificationLevel := &VerificationLevel{
188 Name: "custom",
189 Enforcement: make(map[ValidationType]ValidationAction),
190 }
191
192 // populate the custom verification level with the base verification
193 // settings
194 for k, v := range baseLevel.Enforcement {
195 customVerificationLevel.Enforcement[k] = v
196 }
197
198 // override the verification actions with the user configured settings
199 for key, value := range signatureVerification.Override {
200 var validationType ValidationType
201 for _, t := range ValidationTypes {
202 if t == key {
203 validationType = t
204 break
205 }
206 }
207 if validationType == "" {
208 return nil, fmt.Errorf("verification type %q in custom signature verification is not supported, supported values are %q", key, ValidationTypes)
209 }
210
211 var validationAction ValidationAction
212 for _, action := range ValidationActions {
213 if action == value {
214 validationAction = action
215 break
216 }
217 }
218 if validationAction == "" {
219 return nil, fmt.Errorf("verification action %q in custom signature verification is not supported, supported values are %q", value, ValidationActions)
220 }
221
222 if validationType == TypeIntegrity {
223 return nil, fmt.Errorf("%q verification can not be overridden in custom signature verification", key)
224 } else if validationType != TypeRevocation && validationAction == ActionSkip {
225 return nil, fmt.Errorf("%q verification can not be skipped in custom signature verification", key)
226 }
227
228 customVerificationLevel.Enforcement[validationType] = validationAction
229 }
230 return customVerificationLevel, nil
231 }
232
233 func getDocument(path string, v any) error {
234 path, err := dir.ConfigFS().SysPath(path)
235 if err != nil {
236 return err
237 }
238
239 // throw error if path is a directory or a symlink or does not exist.
240 fileInfo, err := os.Lstat(path)
241 if err != nil {
242 if errors.Is(err, os.ErrNotExist) {
243 return errPolicyNotExist{}
244 }
245 return err
246 }
247
248 mode := fileInfo.Mode()
249 if mode.IsDir() || mode&fs.ModeSymlink != 0 {
250 return fmt.Errorf("trust policy is not a regular file (symlinks are not supported). To create a trust policy, see: %s", trustPolicyLink)
251 }
252
253 jsonFile, err := os.Open(path)
254 if err != nil {
255 if errors.Is(err, os.ErrPermission) {
256 return fmt.Errorf("unable to read trust policy due to file permissions, please verify the permissions of %s", path)
257 }
258 return err
259 }
260 defer jsonFile.Close()
261
262 err = json.NewDecoder(jsonFile).Decode(v)
263 if err != nil {
264 return fmt.Errorf("malformed trust policy. To create a trust policy, see: %s", trustPolicyLink)
265 }
266 return nil
267 }
268
269 func validatePolicyCore(name string, signatureVerification SignatureVerification, trustStores, trustedIdentities []string) error {
270 // Verify statement name is valid
271 if name == "" {
272 return errors.New("a trust policy statement is missing a name, every statement requires a name")
273 }
274
275 // Verify signature verification is valid
276 verificationLevel, err := signatureVerification.GetVerificationLevel()
277 if err != nil {
278 return fmt.Errorf("trust policy statement %q has invalid signatureVerification: %w", name, err)
279 }
280 if signatureVerification.VerifyTimestamp != "" &&
281 signatureVerification.VerifyTimestamp != OptionAlways &&
282 signatureVerification.VerifyTimestamp != OptionAfterCertExpiry {
283 return fmt.Errorf("trust policy statement %q has invalid signatureVerification: verifyTimestamp must be %q or %q, but got %q", name, OptionAlways, OptionAfterCertExpiry, signatureVerification.VerifyTimestamp)
284 }
285
286 // Any signature verification other than "skip" needs a trust store and
287 // trusted identities
288 if verificationLevel.Name == "skip" {
289 if len(trustStores) > 0 || len(trustedIdentities) > 0 {
290 return fmt.Errorf("trust policy statement %q is set to skip signature verification but configured with trust stores and/or trusted identities, remove them if signature verification needs to be skipped", name)
291 }
292 } else {
293 if len(trustStores) == 0 || len(trustedIdentities) == 0 {
294 return fmt.Errorf("trust policy statement %q is either missing trust stores or trusted identities, both must be specified", name)
295 }
296
297 // Verify Trust Store is valid
298 if err := validateTrustStore(name, trustStores); err != nil {
299 return err
300 }
301
302 // Verify Trusted Identities are valid
303 if err := validateTrustedIdentities(name, trustedIdentities); err != nil {
304 return err
305 }
306 }
307 return nil
308 }
309
310 // validateTrustStore validates if the policy statement is following the
311 // Notary Project spec rules for truststore
312 func validateTrustStore(policyName string, trustStores []string) error {
313 for _, trustStore := range trustStores {
314 storeType, namedStore, found := strings.Cut(trustStore, ":")
315 if !found {
316 return fmt.Errorf("trust policy statement %q has malformed trust store value %q. The required format is <TrustStoreType>:<TrustStoreName>", policyName, trustStore)
317 }
318 if !isValidTrustStoreType(storeType) {
319 return fmt.Errorf("trust policy statement %q uses an unsupported trust store type %q in trust store value %q", policyName, storeType, trustStore)
320 }
321 if !file.IsValidFileName(namedStore) {
322 return fmt.Errorf("trust policy statement %q uses an unsupported trust store name %q in trust store value %q. Named store name needs to follow [a-zA-Z0-9_.-]+ format", policyName, namedStore, trustStore)
323 }
324 }
325
326 return nil
327 }
328
329 // validateTrustedIdentities validates if the policy statement is following the
330 // Notary Project spec rules for trusted identities
331 func validateTrustedIdentities(policyName string, tis []string) error {
332 // If there is a wildcard in trusted identities, there shouldn't be any other
333 //identities
334 if len(tis) > 1 && slices.Contains(tis, trustpolicy.Wildcard) {
335 return fmt.Errorf("trust policy statement %q uses a wildcard trusted identity '*', a wildcard identity cannot be used in conjunction with other values", policyName)
336 }
337
338 var parsedDNs []parsedDN
339 // If there are trusted identities, verify they are valid
340 for _, identity := range tis {
341 if identity == "" {
342 return fmt.Errorf("trust policy statement %q has an empty trusted identity", policyName)
343 }
344
345 if identity != trustpolicy.Wildcard {
346 identityPrefix, identityValue, found := strings.Cut(identity, ":")
347 if !found {
348 return fmt.Errorf("trust policy statement %q has trusted identity %q missing separator", policyName, identity)
349 }
350
351 // notation natively supports x509.subject identities only
352 if identityPrefix == trustpolicy.X509Subject {
353 // identityValue cannot be empty
354 if identityValue == "" {
355 return fmt.Errorf("trust policy statement %q has trusted identity %q without an identity value", policyName, identity)
356 }
357 dn, err := pkix.ParseDistinguishedName(identityValue)
358 if err != nil {
359 return fmt.Errorf("trust policy statement %q has trusted identity %q with invalid identity value: %w", policyName, identity, err)
360 }
361 parsedDNs = append(parsedDNs, parsedDN{RawString: identity, ParsedMap: dn})
362 }
363 }
364 }
365
366 // Verify there are no overlapping DNs
367 if err := validateOverlappingDNs(policyName, parsedDNs); err != nil {
368 return err
369 }
370
371 // No error
372 return nil
373 }
374
375 func validateOverlappingDNs(policyName string, parsedDNs []parsedDN) error {
376 for i, dn1 := range parsedDNs {
377 for j, dn2 := range parsedDNs {
378 if i != j && pkix.IsSubsetDN(dn1.ParsedMap, dn2.ParsedMap) {
379 return fmt.Errorf("trust policy statement %q has overlapping x509 trustedIdentities, %q overlaps with %q", policyName, dn1.RawString, dn2.RawString)
380 }
381 }
382 }
383
384 return nil
385 }
386
387 // isValidTrustStoreType returns true if the given string is a valid
388 // truststore.Type, otherwise false.
389 func isValidTrustStoreType(s string) bool {
390 for _, p := range truststore.Types {
391 if s == string(p) {
392 return true
393 }
394 }
395 return false
396 }
397
398 // parsedDN holds raw and parsed Distinguished Names
399 type parsedDN struct {
400 RawString string
401 ParsedMap map[string]string
402 }