Coverage Report

Created: 2026-10-27 07:01

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/boringssl/crypto/x509/policy.cc
Line
Count
Source
1
// Copyright 2022 The BoringSSL Authors
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     https://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
#include <openssl/base.h>
16
#include <openssl/x509.h>
17
18
#include <assert.h>
19
20
#include <algorithm>
21
#include <optional>
22
#include <utility>
23
24
#include <openssl/mem.h>
25
#include <openssl/obj.h>
26
#include <openssl/span.h>
27
#include <openssl/stack.h>
28
29
#include "../internal.h"
30
#include "../mem_internal.h"
31
#include "internal.h"
32
33
34
BSSL_NAMESPACE_BEGIN
35
namespace {
36
37
// This file computes the X.509 policy graph, as described in RFC 9618.
38
// Implementation notes:
39
//
40
//  (1) It does not track "qualifier_set". This is not needed as it is not
41
//      output by this implementation.
42
//
43
//  (2) "expected_policy_set" is not tracked explicitly and built temporarily
44
//      as part of building the graph.
45
//
46
//  (3) anyPolicy nodes are not tracked explicitly.
47
//
48
//  (4) Some pruning steps are deferred to when policies are evaluated, as a
49
//      reachability pass.
50
51
0
bool is_any_policy(const ASN1_OBJECT *obj) {
52
0
  return OBJ_obj2nid(obj) == NID_any_policy;
53
0
}
54
55
// An X509PolicyNode is a node in the policy graph. It corresponds to a node
56
// from RFC 5280, section 6.1.2, step (a), but we store some fields differently.
57
struct X509PolicyNode {
58
0
  static std::optional<X509PolicyNode> Create(const ASN1_OBJECT *policy) {
59
0
    assert(!is_any_policy(policy));
60
0
    X509PolicyNode node;
61
0
    node.policy.reset(OBJ_dup(policy));
62
0
    if (node.policy == nullptr) {
63
0
      return std::nullopt;
64
0
    }
65
0
    return node;
66
0
  }
67
68
0
  bool operator<(const X509PolicyNode &other) const {
69
0
    return OBJ_cmp(policy.get(), other.policy.get()) < 0;
70
0
  }
71
72
0
  bool parent_is_any_policy() const { return parent_policies.empty(); }
73
74
  // policy is the "valid_policy" field from RFC 5280.
75
  UniquePtr<ASN1_OBJECT> policy;
76
77
  // parent_policies, if non-empty, is the list of "valid_policy" values for all
78
  // nodes which are a parent of this node. In this case, no entry in this list
79
  // will be anyPolicy. This list is in no particular order and may contain
80
  // duplicates if the corresponding certificate had duplicate mappings.
81
  //
82
  // If empty, this node has a single parent, anyPolicy. The node is then a root
83
  // policy, and is in authorities-constrained-policy-set if it has a path to a
84
  // leaf node.
85
  //
86
  // Note it is not possible for a policy to have both anyPolicy and a
87
  // concrete policy as a parent. Section 6.1.3, step (d.1.ii) only runs if
88
  // there was no match in step (d.1.i). We do not need to represent a parent
89
  // list of, say, {anyPolicy, OID1, OID2}.
90
  Vector<UniquePtr<ASN1_OBJECT>> parent_policies;
91
92
  // mapped is whether this node matches a policy mapping in the certificate.
93
  bool mapped = false;
94
95
  // reachable is whether this node is reachable from some valid policy in the
96
  // end-entity certificate. It is computed during `has_explicit_policy`.
97
  bool reachable = false;
98
};
99
100
// An X509PolicyLevel is the collection of nodes at the same depth in the
101
// policy graph. This structure can also be used to represent a level's
102
// "expected_policy_set" values. See `process_policy_mappings`.
103
class X509PolicyLevel {
104
 public:
105
0
  bool has_any_policy() const { return has_any_policy_; }
106
0
  bool is_empty() const { return !has_any_policy_ && nodes_.empty(); }
107
0
  Span<const X509PolicyNode> nodes() const { return nodes_; }
108
109
0
  void set_has_any_policy(bool v) { has_any_policy_ = v; }
110
111
  // Although this is mutable, callers may not modify the node's policy.
112
0
  Span<X509PolicyNode> nodes() { return Span(nodes_); }
113
114
0
  void Clear() {
115
0
    has_any_policy_ = false;
116
0
    nodes_.clear();
117
0
  }
118
119
  // Find returns the node corresponding to `policy`, or nullptr if none exists.
120
0
  X509PolicyNode *Find(const ASN1_OBJECT *policy) {
121
    // The list is sorted, so we can binary search.
122
0
    auto it = std::lower_bound(
123
0
        nodes_.begin(), nodes_.end(), policy,
124
0
        [](const X509PolicyNode &node, const ASN1_OBJECT *obj) {
125
0
          return OBJ_cmp(node.policy.get(), obj) < 0;
126
0
        });
127
0
    if (it == nodes_.end() || OBJ_cmp(it->policy.get(), policy) != 0) {
128
0
      return nullptr;
129
0
    }
130
0
    return &*it;
131
0
  }
132
133
  // AddNodes adds the nodes in `nodes`. It returns true on success and false on
134
  // error. No policy in `nodes` may already be present. This method leaves
135
  // the objects in `nodes` in a moved-from state.
136
  //
137
  // This method re-sorts the nodes, so it runs in time proportional to the
138
  // total size of the level. However, each level is only added to three times
139
  // in the course of policy validation.
140
0
  bool AddNodes(Span<X509PolicyNode> nodes) {
141
0
    if (!nodes_.AppendMove(nodes)) {
142
0
      return false;
143
0
    }
144
0
    std::sort(nodes_.begin(), nodes_.end());
145
0
#if !defined(NDEBUG)
146
    // There should be no duplicate nodes.
147
0
    for (size_t i = 1; i < nodes_.size(); i++) {
148
0
      assert(OBJ_cmp(nodes_[i - 1].policy.get(), nodes_[i].policy.get()) != 0);
149
0
    }
150
0
#endif
151
0
    return true;
152
0
  }
153
154
  // EraseNodesIf removes all nodes that satisfy the predicate `pred`.
155
  template <typename Pred>
156
0
  void EraseNodesIf(Pred pred) {
157
0
    nodes_.EraseIf(pred);
158
0
  }
Unexecuted instantiation: policy.cc:void bssl::(anonymous namespace)::X509PolicyLevel::EraseNodesIf<bssl::(anonymous namespace)::process_certificate_policies(x509_st const*, bssl::(anonymous namespace)::X509PolicyLevel*, int)::$_0>(bssl::(anonymous namespace)::process_certificate_policies(x509_st const*, bssl::(anonymous namespace)::X509PolicyLevel*, int)::$_0)
Unexecuted instantiation: policy.cc:void bssl::(anonymous namespace)::X509PolicyLevel::EraseNodesIf<bssl::(anonymous namespace)::process_policy_mappings(x509_st const*, bssl::(anonymous namespace)::X509PolicyLevel*, bool)::$_0>(bssl::(anonymous namespace)::process_policy_mappings(x509_st const*, bssl::(anonymous namespace)::X509PolicyLevel*, bool)::$_0)
159
160
 private:
161
  // nodes is the list of nodes at this depth, except for the anyPolicy node, if
162
  // any. This list is sorted by policy OID for efficient lookup.
163
  Vector<X509PolicyNode> nodes_;
164
165
  // has_any_policy is whether there is an anyPolicy node at this depth.
166
  bool has_any_policy_ = false;
167
};
168
169
0
int policyinfo_cmp(const POLICYINFO *const *a, const POLICYINFO *const *b) {
170
0
  return OBJ_cmp((*a)->policyid, (*b)->policyid);
171
0
}
172
173
// process_certificate_policies updates `level` to incorporate `x509`'s
174
// certificate policies extension. This implements steps (d) and (e) of RFC
175
// 5280, section 6.1.3. `level` must contain the previous level's
176
// "expected_policy_set" information. For all but the top-most level, this is
177
// the output of `process_policy_mappings`. `any_policy_allowed` specifies
178
// whether anyPolicy is allowed or inhibited, taking into account the exception
179
// for self-issued certificates.
180
bool process_certificate_policies(const X509 *x509, X509PolicyLevel *level,
181
0
                                  int any_policy_allowed) {
182
0
  int critical;
183
0
  UniquePtr<CERTIFICATEPOLICIES> policies(
184
0
      reinterpret_cast<CERTIFICATEPOLICIES *>(X509_get_ext_d2i(
185
0
          x509, NID_certificate_policies, &critical, nullptr)));
186
0
  if (policies == nullptr) {
187
0
    if (critical != -1) {
188
0
      return false;  // Syntax error in the extension.
189
0
    }
190
191
    // RFC 5280, section 6.1.3, step (e).
192
0
    level->Clear();
193
0
    return true;
194
0
  }
195
196
  // certificatePolicies may not be empty. See RFC 5280, section 4.2.1.4.
197
  // TODO(https://crbug.com/boringssl/443): Move this check into the parser.
198
0
  if (sk_POLICYINFO_num(policies.get()) == 0) {
199
0
    OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION);
200
0
    return false;
201
0
  }
202
203
0
  sk_POLICYINFO_set_cmp_func(policies.get(), policyinfo_cmp);
204
0
  sk_POLICYINFO_sort(policies.get());
205
0
  bool cert_has_any_policy = false;
206
0
  for (size_t i = 0; i < sk_POLICYINFO_num(policies.get()); i++) {
207
0
    const POLICYINFO *policy = sk_POLICYINFO_value(policies.get(), i);
208
0
    if (is_any_policy(policy->policyid)) {
209
0
      cert_has_any_policy = true;
210
0
    }
211
0
    if (i > 0 && OBJ_cmp(sk_POLICYINFO_value(policies.get(), i - 1)->policyid,
212
0
                         policy->policyid) == 0) {
213
      // Per RFC 5280, section 4.2.1.4, `policies` may not have duplicates.
214
0
      OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION);
215
0
      return false;
216
0
    }
217
0
  }
218
219
  // This does the same thing as RFC 5280, section 6.1.3, step (d), though in
220
  // a slightly different order. `level` currently contains
221
  // "expected_policy_set" values of the previous level. See
222
  // `process_policy_mappings` for details.
223
0
  const bool previous_level_has_any_policy = level->has_any_policy();
224
225
  // First, we handle steps (d.1.i) and (d.2). The net effect of these two
226
  // steps is to intersect `level` with `policies`, ignoring anyPolicy if it
227
  // is inhibited.
228
0
  if (!cert_has_any_policy || !any_policy_allowed) {
229
0
    level->EraseNodesIf([&](const X509PolicyNode &node) {
230
0
      assert(sk_POLICYINFO_is_sorted(policies.get()));
231
      // Erase the node if it not present in the current certificate.
232
0
      POLICYINFO info;
233
0
      info.policyid = node.policy.get();
234
0
      return !sk_POLICYINFO_find(policies.get(), nullptr, &info);
235
0
    });
236
0
    level->set_has_any_policy(false);
237
0
  }
238
239
  // Step (d.1.ii) may attach new nodes to the previous level's anyPolicy
240
  // node.
241
0
  if (previous_level_has_any_policy) {
242
0
    Vector<X509PolicyNode> new_nodes;
243
0
    for (const POLICYINFO *policy : policies.get()) {
244
      // Though we've reordered the steps slightly, `policy` is in `level` if
245
      // and only if it would have been a match in step (d.1.ii).
246
0
      if (!is_any_policy(policy->policyid) &&
247
0
          level->Find(policy->policyid) == nullptr) {
248
0
        auto node = X509PolicyNode::Create(policy->policyid);
249
0
        if (!node.has_value() || !new_nodes.Push(*std::move(node))) {
250
0
          return false;
251
0
        }
252
0
      }
253
0
    }
254
0
    if (!level->AddNodes(Span(new_nodes))) {
255
0
      return false;
256
0
    }
257
0
  }
258
259
0
  return true;
260
0
}
261
262
int compare_issuer_policy(const POLICY_MAPPING *const *a,
263
0
                          const POLICY_MAPPING *const *b) {
264
0
  return OBJ_cmp((*a)->issuerDomainPolicy, (*b)->issuerDomainPolicy);
265
0
}
266
267
int compare_subject_policy(const POLICY_MAPPING *const *a,
268
0
                           const POLICY_MAPPING *const *b) {
269
0
  return OBJ_cmp((*a)->subjectDomainPolicy, (*b)->subjectDomainPolicy);
270
0
}
271
272
// process_policy_mappings processes the policy mappings extension of `cert`,
273
// whose corresponding graph level is `level`. `mapping_allowed` specifies
274
// whether policy mapping is inhibited at this point. On success, it returns an
275
// `X509PolicyLevel` containing the "expected_policy_set" for `level`. On error,
276
// it returns std::nullopt. This implements steps (a) and (b) of RFC 5280,
277
// section 6.1.4.
278
//
279
// We represent the "expected_policy_set" as an `X509PolicyLevel`.
280
// `has_any_policy` indicates whether there is an anyPolicy node with
281
// "expected_policy_set" of {anyPolicy}. If a node with policy oid P1 contains
282
// P2 in its "expected_policy_set", the level will contain a node of policy P2
283
// with P1 in `parent_policies`.
284
//
285
// This is equivalent to the `X509PolicyLevel` that would result if the next
286
// certificates contained anyPolicy. `process_certificate_policies` will filter
287
// this result down to compute the actual level.
288
std::optional<X509PolicyLevel> process_policy_mappings(const X509 *cert,
289
                                                       X509PolicyLevel *level,
290
0
                                                       bool mapping_allowed) {
291
0
  int critical;
292
0
  UniquePtr<POLICY_MAPPINGS> mappings(reinterpret_cast<POLICY_MAPPINGS *>(
293
0
      X509_get_ext_d2i(cert, NID_policy_mappings, &critical, nullptr)));
294
0
  if (mappings == nullptr && critical != -1) {
295
    // Syntax error in the policy mappings extension.
296
0
    return std::nullopt;
297
0
  }
298
299
0
  if (mappings != nullptr) {
300
    // PolicyMappings may not be empty. See RFC 5280, section 4.2.1.5.
301
    // TODO(https://crbug.com/boringssl/443): Move this check into the parser.
302
0
    if (sk_POLICY_MAPPING_num(mappings.get()) == 0) {
303
0
      OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION);
304
0
      return std::nullopt;
305
0
    }
306
307
    // RFC 5280, section 6.1.4, step (a).
308
0
    for (const POLICY_MAPPING *mapping : mappings.get()) {
309
0
      if (is_any_policy(mapping->issuerDomainPolicy) ||
310
0
          is_any_policy(mapping->subjectDomainPolicy)) {
311
0
        return std::nullopt;
312
0
      }
313
0
    }
314
315
    // Sort to group by issuerDomainPolicy.
316
0
    sk_POLICY_MAPPING_set_cmp_func(mappings.get(), compare_issuer_policy);
317
0
    sk_POLICY_MAPPING_sort(mappings.get());
318
319
0
    if (mapping_allowed) {
320
      // Mark nodes as mapped, and add any nodes to `level` which may be
321
      // needed as part of RFC 5280, section 6.1.4, step (b.1).
322
0
      Vector<X509PolicyNode> new_nodes;
323
0
      const ASN1_OBJECT *last_policy = nullptr;
324
0
      for (const POLICY_MAPPING *mapping : mappings.get()) {
325
        // There may be multiple mappings with the same `issuerDomainPolicy`.
326
0
        if (last_policy != nullptr &&
327
0
            OBJ_cmp(mapping->issuerDomainPolicy, last_policy) == 0) {
328
0
          continue;
329
0
        }
330
0
        last_policy = mapping->issuerDomainPolicy;
331
332
0
        X509PolicyNode *node = level->Find(mapping->issuerDomainPolicy);
333
0
        if (node != nullptr) {
334
0
          node->mapped = true;
335
0
        } else {
336
0
          if (!level->has_any_policy()) {
337
0
            continue;
338
0
          }
339
0
          auto new_node = X509PolicyNode::Create(mapping->issuerDomainPolicy);
340
0
          if (!new_node.has_value()) {
341
0
            return std::nullopt;
342
0
          }
343
0
          new_node->mapped = true;
344
0
          if (!new_nodes.Push(*std::move(new_node))) {
345
0
            return std::nullopt;
346
0
          }
347
0
        }
348
0
      }
349
0
      if (!level->AddNodes(Span(new_nodes))) {
350
0
        return std::nullopt;
351
0
      }
352
0
    } else {
353
      // RFC 5280, section 6.1.4, step (b.2). If mapping is inhibited, delete
354
      // all mapped nodes.
355
0
      level->EraseNodesIf([&](const X509PolicyNode &node) {
356
        // `mappings` must have been sorted by `compare_issuer_policy`.
357
0
        assert(sk_POLICY_MAPPING_is_sorted(mappings.get()));
358
        // Check if the node was mapped.
359
0
        POLICY_MAPPING mapping;
360
0
        mapping.issuerDomainPolicy = node.policy.get();
361
0
        return sk_POLICY_MAPPING_find(mappings.get(), /*out_index=*/nullptr,
362
0
                                      &mapping);
363
0
      });
364
      // Dropping the mappings.
365
0
      mappings = nullptr;
366
0
    }
367
0
  }
368
369
  // If a node was not mapped, it retains the original "explicit_policy_set"
370
  // value, itself. Add those to `mappings`.
371
0
  if (mappings == nullptr) {
372
0
    mappings.reset(sk_POLICY_MAPPING_new_null());
373
0
    if (mappings == nullptr) {
374
0
      return std::nullopt;
375
0
    }
376
0
  }
377
0
  for (const X509PolicyNode &node : level->nodes()) {
378
0
    if (!node.mapped) {
379
0
      UniquePtr<POLICY_MAPPING> mapping(POLICY_MAPPING_new());
380
0
      if (mapping == nullptr) {
381
0
        return std::nullopt;
382
0
      }
383
0
      mapping->issuerDomainPolicy = OBJ_dup(node.policy.get());
384
0
      mapping->subjectDomainPolicy = OBJ_dup(node.policy.get());
385
0
      if (mapping->issuerDomainPolicy == nullptr ||
386
0
          mapping->subjectDomainPolicy == nullptr ||
387
0
          !PushToStack(mappings.get(), std::move(mapping))) {
388
0
        return std::nullopt;
389
0
      }
390
0
    }
391
0
  }
392
393
  // Sort to group by subjectDomainPolicy.
394
0
  sk_POLICY_MAPPING_set_cmp_func(mappings.get(), compare_subject_policy);
395
0
  sk_POLICY_MAPPING_sort(mappings.get());
396
397
  // Convert `mappings` to our "expected_policy_set" representation.
398
0
  Vector<X509PolicyNode> next_nodes;
399
0
  for (POLICY_MAPPING *mapping : mappings.get()) {
400
    // Skip mappings where `issuerDomainPolicy` does not appear in the graph.
401
0
    if (!level->has_any_policy() &&
402
0
        level->Find(mapping->issuerDomainPolicy) == nullptr) {
403
0
      continue;
404
0
    }
405
406
0
    if (next_nodes.empty() || OBJ_cmp(next_nodes.back().policy.get(),
407
0
                                      mapping->subjectDomainPolicy) != 0) {
408
0
      auto new_node = X509PolicyNode::Create(mapping->subjectDomainPolicy);
409
0
      if (!new_node.has_value() || !next_nodes.Push(*std::move(new_node))) {
410
0
        return std::nullopt;
411
0
      }
412
0
    }
413
414
    // `mapping` is going to be destroyed, so steal its policy object.
415
0
    UniquePtr<ASN1_OBJECT> policy(
416
0
        std::exchange(mapping->issuerDomainPolicy, nullptr));
417
0
    if (!next_nodes.back().parent_policies.Push(std::move(policy))) {
418
0
      return std::nullopt;
419
0
    }
420
0
  }
421
422
0
  X509PolicyLevel next;
423
0
  next.set_has_any_policy(level->has_any_policy());
424
0
  if (!next.AddNodes(Span(next_nodes))) {
425
0
    return std::nullopt;
426
0
  }
427
0
  return next;
428
0
}
429
430
// apply_skip_certs, if `skip_certs` is non-NULL, sets `*value` to the minimum
431
// of its current value and `skip_certs`. It returns true on success and false
432
// if `skip_certs` is negative.
433
0
bool apply_skip_certs(const ASN1_INTEGER *skip_certs, size_t *value) {
434
0
  if (skip_certs == nullptr) {
435
0
    return true;
436
0
  }
437
438
  // TODO(https://crbug.com/boringssl/443): Move this check into the parser.
439
0
  if (skip_certs->type & V_ASN1_NEG) {
440
0
    OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION);
441
0
    return false;
442
0
  }
443
444
  // If `skip_certs` does not fit in `uint64_t`, it must exceed `*value`.
445
0
  uint64_t u64;
446
0
  if (ASN1_INTEGER_get_uint64(&u64, skip_certs) && u64 < *value) {
447
0
    *value = (size_t)u64;
448
0
  }
449
0
  ERR_clear_error();
450
0
  return true;
451
0
}
452
453
// process_policy_constraints updates `*explicit_policy`, `*policy_mapping`, and
454
// `*inhibit_any_policy` according to `x509`'s policy constraints and inhibit
455
// anyPolicy extensions. It returns one on success and zero on error. This
456
// implements steps (i) and (j) of RFC 5280, section 6.1.4.
457
bool process_policy_constraints(const X509 *x509, size_t *explicit_policy,
458
                                size_t *policy_mapping,
459
0
                                size_t *inhibit_any_policy) {
460
0
  int critical;
461
0
  UniquePtr<POLICY_CONSTRAINTS> constraints(
462
0
      reinterpret_cast<POLICY_CONSTRAINTS *>(
463
0
          X509_get_ext_d2i(x509, NID_policy_constraints, &critical, nullptr)));
464
0
  if (constraints == nullptr && critical != -1) {
465
0
    return false;
466
0
  }
467
0
  if (constraints != nullptr) {
468
0
    if (constraints->requireExplicitPolicy == nullptr &&
469
0
        constraints->inhibitPolicyMapping == nullptr) {
470
      // Per RFC 5280, section 4.2.1.11, at least one of the fields must be
471
      // present.
472
0
      OPENSSL_PUT_ERROR(X509, X509_R_INVALID_POLICY_EXTENSION);
473
0
      return false;
474
0
    }
475
0
    if (!apply_skip_certs(constraints->requireExplicitPolicy,
476
0
                          explicit_policy) ||
477
0
        !apply_skip_certs(constraints->inhibitPolicyMapping, policy_mapping)) {
478
0
      return false;
479
0
    }
480
0
  }
481
482
0
  UniquePtr<ASN1_INTEGER> inhibit_any_policy_ext(
483
0
      reinterpret_cast<ASN1_INTEGER *>(
484
0
          X509_get_ext_d2i(x509, NID_inhibit_any_policy, &critical, nullptr)));
485
0
  if (inhibit_any_policy_ext == nullptr && critical != -1) {
486
0
    return false;
487
0
  }
488
0
  return apply_skip_certs(inhibit_any_policy_ext.get(), inhibit_any_policy);
489
0
}
490
491
// has_explicit_policy returns true if the set of authority-space policy OIDs
492
// `levels` has some non-empty intersection with `user_policies`, and false
493
// otherwise. This mirrors the logic in RFC 5280, section 6.1.5, step (g). This
494
// function modifies `levels` and should only be called at the end of policy
495
// evaluation.
496
bool has_explicit_policy(Span<X509PolicyLevel> levels,
497
0
                         const STACK_OF(ASN1_OBJECT) *user_policies) {
498
0
  assert(user_policies == nullptr || sk_ASN1_OBJECT_is_sorted(user_policies));
499
500
  // Step (g.i). If the policy graph is empty, the intersection is empty.
501
0
  if (levels.empty() || levels.back().is_empty()) {
502
0
    return false;
503
0
  }
504
505
  // Step (g.ii). If the policy graph is not empty and the user set contains
506
  // anyPolicy, the intersection is the entire (non-empty) graph.
507
  //
508
  // If `user_policies` is empty, we interpret it as having a single anyPolicy
509
  // value. The caller may also have supplied anyPolicy explicitly.
510
0
  if (sk_ASN1_OBJECT_num(user_policies) == 0) {
511
0
    return true;
512
0
  }
513
0
  for (const ASN1_OBJECT *user_policy : user_policies) {
514
0
    if (is_any_policy(user_policy)) {
515
0
      return true;
516
0
    }
517
0
  }
518
519
  // Step (g.iii) does not delete anyPolicy nodes, so if the graph has
520
  // anyPolicy, some explicit policy will survive. The actual intersection may
521
  // synthesize some nodes in step (g.iii.3), but we do not return the policy
522
  // list itself, so we skip actually computing this.
523
0
  if (levels.back().has_any_policy()) {
524
0
    return true;
525
0
  }
526
527
  // We defer pruning the tree, so as we look for nodes with parent anyPolicy,
528
  // step (g.iii.1), we must limit to nodes reachable from the bottommost level.
529
  // Start by marking each of those nodes as reachable.
530
0
  for (X509PolicyNode &node : levels.back().nodes()) {
531
0
    node.reachable = true;
532
0
  }
533
534
0
  const size_t num_levels = levels.size();
535
0
  for (size_t i = num_levels - 1; i < num_levels; i--) {
536
0
    X509PolicyLevel &level = levels[i];
537
0
    for (X509PolicyNode &node : level.nodes()) {
538
0
      if (!node.reachable) {
539
0
        continue;
540
0
      }
541
0
      if (node.parent_is_any_policy()) {
542
        // `node`'s parent is anyPolicy and is part of "valid_policy_node_set".
543
        // If it exists in `user_policies`, the intersection is non-empty and we
544
        // can return immediately.
545
0
        if (sk_ASN1_OBJECT_find(user_policies, /*out_index=*/nullptr,
546
0
                                node.policy.get())) {
547
0
          return true;
548
0
        }
549
0
      } else if (i > 0) {
550
        // `node`'s parents are concrete policies. Mark the parents reachable,
551
        // to be inspected by the next loop iteration.
552
0
        X509PolicyLevel &prev = levels[i - 1];
553
0
        for (const auto &parent_policy : node.parent_policies) {
554
0
          X509PolicyNode *parent_node = prev.Find(parent_policy.get());
555
0
          if (parent_node != nullptr) {
556
0
            parent_node->reachable = true;
557
0
          }
558
0
        }
559
0
      }
560
0
    }
561
0
  }
562
563
0
  return false;
564
0
}
565
566
0
int asn1_object_cmp(const ASN1_OBJECT *const *a, const ASN1_OBJECT *const *b) {
567
0
  return OBJ_cmp(*a, *b);
568
0
}
569
570
}  // namespace
571
572
int X509_policy_check(const STACK_OF(X509) *certs,
573
                      const STACK_OF(ASN1_OBJECT) *user_policies,
574
0
                      unsigned long flags, int *out_error_depth) {
575
0
  *out_error_depth = 0;
576
577
  // Skip policy checking if the chain is just the trust anchor.
578
  //
579
  // TODO(crbug.com/525688038): Apply trust anchor constraints. See RFC 5937 and
580
  // ApplyTrustAnchorConstraints from verify_certificate_chain.cc.
581
0
  const size_t num_certs = sk_X509_num(certs);
582
0
  if (num_certs <= 1) {
583
0
    return X509_V_OK;
584
0
  }
585
586
  // See RFC 5280, section 6.1.2, steps (d) through (f).
587
0
  size_t explicit_policy =
588
0
      (flags & X509_V_FLAG_EXPLICIT_POLICY) ? 0 : num_certs + 1;
589
0
  size_t inhibit_any_policy =
590
0
      (flags & X509_V_FLAG_INHIBIT_ANY) ? 0 : num_certs + 1;
591
0
  size_t policy_mapping = (flags & X509_V_FLAG_INHIBIT_MAP) ? 0 : num_certs + 1;
592
593
0
  Vector<X509PolicyLevel> levels;
594
0
  std::optional<X509PolicyLevel> level;
595
0
  for (size_t i = num_certs - 2; i < num_certs; i--) {
596
0
    X509 *cert = sk_X509_value(certs, i);
597
0
    uint32_t ex_flags = X509_get_extension_flags(cert);
598
0
    if (ex_flags & EXFLAG_INVALID) {
599
0
      *out_error_depth = static_cast<int>(i);
600
0
      return X509_V_ERR_OUT_OF_MEM;
601
0
    }
602
0
    const bool is_self_issued = (ex_flags & EXFLAG_SI) != 0;
603
604
    // In all but the first iteration, the previous iteration will have prepared
605
    // "expected_policy_set" for us as a staging level.
606
0
    if (!level.has_value()) {
607
0
      assert(i == num_certs - 2);
608
0
      level.emplace();
609
0
      level->set_has_any_policy(true);
610
0
    }
611
612
    // RFC 5280, section 6.1.3, steps (d) and (e). `any_policy_allowed` is
613
    // computed as in step (d.2).
614
0
    const int any_policy_allowed =
615
0
        inhibit_any_policy > 0 || (i > 0 && is_self_issued);
616
0
    if (!process_certificate_policies(cert, &*level, any_policy_allowed)) {
617
0
      *out_error_depth = static_cast<int>(i);
618
0
      return X509_V_ERR_INVALID_POLICY_EXTENSION;
619
0
    }
620
621
    // RFC 5280, section 6.1.3, step (f).
622
0
    if (explicit_policy == 0 && level->is_empty()) {
623
0
      *out_error_depth = static_cast<int>(i);
624
0
      return X509_V_ERR_NO_EXPLICIT_POLICY;
625
0
    }
626
627
    // Insert the completed level into the list.
628
0
    if (!levels.Push(*std::exchange(level, std::nullopt))) {
629
0
      *out_error_depth = static_cast<int>(i);
630
0
      return X509_V_ERR_OUT_OF_MEM;
631
0
    }
632
0
    level = std::nullopt;
633
634
    // If this is not the leaf certificate, we go to section 6.1.4. If it
635
    // is the leaf certificate, we go to section 6.1.5 instead.
636
0
    if (i != 0) {
637
      // RFC 5280, section 6.1.4, steps (a) and (b).
638
0
      level = process_policy_mappings(cert, &levels.back(), policy_mapping > 0);
639
0
      if (!level.has_value()) {
640
0
        *out_error_depth = static_cast<int>(i);
641
0
        return X509_V_ERR_INVALID_POLICY_EXTENSION;
642
0
      }
643
0
    }
644
645
    // RFC 5280, section 6.1.4, step (h-j) for non-leaves, and section 6.1.5,
646
    // step (a-b) for leaves. In the leaf case, RFC 5280 says only to update
647
    // `explicit_policy`, but `policy_mapping` and `inhibit_any_policy` are no
648
    // longer read at this point, so we use the same process.
649
0
    if (i == 0 || !is_self_issued) {
650
0
      if (explicit_policy > 0) {
651
0
        explicit_policy--;
652
0
      }
653
0
      if (policy_mapping > 0) {
654
0
        policy_mapping--;
655
0
      }
656
0
      if (inhibit_any_policy > 0) {
657
0
        inhibit_any_policy--;
658
0
      }
659
0
    }
660
0
    if (!process_policy_constraints(cert, &explicit_policy, &policy_mapping,
661
0
                                    &inhibit_any_policy)) {
662
0
      *out_error_depth = static_cast<int>(i);
663
0
      return X509_V_ERR_INVALID_POLICY_EXTENSION;
664
0
    }
665
0
  }
666
667
  // RFC 5280, section 6.1.5, step (g). We do not output the policy set, so it
668
  // is only necessary to check if the user-constrained-policy-set is not empty.
669
0
  if (explicit_policy == 0) {
670
    // Build a sorted copy of `user_policies` for more efficient lookup.
671
0
    STACK_OF(ASN1_OBJECT) *user_policies_sorted = nullptr;
672
    // `user_policies_sorted`'s contents are owned by `user_policies`, so we do
673
    // not use `sk_ASN1_OBJECT_pop_free`.
674
0
    Cleanup cleanup = [&] { sk_ASN1_OBJECT_free(user_policies_sorted); };
675
0
    if (user_policies != nullptr) {
676
0
      user_policies_sorted = sk_ASN1_OBJECT_dup(user_policies);
677
0
      if (user_policies_sorted == nullptr) {
678
0
        return X509_V_ERR_OUT_OF_MEM;
679
0
      }
680
0
      sk_ASN1_OBJECT_set_cmp_func(user_policies_sorted, asn1_object_cmp);
681
0
      sk_ASN1_OBJECT_sort(user_policies_sorted);
682
0
    }
683
684
0
    if (!has_explicit_policy(Span(levels), user_policies_sorted)) {
685
0
      return X509_V_ERR_NO_EXPLICIT_POLICY;
686
0
    }
687
0
  }
688
689
0
  return X509_V_OK;
690
0
}
691
692
BSSL_NAMESPACE_END