pkixtestutil.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  5. */
  6. #ifndef mozilla_pkix_test_pkixtestutil_h
  7. #define mozilla_pkix_test_pkixtestutil_h
  8. #include <cstdint>
  9. #include <cstring>
  10. #include <ctime>
  11. #include <string>
  12. #include "pkix/pkixtypes.h"
  13. namespace mozilla {
  14. namespace pkix {
  15. namespace test {
  16. typedef std::basic_string<uint8_t> ByteString;
  17. inline bool ENCODING_FAILED(const ByteString& bs) { return bs.empty(); }
  18. template <size_t L>
  19. inline ByteString BytesToByteString(const uint8_t (&bytes)[L]) {
  20. return ByteString(bytes, L);
  21. }
  22. // XXX: Ideally, we should define this instead:
  23. //
  24. // template <typename T, std::size_t N>
  25. // constexpr inline std::size_t
  26. // ArrayLength(T (&)[N])
  27. // {
  28. // return N;
  29. // }
  30. //
  31. // However, we don't because not all supported compilers support constexpr,
  32. // and we need to calculate array lengths in static_assert sometimes.
  33. //
  34. // XXX: Evaluates its argument twice
  35. #define MOZILLA_PKIX_ARRAY_LENGTH(x) (sizeof(x) / sizeof((x)[0]))
  36. bool InputEqualsByteString(Input input, const ByteString& bs);
  37. ByteString InputToByteString(Input input);
  38. // python DottedOIDToCode.py --tlv id-kp-OCSPSigning 1.3.6.1.5.5.7.3.9
  39. static const uint8_t tlv_id_kp_OCSPSigning[] = {0x06, 0x08, 0x2b, 0x06, 0x01,
  40. 0x05, 0x05, 0x07, 0x03, 0x09};
  41. // python DottedOIDToCode.py --tlv id-kp-serverAuth 1.3.6.1.5.5.7.3.1
  42. static const uint8_t tlv_id_kp_serverAuth[] = {0x06, 0x08, 0x2b, 0x06, 0x01,
  43. 0x05, 0x05, 0x07, 0x03, 0x01};
  44. enum class TestDigestAlgorithmID {
  45. MD2,
  46. MD5,
  47. SHA1,
  48. SHA224,
  49. SHA256,
  50. SHA384,
  51. SHA512,
  52. };
  53. struct TestPublicKeyAlgorithm {
  54. explicit TestPublicKeyAlgorithm(const ByteString& aAlgorithmIdentifier)
  55. : algorithmIdentifier(aAlgorithmIdentifier) {}
  56. bool operator==(const TestPublicKeyAlgorithm& other) const {
  57. return algorithmIdentifier == other.algorithmIdentifier;
  58. }
  59. ByteString algorithmIdentifier;
  60. };
  61. ByteString DSS_P();
  62. ByteString DSS_Q();
  63. ByteString DSS_G();
  64. TestPublicKeyAlgorithm DSS();
  65. TestPublicKeyAlgorithm RSA_PKCS1();
  66. struct TestSignatureAlgorithm {
  67. TestSignatureAlgorithm(const TestPublicKeyAlgorithm& publicKeyAlg,
  68. TestDigestAlgorithmID digestAlg,
  69. const ByteString& algorithmIdentifier, bool accepted);
  70. TestPublicKeyAlgorithm publicKeyAlg;
  71. TestDigestAlgorithmID digestAlg;
  72. ByteString algorithmIdentifier;
  73. bool accepted;
  74. };
  75. TestSignatureAlgorithm md2WithRSAEncryption();
  76. TestSignatureAlgorithm md5WithRSAEncryption();
  77. TestSignatureAlgorithm sha1WithRSAEncryption();
  78. TestSignatureAlgorithm sha256WithRSAEncryption();
  79. // e.g. YMDHMS(2016, 12, 31, 1, 23, 45) => 2016-12-31:01:23:45 (GMT)
  80. mozilla::pkix::Time YMDHMS(uint16_t year, uint16_t month, uint16_t day,
  81. uint16_t hour, uint16_t minutes, uint16_t seconds);
  82. ByteString TLV(uint8_t tag, size_t length, const ByteString& value);
  83. inline ByteString TLV(uint8_t tag, const ByteString& value) {
  84. return TLV(tag, value.length(), value);
  85. }
  86. // Although we can't enforce it without relying on Cuser-defined literals,
  87. // which aren't supported by all of our compilers yet, you should only pass
  88. // string literals as the last parameter to the following two functions.
  89. template <size_t N>
  90. inline ByteString TLV(uint8_t tag, const char (&value)[N]) {
  91. static_assert(N > 0, "cannot have string literal of size 0");
  92. assert(value[N - 1] == 0);
  93. return TLV(tag, ByteString(reinterpret_cast<const uint8_t*>(&value), N - 1));
  94. }
  95. template <size_t N>
  96. inline ByteString TLV(uint8_t tag, size_t length, const char (&value)[N]) {
  97. static_assert(N > 0, "cannot have string literal of size 0");
  98. assert(value[N - 1] == 0);
  99. return TLV(tag, length,
  100. ByteString(reinterpret_cast<const uint8_t*>(&value), N - 1));
  101. }
  102. ByteString Boolean(bool value);
  103. ByteString Integer(long value);
  104. ByteString CN(const ByteString&, uint8_t encodingTag = 0x0c /*UTF8String*/);
  105. inline ByteString CN(const char* value,
  106. uint8_t encodingTag = 0x0c /*UTF8String*/) {
  107. return CN(
  108. ByteString(reinterpret_cast<const uint8_t*>(value), std::strlen(value)),
  109. encodingTag);
  110. }
  111. ByteString OU(const ByteString&, uint8_t encodingTag = 0x0c /*UTF8String*/);
  112. inline ByteString OU(const char* value,
  113. uint8_t encodingTag = 0x0c /*UTF8String*/) {
  114. return OU(
  115. ByteString(reinterpret_cast<const uint8_t*>(value), std::strlen(value)),
  116. encodingTag);
  117. }
  118. ByteString emailAddress(const ByteString&);
  119. inline ByteString emailAddress(const char* value) {
  120. return emailAddress(
  121. ByteString(reinterpret_cast<const uint8_t*>(value), std::strlen(value)));
  122. }
  123. // RelativeDistinguishedName ::=
  124. // SET SIZE (1..MAX) OF AttributeTypeAndValue
  125. //
  126. ByteString RDN(const ByteString& avas);
  127. // Name ::= CHOICE { -- only one possibility for now --
  128. // rdnSequence RDNSequence }
  129. //
  130. // RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
  131. //
  132. ByteString Name(const ByteString& rdns);
  133. inline ByteString CNToDERName(const ByteString& cn) {
  134. return Name(RDN(CN(cn)));
  135. }
  136. inline ByteString CNToDERName(const char* cn) { return Name(RDN(CN(cn))); }
  137. // GeneralName ::= CHOICE {
  138. // otherName [0] OtherName,
  139. // rfc822Name [1] IA5String,
  140. // dNSName [2] IA5String,
  141. // x400Address [3] ORAddress,
  142. // directoryName [4] Name,
  143. // ediPartyName [5] EDIPartyName,
  144. // uniformResourceIdentifier [6] IA5String,
  145. // iPAddress [7] OCTET STRING,
  146. // registeredID [8] OBJECT IDENTIFIER }
  147. inline ByteString RFC822Name(const ByteString& name) {
  148. // (2 << 6) means "context-specific", 1 is the GeneralName tag.
  149. return TLV((2 << 6) | 1, name);
  150. }
  151. template <size_t L>
  152. inline ByteString RFC822Name(const char (&bytes)[L]) {
  153. return RFC822Name(
  154. ByteString(reinterpret_cast<const uint8_t*>(&bytes), L - 1));
  155. }
  156. inline ByteString DNSName(const ByteString& name) {
  157. // (2 << 6) means "context-specific", 2 is the GeneralName tag.
  158. return TLV((2 << 6) | 2, name);
  159. }
  160. template <size_t L>
  161. inline ByteString DNSName(const char (&bytes)[L]) {
  162. return DNSName(ByteString(reinterpret_cast<const uint8_t*>(&bytes), L - 1));
  163. }
  164. inline ByteString DirectoryName(const ByteString& name) {
  165. // (2 << 6) means "context-specific", (1 << 5) means "constructed", and 4 is
  166. // the DirectoryName tag.
  167. return TLV((2 << 6) | (1 << 5) | 4, name);
  168. }
  169. inline ByteString IPAddress() {
  170. // (2 << 6) means "context-specific", 7 is the GeneralName tag.
  171. return TLV((2 << 6) | 7, ByteString());
  172. }
  173. template <size_t L>
  174. inline ByteString IPAddress(const uint8_t (&bytes)[L]) {
  175. // (2 << 6) means "context-specific", 7 is the GeneralName tag.
  176. return TLV((2 << 6) | 7, ByteString(bytes, L));
  177. }
  178. // Names should be zero or more GeneralNames, like DNSName and IPAddress return,
  179. // concatenated together.
  180. //
  181. // CreatedEncodedSubjectAltName(ByteString()) results in a SAN with an empty
  182. // sequence. CreateEmptyEncodedSubjectName() results in a SAN without any
  183. // sequence.
  184. ByteString CreateEncodedSubjectAltName(const ByteString& names);
  185. ByteString CreateEncodedEmptySubjectAltName();
  186. class TestKeyPair {
  187. public:
  188. virtual ~TestKeyPair() {}
  189. const TestPublicKeyAlgorithm publicKeyAlg;
  190. // The DER encoding of the entire SubjectPublicKeyInfo structure. This is
  191. // what is encoded in certificates.
  192. const ByteString subjectPublicKeyInfo;
  193. // The DER encoding of subjectPublicKeyInfo.subjectPublicKey. This is what is
  194. // hashed to create CertIDs for OCSP.
  195. const ByteString subjectPublicKey;
  196. virtual Result SignData(const ByteString& tbs,
  197. const TestSignatureAlgorithm& signatureAlgorithm,
  198. /*out*/ ByteString& signature) const = 0;
  199. virtual TestKeyPair* Clone() const = 0;
  200. protected:
  201. TestKeyPair(const TestPublicKeyAlgorithm& publicKeyAlg,
  202. const ByteString& spk);
  203. TestKeyPair(const TestKeyPair&) = delete;
  204. void operator=(const TestKeyPair&) = delete;
  205. };
  206. TestKeyPair* CloneReusedKeyPair();
  207. TestKeyPair* GenerateKeyPair();
  208. TestKeyPair* GenerateDSSKeyPair();
  209. inline void DeleteTestKeyPair(TestKeyPair* keyPair) { delete keyPair; }
  210. typedef std::unique_ptr<TestKeyPair> ScopedTestKeyPair;
  211. Result TestVerifyECDSASignedDigest(const SignedDigest& signedDigest,
  212. Input subjectPublicKeyInfo);
  213. Result TestVerifyRSAPKCS1SignedDigest(const SignedDigest& signedDigest,
  214. Input subjectPublicKeyInfo);
  215. Result TestDigestBuf(Input item, DigestAlgorithm digestAlg,
  216. /*out*/ uint8_t* digestBuf, size_t digestBufLen);
  217. // Replace one substring in item with another of the same length, but only if
  218. // the substring was found exactly once. The "same length" restriction is
  219. // useful for avoiding invalidating lengths encoded within the item. The
  220. // "only once" restriction is helpful for avoiding making accidental changes.
  221. //
  222. // The string to search for must be 8 or more bytes long so that it is
  223. // extremely unlikely that there will ever be any false positive matches
  224. // in digital signatures, keys, hashes, etc.
  225. Result TamperOnce(/*in/out*/ ByteString& item, const ByteString& from,
  226. const ByteString& to);
  227. ///////////////////////////////////////////////////////////////////////////////
  228. // Encode Certificates
  229. enum Version { v1 = 0, v2 = 1, v3 = 2 };
  230. // signature is assumed to be the DER encoding of an AlgorithmIdentifer. It is
  231. // put into the signature field of the TBSCertificate. In most cases, it will
  232. // be the same as signatureAlgorithm, which is the algorithm actually used
  233. // to sign the certificate.
  234. // serialNumber is assumed to be the DER encoding of an INTEGER.
  235. //
  236. // If extensions is null, then no extensions will be encoded. Otherwise,
  237. // extensions must point to an array of ByteStrings, terminated with an empty
  238. // ByteString. (If the first item of the array is empty then an empty
  239. // Extensions sequence will be encoded.)
  240. ByteString CreateEncodedCertificate(
  241. long version, const TestSignatureAlgorithm& signature,
  242. const ByteString& serialNumber, const ByteString& issuerNameDER,
  243. time_t notBefore, time_t notAfter, const ByteString& subjectNameDER,
  244. const TestKeyPair& subjectKeyPair,
  245. /*optional*/ const ByteString* extensions, const TestKeyPair& issuerKeyPair,
  246. const TestSignatureAlgorithm& signatureAlgorithm);
  247. ByteString CreateEncodedSerialNumber(long value);
  248. enum class Critical { No = 0, Yes = 1 };
  249. ByteString CreateEncodedBasicConstraints(
  250. bool isCA,
  251. /*optional in*/ const long* pathLenConstraint, Critical critical);
  252. // Creates a DER-encoded extKeyUsage extension with one EKU OID.
  253. ByteString CreateEncodedEKUExtension(Input eku, Critical critical);
  254. ///////////////////////////////////////////////////////////////////////////////
  255. // Encode OCSP responses
  256. class OCSPResponseExtension final {
  257. public:
  258. OCSPResponseExtension();
  259. ByteString id;
  260. bool critical;
  261. ByteString value;
  262. OCSPResponseExtension* next;
  263. };
  264. class OCSPResponseContext final {
  265. public:
  266. OCSPResponseContext(const CertID& certID, std::time_t time);
  267. const CertID& certID;
  268. // TODO(bug 980538): add a way to specify what certificates are included.
  269. // The fields below are in the order that they appear in an OCSP response.
  270. enum OCSPResponseStatus {
  271. successful = 0,
  272. malformedRequest = 1,
  273. internalError = 2,
  274. tryLater = 3,
  275. // 4 is not used
  276. sigRequired = 5,
  277. unauthorized = 6,
  278. };
  279. uint8_t responseStatus; // an OCSPResponseStatus or an invalid value
  280. bool skipResponseBytes; // If true, don't include responseBytes
  281. // responderID
  282. ByteString signerNameDER; // If set, responderID will use the byName
  283. // form; otherwise responderID will use the
  284. // byKeyHash form.
  285. std::time_t producedAt;
  286. // SingleResponse extensions (for the certID given in the constructor).
  287. OCSPResponseExtension* singleExtensions;
  288. // ResponseData extensions.
  289. OCSPResponseExtension* responseExtensions;
  290. bool includeEmptyExtensions; // If true, include the extension wrapper
  291. // regardless of if there are any actual
  292. // extensions.
  293. ScopedTestKeyPair signerKeyPair;
  294. TestSignatureAlgorithm signatureAlgorithm;
  295. bool badSignature; // If true, alter the signature to fail verification
  296. const ByteString* certs; // optional; array terminated by an empty string
  297. // The following fields are on a per-SingleResponse basis. In the future we
  298. // may support including multiple SingleResponses per response.
  299. enum CertStatus {
  300. good = 0,
  301. revoked = 1,
  302. unknown = 2,
  303. };
  304. uint8_t certStatus; // CertStatus or an invalid value
  305. std::time_t revocationTime; // For certStatus == revoked
  306. std::time_t thisUpdate;
  307. std::time_t nextUpdate;
  308. bool includeNextUpdate;
  309. };
  310. ByteString CreateEncodedOCSPResponse(OCSPResponseContext& context);
  311. }
  312. }
  313. } // namespace mozilla::pkix::test
  314. #endif // mozilla_pkix_test_pkixtestutil_h