-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathimplementation.go
More file actions
436 lines (362 loc) · 12.7 KB
/
implementation.go
File metadata and controls
436 lines (362 loc) · 12.7 KB
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// SPDX-FileCopyrightText: Copyright 2025 Carabiner Systems, Inc
// SPDX-License-Identifier: Apache-2.0
package policy
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"github.com/carabiner-dev/attestation"
"github.com/carabiner-dev/collector/envelope"
"github.com/carabiner-dev/hasher"
sapi "github.com/carabiner-dev/signer/api/v1"
"github.com/hjson/hjson-go/v4"
intoto "github.com/in-toto/attestation/go/v1"
"google.golang.org/protobuf/encoding/protojson"
v1 "github.com/carabiner-dev/policy/api/v1"
"github.com/carabiner-dev/policy/options"
)
type parserImplementation interface {
ParsePolicySet(*options.ParseOptions, []byte) (*v1.PolicySet, attestation.Verification, error)
ParsePolicy(*options.ParseOptions, []byte) (*v1.Policy, attestation.Verification, error)
ParsePolicyGroup(*options.ParseOptions, []byte) (*v1.PolicyGroup, attestation.Verification, error)
}
type defaultParserImplementationV1 struct{}
// checkJSONDepth validates that JSON data does not exceed the maximum nesting depth.
// This prevents stack overflow attacks from deeply nested structures.
func checkJSONDepth(data []byte, maxDepth int) (int, error) {
if maxDepth <= 0 {
return 0, nil
}
dec := json.NewDecoder(bytes.NewReader(data))
var depth, maxObserved int
for {
token, err := dec.Token()
if err == io.EOF {
break
}
if err != nil {
//nolint:nilerr // Invalid JSON will be caught later by the actual parser
return maxObserved, nil
}
switch token {
case json.Delim('['), json.Delim('{'):
depth++
if depth > maxObserved {
maxObserved = depth
}
if depth > maxDepth {
return maxObserved, options.NewJSONDepthError(maxDepth, depth, "")
}
case json.Delim(']'), json.Delim('}'):
depth--
}
}
return maxObserved, nil
}
// validatePolicySetLimits validates that a PolicySet does not exceed configured limits.
func validatePolicySetLimits(opts *options.ParseOptions, set *v1.PolicySet) error {
limits := opts.Limits
// Check policies per set
if limits.MaxPoliciesPerSet > 0 && len(set.GetPolicies()) > limits.MaxPoliciesPerSet {
return options.NewCollectionSizeError(
"policies per set",
limits.MaxPoliciesPerSet,
len(set.GetPolicies()),
set.GetId(),
)
}
// Check groups per set
if limits.MaxGroupsPerSet > 0 && len(set.GetGroups()) > limits.MaxGroupsPerSet {
return options.NewCollectionSizeError(
"groups per set",
limits.MaxGroupsPerSet,
len(set.GetGroups()),
set.GetId(),
)
}
// Validate nested policies
for i, p := range set.GetPolicies() {
if err := validatePolicyLimits(opts, p); err != nil {
return fmt.Errorf("policy #%d: %w", i, err)
}
}
// Validate nested groups
for i, g := range set.GetGroups() {
if err := validatePolicyGroupLimits(opts, g); err != nil {
return fmt.Errorf("group #%d: %w", i, err)
}
}
return nil
}
// validatePolicyLimits validates that a Policy does not exceed configured limits.
func validatePolicyLimits(opts *options.ParseOptions, p *v1.Policy) error {
limits := opts.Limits
// Check tenets per policy
if limits.MaxTenetsPerPolicy > 0 && len(p.GetTenets()) > limits.MaxTenetsPerPolicy {
return options.NewCollectionSizeError(
"tenets per policy",
limits.MaxTenetsPerPolicy,
len(p.GetTenets()),
p.GetId(),
)
}
return nil
}
// validatePolicyGroupLimits validates that a PolicyGroup does not exceed configured limits.
func validatePolicyGroupLimits(opts *options.ParseOptions, g *v1.PolicyGroup) error {
limits := opts.Limits
// Check blocks per group
if limits.MaxBlocksPerGroup > 0 && len(g.GetBlocks()) > limits.MaxBlocksPerGroup {
return options.NewCollectionSizeError(
"blocks per group",
limits.MaxBlocksPerGroup,
len(g.GetBlocks()),
g.GetId(),
)
}
// Check policies per block and validate nested policies
for i, block := range g.GetBlocks() {
if limits.MaxPoliciesPerBlock > 0 && len(block.GetPolicies()) > limits.MaxPoliciesPerBlock {
return options.NewCollectionSizeError(
"policies per block",
limits.MaxPoliciesPerBlock,
len(block.GetPolicies()),
fmt.Sprintf("%s/block#%d", g.GetId(), i),
)
}
for j, p := range block.GetPolicies() {
if err := validatePolicyLimits(opts, p); err != nil {
return fmt.Errorf("block #%d, policy #%d: %w", i, j, err)
}
}
}
return nil
}
// normalizeToJSON attempts to parse data as JSON first. If that fails,
// it tries to parse as HJSON and converts it to JSON. This allows transparent
// support for both JSON and HJSON policy formats.
// If maxDepth > 0, it also validates that the JSON depth does not exceed the limit.
func normalizeToJSON(data []byte, maxDepth int) ([]byte, error) {
// First, try to parse as strict JSON to validate it's well-formed
var jsonTest any
if err := json.Unmarshal(data, &jsonTest); err == nil {
// Data is valid JSON, check depth limit before returning
if _, err := checkJSONDepth(data, maxDepth); err != nil {
return nil, err
}
return data, nil
}
// If JSON parsing failed, try HJSON
var hjsonData any
if err := hjson.Unmarshal(data, &hjsonData); err != nil {
// Neither JSON nor HJSON worked, return original error context
return nil, fmt.Errorf("failed to parse as JSON or HJSON: %w", err)
}
// Convert HJSON-parsed data back to standard JSON
jsonData, err := json.Marshal(hjsonData)
if err != nil {
return nil, fmt.Errorf("converting HJSON to JSON: %w", err)
}
// Check depth limit on the normalized JSON
if _, err := checkJSONDepth(jsonData, maxDepth); err != nil {
return nil, err
}
return jsonData, nil
}
// ParsePolicySet parses a policy set from a byte slice.
func (dpi *defaultParserImplementationV1) ParsePolicySet(opts *options.ParseOptions, policySetData []byte) (*v1.PolicySet, attestation.Verification, error) {
// Normalize HJSON to JSON if needed (must happen before envelope parsing)
policySetData, err := normalizeToJSON(policySetData, opts.Limits.MaxJSONDepth)
if err != nil {
return nil, nil, fmt.Errorf("normalizing policy data: %w", err)
}
// Extract the policy predicate, if any
policySetData, verification, err := parseEnvelope(opts, policySetData)
if err != nil {
return nil, nil, fmt.Errorf("testing for signature envelope: %w", err)
}
set := &v1.PolicySet{}
err = protojson.UnmarshalOptions{
AllowPartial: false,
DiscardUnknown: false,
}.Unmarshal(policySetData, set)
if err != nil {
return nil, verification, fmt.Errorf("parsing policy set source: %w", err)
}
// Validate collection sizes
if err := validatePolicySetLimits(opts, set); err != nil {
return nil, verification, err
}
// hash the data to record it in the policy origin
hset, err := hasher.New().HashReaders([]io.Reader{bytes.NewReader(policySetData)})
if err != nil {
return nil, nil, fmt.Errorf("hashing policy data: %w", err)
}
if set.GetMeta() == nil {
set.Meta = &v1.PolicySetMeta{}
}
if set.GetMeta().GetOrigin() == nil {
set.GetMeta().Origin = &intoto.ResourceDescriptor{}
}
set.GetMeta().GetOrigin().Digest = hset.ToResourceDescriptors()[0].Digest
set.GetMeta().GetOrigin().Name = set.GetId()
if set.GetMeta().GetEnforce() == "" {
set.GetMeta().Enforce = EnforceOn
}
for _, p := range set.Policies {
// Don't apply defaults to policies with remote sources
// They will get their defaults from the remote policy during assembly
if p.GetSource() != nil {
continue
}
if p.GetMeta() == nil {
p.Meta = &v1.Meta{}
}
if p.GetMeta().GetAssertMode() == "" {
p.GetMeta().AssertMode = AssertModeAND
}
if p.GetMeta().GetEnforce() == "" {
p.GetMeta().Enforce = EnforceOn
}
}
return set, verification, nil
}
// ParsePolicy parses a policy from a byte slice.
func (dpi *defaultParserImplementationV1) ParsePolicy(opts *options.ParseOptions, policyData []byte) (*v1.Policy, attestation.Verification, error) {
// Normalize HJSON to JSON if needed (must happen before envelope parsing)
policyData, err := normalizeToJSON(policyData, opts.Limits.MaxJSONDepth)
if err != nil {
return nil, nil, fmt.Errorf("normalizing policy data: %w", err)
}
// Extract the policy when used as a envelope's predicate
policyData, verification, err := parseEnvelope(opts, policyData)
if err != nil {
return nil, nil, fmt.Errorf("testing for signature envelope: %w", err)
}
p := &v1.Policy{}
err = protojson.UnmarshalOptions{}.Unmarshal(policyData, p)
if err != nil {
return nil, verification, fmt.Errorf("parsing policy source: %w", err)
}
// Validate collection sizes
if err := validatePolicyLimits(opts, p); err != nil {
return nil, verification, err
}
// hash the data to record it in the policy origin
hset, err := hasher.New().HashReaders([]io.Reader{bytes.NewReader(policyData)})
if err != nil {
return nil, nil, fmt.Errorf("hashing policy data: %w", err)
}
if p.GetMeta() == nil {
p.Meta = &v1.Meta{}
}
if p.GetMeta().GetOrigin() == nil {
p.GetMeta().Origin = &intoto.ResourceDescriptor{}
}
p.GetMeta().GetOrigin().Digest = hset.ToResourceDescriptors()[0].Digest
p.GetMeta().GetOrigin().Name = p.GetId()
if p.GetMeta().GetEnforce() == "" {
p.GetMeta().Enforce = EnforceOn
}
if p.GetMeta().GetAssertMode() == "" {
p.GetMeta().AssertMode = AssertModeAND
}
return p, verification, nil
}
// ParsePolicyGroup parses a PolicyGroup from a byte slice.
func (dpi *defaultParserImplementationV1) ParsePolicyGroup(opts *options.ParseOptions, policyData []byte) (*v1.PolicyGroup, attestation.Verification, error) {
// Normalize HJSON to JSON if needed (must happen before envelope parsing)
policyData, err := normalizeToJSON(policyData, opts.Limits.MaxJSONDepth)
if err != nil {
return nil, nil, fmt.Errorf("normalizing policygroup data: %w", err)
}
// Extract the policy when used as a envelope's predicate
policyGroupData, verification, err := parseEnvelope(opts, policyData)
if err != nil {
return nil, nil, fmt.Errorf("testing for signature envelope: %w", err)
}
g := &v1.PolicyGroup{}
err = protojson.UnmarshalOptions{}.Unmarshal(policyGroupData, g)
if err != nil {
return nil, verification, fmt.Errorf("parsing group source: %w", err)
}
// Validate collection sizes
if err := validatePolicyGroupLimits(opts, g); err != nil {
return nil, verification, err
}
// hash the data to record it in the policy origin
hset, err := hasher.New().HashReaders([]io.Reader{bytes.NewReader(policyData)})
if err != nil {
return nil, nil, fmt.Errorf("hashing policy data: %w", err)
}
if g.GetMeta() == nil {
g.Meta = &v1.PolicyGroupMeta{}
}
if g.GetMeta().GetOrigin() == nil {
g.GetMeta().Origin = &intoto.ResourceDescriptor{}
}
g.GetMeta().GetOrigin().Digest = hset.ToResourceDescriptors()[0].Digest
g.GetMeta().GetOrigin().Name = g.GetId()
if g.GetMeta().GetEnforce() == "" {
g.GetMeta().Enforce = EnforceOn
}
return g, verification, nil
}
// parseEnvelope parses a policy when wrapped in a cryptographic envelope.
func parseEnvelope(opts *options.ParseOptions, bundleData []byte) ([]byte, attestation.Verification, error) {
p := envelope.Parsers
envelopes, err := p.Parse(bytes.NewBuffer(bundleData))
if err != nil {
if errors.Is(err, attestation.ErrNotCorrectFormat) {
return bundleData, nil, nil
}
return nil, nil, fmt.Errorf("parsing bundle: %w", err)
}
if len(envelopes) == 0 {
return nil, nil, errors.New("no envelopes found in data")
}
// If no signature verification was requested, we can end here.
if !opts.VerifySignatures {
return envelopes[0].GetPredicate().GetData(), envelopes[0].GetPredicate().GetVerification(), nil
}
// Verify the signatures
if err := envelopes[0].Verify(opts.PublicKeys); err != nil {
return nil, nil, fmt.Errorf("verifying policy envelope: %w", err)
}
// If the envelope is not signed (verification is nil), then we can end here
verification := envelopes[0].GetPredicate().GetVerification()
if verification == nil {
return envelopes[0].GetPredicate().GetData(), nil, nil
}
v, ok := verification.(*sapi.Verification)
if !ok {
return nil, nil, fmt.Errorf("unsupported verification result type: %T", verification)
}
validIds := []*sapi.Identity{}
for _, idstring := range opts.IdentityStrings {
id, err := sapi.NewIdentityFromSpec(idstring)
if err != nil {
return nil, nil, fmt.Errorf("parsing id string %q: %w", idstring, err)
}
validIds = append(validIds, id)
}
// If there were valid identities specified, we mutate the verification
// results, in other words, white listing here and fail it if needed.
if len(validIds) > 0 {
acceptedIds := []*sapi.Identity{}
for _, id := range validIds {
if v.MatchesIdentity(id) {
acceptedIds = append(acceptedIds, id)
}
}
v.GetSignature().Identities = acceptedIds
if len(acceptedIds) == 0 {
v.GetSignature().Verified = false
v.GetSignature().Error = fmt.Sprintf("unable to match signer with %d allowed identities", len(validIds))
}
verification = v
}
return envelopes[0].GetPredicate().GetData(), verification, nil
}