StormByte-Crypto 3.1.0
C++26 cryptography module of the StormByte suite
Loading...
Searching...
No Matches
certificate.hxx
Go to the documentation of this file.
1/*
2 * Copyright (C) 2024-2026 David C. Manuelda (StormBytePP)
3 *
4 * This file is part of StormByte-Crypto.
5 *
6 * StormByte-Crypto original source is dual-licensed:
7 *
8 * 1. GNU Lesser General Public License v3.0 (or later)
9 * You may redistribute and/or modify this file under the terms of the
10 * GNU Lesser General Public License as published by the Free Software
11 * Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * 2. Commercial license
15 * Alternatively, this file may be used under the terms of a commercial
16 * license agreement with the copyright holder
17 * (David C. Manuelda <StormByte@gmail.com>).
18 *
19 * Both licenses apply only to original StormByte-Crypto source in this
20 * repository. They do not cover other StormByte modules or any third-party
21 * material shipped with this repository (including everything under
22 * thirdparty/, in particular Crypto++, bundled libbzip2, the StormByte-Buffer
23 * tree and the StormByte suite it vendors), which remains under its own license.
24 *
25 * Neither license grants any patent rights. Any patent licenses required
26 * to use this software or third-party components must be obtained separately
27 * from the patent holders.
28 *
29 * StormByte-Crypto is distributed in the hope that it will be useful,
30 * but WITHOUT ANY WARRANTY; without even the implied warranty of
31 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
32 * GNU Lesser General Public License for more details.
33 *
34 * You should have received a copy of the GNU Lesser General Public License
35 * version 3 along with StormByte-Crypto. If not, see
36 * <https://www.gnu.org/licenses/lgpl-3.0.html>.
37 *
38 * SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-StormByte-Commercial
39 */
40
41#pragma once
42
45#include <StormByte/expected.hxx>
46#include <StormByte/safe/binary.hxx>
47#include <StormByte/safe/optional.hxx>
48#include <StormByte/safe/string.hxx>
49#include <StormByte/safe/vector.hxx>
50
51#include <chrono>
52#include <cstddef>
53#include <cstdint>
54#include <span>
55#include <string_view>
56
61namespace StormByte {
66 namespace Crypto {
71 namespace X509 {
75 using TimePoint = std::chrono::sys_seconds;
77
82 enum class KeyUsage: std::uint16_t {
83 DigitalSignature = 1u << 0,
84 NonRepudiation = 1u << 1,
85 KeyEncipherment = 1u << 2,
86 DataEncipherment = 1u << 3,
87 KeyAgreement = 1u << 4,
88 KeyCertSign = 1u << 5,
89 CRLSign = 1u << 6,
90 EncipherOnly = 1u << 7,
91 DecipherOnly = 1u << 8
92 };
93
98 enum class SubjectAltNameType {
101 };
102
114
119 enum class TLSRole {
122 };
123
131
144
149
157 public:
161 SubjectAltName() noexcept;
162
169
175
181
185 ~SubjectAltName() noexcept;
186
192 SubjectAltName& operator=(const SubjectAltName& other);
193
199 SubjectAltName& operator=(SubjectAltName&& other) noexcept;
200
205 SubjectAltNameType Type() const noexcept;
206
212 const Safe::Binary& Value() const noexcept;
213
214 private:
215 SubjectAltNameType m_type;
216 Safe::Binary m_value;
217 };
218
219 }
220 }
221}
222
224
229namespace StormByte {
234 namespace Crypto {
239 namespace X509 {
244
249
263 public:
271 Certificate() noexcept;
272
278
283 Certificate(Certificate&& other) noexcept;
284
288 ~Certificate() noexcept;
289
295 Certificate& operator=(const Certificate& other);
296
302 Certificate& operator=(Certificate&& other) noexcept;
303
309 bool operator==(const Certificate& other) const noexcept;
311
322 static bool Parse(std::span<const std::byte> der, Certificate& out) noexcept;
323
329 Safe::Binary Save(KeyPair::StorageFormat format = KeyPair::StorageFormat::PEM) const;
330
335 const Safe::Binary& Der() const noexcept;
337
346 unsigned Version() const noexcept;
347
352 Safe::Binary SerialNumber() const;
353
358 Safe::String SubjectCommonName() const;
359
366 bool HasUniqueSubjectCommonName(std::string_view expected) const noexcept;
367
372 Safe::String IssuerCommonName() const;
373
378 TimePoint NotBefore() const noexcept;
379
384 TimePoint NotAfter() const noexcept;
385
390 bool IsCA() const noexcept;
391
396 Safe::Optional<std::uint32_t> PathLength() const;
397
403 bool HasKeyUsage(KeyUsage usage) const noexcept;
404
409 KeyPair::Generic::PointerType PublicKey() const noexcept;
411
421 bool IsValidAt(TimePoint at) const noexcept;
422
430 bool IsIssuedBy(const Certificate& issuer) const noexcept;
431
445 bool VerifyChain(std::span<const Certificate> intermediates, const Certificate& anchor,
446 TimePoint at) const noexcept;
447
454 bool VerifyChain(std::span<const Certificate> intermediates, const Certificate& anchor) const noexcept;
455
482
498
509 std::span<const std::byte> message, std::span<const std::byte> signature) const noexcept;
511
534
557 ExpectedIdentity VerifyDNSName(std::string_view expected) const;
558
572 ExpectedIdentity VerifyIPAddress(std::span<const std::byte> expected) const;
574
575 private:
580 struct Range {
581 std::size_t offset = 0;
582 std::size_t length = 0;
583 };
584
585 friend class TLSPeerVerifier;
586 friend class RevocationVerifier;
587
588 Safe::Binary m_der;
589 Range m_tbs;
590 Range m_signature_algorithm;
591 Range m_signature;
592 Range m_serial;
593 Range m_issuer;
594 Range m_subject;
595 Range m_public_key;
596 Range m_subject_alt_name;
597 Range m_extended_key_usage;
598 Range m_key_usage_der;
599 std::int64_t m_not_before = 0;
600 std::int64_t m_not_after = 0;
601 std::uint32_t m_path_length = 0;
602 std::uint16_t m_key_usage = 0;
603 std::uint8_t m_version = 1;
604 bool m_ca = false;
605 bool m_has_path_length = false;
606 bool m_has_key_usage = false;
607 bool m_unknown_critical = false;
608 bool m_has_subject_alt_name = false;
609 bool m_has_extended_key_usage = false;
610
611
617 std::span<const std::byte> View(const Range& range) const noexcept;
618
626 bool VerifySignedData(std::span<const std::byte> algorithm,
627 std::span<const std::byte> message, std::span<const std::byte> signature) const noexcept;
628 };
629 }
630 }
631}
632
634
635namespace StormByte::Crypto::X509 {
641 STORMBYTE_CRYPTO_PUBLIC Safe::Optional<Certificate> Load(std::span<const std::byte> data) noexcept;
642
648 STORMBYTE_CRYPTO_PUBLIC Safe::Vector<Certificate> LoadAll(std::span<const std::byte> data) noexcept;
649}
Immutable, strictly DER-parsed X.509 certificate.
Definition certificate.hxx:262
bool VerifyDetachedSignature(DetachedSignatureAlgorithm algorithm, std::span< const std::byte > message, std::span< const std::byte > signature) const noexcept
Verifies a detached signature with this certificate's public key.
static bool Parse(std::span< const std::byte > der, Certificate &out) noexcept
Parses a single DER certificate; see also X509::Load.
unsigned Version() const noexcept
Returns the certificate version.
TimePoint NotBefore() const noexcept
Returns the start of the validity period.
friend class RevocationVerifier
Offline CRL/OCSP verification shares parsed certificate state.
Definition certificate.hxx:586
friend class TLSPeerVerifier
Additive peer composition shares immutable parser state.
Definition certificate.hxx:585
KeyPair::Generic::PointerType PublicKey() const noexcept
Returns the subject public key.
ExpectedSubjectAltNames SubjectAltNames() const
Extracts the supported entries of the subjectAltName extension.
ExpectedIdentity VerifyDNSName(std::string_view expected) const
Checks that the certificate asserts an expected DNS host name.
bool HasKeyUsage(KeyUsage usage) const noexcept
Tells whether the key may be used for usage.
ExpectedPurpose VerifyTLSPurpose(TLSRole role) const
Checks only EKU and KU for a TLS 1.3 certificate signing role.
Certificate() noexcept
Empty certificate; it has no DER and never verifies.
bool IsIssuedBy(const Certificate &issuer) const noexcept
Checks name chaining and the signature against issuer.
ExpectedIdentity VerifyIPAddress(std::span< const std::byte > expected) const
Checks that the certificate asserts an expected IP address.
bool IsCA() const noexcept
Tells whether basicConstraints marks the certificate as a CA.
Safe::Binary SerialNumber() const
Returns the serial number.
Safe::Optional< std::uint32_t > PathLength() const
Returns the basicConstraints path length constraint.
const Safe::Binary & Der() const noexcept
Returns the original DER encoding.
Safe::String SubjectCommonName() const
Returns the subject common name.
Safe::String IssuerCommonName() const
Returns the issuer common name.
ExpectedPurpose VerifyCodeSigningPurpose() const
Checks only EKU and KU for code signing.
bool HasUniqueSubjectCommonName(std::string_view expected) const noexcept
Matches exactly one subject CN against a byte-exact identity.
TimePoint NotAfter() const noexcept
Returns the end of the validity period.
bool VerifyChain(std::span< const Certificate > intermediates, const Certificate &anchor, TimePoint at) const noexcept
Verifies this certificate up to a trusted anchor.
Safe::Binary Save(KeyPair::StorageFormat format=KeyPair::StorageFormat::PEM) const
Encodes the certificate.
bool IsValidAt(TimePoint at) const noexcept
Checks the validity period.
Verifies supplied CRL/OCSP evidence offline using Crypto primitives.
Definition revocation.hxx:120
const Safe::Binary & Value() const noexcept
Returns the raw value.
SubjectAltName() noexcept
Empty DNS entry with no value.
STORMBYTE_DECLARE_MAYBE_SAFE(class StormByte::System::Device::Access)
Keypairs of the Crypto module.
X.509 certificate parsing and chain verification.
StormByte::Expected< void, PurposeError > ExpectedPurpose
Success when certificate usage permits a purpose, or a typed error.
Definition certificate.hxx:148
Safe::Vector< Certificate > LoadAll(std::span< const std::byte > data) noexcept
Loads every CERTIFICATE block of a PEM bundle, in order.
TLSRole
Certificate signing role in TLS 1.3 (RFC 8446 §4.4.2.2).
Definition certificate.hxx:119
@ Client
Certificate used by the TLS client.
Definition certificate.hxx:121
@ Server
Certificate used by the TLS server.
Definition certificate.hxx:120
Safe::Optional< Certificate > Load(std::span< const std::byte > data) noexcept
Loads one certificate from DER or PEM.
StormByte::Expected< void, IdentityError > ExpectedIdentity
Success when the expected identity is present, or a typed error.
Definition certificate.hxx:248
PurposeError
Errors of narrowly scoped certificate-purpose checks.
Definition certificate.hxx:136
@ InvalidCertificate
Certificate is empty or moved from.
Definition certificate.hxx:138
@ KeyUsageNotAllowed
Present KU lacks digitalSignature.
Definition certificate.hxx:142
@ ExtendedKeyUsageNotAllowed
EKU does not permit the requested purpose.
Definition certificate.hxx:140
@ MalformedExtendedKeyUsage
EKU is not a non-empty strict DER sequence of valid OIDs.
Definition certificate.hxx:139
@ MalformedKeyUsage
Present KU violates DER named-bit-string encoding or its 1..9-bit range.
Definition certificate.hxx:141
@ UnsupportedRole
Role is not Server or Client.
Definition certificate.hxx:137
std::chrono::sys_seconds TimePoint
Point in time with second precision, as stored in certificates.
Definition certificate.hxx:75
DetachedSignatureAlgorithm
Supported algorithms and encodings for detached signatures.
Definition certificate.hxx:128
@ ECDSA_SHA384
ECDSA with SHA-384, encoded as a DER SEQUENCE of INTEGERs.
Definition certificate.hxx:129
SubjectAltNameType
Supported subjectAltName general name kinds (RFC 5280 §4.2.1.6).
Definition certificate.hxx:98
@ IP
iPAddress, 4 (IPv4) or 16 (IPv6) network-order bytes.
Definition certificate.hxx:100
@ DNS
dNSName, an ASCII host name or a leftmost-label wildcard pattern.
Definition certificate.hxx:99
StormByte::Expected< Safe::Vector< SubjectAltName >, IdentityError > ExpectedSubjectAltNames
Supported subjectAltName entries, or a typed extraction error.
Definition certificate.hxx:243
KeyUsage
Bits of the keyUsage extension (RFC 5280 §4.2.1.3).
Definition certificate.hxx:82
@ CRLSign
cRLSign
Definition certificate.hxx:89
@ DecipherOnly
decipherOnly
Definition certificate.hxx:91
@ KeyEncipherment
keyEncipherment
Definition certificate.hxx:85
@ DigitalSignature
digitalSignature
Definition certificate.hxx:83
@ KeyAgreement
keyAgreement
Definition certificate.hxx:87
@ DataEncipherment
dataEncipherment
Definition certificate.hxx:86
@ KeyCertSign
keyCertSign
Definition certificate.hxx:88
@ NonRepudiation
nonRepudiation (contentCommitment)
Definition certificate.hxx:84
@ EncipherOnly
encipherOnly
Definition certificate.hxx:90
IdentityError
Errors of subjectAltName extraction and expected-identity verification.
Definition certificate.hxx:107
@ MalformedSubjectAltName
The subjectAltName extension or one of its entries is malformed.
Definition certificate.hxx:111
@ InvalidExpectedName
The expected DNS name is not an acceptable ASCII host name.
Definition certificate.hxx:108
@ InvalidExpectedAddress
The expected IP address is not exactly 4 or 16 bytes.
Definition certificate.hxx:109
@ MissingSubjectAltName
The certificate has no subjectAltName extension.
Definition certificate.hxx:110
@ NoMatch
The extension is well formed but no entry matches the expected identity.
Definition certificate.hxx:112
Crypto module of the StormByte suite.
Definition aead.hxx:53
Root namespace of the StormByte suite.
std::conditional_t< Type::Reference< T >, std::expected< std::reference_wrapper< std::remove_reference_t< T > >, Safe::Shared< E > >, std::expected< T, Safe::Shared< E > > > Expected
STL namespace.
#define STORMBYTE_CRYPTO_PUBLIC
Definition visibility.h:53