x509cert.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. // x509cert.h - X.509 certificate read and write routines for Crypto++.
  2. // Written and placed in the public domain by Jeffrey Walton
  3. // and Geoff Beier
  4. /// \file x509cert.h
  5. /// \brief Classes and functions to read X.509 certificates
  6. /// \details X509Certificate is a partial implementation of X.509 certificate
  7. /// parsing. The class loads a DER encoded certificate and presents many of
  8. /// the more important attributes and values through accessor functions. The
  9. /// attributes and values include signature, signature algorithm, toBeSigned,
  10. /// and subjectPublicKeyInfo exposed as a X509PubliKey ready for use in
  11. /// Crypto++ library algorithms.
  12. /// \details This is a library add-on. You must download and compile it
  13. /// yourself as part of the library.
  14. /// \since Crypto++ 8.3
  15. /// \sa <A HREF="http://www.cryptopp.com/wiki/X509Certificate">X509Certificate</A>
  16. /// and <A HREF="http://www.cryptopp.com/wiki/PEM_Pack">PEM Pack</A> on the
  17. /// Crypto++ wiki.
  18. /////////////////////////////////////////////////////////////////////////////
  19. #ifndef CRYPTOPP_X509_CERTIFICATE_H
  20. #define CRYPTOPP_X509_CERTIFICATE_H
  21. #include "cryptlib.h"
  22. #include "secblock.h"
  23. #include "stdcpp.h"
  24. #include "asn.h"
  25. #include <iosfwd>
  26. #include <string>
  27. #include <vector>
  28. #include <sstream>
  29. NAMESPACE_BEGIN(CryptoPP)
  30. // Forward declaration
  31. class Integer;
  32. /// \brief Convert OID to a LDAP name
  33. /// \param oid the object identifier
  34. /// \param defaultName the name to use if lookup fails
  35. /// \returns the LDAP name for display
  36. /// \details LDAP names are specified in ITU X.520 and other places, like the RFCs.
  37. /// If defaultName is NULL, then the OID is used.
  38. std::string OidToNameLookup(const OID& oid, const char *defaultName=NULLPTR);
  39. /// \brief ASNTag initializer
  40. /// \details 0 is an invalid tag value
  41. const ASNTag InvalidTag = static_cast<ASNTag>(0);
  42. //////////////////////////////////////////////////
  43. /// \brief X.500 Relative Distinguished Name value
  44. struct RdnValue : public ASN1Object
  45. {
  46. virtual ~RdnValue() {}
  47. RdnValue() : m_tag(InvalidTag) {}
  48. void BERDecode(BufferedTransformation &bt);
  49. void DEREncode(BufferedTransformation &bt) const;
  50. bool ValidateTag(byte tag) const;
  51. /// \brief Print an RDN value
  52. /// \returns ostream reference
  53. std::ostream& Print(std::ostream& out) const;
  54. /// \brief Textual representation
  55. /// \returns string representing the value
  56. std::string EncodeValue() const;
  57. OID m_oid;
  58. SecByteBlock m_value;
  59. ASNTag m_tag;
  60. };
  61. /// \brief Array of Relative Distinguished Name values
  62. /// \details Vector or RdnValue
  63. /// \sa RdnValue
  64. typedef std::vector<RdnValue> RdnValueArray;
  65. //////////////////////////////////////////////////
  66. /// \brief X.690 Date value
  67. struct DateValue : public ASN1Object
  68. {
  69. DateValue() : m_tag(InvalidTag) {}
  70. virtual ~DateValue() {}
  71. void BERDecode(BufferedTransformation &bt);
  72. void DEREncode(BufferedTransformation &bt) const;
  73. bool ValidateTag(byte tag) const;
  74. /// \brief Print a Date value
  75. /// \returns ostream reference
  76. std::ostream& Print(std::ostream& out) const;
  77. /// \brief Textual representation
  78. /// \returns string representing the value
  79. std::string EncodeValue() const;
  80. SecByteBlock m_value;
  81. ASNTag m_tag;
  82. };
  83. //////////////////////////////////////////////////
  84. /// \brief X.509 Extension value
  85. struct ExtensionValue : public ASN1Object
  86. {
  87. virtual ~ExtensionValue() {}
  88. ExtensionValue() : m_tag(InvalidTag), m_critical(false) {}
  89. void BERDecode(BufferedTransformation &bt);
  90. void DEREncode(BufferedTransformation &bt) const;
  91. bool ValidateTag(byte tag) const;
  92. /// \brief Print an Extension value
  93. /// \returns ostream reference
  94. std::ostream& Print(std::ostream& out) const;
  95. /// \brief Textual representation
  96. /// \returns string representing the value
  97. std::string EncodeValue() const;
  98. OID m_oid;
  99. SecByteBlock m_value;
  100. ASNTag m_tag;
  101. bool m_critical;
  102. };
  103. /// \brief Array of X.509 Extension values
  104. /// \details Vector or ExtensionValue
  105. /// \sa ExtensionValue
  106. typedef std::vector<ExtensionValue> ExtensionValueArray;
  107. //////////////////////////////////////////////////
  108. /// \brief X.509 KeyIdentifier value
  109. struct KeyIdentifierValue : public ASN1Object
  110. {
  111. enum KeyIdentifierEnum {
  112. /// \brief Hash of the public key
  113. Hash=1,
  114. /// \brief Distinguised name and serial number
  115. DnAndSn
  116. };
  117. /// \brief Invalid identifier
  118. static const KeyIdentifierEnum InvalidKeyIdentifier = static_cast<KeyIdentifierEnum>(0);
  119. virtual ~KeyIdentifierValue() {}
  120. KeyIdentifierValue() : m_type(InvalidKeyIdentifier) {}
  121. void BERDecode(BufferedTransformation &bt);
  122. void DEREncode(BufferedTransformation &bt) const;
  123. bool ValidateTag(byte tag) const;
  124. /// \brief Print an Extension value
  125. /// \returns ostream reference
  126. std::ostream& Print(std::ostream& out) const;
  127. /// \brief Textual representation
  128. /// \returns string representing the value
  129. std::string EncodeValue() const;
  130. // The hash of the key is placed in m_value.
  131. // The remaining bits, like DN and Serno, are placed in m_other.
  132. OID m_oid;
  133. SecByteBlock m_value;
  134. SecByteBlock m_other; // raw
  135. KeyIdentifierEnum m_type;
  136. };
  137. //////////////////////////////////////////////////
  138. /// \brief X.509 KU and EKU value
  139. /// \details KeyUsageValue represents Key Usage and Extended Key Usage values
  140. /// \sa KeyUsageValueArray
  141. struct KeyUsageValue : public ASN1Object
  142. {
  143. // https://www.iana.org/assignments/smi-numbers/smi-numbers.xhtml#smi-numbers-1.3.6.1.5.5.7.3
  144. enum KeyUsageEnum {
  145. /// \brief Digital signature
  146. digitalSignature=0,
  147. /// \brief Signature verification
  148. /// \details nonRepudiation applies to non-certificate data
  149. nonRepudiation=1,
  150. /// \brief Signature verification
  151. /// \details contentCommitment is nonRepudiation and applies to non-certificate data
  152. contentCommitment=nonRepudiation,
  153. /// \brief Key transport
  154. keyEncipherment,
  155. /// \brief Data encryption
  156. /// \details Encryption occurs with the public key, and not a symmetric key
  157. dataEncipherment,
  158. /// \brief Key agreement
  159. keyAgreement,
  160. /// \brief Certificate signature verification
  161. keyCertSign,
  162. /// \brief Certificate revocation list signature verification
  163. cRLSign,
  164. /// \brief Data encryption
  165. /// \details Data encryption occurs with a key agreement key
  166. encipherOnly,
  167. /// \brief Data decryption
  168. /// \details Data decryption occurs with a key agreement key
  169. decipherOnly,
  170. /// \brief TLS server authentication
  171. serverAuth,
  172. /// \brief TLS client authentication
  173. clientAuth,
  174. /// \brief Code signing
  175. codeSigning,
  176. /// \brief Email protection
  177. emailProtection,
  178. /// \brief IPsec end system
  179. ipsecEndSystem,
  180. /// \brief IPsec tunnel
  181. ipsecTunnel,
  182. /// \brief IPsec user
  183. ipsecUser,
  184. /// \brief Time stamping
  185. timeStamping,
  186. /// \brief OCSP signing
  187. OCSPSigning,
  188. /// \brief Data Validation and Certification Server
  189. dvcs,
  190. /// \brief Border gateway CA server
  191. sbgpCertAAServerAuth,
  192. /// \brief SCVP responder
  193. scvpResponder,
  194. /// \brief Extensible Authentication Protocol (EAP) over PPP
  195. eapOverPPP,
  196. /// \brief Extensible Authentication Protocol (EAP) over LAN
  197. eapOverLAN,
  198. /// \brief Server-Based Certificate Validation Protocol
  199. scvpServer,
  200. /// \brief Server-Based Certificate Validation Protocol
  201. scvpClient,
  202. /// \brief IPsec Internet Key Exchange
  203. ipsecIKE,
  204. /// \brief Control And Provisioning of Wireless Access Points (CAPWAP) Protocol
  205. capwapAC,
  206. /// \brief Control And Provisioning of Wireless Access Points (CAPWAP) Protocol
  207. capwapWTP,
  208. /// \brief Session Initiation Protocol (SIP) X.509 Certificates
  209. sipDomain,
  210. /// \brief X.509v3 Certificates for Secure Shell Authentication
  211. secureShellClient,
  212. /// \brief X.509v3 Certificates for Secure Shell Authentication
  213. secureShellServer,
  214. /// \brief Certificate Profile and Certificate Management for SEcure Neighbor Discovery (SEND)
  215. sendRouter,
  216. /// \brief Certificate Profile and Certificate Management for SEcure Neighbor Discovery (SEND)
  217. sendProxiedRouter,
  218. /// \brief Certificate Profile and Certificate Management for SEcure Neighbor Discovery (SEND)
  219. sendOwner,
  220. /// \brief Certificate Profile and Certificate Management for SEcure Neighbor Discovery (SEND)
  221. sendProxiedOwner,
  222. /// \brief Certificate Management over CMS
  223. cmcCA,
  224. /// \brief Certificate Management over CMS
  225. cmcRA,
  226. /// \brief Certificate Management over CMS
  227. cmcArchive,
  228. /// \brief BGPsec Router Certificates, Certificate Revocation Lists, and Certification Requests
  229. bgpsecRouter,
  230. /// \brief Certificate profile for carrying logotypes
  231. brandIndicatorforMessageIdentification
  232. };
  233. /// \brief Invalid key usage
  234. static const KeyUsageEnum InvalidKeyUsage = static_cast<KeyUsageEnum>(128);
  235. virtual ~KeyUsageValue() {}
  236. /// \brief Construct a KeyUsageValue
  237. /// \details Use this ctor for Extended Key Usage (EKU).
  238. /// KeyUsageEnum can be looked up based on a unique OID.
  239. KeyUsageValue(const OID& oid);
  240. /// \brief Construct a KeyUsageValue
  241. /// \details Use this ctor for Key Usage (KU). KeyUsageEnum
  242. /// bitmask is a value of a common OID.
  243. KeyUsageValue(const OID& oid, KeyUsageEnum usage);
  244. void BERDecode(BufferedTransformation &bt);
  245. void DEREncode(BufferedTransformation &bt) const;
  246. /// \brief Print an Extension value
  247. /// \returns ostream reference
  248. std::ostream& Print(std::ostream& out) const;
  249. /// \brief Textual representation
  250. /// \returns string representing the value
  251. std::string EncodeValue() const;
  252. OID m_oid;
  253. // SecByteBlock m_value;
  254. KeyUsageEnum m_usage;
  255. };
  256. /// \brief Array of X.509 Key usage values
  257. /// \details Vector or KeyUsageValue
  258. /// \sa KeyUsageValue
  259. typedef std::vector<KeyUsageValue> KeyUsageValueArray;
  260. //////////////////////////////////////////////////
  261. /// \brief X.509 Basic Constraint
  262. struct BasicConstraintValue : public ASN1Object
  263. {
  264. virtual ~BasicConstraintValue() {}
  265. BasicConstraintValue(bool critical=true) : m_pathLen(0), m_critical(critical), m_ca(false) {}
  266. void BERDecode(BufferedTransformation &bt);
  267. void DEREncode(BufferedTransformation &bt) const;
  268. /// \brief Print an Extension value
  269. /// \returns ostream reference
  270. std::ostream& Print(std::ostream& out) const;
  271. /// \brief Textual representation
  272. /// \returns string representing the value
  273. std::string EncodeValue() const;
  274. word32 m_pathLen;
  275. bool m_critical, m_ca;
  276. };
  277. //////////////////////////////////////////////////
  278. /// \brief Identity value
  279. /// \details IdentityValue holds an identity and provides a textual representation of it.
  280. struct IdentityValue
  281. {
  282. /// \brief Identity source
  283. enum IdentityEnum {
  284. /// \brief Subject Unique Identifier
  285. /// \details Optional part of X.509 v2 specification
  286. UniqueId=1,
  287. /// \brief Subject Distinguished Name
  288. /// \details Subject Distinguished Name (DN), which is a mashup of the RDNs
  289. SubjectDN,
  290. /// \brief Subject Common Name
  291. /// \details Common Name RDN, optional part of Subject Distinguished Name (DN)
  292. SubjectCN,
  293. /// \brief Subject Unique Identifier
  294. /// \details Subject Unique Identifier RDN, optional part of Subject Distinguished Name (DN)
  295. SubjectUID,
  296. /// \brief PKCS #9 email address
  297. /// \details PKCS #9 Email RDN, optional part of Subject Distinguished Name (DN)
  298. SubjectEmail,
  299. /// \brief Subject Public Key Identifier (SPKI)
  300. /// \details Optional part of X.509 v3 specification
  301. SubjectPKI,
  302. /// \brief SAN otherName
  303. /// \details Optional Subject Alternate Name (SAN)
  304. otherName,
  305. /// \brief SAN rfc822Name
  306. /// \details Optional Subject Alternate Name (SAN)
  307. rfc822Name,
  308. /// \brief SAN dNSName
  309. /// \details Optional Subject Alternate Name (SAN)
  310. dNSName,
  311. /// \brief SAN x400Address
  312. /// \details Optional Subject Alternate Name (SAN)
  313. x400Address,
  314. /// \brief SAN directoryName
  315. /// \details Optional Subject Alternate Name (SAN)
  316. directoryName,
  317. /// \brief SAN ediPartyName
  318. /// \details Optional Subject Alternate Name (SAN)
  319. ediPartyName,
  320. /// \brief SAN uniformResourceIdentifier
  321. /// \details Optional Subject Alternate Name (SAN)
  322. uniformResourceIdentifier,
  323. /// \brief SAN iPAddress
  324. /// \details Optional Subject Alternate Name (SAN)
  325. iPAddress,
  326. /// \brief SAN registeredID
  327. /// \details Optional Subject Alternate Name (SAN)
  328. registeredID,
  329. /// \brief nsServer
  330. /// \details Optional part of original Netscape specification
  331. nsServer,
  332. /// \brief msOtherNameUPN
  333. /// \details Microsoft Kerberos UserPrincipalName extracted from SAN otherName
  334. msOtherNameUPN
  335. };
  336. static const IdentityEnum InvalidIdentityEnum = static_cast<IdentityEnum>(0);
  337. virtual ~IdentityValue() {}
  338. IdentityValue(const SecByteBlock &value, IdentityEnum src);
  339. IdentityValue(const std::string &value, IdentityEnum src);
  340. IdentityValue(const OID &oid, const SecByteBlock &value, IdentityEnum src);
  341. IdentityValue(const OID &oid, const std::string &value, IdentityEnum src);
  342. /// \brief Print an Identity value
  343. /// \returns ostream reference
  344. std::ostream& Print(std::ostream& out) const;
  345. /// \brief Textual representation
  346. /// \returns string representing the value
  347. std::string EncodeValue() const;
  348. /// \brief Convert otherName into a different IdentityValue
  349. /// \details ConvertOtherName() operates on this object.
  350. /// m_value and m_src can be changed to a new identity
  351. /// type, like a UPN string and msOtherNameUPN type.
  352. void ConvertOtherName();
  353. OID m_oid;
  354. SecByteBlock m_value; // Raw value from source
  355. IdentityEnum m_src;
  356. };
  357. /// \brief Array of Identity values
  358. /// \details Vector or IdentityValue
  359. /// \sa IdentityValue
  360. typedef std::vector<IdentityValue> IdentityValueArray;
  361. //////////////////////////////////////////////////
  362. /// \brief X.509 Certificate
  363. /// \details X509Certificate is a partial implementation of X.509 certificate
  364. /// support. The class loads a DER encoded certificate and presents many of
  365. /// the important attributes and values through accessor functions. The
  366. /// attributes and values include signature, signature algorithm, toBeSigned,
  367. /// serialNumber, issuerDistinguishedName, subjectDistinguishedName, and
  368. /// subjectPublicKeyInfo exposed as a X509PubliKey ready for use in Crypto++
  369. /// library algorithms.
  370. /// \details Most member functions related to saving or encoding a certificate
  371. /// have not been cut-in. Calling member functions that have not been cut-in will
  372. /// result in NotImplemented exception. Future versions of the X509Certificate
  373. /// can provide them.
  374. /// \throws NotImplemented if a particular function has not been cut-in. Member
  375. /// functions that throw NotImplemented include <tt>DEREncode*</tt>.
  376. /// \details This is a library add-on. You must download and compile it
  377. /// yourself as part of the library.
  378. /// \since Crypto++ 8.3
  379. /// \sa <A HREF="http://www.cryptopp.com/wiki/X509Certificate">X509Certificate</A>
  380. /// and <A HREF="http://www.cryptopp.com/wiki/PEM_Pack">PEM Pack</A> on the
  381. /// Crypto++ wiki.
  382. class X509Certificate : public ASN1CryptoMaterial<Certificate>
  383. {
  384. public:
  385. /// \brief Certificate version
  386. enum Version {
  387. /// \brief Version 1
  388. v1=0,
  389. /// \brief Version 2
  390. v2,
  391. /// \brief Version 3
  392. v3
  393. };
  394. public:
  395. virtual ~X509Certificate() {}
  396. X509Certificate() {}
  397. // NameValuePairs
  398. virtual void AssignFrom (const NameValuePairs &source);
  399. virtual bool GetVoidValue (const char *name, const std::type_info &valueType, void *pValue) const;
  400. /// \name VALIDATION
  401. //@{
  402. // CryptoMaterial
  403. virtual bool Validate (RandomNumberGenerator &rng, unsigned int level) const;
  404. /// \brief Validate signature on this certificate
  405. /// \param rng a RandomNumberGenerator for objects which use randomized
  406. /// testing
  407. /// \param key the public key of the keypair used to sign this certificate
  408. /// \returns true if the test succeeds, false otherwise
  409. /// \details If this certificate is self-signed then the signature can be
  410. /// verified using the public key in this certificate. In this case call
  411. /// ValidateSignature() with GetSubjectPublicKey().
  412. /// \details If this certificate is signed by a CA certificate, then call
  413. /// ValidateSignature() using signing CA's public key. The CA's public
  414. /// key is found in the CA certificate using GetSubjectPublicKey().
  415. /// \sa GetSubjectPublicKey
  416. bool ValidateSignature (RandomNumberGenerator &rng, const X509PublicKey &key) const;
  417. //@}
  418. /// \name ENCODE/DECODE
  419. //@{
  420. // ASN1CryptoMaterial
  421. virtual void Save (BufferedTransformation &bt) const;
  422. virtual void Load (BufferedTransformation &bt);
  423. // ASN1Object
  424. virtual void BERDecode (BufferedTransformation &bt);
  425. virtual void DEREncode (BufferedTransformation &bt) const;
  426. //@}
  427. /// \name ASN.1 OPTIONAL
  428. //@{
  429. /// \brief Determine if Issuer UniqueId is present
  430. /// \returns true if Issuer UniqueId is present, false otherwise
  431. /// \details Issuer UniqueId is optional and available with X.509 v2.
  432. /// \sa HasSubjectUniqueId, GetIssuerUniqueId
  433. bool HasIssuerUniqueId() const;
  434. /// \brief Determine if Subject UniqueId is present
  435. /// \returns true if Subject UniqueId is present, false otherwise
  436. /// \details Subject UniqueId is optional and available with X.509 v2.
  437. /// \sa HasIssuerUniqueId, GetSubjectUniqueId
  438. bool HasSubjectUniqueId() const;
  439. /// \brief Determine if Extensions are present
  440. /// \returns true if Extensions are present, false otherwise
  441. /// \details Extensions are optional and available with X.509 v3.
  442. /// \sa GetExtensions
  443. bool HasExtensions() const;
  444. /// \brief Determine if AKI is present
  445. /// \returns true if Authority Key Identifier is present, false otherwise
  446. /// \details AKI is an optional extension and available with X.509 v3.
  447. /// \sa HasSubjectKeyIdentifier, GetAuthorityKeyIdentifier
  448. bool HasAuthorityKeyIdentifier() const;
  449. /// \brief Determine if SPKI is present
  450. /// \returns true if Subject Public Key Identifier is present, false otherwise
  451. /// \details SPKI is an optional extension and available with X.509 v3.
  452. /// \sa HasAuthorityKeyIdentifier, GetSubjectKeyIdentifier
  453. bool HasSubjectKeyIdentifier() const;
  454. //@}
  455. /// \name ACCESSORS
  456. //@{
  457. /// \brief Retrieve complete DER encoded certicate
  458. /// \returns the certificate data
  459. /// \sa GetToBeSigned, GetCertificateSignature
  460. const SecByteBlock& GetCertificate () const
  461. { return m_origCertificate; }
  462. /// \brief Retrieve DER encoded ToBeSigned
  463. /// \returns the toBeSigned data
  464. /// \sa GetCertificate, GetCertificateSignature
  465. const SecByteBlock& GetToBeSigned () const;
  466. /// \brief Version number
  467. /// \returns Certificate version number
  468. /// \note Version number is 0 based, so X.509 v3 value is 2.
  469. Version GetVersion() const
  470. { return m_version; }
  471. /// \brief Serial number
  472. /// \returns Certificate serial number
  473. const Integer& GetSerialNumber() const
  474. { return m_serialNumber; }
  475. /// \brief Certificate signature algorithm
  476. /// \returns Certificate signature algorithm
  477. /// \sa GetCertificate, GetToBeSigned, GetCertificateSignature
  478. const OID& GetCertificateSignatureAlgorithm() const
  479. { return m_certSignatureAlgortihm; }
  480. /// \brief Certificate signature
  481. /// \returns Certificate signature
  482. /// \sa GetCertificate, GetToBeSigned, GetCertificateSignatureAlgorithm
  483. const SecByteBlock& GetCertificateSignature() const
  484. { return m_certSignature; }
  485. /// \brief Validity not before
  486. /// \returns Validity not before
  487. /// \sa GetNotAfter
  488. const DateValue& GetNotBefore() const
  489. { return m_notBefore; }
  490. /// \brief Validity not after
  491. /// \returns Validity not after
  492. /// \sa GetNotBefore
  493. const DateValue& GetNotAfter() const
  494. { return m_notAfter; }
  495. /// \brief Issuer distinguished name
  496. /// \returns Issuer distinguished name
  497. const RdnValueArray& GetIssuerDistinguishedName() const
  498. { return m_issuerName; }
  499. /// \brief Subject distinguished name
  500. /// \returns Subject distinguished name
  501. const RdnValueArray& GetSubjectDistinguishedName() const
  502. { return m_subjectName; }
  503. /// \brief Issuer UniqueId
  504. /// \returns Issuer UniqueId
  505. /// \details Issuer UniqueId is optional and available with X.509 v2.
  506. /// \sa HasIssuerUniqueId
  507. const SecByteBlock& GetIssuerUniqueId() const
  508. { return m_issuerUid.get() ? *m_issuerUid.get() : g_nullByteBlock; }
  509. /// \brief Subject UniqueId
  510. /// \returns Subject UniqueId
  511. /// \details Subject UniqueId is optional and available with X.509 v2.
  512. /// \sa HasSubjectUniqueId
  513. const SecByteBlock& GetSubjectUniqueId() const
  514. { return m_subjectUid.get() ? *m_subjectUid.get() : g_nullByteBlock; }
  515. /// \brief Certificate extensions
  516. /// \returns Certificate extensions array
  517. /// \details Certificate extensions are available with X.509 v3.
  518. /// \sa HasExtensions
  519. const ExtensionValueArray& GetExtensions() const
  520. { return m_extensions.get() ? *m_extensions.get() : g_nullExtensions; }
  521. /// \brief Subject public key algorithm
  522. /// \returns Subject public key algorithm
  523. /// \sa GetSubjectPublicKey
  524. const OID& GetSubjectPublicKeyAlgorithm() const
  525. { return m_subjectSignatureAlgortihm; }
  526. /// \brief Subject public key
  527. /// \returns Subject public key
  528. /// \sa GetSubjectPublicKeyAlgorithm
  529. const X509PublicKey& GetSubjectPublicKey() const
  530. { return *m_subjectPublicKey.get(); }
  531. /// \brief Authority key identifier
  532. /// \returns Authority key identifier
  533. /// \details Authority key identifier is optional and available with X.509 v3.
  534. /// \sa HasAuthorityKeyIdentifier, GetSubjectKeyIdentifier
  535. const KeyIdentifierValue& GetAuthorityKeyIdentifier() const;
  536. /// \brief Subject key identifier
  537. /// \returns Subject key identifier
  538. /// \details Subject key identifier is optional and available with X.509 v3.
  539. /// \sa HasSubjectKeyIdentifier, GetAuthorityKeyIdentifier
  540. const KeyIdentifierValue& GetSubjectKeyIdentifier() const;
  541. /// \brief Identities
  542. /// \returns Identities
  543. /// \details GetSubjectIdentities() collects the identities in the certificate.
  544. const IdentityValueArray& GetSubjectIdentities() const;
  545. /// \brief Identities
  546. /// \returns Identities
  547. /// \details GetSubjectIdentities() collects the identities in the certificate.
  548. const KeyUsageValueArray& GetSubjectKeyUsage() const;
  549. //@}
  550. /// \name CERTIFICATE
  551. //@{
  552. /// \brief Determine if certificate is a CA
  553. /// \returns true if the certificate is a CA, false otherwise
  554. /// \details There are two types of certificates. The first is a CA certificate and
  555. /// signaled with <tt>basicConstraint, CA:TRUE</tt>. The second is an end entity
  556. /// certificate and signaled with <tt>basicConstraint, CA:FALSE</tt>.
  557. /// CA certificates can certify other certificates, while end entity certificates
  558. /// cannot. End entity certificates are leaf certificates.
  559. /// \sa IsSelfSigned
  560. bool IsCertificateAuthority() const;
  561. /// \brief Determine if certificate is self-signed
  562. /// \returns true if the certificate is self-signed, false otherwise
  563. /// \sa IsCertificateAuthority
  564. bool IsSelfSigned() const;
  565. //@}
  566. /// \name DEBUG
  567. //@{
  568. /// \brief Print a certificate
  569. /// \param out ostream object
  570. /// \returns ostream reference
  571. /// \details Print() displays some of the fields of a certificate for
  572. /// debug purposes. Users should modify the class or override this
  573. /// class in a derived class to suit their taste.
  574. virtual std::ostream& Print(std::ostream& out) const;
  575. /// \brief Write certificate data
  576. /// \param bt BufferedTransformation object
  577. /// \details WriteCertificateBytes() is a debug function. It dumps
  578. /// the bytes stored in m_origCertificate. WriteCertificateBytes()
  579. /// also sets up a try/catch and silently swallows exceptions.
  580. void WriteCertificateBytes(BufferedTransformation &bt) const;
  581. //@}
  582. protected:
  583. // Crib away the original certificate
  584. void SaveCertificateBytes(BufferedTransformation &bt);
  585. // Clear old certificate data
  586. void Reset();
  587. // RFC 2459, section 7.3.1, http://www.ietf.org/rfc/rfc2459.txt
  588. virtual bool BERDecodeAlgorithmParameters (BufferedTransformation &bt)
  589. {BERDecodeNull(bt); return false;}
  590. virtual bool DEREncodeAlgorithmParameters (BufferedTransformation &bt) const
  591. {DEREncodeNull(bt); return false;}
  592. // X509Certificate
  593. void BERDecodeVersion(BufferedTransformation &bt, Version &version);
  594. void BERDecodeSerialNumber(BufferedTransformation &bt, Integer &serno);
  595. void BERDecodeSignature(BufferedTransformation &bt, SecByteBlock &signature);
  596. void BERDecodeSignatureAlgorithm(BufferedTransformation &bt, OID &algorithm);
  597. void BERDecodeDistinguishedName(BufferedTransformation &bt, RdnValueArray &rdnArray);
  598. void BERDecodeValidity(BufferedTransformation &bt, DateValue &notBefore, DateValue &notAfter);
  599. void BERDecodeSubjectPublicKeyInfo(BufferedTransformation &bt, member_ptr<X509PublicKey>& publicKey);
  600. // Optional attributes
  601. bool HasOptionalAttribute(const BufferedTransformation &bt, byte tag) const;
  602. void BERDecodeIssuerUniqueId(BufferedTransformation &bt);
  603. void BERDecodeSubjectUniqueId(BufferedTransformation &bt);
  604. void BERDecodeExtensions(BufferedTransformation &bt);
  605. // BERDecodeSubjectPublicKeyInfo peeks at the subjectPublicKeyInfo because the
  606. // information is less ambiguous. If we used subjectPublicKeyAlgorithm we would
  607. // still need to peek because subjectPublicKeyAlgorithm lacks field information
  608. // (prime vs. binary). We need a field to instantiate a key. For example,
  609. // subjectPublicKeyAlgorithm==ecdsa_with_sha384() does not contain enough
  610. // information to determine PublicKey_EC<ECP> or PublicKey_EC<EC2N>.
  611. void GetSubjectPublicKeyInfoOids(const BufferedTransformation &bt, OID& algorithm, OID& field) const;
  612. // Identity helper functions. Find them wherever we can.
  613. void GetIdentitiesFromSubjectDistName(IdentityValueArray& identityArray) const;
  614. void GetIdentitiesFromSubjectAltName(IdentityValueArray& identityArray) const;
  615. void GetIdentitiesFromSubjectUniqueId(IdentityValueArray& identityArray) const;
  616. void GetIdentitiesFromSubjectPublicKeyId(IdentityValueArray& identityArray) const;
  617. void GetIdentitiesFromNetscapeServer(IdentityValueArray& identityArray) const;
  618. // Find an extension with the OID. Returns false and end() if not found.
  619. bool FindExtension(const OID& oid, ExtensionValueArray::const_iterator& loc) const;
  620. // Get the verifier object for an algorithm and key
  621. PK_Verifier* GetPK_VerifierObject(const OID &algorithm, const X509PublicKey &key) const;
  622. private:
  623. // Version and serial number, required v1
  624. Version m_version;
  625. Integer m_serialNumber;
  626. // Certificate algorithm and signature, required v1
  627. OID m_certSignatureAlgortihm;
  628. SecByteBlock m_certSignature;
  629. // Issuer and subject DNs, required v1
  630. RdnValueArray m_issuerName;
  631. RdnValueArray m_subjectName;
  632. // Validity dates, required v1
  633. DateValue m_notBefore, m_notAfter;
  634. // The subject's key and algorithm, required v1
  635. OID m_subjectSignatureAlgortihm;
  636. member_ptr<X509PublicKey> m_subjectPublicKey;
  637. // Issue and Subject UniqueId, optional v2
  638. ASNOptional<SecByteBlock> m_issuerUid;
  639. ASNOptional<SecByteBlock> m_subjectUid;
  640. // Extensions, optional v3
  641. ASNOptional<ExtensionValueArray> m_extensions;
  642. // AKI and SPKI extensions, optional v3
  643. mutable member_ptr<KeyIdentifierValue> m_authorityKeyIdentifier; // lazy
  644. mutable member_ptr<KeyIdentifierValue> m_subjectKeyIdentifier; // lazy
  645. // KU and EKU, optional v3
  646. mutable member_ptr<KeyUsageValueArray> m_keyUsage; // lazy
  647. // Identities
  648. mutable member_ptr<IdentityValueArray> m_identities; // lazy
  649. // To be signed, required v1
  650. mutable member_ptr<SecByteBlock> m_toBeSigned; // lazy
  651. // Hack so we can examine the octets. Also see WriteCertificateBytes.
  652. SecByteBlock m_origCertificate;
  653. // Null values so we can return something
  654. static const SecByteBlock g_nullByteBlock;
  655. static const ExtensionValueArray g_nullExtensions;
  656. };
  657. //////////////////////////////////////////////////
  658. inline std::ostream& operator<<(std::ostream& out, const X509Certificate &cert)
  659. { return cert.Print(out); }
  660. inline std::ostream& operator<<(std::ostream& out, const RdnValue &value)
  661. { return value.Print(out); }
  662. inline std::ostream& operator<<(std::ostream& out, const DateValue &value)
  663. { return value.Print(out); }
  664. inline std::ostream& operator<<(std::ostream& out, const KeyIdentifierValue &value)
  665. { return value.Print(out); }
  666. inline std::ostream& operator<<(std::ostream& out, const KeyUsageValue &value)
  667. { return value.Print(out); }
  668. inline std::ostream& operator<<(std::ostream& out, const IdentityValue &value)
  669. { return value.Print(out); }
  670. inline bool operator==(const RdnValue &first, const RdnValue &second)
  671. { return first.m_value == second.m_value; }
  672. inline bool operator==(const KeyIdentifierValue &first, const KeyIdentifierValue &second)
  673. { return first.m_value == second.m_value; }
  674. inline std::ostream& operator<<(std::ostream& out, const RdnValueArray &values)
  675. {
  676. RdnValueArray::const_iterator first = values.begin();
  677. RdnValueArray::const_iterator last = values.end();
  678. std::ostringstream oss;
  679. while (first != last)
  680. {
  681. oss << *first;
  682. if (++first != last)
  683. { oss << "; "; }
  684. }
  685. return out << oss.str();
  686. }
  687. inline std::ostream& operator<<(std::ostream& out, const IdentityValueArray &values)
  688. {
  689. IdentityValueArray::const_iterator first = values.begin();
  690. IdentityValueArray::const_iterator last = values.end();
  691. std::ostringstream oss;
  692. while (first != last)
  693. {
  694. oss << *first;
  695. if (++first != last)
  696. { oss << "\n"; }
  697. }
  698. return out << oss.str();
  699. }
  700. inline std::ostream& operator<<(std::ostream& out, const KeyUsageValueArray &values)
  701. {
  702. KeyUsageValueArray::const_iterator first = values.begin();
  703. KeyUsageValueArray::const_iterator last = values.end();
  704. std::ostringstream oss;
  705. while (first != last)
  706. {
  707. oss << *first;
  708. if (++first != last)
  709. { oss << ", "; }
  710. }
  711. return out << oss.str();
  712. }
  713. //////////////////////////////////////////////////
  714. // Make these defines to avoid global objects
  715. #define id_sha1WithRSASignature (OID(1)+2+840+113549+1+1+5)
  716. #define id_sha256WithRSAEncryption (OID(1)+2+840+113549+1+1+11)
  717. #define id_sha384WithRSAEncryption (OID(1)+2+840+113549+1+1+12)
  718. #define id_sha512WithRSAEncryption (OID(1)+2+840+113549+1+1+13)
  719. #define id_secp256v1 (OID(1)+2+840+10045+3+1+7)
  720. #define id_ecdsaWithSHA1 (OID(1)+2+840+10045+4+1)
  721. #define id_ecdsaWithSHA256 (OID(1)+2+840+10045+4+3+2)
  722. #define id_ecdsaWithSHA384 (OID(1)+2+840+10045+4+3+3)
  723. #define id_ecdsaWithSHA512 (OID(1)+2+840+10045+4+3+4)
  724. NAMESPACE_END
  725. #endif // CRYPTOPP_X509_CERTIFICATE_H