| 1: | <?php |
| 2: | /** |
| 3: | * XMLDSigToken.php |
| 4: | * |
| 5: | * Copyright © 2017-2026 - Thierry Thiers <webcoder31@gmail.com> |
| 6: | * |
| 7: | * This software is governed by the CeCILL-C license under French law and |
| 8: | * abiding by the rules of distribution of free software. You can use, modify |
| 9: | * and/or redistribute the software under the terms of the CeCILL-C license as |
| 10: | * circulated by CEA, CNRS and INRIA at the following URL: |
| 11: | * |
| 12: | * http://www.cecill.info |
| 13: | * |
| 14: | * As a counterpart to the access to the source code and rights to copy, modify |
| 15: | * and redistribute granted by the license, users are provided only with a |
| 16: | * limited warranty and the software's author, the holder of the economic |
| 17: | * rights, and the successive licensors have only limited liability. |
| 18: | * |
| 19: | * In this respect, the user's attention is drawn to the risks associated with |
| 20: | * loading, using, modifying and/or developing or reproducing the software by |
| 21: | * the user in light of its specific status of free software, that may mean that |
| 22: | * it is complicated to manipulate, and that also therefore means that it is |
| 23: | * reserved for developers and experienced professionals having in-depth |
| 24: | * computer knowledge. Users are therefore encouraged to load and test the |
| 25: | * software's suitability as regards their requirements in conditions enabling |
| 26: | * the security of their systems and/or data to be ensured and, more generally, |
| 27: | * to use and operate it in the same conditions as regards security. |
| 28: | * |
| 29: | * The fact that you are presently reading this means that you have had |
| 30: | * knowledge of the CeCILL-C license and that you accept its terms. |
| 31: | * |
| 32: | * @author Thierry Thiers <webcoder31@gmail.com> |
| 33: | * @copyright 2017-2026 - Thierry Thiers <webcoder31@gmail.com> |
| 34: | * @license http://www.cecill.info CeCILL-C License |
| 35: | * @version 2.1.0 |
| 36: | */ |
| 37: | |
| 38: | |
| 39: | // Namespace. |
| 40: | namespace webcoder31\ezxmldsig\token; |
| 41: | |
| 42: | // Use. |
| 43: | use DateTime; |
| 44: | use DateTimeZone; |
| 45: | use DOMDocument; |
| 46: | use DOMElement; |
| 47: | use DOMNode; |
| 48: | use DOMXPath; |
| 49: | use Exception; |
| 50: | use RobRichards\XMLSecLibs\XMLSecurityDSig; |
| 51: | use RobRichards\XMLSecLibs\XMLSecEnc; |
| 52: | use RobRichards\XMLSecLibs\XMLSecurityKey; |
| 53: | use webcoder31\ezxmldsig\core\Algorithms; |
| 54: | use webcoder31\ezxmldsig\core\Canonicalization; |
| 55: | use webcoder31\ezxmldsig\core\X509Cert; |
| 56: | use webcoder31\ezxmldsig\core\Xml; |
| 57: | |
| 58: | /** |
| 59: | * Build or analyze an XML token. |
| 60: | * |
| 61: | * An XML token is an enveloping XML Digital Signature (cf. RFC 3275) |
| 62: | * containing signed and timestamped user data. These data may also be |
| 63: | * encrypted. In this case we talk about Secure XML token. |
| 64: | * |
| 65: | * **This class uses the following default algorithms to operate:** |
| 66: | * |
| 67: | * - Algorithm used to canonicalize data before signing is: |
| 68: | * http://www.w3.org/TR/2001/REC-xml-c14n-20010315. |
| 69: | * |
| 70: | * - Algorithm used to generate the signature is: |
| 71: | * http://www.w3.org/2001/04/xmldsig-more#rsa-sha256. |
| 72: | * |
| 73: | * - Algorithm used to compute the hash of token data is: |
| 74: | * http://www.w3.org/2001/04/xmlenc#sha256. |
| 75: | * |
| 76: | * - Algorithm used to encode data's values is: Base64. |
| 77: | * |
| 78: | * The analysis expects these algorithms unless its options name others (see |
| 79: | * `__construct()`), and it requires a trust anchor: the CA certificates |
| 80: | * and/or the pinned certificate the signing certificate is verified against. |
| 81: | * Without it, no token is valid. |
| 82: | * |
| 83: | * **An XML token looks like this:** |
| 84: | * |
| 85: | * ```xml |
| 86: | * <?xml version="1.0"?> |
| 87: | * <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> |
| 88: | * <ds:SignedInfo> |
| 89: | * <ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> |
| 90: | * <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> |
| 91: | * <ds:Reference URI="#Token"> |
| 92: | * <ds:Transforms> |
| 93: | * <ds:Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> |
| 94: | * </ds:Transforms> |
| 95: | * <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> |
| 96: | * <ds:DigestValue>---- TOKEN HASH ----</ds:DigestValue> |
| 97: | * </ds:Reference> |
| 98: | * </ds:SignedInfo> |
| 99: | * <ds:SignatureValue>---- SIGNATURE VALUE ----</ds:SignatureValue> |
| 100: | * <ds:KeyInfo> |
| 101: | * <ds:X509Data> |
| 102: | * <ds:X509Certificate>---- X.509 CERTIFICATE ----</ds:X509Certificate> |
| 103: | * </ds:X509Data> |
| 104: | * </ds:KeyInfo> |
| 105: | * <ds:Object Id="Token"> |
| 106: | * <Token> |
| 107: | * <TokenTimestamp>2026-10-17T04:43:05Z</TokenTimestamp> |
| 108: | * <TokenId>---- 128-BIT RANDOM IDENTIFIER (HEXADECIMAL) ----</TokenId> |
| 109: | * <TokenData> |
| 110: | * <data1 Algorithm="base64">---- BASE64 ENCODED DATA ----</data1> |
| 111: | * <data2 Algorithm="base64">---- BASE64 ENCODED DATA ----</data2> |
| 112: | * <data3> |
| 113: | * <data31 Algorithm="base64">---- BASE64 ENCODED DATA ----</data31> |
| 114: | * <data32 Algorithm="base64">---- BASE64 ENCODED DATA ----</data32> |
| 115: | * </data3> |
| 116: | * <data4 Algorithm="base64">---- BASE64 ENCODED DATA ----</data4> |
| 117: | * </TokenData> |
| 118: | * </Token> |
| 119: | * </ds:Object> |
| 120: | * </ds:Signature> |
| 121: | * ``` |
| 122: | * |
| 123: | * **The signing process consists of the following actions:** |
| 124: | * |
| 125: | * - Load data from an associative array. |
| 126: | * |
| 127: | * - Encode data values using Base64. |
| 128: | * |
| 129: | * - Build a node from the encoded array of data (cf. node `<TokenData />`). |
| 130: | * |
| 131: | * - Compute an UTC timestamp and store it in a node `<TokenTimestamp />`. |
| 132: | * |
| 133: | * - Generate a random identifier of 128 bits (`random_bytes()`) and store |
| 134: | * it, in hexadecimal, in a node `<TokenId />`. Signed with the rest of the |
| 135: | * token, it lets the receiver refuse a token it has already accepted (see |
| 136: | * `getTokenId()`). |
| 137: | * |
| 138: | * - Aggregate the nodes `<TokenTimestamp />`, `<TokenId />` and |
| 139: | * `<TokenData />` inside a node `<Token />`. |
| 140: | * |
| 141: | * - Load the base DOM document representing an XML digital signature: |
| 142: | * |
| 143: | * ```xml |
| 144: | * <ds:Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> |
| 145: | * <ds:SignedInfo> |
| 146: | * <ds:SignatureMethod /> |
| 147: | * </ds:SignedInfo> |
| 148: | * </ds:Signature> |
| 149: | * ``` |
| 150: | * |
| 151: | * - Create a node `<ds:Object Id="Token" />` and append it to the node |
| 152: | * `<ds:Signature />`. |
| 153: | * |
| 154: | * - Add the node `<Token />` to the node `<ds:Object Id="Token" />`. |
| 155: | * |
| 156: | * - NOTE: If data encryption is requested, this process will take place here |
| 157: | * (this will be described later). |
| 158: | * |
| 159: | * - Build a node `<ds:Reference URI="#Token" />` and append it to the node |
| 160: | * `<ds:SignedInfo />`. This consists of: |
| 161: | * |
| 162: | * - Canonicalizing the content of the node `<ds:Object Id="Token" />`. |
| 163: | * |
| 164: | * - Computing the hash (SHA-256 by default) of the canonicalized node and |
| 165: | * storing it in the node `<ds:DigestValue />`. |
| 166: | * |
| 167: | * - Include, in the XML token, the X.509 certificate associated to the |
| 168: | * private key that will be used to perform the signing (see the next steps |
| 169: | * below). This certificate will be used to perform the signature validation |
| 170: | * process, avoiding the need, for the receiver of the XML Digital Signature, |
| 171: | * to own it on its side. |
| 172: | * |
| 173: | * - Canonicalize the content of the node `<ds:SignedInfo />`. |
| 174: | * |
| 175: | * - Compute the signature of the canonicalized node using the private key |
| 176: | * dedicated to perform signing. |
| 177: | * |
| 178: | * - Store the result in the node `<ds:SignatureValue />`. |
| 179: | * |
| 180: | * - Save the DOM document in XML format. |
| 181: | * |
| 182: | * **The signature validation process consists of the following actions:** |
| 183: | * |
| 184: | * - Load the XML Digital Signature in a DOM document. A document with a |
| 185: | * document type declaration (DOCTYPE), or not encoded in UTF-8, is |
| 186: | * refused before it is parsed, and the parser never accesses the network |
| 187: | * (see `Xml::load()`). |
| 188: | * |
| 189: | * - Verify that the algorithms of the XML Digital Signature are the |
| 190: | * expected ones. |
| 191: | * |
| 192: | * - Compute the hash of the content of the node `<ds:Object Id="Token" />` |
| 193: | * with the digest algorithm. |
| 194: | * |
| 195: | * - Compare the computed hash with the one stored in the node |
| 196: | * `<ds:DigestValue />`. If the hashes are different, this means that the |
| 197: | * content of the node `<ds:Object Id="Token" />` has been altered. |
| 198: | * |
| 199: | * - Canonicalize the content of the node `<ds:SignedInfo />`. |
| 200: | * |
| 201: | * - Compute the signature of the node `<ds:SignedInfo />` using the X.509 |
| 202: | * certificate included in the XML token. |
| 203: | * |
| 204: | * - Compare the computed signature with the one stored in the node |
| 205: | * `<ds:SignatureValue>`. If the signatures are different, this means that |
| 206: | * the content of the node `<ds:SignedInfo />` has not been signed using the |
| 207: | * private key associated to the X.509 certificate included in the XML |
| 208: | * Digital Signature. |
| 209: | * |
| 210: | * - Verify that the X.509 certificate included in the XML Digital Signature |
| 211: | * is trusted, against the trust anchor given to the analysis: CA |
| 212: | * certificates up to which OpenSSL verifies the chain of the certificate, |
| 213: | * and/or the pinned certificate the token must be signed with. Without a |
| 214: | * trust anchor, no token is valid: anyone can sign a token with a |
| 215: | * certificate of their own. |
| 216: | * |
| 217: | * - NOTE: If data decryption is required, this process will take place here |
| 218: | * (this will be described later). |
| 219: | * |
| 220: | * - Extract the timestamp and the identifier stored in the content of the |
| 221: | * node `<ds:Object Id="Token" />` and memorise them. A token without |
| 222: | * identifier is rejected. |
| 223: | * |
| 224: | * - Extract the data stored in the content of the node |
| 225: | * `<ds:Object Id="Token" />`. |
| 226: | * |
| 227: | * - Decode data values using Base64. |
| 228: | * |
| 229: | * - Build an associative array containing the decoded data. |
| 230: | * |
| 231: | * **Token data encryption / decryption:** |
| 232: | * |
| 233: | * The token data may also be encrypted before signing. In this case the class |
| 234: | * will use the following default algorithms to perform encryption and |
| 235: | * decryption of data: |
| 236: | * |
| 237: | * - Algorithm used to encrypt / decrypt data is: |
| 238: | * http://www.w3.org/2009/xmlenc11#aes256-gcm (authenticated symmetric |
| 239: | * ciphering). |
| 240: | * |
| 241: | * - Algorithm used to encrypt / decrypt the session key is: |
| 242: | * http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p (asymmetric ciphering). |
| 243: | * |
| 244: | * **A secure (encrypted) XML token looks like this:** |
| 245: | * |
| 246: | * ```xml |
| 247: | * <?xml version="1.0"?> |
| 248: | * <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"> |
| 249: | * <ds:SignedInfo> |
| 250: | * <ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> |
| 251: | * <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/> |
| 252: | * <ds:Reference URI="#Token"> |
| 253: | * <ds:Transforms> |
| 254: | * <ds:Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/> |
| 255: | * </ds:Transforms> |
| 256: | * <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/> |
| 257: | * <ds:DigestValue>---- TOKEN HASH ----</ds:DigestValue> |
| 258: | * </ds:Reference> |
| 259: | * </ds:SignedInfo> |
| 260: | * <ds:SignatureValue>---- SIGNATURE VALUE ----</ds:SignatureValue> |
| 261: | * <ds:KeyInfo> |
| 262: | * <ds:X509Data> |
| 263: | * <ds:X509Certificate>---- X.509 CERTIFICATE ----</ds:X509Certificate> |
| 264: | * </ds:X509Data> |
| 265: | * </ds:KeyInfo> |
| 266: | * <ds:Object Id="Token"> |
| 267: | * <xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Type="http://www.w3.org/2001/04/xmlenc#Element"> |
| 268: | * <xenc:EncryptionMethod Algorithm="http://www.w3.org/2009/xmlenc11#aes256-gcm"/> |
| 269: | * <ds:KeyInfo xmlns:dsig="http://www.w3.org/2000/09/xmldsig#"> |
| 270: | * <xenc:EncryptedKey> |
| 271: | * <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"/> |
| 272: | * <xenc:CipherData> |
| 273: | * <xenc:CipherValue>---- CIPHERED SESSION KEY ----</xenc:CipherValue> |
| 274: | * </xenc:CipherData> |
| 275: | * </xenc:EncryptedKey> |
| 276: | * </ds:KeyInfo> |
| 277: | * <xenc:CipherData> |
| 278: | * <xenc:CipherValue>---- ENCRYPTED DATA ----</xenc:CipherValue> |
| 279: | * </xenc:CipherData> |
| 280: | * </xenc:EncryptedData> |
| 281: | * </ds:Object> |
| 282: | * </ds:Signature> |
| 283: | * ``` |
| 284: | * |
| 285: | * **The encryption process is the following:** |
| 286: | * |
| 287: | * - Randomly generate a session key. |
| 288: | * |
| 289: | * - Cipher the session key using the X.509 certificate dedicated to the |
| 290: | * encryption process, in order to transmit it safely in the XML Digital |
| 291: | * Signature. |
| 292: | * |
| 293: | * - Store the ciphered session key in the node `<xenc:CipherValue />` which is |
| 294: | * located inside the node `<xenc:EncryptedKey />`. |
| 295: | * |
| 296: | * - Encrypt the node `<Token />`, the only child of the node |
| 297: | * `<ds:Object Id="Token" />`, using the non-ciphered session key, and store |
| 298: | * the result in the last node `<xenc:CipherValue />`. The node |
| 299: | * `<xenc:EncryptedData />` replaces the node `<Token />` and declares the |
| 300: | * type `http://www.w3.org/2001/04/xmlenc#Element`: an element is encrypted. |
| 301: | * Versions up to 1.1 declared the type |
| 302: | * `http://www.w3.org/2001/04/xmlenc#Content` (the content of the node |
| 303: | * `<ds:Object />`) for the same encrypted bytes. |
| 304: | * |
| 305: | * **The decryption process is the following:** |
| 306: | * |
| 307: | * - Retrieve the node `<xenc:EncryptedData />`. |
| 308: | * |
| 309: | * - Decipher the ciphered session key stored in the node `<xenc:CipherValue />` |
| 310: | * (the one which is located inside the node `<xenc:EncryptedKey />`) using |
| 311: | * the private key associated to the X.509 certificate that has been used to |
| 312: | * perform the encryption. |
| 313: | * |
| 314: | * - Decrypt the content of the last node `<xenc:CipherValue />` using the |
| 315: | * deciphered session key, and put the plaintext, the node `<Token />`, in |
| 316: | * place of the node `<xenc:EncryptedData />`. Both types XML Encryption 1.1 |
| 317: | * defines for an XML plaintext are read, `Element` and `Content`, as the |
| 318: | * standard requires: tokens of the versions up to 1.1, and tokens that |
| 319: | * other XML Encryption libraries encrypt, are decrypted. Any other type is |
| 320: | * refused. The plaintext is read as an XML fragment whatever its type: it |
| 321: | * cannot hold a document type declaration (DOCTYPE). |
| 322: | * |
| 323: | * The decryption only takes place once the digest, the signature, the trust |
| 324: | * in the signing certificate and the algorithms have been verified, and |
| 325: | * every failure that depends on the encrypted content gives the same error, |
| 326: | * `Token decryption failed!`. RSA 1.5 is refused, and a CBC algorithm is |
| 327: | * only accepted when the analysis declares it (see `__construct()`). |
| 328: | * |
| 329: | * **Replay:** |
| 330: | * |
| 331: | * A valid token can be submitted again for as long as `isOutOfDate()` |
| 332: | * accepts it. The class keeps no list of the tokens it has analyzed: the |
| 333: | * caller must keep the identifiers it accepted (`getTokenId()`) and refuse a |
| 334: | * token whose identifier is among them. |
| 335: | */ |
| 336: | class XMLDSigToken |
| 337: | { |
| 338: | /* CONSTANTS */ |
| 339: | |
| 340: | /** @const string The default XMLDSIG namespace prefix used in the XML digital |
| 341: | signature. */ |
| 342: | const XMLDSIG_NS_PREFIX = 'ds'; |
| 343: | |
| 344: | /** @const string The name of the token node. */ |
| 345: | const TOKEN_NAME = 'Token'; |
| 346: | |
| 347: | /** @const string The name of the token data node. */ |
| 348: | const TOKEN_DATA_NAME = 'TokenData'; |
| 349: | |
| 350: | /** @const string The name of the token timestamp node. */ |
| 351: | const TOKEN_TIMESTAMP_NAME = 'TokenTimestamp'; |
| 352: | |
| 353: | /** @const string The name of the token identifier node. */ |
| 354: | const TOKEN_ID_NAME = 'TokenId'; |
| 355: | |
| 356: | /** @const int The number of random bytes of the token identifier, written |
| 357: | in hexadecimal (see getTokenId()). */ |
| 358: | const TOKEN_ID_BYTES = 16; |
| 359: | |
| 360: | /** @const string The name of the node that holds one audience of the |
| 361: | token (see getAudience()). A token holds one such node per audience. */ |
| 362: | const TOKEN_AUDIENCE_NAME = 'TokenAudience'; |
| 363: | |
| 364: | /** @const string The name of the token expiry node (see getExpiry()). */ |
| 365: | const TOKEN_EXPIRY_NAME = 'TokenExpiry'; |
| 366: | |
| 367: | /** @const int The latest expiry the format of the timestamp can write |
| 368: | (9999-12-31T23:59:59Z), as a UNIX timestamp. */ |
| 369: | private const MAX_EXPIRY_TIME = 253402300799; |
| 370: | |
| 371: | /** @const string The format of the token timestamp (YYYY-MM-DDThh:mm:ssZ). |
| 372: | NOTE: The timestamp should always be expressed in UTC. */ |
| 373: | const TOKEN_TIMESTAMP_FORMAT = 'Y-m-d\TH:i:s\Z'; |
| 374: | |
| 375: | /** @const int The default time to live (in seconds) used to check token |
| 376: | peremption. */ |
| 377: | const TOKEN_DEFAULT_TTL = 60; |
| 378: | |
| 379: | /** @const int The synchronization offset (in seconds) allowed for verifying |
| 380: | if token is out of date. */ |
| 381: | const DESYNC_TOLERANCE = 30; |
| 382: | |
| 383: | |
| 384: | const C14N = Algorithms::C14N; |
| 385: | const C14N_COMMENTS = Algorithms::C14N_COMMENTS; |
| 386: | const EXC_C14N = Algorithms::EXC_C14N; |
| 387: | const EXC_C14N_COMMENTS = Algorithms::EXC_C14N_COMMENTS; |
| 388: | |
| 389: | const SHA1 = Algorithms::SHA1; |
| 390: | const SHA256 = Algorithms::SHA256; |
| 391: | const SHA384 = Algorithms::SHA384; |
| 392: | const SHA512 = Algorithms::SHA512; |
| 393: | const RIPEMD160 = Algorithms::RIPEMD160; |
| 394: | |
| 395: | const TRIPLEDES_CBC = XMLSecurityKey::TRIPLEDES_CBC; |
| 396: | const AES128_CBC = XMLSecurityKey::AES128_CBC; |
| 397: | const AES192_CBC = XMLSecurityKey::AES192_CBC; |
| 398: | const AES256_CBC = XMLSecurityKey::AES256_CBC; |
| 399: | const AES128_GCM = XMLSecurityKey::AES128_GCM; |
| 400: | const AES192_GCM = XMLSecurityKey::AES192_GCM; |
| 401: | const AES256_GCM = XMLSecurityKey::AES256_GCM; |
| 402: | const RSA_OAEP_MGF1P = XMLSecurityKey::RSA_OAEP_MGF1P; |
| 403: | const DSA_SHA1 = XMLSecurityKey::DSA_SHA1; |
| 404: | const RSA_SHA1 = Algorithms::RSA_SHA1; |
| 405: | const RSA_SHA256 = Algorithms::RSA_SHA256; |
| 406: | const RSA_SHA384 = Algorithms::RSA_SHA384; |
| 407: | const RSA_SHA512 = Algorithms::RSA_SHA512; |
| 408: | const HMAC_SHA1 = XMLSecurityKey::HMAC_SHA1; |
| 409: | |
| 410: | /** @const array The context each option applies to (see |
| 411: | _checkOptions()). */ |
| 412: | private const OPTION_CONTEXTS = [ |
| 413: | 'base64Encode' => 'creation', |
| 414: | 'xmldsigNsPrefix' => 'creation', |
| 415: | 'audience' => 'creation', |
| 416: | 'validity' => 'creation', |
| 417: | 'expectedAudience' => 'analysis', |
| 418: | 'canonicalizationAlgorithm' => 'any', |
| 419: | 'signatureAlgorithm' => 'any', |
| 420: | 'digestAlgorithm' => 'any', |
| 421: | 'checkSigningAlgorithms' => 'analysis', |
| 422: | 'caCertPath' => 'analysis', |
| 423: | 'signerCertPath' => 'analysis', |
| 424: | 'expectedSubject' => 'analysis', |
| 425: | 'sessionKeyCipheringAlgorithm' => 'encryption', |
| 426: | 'cryptAlgorithm' => 'encryption', |
| 427: | 'checkCryptingAlgorithms' => 'decryption', |
| 428: | ]; |
| 429: | |
| 430: | /** @const string The error of every failure that depends on the |
| 431: | decrypted content (see _decryptToken()). */ |
| 432: | private const DECRYPTION_FAILED = 'Token decryption failed!'; |
| 433: | |
| 434: | |
| 435: | /* PROPERTIES */ |
| 436: | |
| 437: | /** @var string The XML namespace (xmlns) prefix to use in the XML digital |
| 438: | signature tags. */ |
| 439: | private $xmldsigNsPrefix = self::XMLDSIG_NS_PREFIX; |
| 440: | |
| 441: | /** @var string The algorithm that should be used to canonicalize the node |
| 442: | "ds:Signature/ds:SignedInfo" of the XML digital signature before signing |
| 443: | it. */ |
| 444: | private $canonicalizationAlgorithm = self::C14N; |
| 445: | |
| 446: | /** @var string The algorithm that should be used to sign the computed hash |
| 447: | of the token. */ |
| 448: | private $signatureAlgorithm = self::RSA_SHA256; |
| 449: | |
| 450: | /** @var string The algorithm that should be used to compute the hash of the |
| 451: | token. */ |
| 452: | private $digestAlgorithm = self::SHA256; |
| 453: | |
| 454: | /** @var string The algorithm that should be used to canonicalize the token |
| 455: | before computing its hash. NOTE: In our case, it is the same algorithm as |
| 456: | the one used to canonicalize the node "ds:Signature/ds:signedInfo" |
| 457: | (see: $canonicalizationAlgorithm property). */ |
| 458: | private $transformAlgorithm = self::C14N; |
| 459: | |
| 460: | /** @var boolean Whether to check the algorithms actually used (read from |
| 461: | the XML digital signature) to sign the token or not. */ |
| 462: | private $checkSigningAlgorithms = true; |
| 463: | |
| 464: | /** @var string The algorithm that should be used to generate the session |
| 465: | key which will be used to encrypt the token. */ |
| 466: | private $sessionKeyCipheringAlgorithm = self::AES256_GCM; |
| 467: | |
| 468: | /** @var string The algorithm that should be used to encrypt the token with |
| 469: | the generated session key. */ |
| 470: | private $cryptAlgorithm = self::RSA_OAEP_MGF1P; |
| 471: | |
| 472: | /** @var boolean Whether to check the algorithms actually used (read from |
| 473: | the XML digital signature) to encrypt the token or not. */ |
| 474: | private $checkCryptingAlgorithms = true; |
| 475: | |
| 476: | /** @var DOMXPath The DOMXPath object used to navigate through the XML |
| 477: | digital signature enveloping the token. */ |
| 478: | private $xpath = null; |
| 479: | |
| 480: | /** @var string The content of the private key used to sign the token |
| 481: | data. */ |
| 482: | private $signKey = null; |
| 483: | |
| 484: | /** @var string The password to access the private key used to sign the |
| 485: | token data. */ |
| 486: | private $signKeyPassword = null; |
| 487: | |
| 488: | /** @var string The content of the X.509 certificate associated to the |
| 489: | private key (cf. $signKey) used to sign the token. This certificate is |
| 490: | included in the XML token, in order to verify that the XML |
| 491: | Digital Signature is valid. */ |
| 492: | private $signCert = null; |
| 493: | |
| 494: | /** @var string The content of the private key used to decrypt the token. */ |
| 495: | private $cryptKey = null; |
| 496: | |
| 497: | /** @var string The password to access the private key used to decrypt the |
| 498: | token. */ |
| 499: | private $cryptKeyPassword = null; |
| 500: | |
| 501: | /** @var string The content of the X.509 certificate associated to the |
| 502: | private key used to encrypt the session key used to encrypt the token. */ |
| 503: | private $cryptCert = null; |
| 504: | |
| 505: | /** @var string The XML digital signature enveloping the token. */ |
| 506: | private $xml = null; |
| 507: | |
| 508: | /** @var array The token data (a flat or multidimensional associative |
| 509: | array). */ |
| 510: | private $data = null; |
| 511: | |
| 512: | /** @var boolean Flag that indicates whether the token data should be base64 |
| 513: | encoded when building the XML token or not. */ |
| 514: | private $base64EncodeData = true; |
| 515: | |
| 516: | /** @var string The token timestamp (format: 'yyyy-MM-ddThh:mm:ssZ'). */ |
| 517: | private $timestamp = null; |
| 518: | |
| 519: | /** @var string The token identifier (see getTokenId()). */ |
| 520: | private $tokenId = null; |
| 521: | |
| 522: | /** @var array|null The audiences of the token to create (option |
| 523: | "audience"). */ |
| 524: | private $audienceToWrite = null; |
| 525: | |
| 526: | /** @var array|null The audiences read from the token (see |
| 527: | getAudience()). */ |
| 528: | private $audience = null; |
| 529: | |
| 530: | /** @var int|null The validity of the token to create, in seconds (option |
| 531: | "validity"). */ |
| 532: | private $validity = null; |
| 533: | |
| 534: | /** @var string|null The token expiry (format: 'yyyy-MM-ddThh:mm:ssZ', see |
| 535: | getExpiry()). */ |
| 536: | private $expiry = null; |
| 537: | |
| 538: | /** @var boolean Whether the analyzed token has a node "TokenExpiry", |
| 539: | well formed or not (see isOutOfDate()). */ |
| 540: | private $hasExpiryNode = false; |
| 541: | |
| 542: | /** @var string|null The audience the analyzed token must be addressed to |
| 543: | (option "expectedAudience"). */ |
| 544: | private $expectedAudience = null; |
| 545: | |
| 546: | /** @var X509Cert The X.509 certificate included in the XML Digital |
| 547: | Signature. */ |
| 548: | private $x509Certificate = null; |
| 549: | |
| 550: | /** @var array|null The paths of the PEM files holding the trusted CA |
| 551: | certificates (option "caCertPath"). */ |
| 552: | private $trustedCACertPaths = null; |
| 553: | |
| 554: | /** @var string|null The pinned signing certificate, in PEM format (option |
| 555: | "signerCertPath"), or, when the object creates a token, the certificate |
| 556: | of its own signing key. */ |
| 557: | private $pinnedSignerCert = null; |
| 558: | |
| 559: | /** @var array|string|null The subject expected for the signing |
| 560: | certificate (option "expectedSubject"). */ |
| 561: | private $expectedSubject = null; |
| 562: | |
| 563: | /** @var boolean Flag that indicates whether the X.509 certificate included |
| 564: | in the XML Digital Signature is trusted or not. */ |
| 565: | private $isCertTrusted = null; |
| 566: | |
| 567: | /** @var boolean Flag that indicates whether the token is encrypted or |
| 568: | not. */ |
| 569: | private $isDataEncrypted = null; |
| 570: | |
| 571: | /** @var boolean Flag that indicates whether the token hash is valid or |
| 572: | not. */ |
| 573: | private $isDigestValueOk = null; |
| 574: | |
| 575: | /** @var boolean Flag that indicates whether the token hash signature is |
| 576: | valid or not. */ |
| 577: | private $isSignatureValueOk = null; |
| 578: | |
| 579: | /** @var string Error encountered during the analysis of |
| 580: | the XML digital signature enveloping the token. */ |
| 581: | private $error = null; |
| 582: | |
| 583: | /** @var array List of the anomalies encountered during the analysis |
| 584: | of the XML digital signature enveloping the token. */ |
| 585: | private $anomalies = array(); |
| 586: | |
| 587: | /** |
| 588: | * Defines a custom output for `print_r()` and `var_dump()` functions, |
| 589: | * in order to hide cryptographic material used by the object for |
| 590: | * security reasons. |
| 591: | */ |
| 592: | public function __debugInfo() |
| 593: | { |
| 594: | return [ |
| 595: | 'isValid' => $this->isSignatureValid(), |
| 596: | 'isDigestValueOk' => $this->isDigestValueOk, |
| 597: | 'isSignatureValueOk' => $this->isSignatureValueOk, |
| 598: | 'isCertTrusted' => $this->isCertTrusted, |
| 599: | 'isDataEncrypted' => $this->isDataEncrypted, |
| 600: | 'timestamp' => $this->timestamp, |
| 601: | 'tokenId' => $this->getTokenId(), |
| 602: | 'audience' => $this->getAudience(), |
| 603: | 'expiry' => $this->getExpiry(), |
| 604: | 'data' => $this->data, |
| 605: | 'error' => $this->error, |
| 606: | 'anomalies' => $this->anomalies |
| 607: | ]; |
| 608: | } |
| 609: | |
| 610: | |
| 611: | /** |
| 612: | * Instantiate an XMLDSigToken object. |
| 613: | * |
| 614: | * This constructor is `protected`. To get an instance of an XMLDSigToken |
| 615: | * object use one of the following `static` functions according to what the |
| 616: | * object is intended for: |
| 617: | * |
| 618: | * - `createXMLToken()` |
| 619: | * |
| 620: | * - `createSecureXMLToken()` |
| 621: | * |
| 622: | * - `analyzeXMLToken()` |
| 623: | * |
| 624: | * - `analyzeSecureXMLToken()` |
| 625: | * |
| 626: | * An XMLDSigToken object allows creating an XML token and also analyzing an |
| 627: | * existing XML token. The type of the `$xmlOrData` parameter determines how |
| 628: | * the object behaves. |
| 629: | * |
| 630: | * **XML token creation:** |
| 631: | * |
| 632: | * If `$xmlOrData` is an array (a flat or multidimensional associative |
| 633: | * array), the object will create an enveloping XML digital signature |
| 634: | * containing an XML token that holds the provided data and a timestamp |
| 635: | * generated automatically, with a random identifier (see `getTokenId()`). |
| 636: | * In this case, the `$signKeyPath` and `$signCertPath` parameters are |
| 637: | * required. If the `$cryptCertPath` parameter is also provided, the XML |
| 638: | * token will be encrypted for the owner of this certificate. The |
| 639: | * `$cryptKeyPath` parameter, the private key of the recipient, is |
| 640: | * optional: given, it is used to decrypt the created token and check its |
| 641: | * content too. If this private key is protected by a password, this |
| 642: | * password may be passed using the `$cryptKeyPassword` parameter. |
| 643: | * |
| 644: | * **XML token analysis:** |
| 645: | * |
| 646: | * If `$xmlOrData` is a string, the object will treat it as an enveloping |
| 647: | * XML digital signature containing a token: |
| 648: | * |
| 649: | * - It will check that the signature is valid. |
| 650: | * |
| 651: | * - It will decrypt the token if this one is encrypted. |
| 652: | * |
| 653: | * - It will extract timestamp and data from the token. |
| 654: | * |
| 655: | * In this case, the `$xmlOrData` parameter and a trust anchor (the |
| 656: | * options `caCertPath` and/or `signerCertPath`, see below) are required: |
| 657: | * without a trust anchor, no token is valid. If the XML |
| 658: | * token is encrypted, the `$cryptKeyPath` parameter must also be provided. |
| 659: | * If the private key used for decryption (cf. `$cryptKeyPath` parameter) is |
| 660: | * protected by a password, this password may be passed using the |
| 661: | * `$cryptKeyPassword` parameter. |
| 662: | * |
| 663: | * When the object creates a token, it analyzes it right away to check it, |
| 664: | * and trusts the certificate of its own signing key (`$signCertPath`) for |
| 665: | * that: the trust options do not apply to token creation. An encrypted |
| 666: | * token created without `$cryptKeyPath` is checked up to its decryption |
| 667: | * (structure, algorithms, digest, signature, trust in the signing |
| 668: | * certificate) and its content is not read (see `createSecureXMLToken()`). |
| 669: | * |
| 670: | * **Configuring the object:** |
| 671: | * |
| 672: | * The `$options` parameter of this function allows to override the default |
| 673: | * configuration of the object passing it the desired options via an |
| 674: | * associative array. |
| 675: | * |
| 676: | * Example: |
| 677: | * |
| 678: | * ```php |
| 679: | * $options = [ |
| 680: | * 'base64Encode' => false, |
| 681: | * 'xmldsigNsPrefix' => '' |
| 682: | * ]; |
| 683: | * ``` |
| 684: | * |
| 685: | * Each option applies to a context: token creation (`createXMLToken()`, |
| 686: | * `createSecureXMLToken()`), token analysis (`analyzeXMLToken()`, |
| 687: | * `analyzeSecureXMLToken()`), or both. The encryption options only apply |
| 688: | * when an encryption certificate (creation) or a decryption key |
| 689: | * (analysis) is given. An unknown option, an option given out of its |
| 690: | * context, or an option whose value is NULL or invalid throws an |
| 691: | * exception. |
| 692: | * |
| 693: | * The algorithm options apply to both contexts: at creation, they are the |
| 694: | * algorithms the token is built with; at analysis, the algorithms the |
| 695: | * token must have been built with. A token built with other algorithms is |
| 696: | * rejected (`getError()` lists them), unless `checkSigningAlgorithms` or |
| 697: | * `checkCryptingAlgorithms` is FALSE. To analyze a token built with |
| 698: | * RSA-SHA1 and SHA-1: |
| 699: | * |
| 700: | * ```php |
| 701: | * $options = [ |
| 702: | * 'caCertPath' => ['intermediate.cert.pem', 'root.cert.pem'], |
| 703: | * 'signatureAlgorithm' => XMLDSigToken::RSA_SHA1, |
| 704: | * 'digestAlgorithm' => XMLDSigToken::SHA1 |
| 705: | * ]; |
| 706: | * ``` |
| 707: | * |
| 708: | * Available options are the following: |
| 709: | * |
| 710: | * - **`caCertPath`** [string|array] Analysis only. The path, or the list |
| 711: | * of paths, of PEM files holding the trusted CA certificates. The |
| 712: | * signing certificate is only trusted if OpenSSL builds and verifies |
| 713: | * its chain, from these certificates only, up to a self-signed |
| 714: | * certificate of these files (see `X509Cert::isTrustedBy()`). To trust |
| 715: | * the certificates issued by an intermediate CA, give its certificate |
| 716: | * and the certificates up to its root, in one file or in several: |
| 717: | * `['intermediate.cert.pem', 'root.cert.pem']`. A chain that stops at |
| 718: | * an intermediate CA is rejected: with the intermediate CA alone, |
| 719: | * `isSignatureValid()` returns FALSE and `getError()` returns "Signing |
| 720: | * certificate is not issued by a trusted CA: its chain could not be |
| 721: | * verified up to the CA certificates of the option 'caCertPath', which |
| 722: | * must hold the issuing CA and the certificates up to its root!". |
| 723: | * Only the signing certificate is taken from the token, so a |
| 724: | * certificate issued by another intermediate CA of the same root is |
| 725: | * rejected; a certificate issued directly by a CA of the files (the |
| 726: | * root included) is accepted. |
| 727: | * <br/>Default value: none. |
| 728: | * |
| 729: | * - **`signerCertPath`** [string] Analysis only. The path to the PEM |
| 730: | * certificate the token must be signed with (certificate pinning): the |
| 731: | * signing certificate must be this very certificate. Given alone, it is |
| 732: | * the trust anchor; given with `caCertPath`, both are required. |
| 733: | * <br/>Default value: none. |
| 734: | * |
| 735: | * - **`expectedSubject`** [string|array] Analysis only. The subject the |
| 736: | * signing certificate must have, either: |
| 737: | * |
| 738: | * - an array of the subject fields to check, as returned by |
| 739: | * `getCertSubject()`: `['O' => 'Lothbrok Ltd', 'OU' => 'Jarl Dept']`. |
| 740: | * Fields that are not given are not checked. |
| 741: | * |
| 742: | * - or a string, compared as is with the full Distinguished Name |
| 743: | * returned by `getCertDN()`. This is the OpenSSL "oneline" format |
| 744: | * (`openssl_x509_parse()`, key `name`): every field of the subject, |
| 745: | * in the order of the certificate, each written `/<short name>=<value>` |
| 746: | * with no space and no escaping, e.g. |
| 747: | * `'/C=DK/ST=Jylland/L=Kattegat/O=Lothbrok Ltd/OU=Signature Dept/CN=www.lothbrok.dk/emailAddress=ivar@lothbrok.dk'`. |
| 748: | * It is neither the RFC 2253 form (`CN=...,O=...`) nor the form |
| 749: | * printed by the `openssl` command line (`C=DK, ST=...`): copy it |
| 750: | * from `getCertDN()` or `X509Cert::getDN()`. |
| 751: | * |
| 752: | * Character case is significant. It does not replace a trust anchor. |
| 753: | * <br/>Default value: none. |
| 754: | * |
| 755: | * - **`expectedAudience`** [string] Analysis only. The audience of this |
| 756: | * receiver, which the token must be addressed to (see `audience`): |
| 757: | * `isSignatureValid()` returns FALSE if the token names no audience or |
| 758: | * does not name this one. A token that names audiences is rejected |
| 759: | * when this option is not given, so that a receiver of the issuer |
| 760: | * cannot accept a token addressed to another one. Compared as is |
| 761: | * (character case included). |
| 762: | * <br/>Default value: none. |
| 763: | * |
| 764: | * - **`audience`** [string|array] Creation only. The audience, or the |
| 765: | * list of audiences, the token is addressed to: names of the receivers |
| 766: | * (an application name, a URL...), agreed between the issuer and each |
| 767: | * receiver. Each one is a non-empty string, with no surrounding white |
| 768: | * space and no control character. They are written in the token, |
| 769: | * covered by the signature (see `getAudience()`). |
| 770: | * <br/>Default value: none (the token names no audience). |
| 771: | * |
| 772: | * - **`validity`** [int] Creation only. The number of seconds after which |
| 773: | * the token is out of date, whatever the time to live the receiver |
| 774: | * gives to `isOutOfDate()`. The expiry date is written in the token, |
| 775: | * covered by the signature (see `getExpiry()`). |
| 776: | * <br/>Default value: none (only the receiver sets the time to live). |
| 777: | * |
| 778: | * - **`base64Encode`** [boolean] Creation only. Whether to base64 encode |
| 779: | * token data or not. |
| 780: | * <br/>Default value: **`TRUE`**. |
| 781: | * |
| 782: | * - **`xmldsigNsPrefix`** [string] Creation only. The XML namespace |
| 783: | * (xmlns) prefix to use in the XML digital signature tags. Set it to |
| 784: | * empty string to avoid prefix usage. |
| 785: | * <br/>Default value: **`'ds'`**. |
| 786: | * |
| 787: | * - **`checkSigningAlgorithms`** [boolean] Analysis only. Whether to |
| 788: | * check that the algorithms used to sign the token are the expected |
| 789: | * ones or not. Even when FALSE, an algorithm that is not in the lists |
| 790: | * below is rejected. |
| 791: | * <br/>Default value: **`TRUE`**. |
| 792: | * |
| 793: | * - **`checkCryptingAlgorithms`** [boolean] Analysis with a decryption |
| 794: | * key only. Whether to check that the algorithms used to encrypt the |
| 795: | * token are the expected ones or not. Even when FALSE, an algorithm |
| 796: | * that is not in the lists below is rejected. |
| 797: | * <br/>Default value: **`TRUE`**. |
| 798: | * |
| 799: | * - **`canonicalizationAlgorithm`** [string] Creation and analysis. The |
| 800: | * algorithm used to canonicalize the XML digital signature and to |
| 801: | * canonicalize token data before computing its hash. |
| 802: | * <br/>Possible values: |
| 803: | * |
| 804: | * - **`C14N`** (Default value) |
| 805: | * <br/>cf. http://www.w3.org/TR/2001/REC-xml-c14n-20010315 |
| 806: | * |
| 807: | * - `C14N_COMMENTS` |
| 808: | * <br/>cf. http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments |
| 809: | * |
| 810: | * - `EXC_C14N` |
| 811: | * <br/>cf. http://www.w3.org/2001/10/xml-exc-c14n# |
| 812: | * |
| 813: | * - `EXC_C14N_COMMENTS` |
| 814: | * <br/>cf. http://www.w3.org/2001/10/xml-exc-c14n#WithComments |
| 815: | * |
| 816: | * - **`signatureAlgorithm`** [string] Creation and analysis. The |
| 817: | * asymmetric algorithm used to sign the hash of token data. Key |
| 818: | * transport algorithms (see `cryptAlgorithm`) are rejected. |
| 819: | * <br/>Possible values: |
| 820: | * |
| 821: | * - `RSA_SHA1` |
| 822: | * <br/>cf. http://www.w3.org/2000/09/xmldsig#rsa-sha1 |
| 823: | * |
| 824: | * - **`RSA_SHA256`** (Default value) |
| 825: | * <br/>cf. http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 |
| 826: | * |
| 827: | * - `RSA_SHA384` |
| 828: | * <br/>cf. http://www.w3.org/2001/04/xmldsig-more#rsa-sha384 |
| 829: | * |
| 830: | * - `RSA_SHA512` |
| 831: | * <br/>cf. http://www.w3.org/2001/04/xmldsig-more#rsa-sha512 |
| 832: | * |
| 833: | * - **`digestAlgorithm`** [string] Creation and analysis. The algorithm |
| 834: | * used to compute the hash of token data. |
| 835: | * <br/>Possible values: |
| 836: | * |
| 837: | * - `SHA1` |
| 838: | * <br/>cf. http://www.w3.org/2000/09/xmldsig#sha1 |
| 839: | * |
| 840: | * - **`SHA256`** (Default value) |
| 841: | * <br/>cf. http://www.w3.org/2001/04/xmlenc#sha256 |
| 842: | * |
| 843: | * - `SHA384` |
| 844: | * <br/>cf. http://www.w3.org/2001/04/xmldsig-more#sha384 |
| 845: | * |
| 846: | * - `SHA512` |
| 847: | * <br/>cf. http://www.w3.org/2001/04/xmlenc#sha512 |
| 848: | * |
| 849: | * - `RIPEMD160` |
| 850: | * <br/>cf. http://www.w3.org/2001/04/xmlenc#ripemd160 |
| 851: | * |
| 852: | * - **`sessionKeyCipheringAlgorithm`** [string] Encryption only |
| 853: | * (creation with an encryption certificate, analysis with a decryption |
| 854: | * key). The symmetric algorithm used to encrypt token data with a |
| 855: | * generated session key. |
| 856: | * <br/>Possible values: |
| 857: | * |
| 858: | * - `AES128_GCM` |
| 859: | * <br/>cf. http://www.w3.org/2009/xmlenc11#aes128-gcm |
| 860: | * |
| 861: | * - `AES192_GCM` |
| 862: | * <br/>cf. http://www.w3.org/2009/xmlenc11#aes192-gcm |
| 863: | * |
| 864: | * - **`AES256_GCM`** (Default value) |
| 865: | * <br/>cf. http://www.w3.org/2009/xmlenc11#aes256-gcm |
| 866: | * |
| 867: | * - `TRIPLEDES_CBC` |
| 868: | * <br/>cf. http://www.w3.org/2001/04/xmlenc#tripledes-cbc |
| 869: | * |
| 870: | * - `AES128_CBC` |
| 871: | * <br/>cf. http://www.w3.org/2001/04/xmlenc#aes128-cbc |
| 872: | * |
| 873: | * - `AES192_CBC` |
| 874: | * <br/>cf. http://www.w3.org/2001/04/xmlenc#aes192-cbc |
| 875: | * |
| 876: | * - `AES256_CBC` |
| 877: | * <br/>cf. http://www.w3.org/2001/04/xmlenc#aes256-cbc |
| 878: | * |
| 879: | * The CBC algorithms do not protect the integrity of the data: only |
| 880: | * the signature does. An analysis only decrypts a token encrypted with |
| 881: | * one of them if this option names it, even when |
| 882: | * `checkCryptingAlgorithms` is FALSE. |
| 883: | * |
| 884: | * - **`cryptAlgorithm`** [string] Encryption only (creation with an |
| 885: | * encryption certificate, analysis with a decryption key). The |
| 886: | * asymmetric algorithm used to encrypt the session key with the |
| 887: | * encryption certificate (key transport). Signature algorithms (see |
| 888: | * `signatureAlgorithm`) are rejected, and so is RSA 1.5 |
| 889: | * (http://www.w3.org/2001/04/xmlenc#rsa-1_5), at creation as at |
| 890: | * analysis. |
| 891: | * <br/>Possible values: |
| 892: | * |
| 893: | * - **`RSA_OAEP_MGF1P`** (Default value) |
| 894: | * <br/>cf. http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p |
| 895: | * |
| 896: | * @param mixed $xmlOrData An XML token (string) or token data (associative |
| 897: | * array). |
| 898: | * |
| 899: | * @param string $signKeyPath The path to the PEM private key file that will |
| 900: | * be used to sign the token. |
| 901: | * |
| 902: | * @param string $signKeyPassword The password, if needed, to access the |
| 903: | * private key that will be used to sign the token. Use NULL if no |
| 904: | * password needed. |
| 905: | * |
| 906: | * @param string $signCertPath The path to the PEM X.509 certificate file |
| 907: | * that will be included in the XML digital signature, in order to |
| 908: | * verify the signature. |
| 909: | * |
| 910: | * @param string|null $cryptKeyPath The path to the PEM private key file |
| 911: | * that will be used to decrypt the session key which was used to |
| 912: | * encrypt the token. Required to analyze an encrypted token, optional |
| 913: | * to create one. |
| 914: | * |
| 915: | * @param string|null $cryptKeyPassword The password to access the private |
| 916: | * key that will be used to decrypt the session key which was used to |
| 917: | * encrypt the token. Use NULL if no password needed. |
| 918: | * |
| 919: | * @param string $cryptCertPath The path to the PEM X.509 certificate file |
| 920: | * that will be used to encrypt the session key which will be used to |
| 921: | * encrypt the token. |
| 922: | * |
| 923: | * @param array $options Configuration options. |
| 924: | * |
| 925: | * @throws Exception |
| 926: | * |
| 927: | * @see createXMLToken(), createSecureXMLToken(), analyzeXMLToken(), |
| 928: | * analyzeSecureXMLToken() |
| 929: | */ |
| 930: | protected function __construct( |
| 931: | $xmlOrData, |
| 932: | $signKeyPath = null, |
| 933: | $signKeyPassword = null, |
| 934: | $signCertPath = null, |
| 935: | $cryptKeyPath = null, |
| 936: | $cryptKeyPassword = null, |
| 937: | $cryptCertPath = null, |
| 938: | $options = [] |
| 939: | ) |
| 940: | { |
| 941: | if (!is_array($xmlOrData) && !is_string($xmlOrData)) |
| 942: | { |
| 943: | throw new Exception("Invalid parameter 'xmlOrData'! Parameter must be either an array or a string!"); |
| 944: | } |
| 945: | |
| 946: | // Check the options against what the object is created for: an |
| 947: | // unknown option, or an option that does not apply here, throws |
| 948: | // (see _checkOptions()). |
| 949: | $isCreation = is_array($xmlOrData); |
| 950: | self::_checkOptions($options, $isCreation, !is_null($isCreation ? $cryptCertPath : $cryptKeyPath)); |
| 951: | |
| 952: | // Load configuration options. |
| 953: | $base64Encode = isset($options['base64Encode']) ? $options['base64Encode'] : true; |
| 954: | |
| 955: | $xmldsigNsPrefix = isset($options['xmldsigNsPrefix']) ? $options['xmldsigNsPrefix'] : null; |
| 956: | |
| 957: | $checkSigningAlgorithms = isset($options['checkSigningAlgorithms']) ? $options['checkSigningAlgorithms'] : true; |
| 958: | $checkCryptingAlgorithms = isset($options['checkCryptingAlgorithms']) ? $options['checkCryptingAlgorithms'] : true; |
| 959: | |
| 960: | $canonicalizationAlgorithm = isset($options['canonicalizationAlgorithm']) ? $options['canonicalizationAlgorithm'] : null; |
| 961: | $signatureAlgorithm = isset($options['signatureAlgorithm']) ? $options['signatureAlgorithm'] : null; |
| 962: | $digestAlgorithm = isset($options['digestAlgorithm']) ? $options['digestAlgorithm'] : null; |
| 963: | $sessionKeyCipheringAlgorithm = isset($options['sessionKeyCipheringAlgorithm']) ? $options['sessionKeyCipheringAlgorithm'] : null; |
| 964: | $cryptAlgorithm = isset($options['cryptAlgorithm']) ? $options['cryptAlgorithm'] : null; |
| 965: | |
| 966: | // If provided, set and store the canonicalization algorithm. |
| 967: | if (!is_null($canonicalizationAlgorithm)) |
| 968: | { |
| 969: | if (self::_isValidCanonicalizationAlgorithm($canonicalizationAlgorithm)) |
| 970: | { |
| 971: | $this->canonicalizationAlgorithm = $canonicalizationAlgorithm; |
| 972: | $this->transformAlgorithm = $canonicalizationAlgorithm; |
| 973: | } |
| 974: | else |
| 975: | { |
| 976: | throw new Exception("Invalid parameter 'canonicalizationAlgorithm'! Unknown canonicalization algorithm."); |
| 977: | } |
| 978: | } |
| 979: | |
| 980: | // If provided, set and store the signature algorithm. |
| 981: | if (!is_null($signatureAlgorithm)) |
| 982: | { |
| 983: | if (self::_isValidSignatureAlgorithm($signatureAlgorithm)) |
| 984: | { |
| 985: | $this->signatureAlgorithm = $signatureAlgorithm; |
| 986: | } |
| 987: | else |
| 988: | { |
| 989: | throw new Exception("Invalid parameter 'signatureAlgorithm'! Unknown signature algorithm."); |
| 990: | } |
| 991: | } |
| 992: | |
| 993: | // If provided, set and store the digest algorithm. |
| 994: | if (!is_null($digestAlgorithm)) |
| 995: | { |
| 996: | if (self::_isValidHashAlgorithm($digestAlgorithm)) |
| 997: | { |
| 998: | $this->digestAlgorithm = $digestAlgorithm; |
| 999: | } |
| 1000: | else |
| 1001: | { |
| 1002: | throw new Exception("Invalid parameter 'digestAlgorithm'! Unknown digest algorithm."); |
| 1003: | } |
| 1004: | } |
| 1005: | |
| 1006: | // If requested, disable check of signature algorithms. |
| 1007: | if (false === $checkSigningAlgorithms) |
| 1008: | { |
| 1009: | $this->checkSigningAlgorithms = false; |
| 1010: | } |
| 1011: | |
| 1012: | // Check what have to be done according to the type of $xmlOrData |
| 1013: | // parameter. |
| 1014: | if ($isCreation) |
| 1015: | { |
| 1016: | // $xmlOrData is an array, so we have to create an XML token. |
| 1017: | |
| 1018: | // Check that $data is a non-empty array. |
| 1019: | if (empty($xmlOrData)) |
| 1020: | { |
| 1021: | throw new Exception("Invalid parameter 'data'! Token data should not be an empty array."); |
| 1022: | } |
| 1023: | |
| 1024: | // Check that $data is an associative array. |
| 1025: | if (count(array_filter(array_keys($xmlOrData), 'is_string')) == 0) |
| 1026: | { |
| 1027: | throw new Exception("Invalid parameter 'data'! Token data should be an associative array."); |
| 1028: | } |
| 1029: | |
| 1030: | // If requested, disable base64 encoding of token data. |
| 1031: | if (false === $base64Encode) |
| 1032: | { |
| 1033: | $this->base64EncodeData = false; |
| 1034: | } |
| 1035: | |
| 1036: | // If provided, store the audiences and the validity of the token |
| 1037: | // (checked by _checkOptions()). |
| 1038: | if (isset($options['audience'])) |
| 1039: | { |
| 1040: | $this->audienceToWrite = (array) $options['audience']; |
| 1041: | } |
| 1042: | if (isset($options['validity'])) |
| 1043: | { |
| 1044: | $this->validity = $options['validity']; |
| 1045: | } |
| 1046: | |
| 1047: | // Check that required private key and X.509 certificate |
| 1048: | // are provided, in order to sign the token. |
| 1049: | if (is_null($signKeyPath)) |
| 1050: | { |
| 1051: | throw new Exception("Missing parameter 'signKeyPath'! A private key is required to sign token."); |
| 1052: | } |
| 1053: | |
| 1054: | // Check that required private key and X.509 certificate |
| 1055: | // are provided, in order to sign the token. |
| 1056: | if (is_null($signCertPath)) |
| 1057: | { |
| 1058: | throw new Exception("Missing parameter 'signCertPath'! An X.509 certificate is required to sign token."); |
| 1059: | } |
| 1060: | |
| 1061: | // Get and store the private key that will be used to sign the token |
| 1062: | // data. |
| 1063: | $signKey = @file_get_contents($signKeyPath); |
| 1064: | if (false === $signKey) |
| 1065: | { |
| 1066: | throw new Exception("Invalid parameter 'signKeyPath'! Cannot read private key to sign token."); |
| 1067: | } |
| 1068: | $this->signKey = $signKey; |
| 1069: | |
| 1070: | // If provided, store the password to access the private key that |
| 1071: | // will be used to sign the token data. |
| 1072: | if (!is_null($signKeyPassword)) |
| 1073: | { |
| 1074: | if (!is_string($signKeyPassword)) |
| 1075: | { |
| 1076: | throw new Exception("Invalid parameter 'signKeyPassword'! Parameter must be a string."); |
| 1077: | } |
| 1078: | $this->signKeyPassword = $signKeyPassword; |
| 1079: | } |
| 1080: | |
| 1081: | // Get and store the X.509 certificate that will be included in the |
| 1082: | // XML token. |
| 1083: | $signCert = @file_get_contents($signCertPath); |
| 1084: | if (false === $signCert) |
| 1085: | { |
| 1086: | throw new Exception("Invalid parameter 'signCertPath'! Cannot read X.509 certificate to sign token."); |
| 1087: | } |
| 1088: | $this->signCert = $signCert; |
| 1089: | |
| 1090: | // The created token is analyzed to check it (see _writeXML()): it |
| 1091: | // must be signed with this very certificate. |
| 1092: | $this->pinnedSignerCert = $signCert; |
| 1093: | |
| 1094: | // If provided, store the prefix namespace to use in the XML digital |
| 1095: | // signature tags. |
| 1096: | if (!is_null($xmldsigNsPrefix)) |
| 1097: | { |
| 1098: | if (!is_string($xmldsigNsPrefix)) |
| 1099: | { |
| 1100: | throw new Exception("Invalid parameter 'xmldsigNsPrefix'! Parameter must be a string."); |
| 1101: | } |
| 1102: | $this->xmldsigNsPrefix = $xmldsigNsPrefix; |
| 1103: | } |
| 1104: | |
| 1105: | // If provided, get and store X.509 certificate that will be used |
| 1106: | // to encrypt the session key which will be used to encrypt the |
| 1107: | // token data. |
| 1108: | if (!is_null($cryptCertPath)) |
| 1109: | { |
| 1110: | $cryptCert = @file_get_contents($cryptCertPath); |
| 1111: | if (false === $cryptCert) |
| 1112: | { |
| 1113: | throw new Exception("Invalid parameter 'cryptCertPath'! Cannot read X.509 certificate to encrypt token."); |
| 1114: | } |
| 1115: | $this->cryptCert = $cryptCert; |
| 1116: | |
| 1117: | // If provided, get and store the private key of the recipient, |
| 1118: | // which decrypts the session key: it is only used to check |
| 1119: | // the decrypted content of the created token. Without it, the |
| 1120: | // created token is checked up to its decryption (see |
| 1121: | // _readXML()), so that the sender needs no private key of the |
| 1122: | // recipient. |
| 1123: | if (!is_null($cryptKeyPath)) |
| 1124: | { |
| 1125: | $cryptKey = @file_get_contents($cryptKeyPath); |
| 1126: | if (false === $cryptKey) |
| 1127: | { |
| 1128: | throw new Exception("Invalid parameter 'cryptKeyPath'! Cannot read private key to decrypt token."); |
| 1129: | } |
| 1130: | $this->cryptKey = $cryptKey; |
| 1131: | } |
| 1132: | |
| 1133: | // If provided, store the password to access the private key |
| 1134: | // that will be used to decrypt the session key. A password |
| 1135: | // without a key would be ignored: it throws instead. |
| 1136: | if (!is_null($cryptKeyPassword)) |
| 1137: | { |
| 1138: | if (is_null($cryptKeyPath)) |
| 1139: | { |
| 1140: | throw new Exception("Invalid parameter 'cryptKeyPassword'! It only applies with the parameter 'cryptKeyPath'."); |
| 1141: | } |
| 1142: | if (!is_string($cryptKeyPassword)) |
| 1143: | { |
| 1144: | throw new Exception("Invalid parameter 'cryptKeyPassword'! Parameter must be a string."); |
| 1145: | } |
| 1146: | $this->cryptKeyPassword = $cryptKeyPassword; |
| 1147: | } |
| 1148: | |
| 1149: | // If provided, set and store the session key algorithm. |
| 1150: | if (!is_null($sessionKeyCipheringAlgorithm)) |
| 1151: | { |
| 1152: | if (self::_isValidSymmetricCipheringAlgorithm($sessionKeyCipheringAlgorithm)) |
| 1153: | { |
| 1154: | $this->sessionKeyCipheringAlgorithm = $sessionKeyCipheringAlgorithm; |
| 1155: | } |
| 1156: | else |
| 1157: | { |
| 1158: | throw new Exception("Invalid parameter 'sessionKeyCipheringAlgorithm'! Unknown session key ciphering algorithm."); |
| 1159: | } |
| 1160: | } |
| 1161: | |
| 1162: | // If provided, set and store the crypt algorithm. |
| 1163: | if (!is_null($cryptAlgorithm)) |
| 1164: | { |
| 1165: | if (self::_isValidKeyTransportAlgorithm($cryptAlgorithm)) |
| 1166: | { |
| 1167: | $this->cryptAlgorithm = $cryptAlgorithm; |
| 1168: | } |
| 1169: | else |
| 1170: | { |
| 1171: | throw new Exception("Invalid parameter 'cryptAlgorithm'! Unknown crypt algorithm."); |
| 1172: | } |
| 1173: | } |
| 1174: | |
| 1175: | // If requested, disable check of used crypt algorithms. |
| 1176: | if (false === $checkCryptingAlgorithms) |
| 1177: | { |
| 1178: | $this->checkCryptingAlgorithms = false; |
| 1179: | } |
| 1180: | } |
| 1181: | |
| 1182: | // Create an XML token with the provided data. |
| 1183: | try |
| 1184: | { |
| 1185: | // NOTE: This function will call the _readXML() function which |
| 1186: | // will verify that the created token is correct and which will |
| 1187: | // terminate setting object properties. |
| 1188: | $this->_writeXML($xmlOrData); |
| 1189: | } |
| 1190: | catch (Exception $e) |
| 1191: | { |
| 1192: | // ERROR: XML token analysis failed on fatal error. |
| 1193: | $this->error = $e->getMessage(); |
| 1194: | } |
| 1195: | } |
| 1196: | else |
| 1197: | { |
| 1198: | // $xmlOrData is a string, so we have to analyze the XML token. |
| 1199: | |
| 1200: | // Load the trust anchor. Its absence is not an error here: the |
| 1201: | // analysis then reports that no certificate can be trusted (see |
| 1202: | // _verifyCertTrust()). |
| 1203: | $this->_loadTrustOptions($options); |
| 1204: | |
| 1205: | // If provided, store the audience the token must be addressed to |
| 1206: | // (checked by _checkOptions(), see _verifyAudience()). |
| 1207: | if (isset($options['expectedAudience'])) |
| 1208: | { |
| 1209: | $this->expectedAudience = $options['expectedAudience']; |
| 1210: | } |
| 1211: | |
| 1212: | // If provided, get and store the private key that will be used |
| 1213: | // to decrypt the session key which was used to encrypt the token. |
| 1214: | if (!is_null($cryptKeyPath)) |
| 1215: | { |
| 1216: | $cryptKey = @file_get_contents($cryptKeyPath); |
| 1217: | if (false === $cryptKey) |
| 1218: | { |
| 1219: | throw new Exception("Invalid parameter 'cryptKeyPath'! Cannot read private key to decrypt token."); |
| 1220: | } |
| 1221: | $this->cryptKey = $cryptKey; |
| 1222: | |
| 1223: | // If provided, store the password to access the private key |
| 1224: | // that will be used to decrypt the session key. |
| 1225: | if (!is_null($cryptKeyPassword)) |
| 1226: | { |
| 1227: | if (!is_string($cryptKeyPassword)) |
| 1228: | { |
| 1229: | throw new Exception("Invalid parameter 'cryptKeyPassword'! Parameter must be a string."); |
| 1230: | } |
| 1231: | $this->cryptKeyPassword = $cryptKeyPassword; |
| 1232: | } |
| 1233: | |
| 1234: | // If provided, set and store the session key algorithm. |
| 1235: | if (!is_null($sessionKeyCipheringAlgorithm)) |
| 1236: | { |
| 1237: | if (self::_isValidSymmetricCipheringAlgorithm($sessionKeyCipheringAlgorithm)) |
| 1238: | { |
| 1239: | $this->sessionKeyCipheringAlgorithm = $sessionKeyCipheringAlgorithm; |
| 1240: | } |
| 1241: | else |
| 1242: | { |
| 1243: | throw new Exception("Invalid parameter 'sessionKeyCipheringAlgorithm'! Unknown session key ciphering algorithm."); |
| 1244: | } |
| 1245: | } |
| 1246: | |
| 1247: | // If provided, set and store the crypt algorithm. |
| 1248: | if (!is_null($cryptAlgorithm)) |
| 1249: | { |
| 1250: | if (self::_isValidKeyTransportAlgorithm($cryptAlgorithm)) |
| 1251: | { |
| 1252: | $this->cryptAlgorithm = $cryptAlgorithm; |
| 1253: | } |
| 1254: | else |
| 1255: | { |
| 1256: | throw new Exception("Invalid parameter 'cryptAlgorithm'! Unknown crypt algorithm."); |
| 1257: | } |
| 1258: | } |
| 1259: | |
| 1260: | // If requested, disable check of used crypt algorithms. |
| 1261: | if (false === $checkCryptingAlgorithms) |
| 1262: | { |
| 1263: | $this->checkCryptingAlgorithms = false; |
| 1264: | } |
| 1265: | } |
| 1266: | |
| 1267: | // Parse the provided XML token to ensure all is correct and to |
| 1268: | // terminate initializing object properties. |
| 1269: | try |
| 1270: | { |
| 1271: | $this->_readXML($xmlOrData); |
| 1272: | } |
| 1273: | catch (Exception $e) |
| 1274: | { |
| 1275: | // ERROR: XML token analysis failed on fatal error. |
| 1276: | $this->error = $e->getMessage(); |
| 1277: | } |
| 1278: | } |
| 1279: | } |
| 1280: | |
| 1281: | |
| 1282: | /** |
| 1283: | * Check the options given to the object against what it is created for. |
| 1284: | * |
| 1285: | * Each option is only read in its context (see `OPTION_CONTEXTS`): token |
| 1286: | * creation, token analysis, both ("any"), encryption (creation with an |
| 1287: | * encryption certificate, or analysis with a decryption key) or |
| 1288: | * decryption (analysis with a decryption key). A misspelt option, or an |
| 1289: | * option given out of its context, would be ignored without notice and |
| 1290: | * leave the token without the configuration the caller asked for: it |
| 1291: | * throws an exception instead, as does an option whose value is NULL or |
| 1292: | * of the wrong type. The values of the algorithm and trust options are |
| 1293: | * checked where they are loaded. |
| 1294: | * |
| 1295: | * @param array $options Configuration options. |
| 1296: | * |
| 1297: | * @param boolean $isCreation TRUE if the object creates a token, FALSE if |
| 1298: | * it analyzes one. |
| 1299: | * |
| 1300: | * @param boolean $isEncryption TRUE if an encryption certificate (token |
| 1301: | * creation) or a decryption key (token analysis) is given. |
| 1302: | * |
| 1303: | * @throws Exception |
| 1304: | */ |
| 1305: | static private function _checkOptions($options, $isCreation, $isEncryption) |
| 1306: | { |
| 1307: | if (!is_array($options)) |
| 1308: | { |
| 1309: | throw new Exception("Invalid parameter 'options'! Parameter must be an array."); |
| 1310: | } |
| 1311: | |
| 1312: | foreach ($options as $name => $value) |
| 1313: | { |
| 1314: | if (!isset(self::OPTION_CONTEXTS[$name])) |
| 1315: | { |
| 1316: | throw new Exception("Unknown option '" . $name . "'!"); |
| 1317: | } |
| 1318: | |
| 1319: | switch (self::OPTION_CONTEXTS[$name]) |
| 1320: | { |
| 1321: | case 'creation': |
| 1322: | if (!$isCreation) |
| 1323: | { |
| 1324: | throw new Exception("Option '" . $name . "' only applies to token creation!"); |
| 1325: | } |
| 1326: | break; |
| 1327: | case 'analysis': |
| 1328: | if ($isCreation) |
| 1329: | { |
| 1330: | throw new Exception("Option '" . $name . "' only applies to token analysis! A created token is checked with the certificate of its own signing key."); |
| 1331: | } |
| 1332: | break; |
| 1333: | case 'encryption': |
| 1334: | if (!$isEncryption) |
| 1335: | { |
| 1336: | throw new Exception("Option '" . $name . "' only applies to an encrypted token! Give the encryption certificate (createSecureXMLToken()) or the decryption key (analyzeSecureXMLToken())."); |
| 1337: | } |
| 1338: | break; |
| 1339: | case 'decryption': |
| 1340: | if ($isCreation || !$isEncryption) |
| 1341: | { |
| 1342: | throw new Exception("Option '" . $name . "' only applies to the analysis of an encrypted token! Give the decryption key (analyzeSecureXMLToken())."); |
| 1343: | } |
| 1344: | break; |
| 1345: | } |
| 1346: | |
| 1347: | if (is_null($value)) |
| 1348: | { |
| 1349: | throw new Exception("Invalid option '" . $name . "'! Its value must not be NULL."); |
| 1350: | } |
| 1351: | |
| 1352: | if (in_array($name, ['base64Encode', 'checkSigningAlgorithms', 'checkCryptingAlgorithms'], true) && !is_bool($value)) |
| 1353: | { |
| 1354: | throw new Exception("Invalid option '" . $name . "'! It must be a boolean."); |
| 1355: | } |
| 1356: | |
| 1357: | if ('xmldsigNsPrefix' === $name && !is_string($value)) |
| 1358: | { |
| 1359: | throw new Exception("Invalid option '" . $name . "'! It must be a string."); |
| 1360: | } |
| 1361: | |
| 1362: | if ('audience' === $name) |
| 1363: | { |
| 1364: | $audiences = is_array($value) ? $value : [$value]; |
| 1365: | if (empty($audiences) || $audiences !== array_values($audiences) || $audiences !== array_filter($audiences, [self::class, '_isValidAudience'])) |
| 1366: | { |
| 1367: | throw new Exception("Invalid option 'audience'! It must be a non-empty string, or a non-empty list of them, without control characters."); |
| 1368: | } |
| 1369: | if (count(array_unique($audiences)) !== count($audiences)) |
| 1370: | { |
| 1371: | throw new Exception("Invalid option 'audience'! An audience is given twice."); |
| 1372: | } |
| 1373: | } |
| 1374: | |
| 1375: | if ('expectedAudience' === $name && !self::_isValidAudience($value)) |
| 1376: | { |
| 1377: | throw new Exception("Invalid option 'expectedAudience'! It must be a non-empty string without control characters."); |
| 1378: | } |
| 1379: | |
| 1380: | if ('validity' === $name && !(is_int($value) && $value > 0)) |
| 1381: | { |
| 1382: | throw new Exception("Invalid option 'validity'! It must be a number of seconds greater than 0."); |
| 1383: | } |
| 1384: | |
| 1385: | // The expiry is written with a four-digit year: a validity that |
| 1386: | // takes it past the year 9999 (or past the range of an integer) |
| 1387: | // could not be written, and would be computed wrong. |
| 1388: | if ('validity' === $name && $value > self::MAX_EXPIRY_TIME - time()) |
| 1389: | { |
| 1390: | throw new Exception("Invalid option 'validity'! The expiry would be after 9999-12-31T23:59:59Z."); |
| 1391: | } |
| 1392: | } |
| 1393: | } |
| 1394: | |
| 1395: | |
| 1396: | /** |
| 1397: | * Indicates whether a value can be an audience of a token (options |
| 1398: | * "audience" and "expectedAudience"): a non-empty UTF-8 string, without |
| 1399: | * surrounding white space, made of characters XML 1.0 can hold as text. |
| 1400: | * |
| 1401: | * Control characters are refused: XML 1.0 cannot hold most of them, and |
| 1402: | * the others (tab, line feed, carriage return) are normalized by XML |
| 1403: | * parsers, so that the audience read back would differ from the one |
| 1404: | * written. So are U+FFFE and U+FFFF, which XML 1.0 cannot hold either. |
| 1405: | * |
| 1406: | * @param mixed $audience The value to check. |
| 1407: | * |
| 1408: | * @return boolean TRUE if the value can be an audience, FALSE otherwise. |
| 1409: | */ |
| 1410: | static private function _isValidAudience($audience) |
| 1411: | { |
| 1412: | return is_string($audience) |
| 1413: | && '' !== $audience |
| 1414: | && trim($audience) === $audience |
| 1415: | && 1 === preg_match('//u', $audience) |
| 1416: | && 0 === preg_match('/[\x00-\x1F\x7F]|[^\x{20}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]/u', $audience); |
| 1417: | } |
| 1418: | |
| 1419: | |
| 1420: | /** |
| 1421: | * Load and check the trust options of an analysis ("caCertPath", |
| 1422: | * "signerCertPath" and "expectedSubject", see `__construct()`). |
| 1423: | * |
| 1424: | * A trust option of the wrong type, or naming a file that cannot be read, |
| 1425: | * throws an exception instead of being ignored: ignoring it would leave |
| 1426: | * the token without the constraint the caller asked for. |
| 1427: | * |
| 1428: | * @param array $options Configuration options. |
| 1429: | * |
| 1430: | * @throws Exception |
| 1431: | */ |
| 1432: | private function _loadTrustOptions($options) |
| 1433: | { |
| 1434: | if (isset($options['caCertPath'])) |
| 1435: | { |
| 1436: | $caCertPaths = $options['caCertPath']; |
| 1437: | if (is_string($caCertPaths)) |
| 1438: | { |
| 1439: | $caCertPaths = [$caCertPaths]; |
| 1440: | } |
| 1441: | if (!is_array($caCertPaths) || empty($caCertPaths)) |
| 1442: | { |
| 1443: | throw new Exception("Invalid option 'caCertPath'! It must be a path or a non-empty list of paths."); |
| 1444: | } |
| 1445: | foreach ($caCertPaths as $caCertPath) |
| 1446: | { |
| 1447: | if (!is_string($caCertPath) || !is_file($caCertPath) || !is_readable($caCertPath)) |
| 1448: | { |
| 1449: | throw new Exception("Invalid option 'caCertPath'! Cannot read CA certificate file: " . (is_string($caCertPath) ? $caCertPath : gettype($caCertPath)) . "."); |
| 1450: | } |
| 1451: | } |
| 1452: | $this->trustedCACertPaths = array_values($caCertPaths); |
| 1453: | } |
| 1454: | |
| 1455: | if (isset($options['signerCertPath'])) |
| 1456: | { |
| 1457: | $signerCert = is_string($options['signerCertPath']) ? @file_get_contents($options['signerCertPath']) : false; |
| 1458: | if (false === $signerCert || false === @openssl_x509_read($signerCert)) |
| 1459: | { |
| 1460: | throw new Exception("Invalid option 'signerCertPath'! Cannot read the pinned X.509 certificate."); |
| 1461: | } |
| 1462: | $this->pinnedSignerCert = $signerCert; |
| 1463: | } |
| 1464: | |
| 1465: | if (isset($options['expectedSubject'])) |
| 1466: | { |
| 1467: | $expectedSubject = $options['expectedSubject']; |
| 1468: | if (!(is_string($expectedSubject) || is_array($expectedSubject)) || empty($expectedSubject)) |
| 1469: | { |
| 1470: | throw new Exception("Invalid option 'expectedSubject'! It must be a non-empty string or array."); |
| 1471: | } |
| 1472: | $this->expectedSubject = $expectedSubject; |
| 1473: | } |
| 1474: | } |
| 1475: | |
| 1476: | |
| 1477: | /** |
| 1478: | * Creates an XML token for the given user data. |
| 1479: | * |
| 1480: | * The created XML token can be retrieved using the function `getXML()`. |
| 1481: | * |
| 1482: | * @param array $data Token data (an associative array that may be |
| 1483: | * multi-dimensional). |
| 1484: | * |
| 1485: | * @param string $signKeyPath The path to the PEM private key file that will |
| 1486: | * be used to sign the token. |
| 1487: | * |
| 1488: | * @param string $signCertPath The path to the PEM X.509 certificate file |
| 1489: | * that will be included in the XML digital signature, in order to |
| 1490: | * verify the signature. |
| 1491: | * |
| 1492: | * @param string $signKeyPassword The password to access the private key |
| 1493: | * that will be used to sign the token. Use NULL if no password needed. |
| 1494: | * |
| 1495: | * @param array $options Configuration options |
| 1496: | * (see `__construct()` for details). |
| 1497: | * |
| 1498: | * @return XMLDSigToken An XMLDSigToken object. If the token cannot be |
| 1499: | * created, `getError()` tells why. |
| 1500: | * |
| 1501: | * @throws Exception |
| 1502: | * |
| 1503: | * @see __construct() |
| 1504: | */ |
| 1505: | public static function createXMLToken( |
| 1506: | $data, |
| 1507: | $signKeyPath, |
| 1508: | $signCertPath, |
| 1509: | $signKeyPassword = null, |
| 1510: | $options = [] |
| 1511: | ) |
| 1512: | { |
| 1513: | return new XMLDSigToken( |
| 1514: | $data, |
| 1515: | $signKeyPath, |
| 1516: | $signKeyPassword, |
| 1517: | $signCertPath, |
| 1518: | $cryptKeyPath = null, |
| 1519: | $cryptKeyPassword = null, |
| 1520: | $cryptCertPath = null, |
| 1521: | $options |
| 1522: | ); |
| 1523: | } |
| 1524: | |
| 1525: | |
| 1526: | /** |
| 1527: | * Creates a secure (encrypted) XML token for the given user data. |
| 1528: | * |
| 1529: | * The created XML token can be retrieved using the function `getXML()`. |
| 1530: | * |
| 1531: | * The token is encrypted for the owner of the encryption certificate |
| 1532: | * (`$cryptCertPath`): only the private key of this certificate decrypts |
| 1533: | * it. The sender does not need this private key: pass NULL as |
| 1534: | * `$cryptKeyPath`. |
| 1535: | * |
| 1536: | * ```php |
| 1537: | * $token = XMLDSigToken::createSecureXMLToken($data, $signKeyPath, $signCertPath, null, $cryptCertPath, $signKeyPassword); |
| 1538: | * ``` |
| 1539: | * |
| 1540: | * The created token is checked right away: |
| 1541: | * |
| 1542: | * - Without `$cryptKeyPath`, the check covers everything that can be |
| 1543: | * verified without decrypting the token: its structure, its |
| 1544: | * algorithms, its digest, its signature and the trust in the signing |
| 1545: | * certificate. `isSignatureValid()` and `isDataEncrypted()` return |
| 1546: | * TRUE, while `getData()`, `getTimestamp()` and `getTokenId()` return |
| 1547: | * NULL: they are inside the encrypted content, which is not decrypted. |
| 1548: | * |
| 1549: | * - With `$cryptKeyPath`, the token is also decrypted and its content |
| 1550: | * read, as by `analyzeSecureXMLToken()`: `getData()`, `getTimestamp()` |
| 1551: | * and `getTokenId()` return what the decrypted token holds. |
| 1552: | * |
| 1553: | * @param array $data Token data (an associative array that may be |
| 1554: | * multi-dimensional). |
| 1555: | * |
| 1556: | * @param string $signKeyPath The path to the PEM private key file that will |
| 1557: | * be used to sign the token. |
| 1558: | * |
| 1559: | * @param string $signCertPath The path to the PEM X.509 certificate file |
| 1560: | * that will be included in the XML digital signature, in order to |
| 1561: | * verify the signature. |
| 1562: | * |
| 1563: | * @param string|null $cryptKeyPath The path to the PEM private key file of |
| 1564: | * the recipient, associated to `$cryptCertPath`, used to decrypt the |
| 1565: | * created token in order to check its content. Use NULL to create the |
| 1566: | * token without it. |
| 1567: | * |
| 1568: | * @param string $cryptCertPath The path to the PEM X.509 certificate file |
| 1569: | * that will be used to encrypt the session key which will be used to |
| 1570: | * encrypt the token. |
| 1571: | * |
| 1572: | * @param string $signKeyPassword The password to access the private key |
| 1573: | * that will be used to sign the token. Use NULL if no password needed. |
| 1574: | * |
| 1575: | * @param string|null $cryptKeyPassword The password to access the private |
| 1576: | * key `$cryptKeyPath`. Use NULL if no password needed, and when |
| 1577: | * `$cryptKeyPath` is NULL. |
| 1578: | * |
| 1579: | * @param array $options Configuration options |
| 1580: | * (see `__construct()` for details). |
| 1581: | * |
| 1582: | * @return XMLDSigToken An XMLDSigToken object. If the token cannot be |
| 1583: | * created, `getError()` tells why. |
| 1584: | * |
| 1585: | * @throws Exception |
| 1586: | * |
| 1587: | * @see __construct() |
| 1588: | */ |
| 1589: | public static function createSecureXMLToken( |
| 1590: | $data, |
| 1591: | $signKeyPath, |
| 1592: | $signCertPath, |
| 1593: | $cryptKeyPath, |
| 1594: | $cryptCertPath, |
| 1595: | $signKeyPassword = null, |
| 1596: | $cryptKeyPassword = null, |
| 1597: | $options = [] |
| 1598: | ) |
| 1599: | { |
| 1600: | // Without an encryption certificate, the constructor would create an |
| 1601: | // unencrypted token. |
| 1602: | if (is_null($cryptCertPath)) |
| 1603: | { |
| 1604: | throw new Exception("Missing parameter 'cryptCertPath'! An X.509 certificate is required to encrypt token."); |
| 1605: | } |
| 1606: | |
| 1607: | return new XMLDSigToken( |
| 1608: | $data, |
| 1609: | $signKeyPath, |
| 1610: | $signKeyPassword, |
| 1611: | $signCertPath, |
| 1612: | $cryptKeyPath, |
| 1613: | $cryptKeyPassword, |
| 1614: | $cryptCertPath, |
| 1615: | $options |
| 1616: | ); |
| 1617: | } |
| 1618: | |
| 1619: | |
| 1620: | /** |
| 1621: | * Parse an XML token. |
| 1622: | * |
| 1623: | * The options must hold a trust anchor, `caCertPath` and/or |
| 1624: | * `signerCertPath`; without it, `isSignatureValid()` returns FALSE. |
| 1625: | * |
| 1626: | * ```php |
| 1627: | * $token = XMLDSigToken::analyzeXMLToken($xml, [ |
| 1628: | * 'caCertPath' => ['path/to/intermediate.cert.pem', 'path/to/root.cert.pem'], |
| 1629: | * ]); |
| 1630: | * ``` |
| 1631: | * |
| 1632: | * @param string $xml An XML token. |
| 1633: | * |
| 1634: | * @param array $options Configuration options, trust anchor included |
| 1635: | * (see `__construct()` for details). |
| 1636: | * |
| 1637: | * @return XMLDSigToken An XMLDSigToken object. If the token is not |
| 1638: | * valid, `isSignatureValid()` returns FALSE and `getError()` tells |
| 1639: | * why. |
| 1640: | * |
| 1641: | * @throws Exception |
| 1642: | * |
| 1643: | * @see __construct() |
| 1644: | */ |
| 1645: | public static function analyzeXMLToken( |
| 1646: | $xml, |
| 1647: | $options = [] |
| 1648: | ) |
| 1649: | { |
| 1650: | return new XMLDSigToken( |
| 1651: | $xml, |
| 1652: | $signKeyPath = null, |
| 1653: | $signKeyPassword = null, |
| 1654: | $signCertPath = null, |
| 1655: | $cryptKeyPath = null, |
| 1656: | $cryptKeyPassword = null, |
| 1657: | $cryptCertPath = null, |
| 1658: | $options |
| 1659: | ); |
| 1660: | } |
| 1661: | |
| 1662: | |
| 1663: | /** |
| 1664: | * Parse an XML token whose data are encrypted. |
| 1665: | * |
| 1666: | * NOTE: An unencrypted token can also be parsed using this function. |
| 1667: | * |
| 1668: | * The options must hold a trust anchor, `caCertPath` and/or |
| 1669: | * `signerCertPath`; without it, `isSignatureValid()` returns FALSE. |
| 1670: | * |
| 1671: | * @param string $xml An XML token. |
| 1672: | * |
| 1673: | * @param string $cryptKeyPath The path to the PEM private key file that |
| 1674: | * will be used to decrypt the session key which was used to encrypt |
| 1675: | * token data. |
| 1676: | * |
| 1677: | * @param string $cryptKeyPassword The password to access the private key |
| 1678: | * that will be used to decrypt the session key which was used to |
| 1679: | * encrypt the token. Use NULL if no password needed. |
| 1680: | * |
| 1681: | * @param array $options Configuration options, trust anchor included |
| 1682: | * (see `__construct()` for details). |
| 1683: | * |
| 1684: | * @return XMLDSigToken An XMLDSigToken object. If the token is not |
| 1685: | * valid, `isSignatureValid()` returns FALSE and `getError()` tells |
| 1686: | * why. |
| 1687: | * |
| 1688: | * @throws Exception |
| 1689: | * |
| 1690: | * @see __construct() |
| 1691: | */ |
| 1692: | public static function analyzeSecureXMLToken( |
| 1693: | $xml, |
| 1694: | $cryptKeyPath, |
| 1695: | $cryptKeyPassword = null, |
| 1696: | $options = [] |
| 1697: | ) |
| 1698: | { |
| 1699: | return new XMLDSigToken( |
| 1700: | $xml, |
| 1701: | $signKeyPath = null, |
| 1702: | $signKeyPassword = null, |
| 1703: | $signCertPath = null, |
| 1704: | $cryptKeyPath, |
| 1705: | $cryptKeyPassword, |
| 1706: | $cryptCertPath = null, |
| 1707: | $options |
| 1708: | ); |
| 1709: | } |
| 1710: | |
| 1711: | |
| 1712: | /** |
| 1713: | * Write the XML Digital Signature representing the XML token for the |
| 1714: | * provided user data. |
| 1715: | * |
| 1716: | * The XML token can then be obtained using the `getXML()` function. |
| 1717: | * |
| 1718: | * @param array $data A flat or multidimensional associative array |
| 1719: | * containing the token data. |
| 1720: | * |
| 1721: | * @throws Exception |
| 1722: | */ |
| 1723: | private function _writeXML($data) |
| 1724: | { |
| 1725: | // Whether to base64 encode data or not. |
| 1726: | $base64Encode = $this->base64EncodeData; |
| 1727: | |
| 1728: | // Create an XML document to hold the token data. |
| 1729: | $xmlDoc = new DOMDocument('1.0', 'UTF-8'); |
| 1730: | |
| 1731: | // Do not format the XML digital signature when it will be saved as an |
| 1732: | // XML string. |
| 1733: | $xmlDoc->formatOutput = false; |
| 1734: | |
| 1735: | // Create the root node "Token" that holds the whole content of the |
| 1736: | // token. |
| 1737: | // NOTE: This node is explicitly created without namespace if no |
| 1738: | // namespace is used for XML digital signature tags. |
| 1739: | if ($this->xmldsigNsPrefix === '') |
| 1740: | { |
| 1741: | $tokenElement = $xmlDoc->createElementNS('', self::TOKEN_NAME); |
| 1742: | } |
| 1743: | else |
| 1744: | { |
| 1745: | $tokenElement = $xmlDoc->createElement(self::TOKEN_NAME); |
| 1746: | } |
| 1747: | $tokenNode = $xmlDoc->appendChild($tokenElement); |
| 1748: | |
| 1749: | // Create a node "timestamp" that holds the token timestamp in the |
| 1750: | // format "YYYY-MM-DDThh:mm:ssZ", using UTC timezone, and append it to |
| 1751: | // the node "Token". |
| 1752: | $dt = new DateTime(); |
| 1753: | $dt->setTimeZone(new DateTimeZone('UTC')); |
| 1754: | $tokenTimestampElement = $xmlDoc->createElement('TokenTimestamp', $dt->format(self::TOKEN_TIMESTAMP_FORMAT)); |
| 1755: | $tokenTimestampNode = $tokenNode->appendChild($tokenTimestampElement); |
| 1756: | |
| 1757: | // Create a node "TokenId" that holds a random identifier, in |
| 1758: | // hexadecimal, and append it to the node "Token". The signature |
| 1759: | // covers it: the receiver can refuse a token whose identifier it has |
| 1760: | // already accepted (see getTokenId()). |
| 1761: | $tokenIdElement = $xmlDoc->createElement(self::TOKEN_ID_NAME, bin2hex(random_bytes(self::TOKEN_ID_BYTES))); |
| 1762: | $tokenNode->appendChild($tokenIdElement); |
| 1763: | |
| 1764: | // If a validity is given, create a node "TokenExpiry" that holds the |
| 1765: | // date after which the token is out of date (see isOutOfDate()), in |
| 1766: | // the format of the timestamp, and append it to the node "Token". |
| 1767: | if (!is_null($this->validity)) |
| 1768: | { |
| 1769: | $expiry = clone $dt; |
| 1770: | $expiry->modify('+' . $this->validity . ' seconds'); |
| 1771: | $tokenNode->appendChild($xmlDoc->createElement(self::TOKEN_EXPIRY_NAME, $expiry->format(self::TOKEN_TIMESTAMP_FORMAT))); |
| 1772: | } |
| 1773: | |
| 1774: | // Create a node "TokenAudience" per audience the token is addressed to |
| 1775: | // (see getAudience()), and append them to the node "Token". The value |
| 1776: | // is added as a text node: the second argument of createElement() |
| 1777: | // would read "&" as the start of an entity reference. |
| 1778: | foreach ((array) $this->audienceToWrite as $audience) |
| 1779: | { |
| 1780: | $audienceElement = $xmlDoc->createElement(self::TOKEN_AUDIENCE_NAME); |
| 1781: | $audienceElement->appendChild($xmlDoc->createTextNode($audience)); |
| 1782: | $tokenNode->appendChild($audienceElement); |
| 1783: | } |
| 1784: | |
| 1785: | /** |
| 1786: | * Inline function to build a node tree, whose root node will be named |
| 1787: | * $nodeName, from the array $data and append it to the given |
| 1788: | * $parentNode node. The values of the leaves are base64 encoded by this |
| 1789: | * function. |
| 1790: | * |
| 1791: | * NOTE: This function is called recursively if $data is a |
| 1792: | * multi-dimensional associative array. |
| 1793: | * |
| 1794: | * @param array $data A flat or multi-dimensional associative array that |
| 1795: | * holds the data to convert in a node tree. |
| 1796: | * |
| 1797: | * @param string $nodeName The name of the node that will hold the node |
| 1798: | * tree. |
| 1799: | * |
| 1800: | * @param DOMNode $parentNode An existing DOM node to which to append |
| 1801: | * the node tree. |
| 1802: | */ |
| 1803: | $dataToNodeTree = function($data, $nodeName, $parentNode) use (&$dataToNodeTree, $base64Encode) |
| 1804: | { |
| 1805: | if(is_array($data)) |
| 1806: | { |
| 1807: | // Appends node. |
| 1808: | $element = $parentNode->ownerDocument->createElement($nodeName); |
| 1809: | $dataNode = $parentNode->appendChild($element); |
| 1810: | |
| 1811: | // Append child nodes/leaves recursively. |
| 1812: | array_walk($data, $dataToNodeTree, $dataNode); |
| 1813: | } |
| 1814: | else |
| 1815: | { |
| 1816: | // Appends leaf. The value is added as a text node, as for the |
| 1817: | // audiences: the second argument of createElement() would read |
| 1818: | // "&" as the start of an entity reference, and alter or lose |
| 1819: | // the value when it is not base64 encoded. |
| 1820: | $element = $parentNode->ownerDocument->createElement($nodeName); |
| 1821: | $element->appendChild($parentNode->ownerDocument->createTextNode($base64Encode ? base64_encode($data) : (string) $data)); |
| 1822: | if ($base64Encode) |
| 1823: | { |
| 1824: | $attribute = $parentNode->ownerDocument->createAttribute('Algorithm'); |
| 1825: | $attribute->value = 'base64'; |
| 1826: | $element->appendChild($attribute); |
| 1827: | } |
| 1828: | $dataNode = $parentNode->appendChild($element); |
| 1829: | } |
| 1830: | }; |
| 1831: | |
| 1832: | // Create a node "TokenData" that holds a node tree representing the |
| 1833: | // token data encoded in base64 and append it to the node "Token". |
| 1834: | $dataToNodeTree($data, self::TOKEN_DATA_NAME, $tokenNode); |
| 1835: | |
| 1836: | // Create an XMLSecurityDSig object. |
| 1837: | // This object will hold the XML Digital Signature we are building. |
| 1838: | $XMLDSig = new XMLSecurityDSig($this->xmldsigNsPrefix); |
| 1839: | $XMLDSig->setCanonicalMethod($this->canonicalizationAlgorithm); |
| 1840: | |
| 1841: | // Add a node "ds:Object" to the XML Digital Signature and attach our |
| 1842: | // node "Token" to it. |
| 1843: | $objectNode = $XMLDSig->addObject($xmlDoc->documentElement); |
| 1844: | $objectNode->setAttribute('Id', self::TOKEN_NAME); |
| 1845: | |
| 1846: | // Encrypt our node "Token" if requested (if an X.509 certificate is |
| 1847: | // provided to perform encryption). |
| 1848: | if (!is_null($this->cryptCert)) |
| 1849: | { |
| 1850: | // Randomly generate a session key for the symmetric algorithm. |
| 1851: | // This key will be used to cipher our node "Token" (the content of |
| 1852: | // the node "ds:Object"). |
| 1853: | $sessionKey = new XMLSecurityKey($this->sessionKeyCipheringAlgorithm); |
| 1854: | $sessionKey->generateSessionKey(); |
| 1855: | |
| 1856: | // Create an asymmetric key from the X.509 certificate using RSA-OAEP |
| 1857: | // algorithm. This key will be used to encrypt the session key. |
| 1858: | $asymKey = new XMLSecurityKey($this->cryptAlgorithm, array('type' => 'public')); |
| 1859: | $asymKey->loadKey($this->cryptCert, false, true); |
| 1860: | if (empty($asymKey->key)) |
| 1861: | { |
| 1862: | // ERROR: Failed loading certificate to encrypt session key! |
| 1863: | throw new Exception("Failed loading certificate to encrypt session key!"); |
| 1864: | } |
| 1865: | |
| 1866: | // Encrypt the session key using the asymmetric key. |
| 1867: | $objXMLSecEnc = new XMLSecEnc(); |
| 1868: | $objXMLSecEnc->encryptKey($asymKey, $sessionKey); |
| 1869: | |
| 1870: | // Encrypt our node "Token", the only child of the node |
| 1871: | // "ds:Object", using the session key: the node "xenc:EncryptedData" |
| 1872: | // replaces it, and declares the type Element (cf. |
| 1873: | // XMLSecEnc::Element), the exact description of what is encrypted. |
| 1874: | // Versions up to 1.1 declared the type Content, the content of the |
| 1875: | // node "ds:Object", for the same bytes; both are read (see |
| 1876: | // _decryptToken()). |
| 1877: | $objXMLSecEnc->setNode($objectNode->firstChild); |
| 1878: | $objXMLSecEnc->type = XMLSecEnc::Element; |
| 1879: | $encryptedObjectNode = $objXMLSecEnc->encryptNode($sessionKey); |
| 1880: | } |
| 1881: | |
| 1882: | // Add a reference to the node "ds:Object" which is contained in the |
| 1883: | // XML Digital Signature itself (case of an enveloping signature). |
| 1884: | // This consists of: |
| 1885: | // - Adding a node "ds:Reference" to the node "ds:SignedInfo". |
| 1886: | // - Computing a hash, using the digest algorithm, from the |
| 1887: | // canonicalized XML string corresponding to the node "ds:Object". |
| 1888: | // - Adding this hash in a child node named "ds:DigestValue". |
| 1889: | // |
| 1890: | // NOTE: Only the first child node of the node "ds:Object" is taken in |
| 1891: | // account to generate the hash which will then be signed. |
| 1892: | $XMLDSig->addReference($objectNode, $this->digestAlgorithm, NULL, array('overwrite' => false, 'force_uri' => true)); |
| 1893: | |
| 1894: | // Create the private key object that will be used to sign the token |
| 1895: | // applying the signature algorithm. If a password is provided, use it |
| 1896: | // to access the private key. |
| 1897: | $privateKey = new XMLSecurityKey($this->signatureAlgorithm, array('type' => 'private')); |
| 1898: | if (!is_null($this->signKeyPassword)) |
| 1899: | { |
| 1900: | $privateKey->passphrase = $this->signKeyPassword; |
| 1901: | } |
| 1902: | |
| 1903: | $privateKey->loadKey($this->signKey, false, false); |
| 1904: | if (empty($privateKey->key)) |
| 1905: | { |
| 1906: | // ERROR: Failed loading private key to sign token data! |
| 1907: | throw new Exception("Failed loading private key to sign token data!"); |
| 1908: | } |
| 1909: | |
| 1910: | // The signature algorithms are RSA ones: OpenSSL would sign with an |
| 1911: | // EC or DSA key all the same, with ECDSA or DSA, in a token declaring |
| 1912: | // an RSA algorithm (see _readXML()). |
| 1913: | $privateKeyDetails = openssl_pkey_get_details($privateKey->key); |
| 1914: | if (!is_array($privateKeyDetails) || OPENSSL_KEYTYPE_RSA !== $privateKeyDetails['type']) |
| 1915: | { |
| 1916: | // ERROR: The signing key is not an RSA key! |
| 1917: | throw new Exception("The signing key is not an RSA key: the signature algorithms are RSA ones!"); |
| 1918: | } |
| 1919: | |
| 1920: | // Add the X.509 certificate associated to the private key to the XML |
| 1921: | // Digital Signature. So, the recipient of the XML token will not need |
| 1922: | // to own it, in order to verify the signature. It will simply get it |
| 1923: | // from the XML token. This consists of adding a node "ds:KeyInfo" that |
| 1924: | // holds the content of the X.509 certificate. |
| 1925: | $XMLDSig->add509Cert($this->signCert); |
| 1926: | |
| 1927: | // Sign the token data using the private security key associated to the |
| 1928: | // X.509 certificate. |
| 1929: | // This consists of: |
| 1930: | // - Computing the signature of the node "ds:SignedInfo". |
| 1931: | // - Adding a node named "ds:SignatureValue" that contains the |
| 1932: | // computed signature. |
| 1933: | $XMLDSig->sign($privateKey); |
| 1934: | |
| 1935: | // Check that the created XML token is well formed (if it's valid and if |
| 1936: | // timestamp and data can be retrieved from it) and, by the way, |
| 1937: | // terminate to initialize the properties of our XMLDSigToken object. |
| 1938: | $this->_readXML($XMLDSig->sigNode->ownerDocument->saveXML(), true); |
| 1939: | } |
| 1940: | |
| 1941: | |
| 1942: | /** |
| 1943: | * Read the XML Digital Signature representing an XML token. |
| 1944: | * |
| 1945: | * This function will check that the provided XML Digital Signature is |
| 1946: | * valid and that its certificate is trusted (see `_verifyCertTrust()`), |
| 1947: | * will decrypt the token data it contains if this one is encrypted |
| 1948: | * and then will extract timestamp and data. |
| 1949: | * |
| 1950: | * The data can then be obtained using the `getData()` function. Nevertheless, |
| 1951: | * you have to ensure that you can trust it using `isSignatureValid()` and |
| 1952: | * `isOutOfDate()`. |
| 1953: | * |
| 1954: | * NOTE: This function is called by the `_writeXML()` function to ensure the |
| 1955: | * XML token it built is correct and because this function sets most of the |
| 1956: | * properties of the XMLDSigToken object that are issued from the analysis |
| 1957: | * of the XML token. A token created encrypted without the private key of |
| 1958: | * the recipient is checked up to its decryption: structure, algorithms, |
| 1959: | * digest, signature and trust in the signing certificate. Its content is |
| 1960: | * not decrypted, and neither its timestamp, its identifier nor its data |
| 1961: | * are read. |
| 1962: | * |
| 1963: | * @param string $xml The XML Digital Signature representing an XML token. |
| 1964: | * |
| 1965: | * @param boolean $isCreation TRUE if the object has just created the |
| 1966: | * token. |
| 1967: | * |
| 1968: | * @throws Exception |
| 1969: | */ |
| 1970: | private function _readXML($xml, $isCreation = false) |
| 1971: | { |
| 1972: | // Store the provided XML Digital Signature. |
| 1973: | $this->xml = $xml; |
| 1974: | |
| 1975: | // Load the enveloping XML Digital Signature into a DOM document, |
| 1976: | // preserving its formatting. A document with a document type |
| 1977: | // declaration is refused before it is parsed (see Xml::load()). |
| 1978: | $xmlDoc = Xml::load($xml, "XML Digital Signature"); |
| 1979: | |
| 1980: | // Instantiate and store a DOMXpath object to navigate through the DOM |
| 1981: | // document that holds the XML Digital Signature. |
| 1982: | $this->xpath = new DOMXPath($xmlDoc); |
| 1983: | $this->xpath->registerNamespace('ds', XMLSecurityDSig::XMLDSIGNS); |
| 1984: | $this->xpath->registerNamespace('xenc', XMLSecEnc::XMLENCNS); |
| 1985: | |
| 1986: | // xmlseclibs computes the digest over the first element of the |
| 1987: | // document whose attribute "Id" is "Token" and, when "ds:Signature" is |
| 1988: | // not the document element, it first detaches "ds:Signature" from the |
| 1989: | // document. A second element "Id=Token", or a "ds:Signature" wrapped |
| 1990: | // in another element, thus lets a copy of the signed "ds:Object", |
| 1991: | // placed where the signature does not cover it, be digested instead of |
| 1992: | // the "ds:Object" the token is read from (signature wrapping). Such |
| 1993: | // documents are rejected. The token is also read only from the node |
| 1994: | // xmlseclibs digested (see below). |
| 1995: | $root = $xmlDoc->documentElement; |
| 1996: | if (XMLSecurityDSig::XMLDSIGNS !== $root->namespaceURI || 'Signature' !== $root->localName) |
| 1997: | { |
| 1998: | // ERROR: XML Digital Signature is malformed! |
| 1999: | throw new Exception("XML digital signature is malformed! The document element must be ds:Signature."); |
| 2000: | } |
| 2001: | if ($this->xpath->query('//@*[local-name()="Id" and .="' . self::TOKEN_NAME . '"]')->length !== 1) |
| 2002: | { |
| 2003: | // ERROR: XML Digital Signature is malformed! |
| 2004: | throw new Exception("XML digital signature is malformed! Exactly one element must have the attribute Id=\"" . self::TOKEN_NAME . "\"."); |
| 2005: | } |
| 2006: | |
| 2007: | // Verify that the XML Digital Signature is well formed. |
| 2008: | $queries = array( |
| 2009: | "//ds:Signature", |
| 2010: | "//ds:Signature/ds:SignedInfo", |
| 2011: | "//ds:Signature/ds:SignedInfo/ds:CanonicalizationMethod", |
| 2012: | "//ds:Signature/ds:SignedInfo/ds:SignatureMethod", |
| 2013: | "//ds:Signature/ds:SignedInfo/ds:Reference", |
| 2014: | "//ds:Signature/ds:SignedInfo/ds:Reference/ds:Transforms", |
| 2015: | "//ds:Signature/ds:SignedInfo/ds:Reference/ds:Transforms/ds:Transform", |
| 2016: | "//ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestMethod", |
| 2017: | "//ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestValue", |
| 2018: | "//ds:Signature/ds:SignatureValue", |
| 2019: | "//ds:Signature/ds:KeyInfo", |
| 2020: | "//ds:Signature/ds:KeyInfo/ds:X509Data", |
| 2021: | "//ds:Signature/ds:KeyInfo/ds:X509Data/ds:X509Certificate", |
| 2022: | "//ds:Signature/ds:Object" |
| 2023: | ); |
| 2024: | |
| 2025: | foreach ($queries as $query) |
| 2026: | { |
| 2027: | if ($this->xpath->query($query)->length !== 1) |
| 2028: | { |
| 2029: | // ERROR: XML Digital Signature is malformed! |
| 2030: | throw new Exception("XML digital signature is malformed!"); |
| 2031: | } |
| 2032: | } |
| 2033: | |
| 2034: | $queries = array( |
| 2035: | // "//ds:Signature/@xmlns" => XMLSecurityDSig::XMLDSIGNS, |
| 2036: | "//ds:Signature/ds:SignedInfo/ds:Reference/@URI" => '#' . self::TOKEN_NAME, |
| 2037: | "//ds:Signature/ds:Object/@Id" => self::TOKEN_NAME |
| 2038: | ); |
| 2039: | |
| 2040: | foreach ($queries as $query => $value) |
| 2041: | { |
| 2042: | if ($this->xpath->evaluate("string(" . $query . ")") !== $value) |
| 2043: | { |
| 2044: | // ERROR: XML digital signature is malformed! |
| 2045: | throw new Exception("XML digital signature is malformed!"); |
| 2046: | } |
| 2047: | } |
| 2048: | |
| 2049: | // Verify the algorithms used to sign the token. |
| 2050: | $queries = array( |
| 2051: | "//ds:Signature/ds:SignedInfo/ds:CanonicalizationMethod/@Algorithm" |
| 2052: | => array( |
| 2053: | 'name' => 'Canonicalization', |
| 2054: | 'validateFunction' => '_isValidCanonicalizationAlgorithm', |
| 2055: | 'expectedValue' => $this->canonicalizationAlgorithm |
| 2056: | ), |
| 2057: | "//ds:Signature/ds:SignedInfo/ds:SignatureMethod/@Algorithm" |
| 2058: | => array( |
| 2059: | 'name' => 'Signature', |
| 2060: | 'validateFunction' => '_isValidSignatureAlgorithm', |
| 2061: | 'expectedValue' => $this->signatureAlgorithm |
| 2062: | ), |
| 2063: | "//ds:Signature/ds:SignedInfo/ds:Reference/ds:Transforms/ds:Transform/@Algorithm" |
| 2064: | => array( |
| 2065: | 'name' => 'Transform', |
| 2066: | 'validateFunction' => '_isValidCanonicalizationAlgorithm', |
| 2067: | 'expectedValue' => $this->transformAlgorithm |
| 2068: | ), |
| 2069: | "//ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestMethod/@Algorithm" |
| 2070: | => array( |
| 2071: | 'name' => 'Digest', |
| 2072: | 'validateFunction' => '_isValidHashAlgorithm', |
| 2073: | 'expectedValue' => $this->digestAlgorithm |
| 2074: | ) |
| 2075: | ); |
| 2076: | |
| 2077: | foreach ($queries as $query => $algorithm) |
| 2078: | { |
| 2079: | $usedAlgorithm = $this->xpath->evaluate("string(" . $query . ")"); |
| 2080: | |
| 2081: | if (empty($usedAlgorithm)) |
| 2082: | { |
| 2083: | // ERROR: Algorithm is missing! |
| 2084: | throw new Exception($algorithm['name'] . " algorithm is missing!"); |
| 2085: | } |
| 2086: | |
| 2087: | if (!call_user_func(self::class . '::' . $algorithm['validateFunction'], $usedAlgorithm)) |
| 2088: | { |
| 2089: | // ERROR: Algorithm is invalid! |
| 2090: | throw new Exception($algorithm['name'] . " algorithm is invalid!"); |
| 2091: | } |
| 2092: | |
| 2093: | if ($usedAlgorithm !== $algorithm['expectedValue'] && $this->checkSigningAlgorithms) |
| 2094: | { |
| 2095: | // ANOMALY: Unauthorized algorithm! |
| 2096: | $this->anomalies[] = "Unauthorized " . $algorithm['name'] . " algorithm! Expected: " . $algorithm['expectedValue'] . ", Used: " . $usedAlgorithm . "."; |
| 2097: | } |
| 2098: | } |
| 2099: | |
| 2100: | // Check whether the token is encrypted or not. |
| 2101: | if ($this->xpath->query("//ds:Signature/ds:Object/xenc:EncryptedData")->length === 1) |
| 2102: | { |
| 2103: | // Verify that the encrypted data is well formed. |
| 2104: | $queries = array( |
| 2105: | "//ds:Signature/ds:Object/xenc:EncryptedData/xenc:EncryptionMethod", |
| 2106: | "//ds:Signature/ds:Object/xenc:EncryptedData/ds:KeyInfo", |
| 2107: | "//ds:Signature/ds:Object/xenc:EncryptedData/ds:KeyInfo/xenc:EncryptedKey", |
| 2108: | "//ds:Signature/ds:Object/xenc:EncryptedData/ds:KeyInfo/xenc:EncryptedKey/xenc:EncryptionMethod", |
| 2109: | "//ds:Signature/ds:Object/xenc:EncryptedData/ds:KeyInfo/xenc:EncryptedKey/xenc:CipherData", |
| 2110: | "//ds:Signature/ds:Object/xenc:EncryptedData/ds:KeyInfo/xenc:EncryptedKey/xenc:CipherData/xenc:CipherValue", |
| 2111: | "//ds:Signature/ds:Object/xenc:EncryptedData/xenc:CipherData", |
| 2112: | "//ds:Signature/ds:Object/xenc:EncryptedData/xenc:CipherData/xenc:CipherValue" |
| 2113: | ); |
| 2114: | |
| 2115: | foreach ($queries as $query) |
| 2116: | { |
| 2117: | if ($this->xpath->query($query)->length !== 1) |
| 2118: | { |
| 2119: | // ERROR: Encrypted data is malformed! |
| 2120: | throw new Exception("Encrypted data is malformed!"); |
| 2121: | } |
| 2122: | } |
| 2123: | |
| 2124: | // The encrypted content is our node "Token": an element, or the |
| 2125: | // content of the node "ds:Object", which XML Encryption 1.1 |
| 2126: | // (section 4.2) describes as the types Element and Content, both |
| 2127: | // of which a decryptor must read. Any other type is refused. |
| 2128: | $queries = array( |
| 2129: | "//ds:Signature/ds:Object/xenc:EncryptedData/@Type" => array(XMLSecEnc::Element, XMLSecEnc::Content) |
| 2130: | ); |
| 2131: | |
| 2132: | foreach ($queries as $query => $values) |
| 2133: | { |
| 2134: | if (!in_array($this->xpath->evaluate("string(" . $query . ")"), $values, true)) |
| 2135: | { |
| 2136: | // ERROR: Encrypted data is malformed! |
| 2137: | throw new Exception("Encrypted data is malformed!"); |
| 2138: | } |
| 2139: | } |
| 2140: | |
| 2141: | // Verify the algorithms used to encrypt the token. |
| 2142: | $queries = array( |
| 2143: | "//ds:Signature/ds:Object/xenc:EncryptedData/xenc:EncryptionMethod/@Algorithm" |
| 2144: | => array( |
| 2145: | 'name' => 'Session Key Ciphering', |
| 2146: | 'validateFunction' => '_isValidSymmetricCipheringAlgorithm', |
| 2147: | 'expectedValue' => $this->sessionKeyCipheringAlgorithm |
| 2148: | ), |
| 2149: | "//ds:Signature/ds:Object/xenc:EncryptedData/ds:KeyInfo/xenc:EncryptedKey/xenc:EncryptionMethod/@Algorithm" |
| 2150: | => array( |
| 2151: | 'name' => 'Crypt', |
| 2152: | 'validateFunction' => '_isValidKeyTransportAlgorithm', |
| 2153: | 'expectedValue' => $this->cryptAlgorithm |
| 2154: | ) |
| 2155: | ); |
| 2156: | |
| 2157: | foreach ($queries as $query => $algorithm) |
| 2158: | { |
| 2159: | $usedAlgorithm = $this->xpath->evaluate("string(" . $query . ")"); |
| 2160: | |
| 2161: | if (empty($usedAlgorithm)) |
| 2162: | { |
| 2163: | // ERROR: Algorithm is missing! |
| 2164: | throw new Exception($algorithm['name'] . " algorithm is missing!"); |
| 2165: | } |
| 2166: | |
| 2167: | if (!call_user_func(self::class . '::' . $algorithm['validateFunction'], $usedAlgorithm)) |
| 2168: | { |
| 2169: | // ERROR: Algorithm is invalid! |
| 2170: | throw new Exception($algorithm['name'] . " algorithm is invalid!"); |
| 2171: | } |
| 2172: | |
| 2173: | if ($usedAlgorithm !== $algorithm['expectedValue'] && $this->checkCryptingAlgorithms) |
| 2174: | { |
| 2175: | // ANOMALY: Unauthorized algorithm! |
| 2176: | $this->anomalies[] = "Unauthorized " . $algorithm['name'] . " algorithm! Expected: " . $algorithm['expectedValue'] . ", Used: " . $usedAlgorithm . "."; |
| 2177: | } |
| 2178: | } |
| 2179: | |
| 2180: | // An algorithm without integrity (CBC) is only accepted when it |
| 2181: | // is the declared one, even if the check of the algorithms is |
| 2182: | // turned off (see _isAuthenticatedCipheringAlgorithm()). |
| 2183: | $usedAlgorithm = $this->xpath->evaluate("string(//ds:Signature/ds:Object/xenc:EncryptedData/xenc:EncryptionMethod/@Algorithm)"); |
| 2184: | if (!self::_isAuthenticatedCipheringAlgorithm($usedAlgorithm) |
| 2185: | && $usedAlgorithm !== $this->sessionKeyCipheringAlgorithm |
| 2186: | && !$this->checkCryptingAlgorithms) |
| 2187: | { |
| 2188: | // ANOMALY: Undeclared unauthenticated algorithm! |
| 2189: | $this->anomalies[] = "Unauthorized Session Key Ciphering algorithm! " . $usedAlgorithm . " has no integrity: declare it with the option 'sessionKeyCipheringAlgorithm' to accept it."; |
| 2190: | } |
| 2191: | } |
| 2192: | |
| 2193: | // Create an XMLSecurityDSig object that rejects empty or failed |
| 2194: | // canonicalizations (see Canonicalization::guardedVerifier()). |
| 2195: | $XMLDSig = Canonicalization::guardedVerifier(); |
| 2196: | |
| 2197: | // Locate the node "ds:Signature". |
| 2198: | $nodeSignature = $XMLDSig->locateSignature($xmlDoc); |
| 2199: | if (is_null($nodeSignature)) |
| 2200: | { |
| 2201: | // ERROR: Cannot locate signature! |
| 2202: | throw new Exception("Cannot locate signature!"); |
| 2203: | } |
| 2204: | |
| 2205: | // The certificate the token carries comes from its sender, and is |
| 2206: | // read before the signature is verified: refuse it, without any PHP |
| 2207: | // message, if it cannot be read. xmlseclibs reads it below without |
| 2208: | // silencing OpenSSL, whose warnings (and, from PHP 8.1, a |
| 2209: | // deprecation) would reach the response or the logs of the receiver. |
| 2210: | // The PEM is rebuilt as XMLSecEnc::staticLocateKeyInfo() does. |
| 2211: | $certNode = $this->xpath->query("/ds:Signature/ds:KeyInfo/ds:X509Data/ds:X509Certificate")->item(0); |
| 2212: | if (!is_null($certNode)) |
| 2213: | { |
| 2214: | $certBase64 = str_replace(array("\r", "\n", " ", "\t"), "", $certNode->textContent); |
| 2215: | $certPem = "-----BEGIN CERTIFICATE-----\n" . chunk_split($certBase64, 64, "\n") . "-----END CERTIFICATE-----\n"; |
| 2216: | if (false === @openssl_x509_read($certPem)) |
| 2217: | { |
| 2218: | // Empty the OpenSSL error queue, which the failure filled. |
| 2219: | while (false !== openssl_error_string()) |
| 2220: | { |
| 2221: | } |
| 2222: | // ERROR: The certificate cannot be read (message of xmlseclibs). |
| 2223: | throw new Exception("Unable to extract public key"); |
| 2224: | } |
| 2225: | } |
| 2226: | |
| 2227: | // Build an XMLSecurityKey object from the X.509 certificate which is |
| 2228: | // included in the XML Digital Signature. |
| 2229: | $objKeyX509 = $XMLDSig->locateKey(); |
| 2230: | if (!$objKeyX509) |
| 2231: | { |
| 2232: | // ERROR: Cannot locate X.509 certificate! |
| 2233: | throw new Exception("Cannot locate X.509 certificate!"); |
| 2234: | } |
| 2235: | |
| 2236: | // Configure the $objKeyX509 XMLSecurityKey object with its related |
| 2237: | // information which should be stored in the node |
| 2238: | // "ds:Signature/ds:KeyInfo". |
| 2239: | if (is_null(XMLSecEnc::staticLocateKeyInfo($objKeyX509, $nodeSignature))) |
| 2240: | { |
| 2241: | // ERROR: Cannot locate key information for X.509 certificate! |
| 2242: | throw new Exception("Cannot locate key information for X.509 certificate!"); |
| 2243: | } |
| 2244: | |
| 2245: | // Create a new X509Cert object for the X.509 certificate found in the |
| 2246: | // XML Digital Signature. |
| 2247: | $this->x509Certificate = new X509Cert($objKeyX509->getX509Certificate()); |
| 2248: | |
| 2249: | // Verify that the hash computed from the node "ds:Signature/ds:Object" |
| 2250: | // is the same as the one stored in the node |
| 2251: | // "ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestValue", and get |
| 2252: | // the node the hash was computed over. The token is read from this |
| 2253: | // node only, never by searching the document: data, timestamp and |
| 2254: | // encrypted content are then those the digest covers. |
| 2255: | $nodeObject = null; |
| 2256: | try |
| 2257: | { |
| 2258: | $XMLDSig->validateReference(); |
| 2259: | |
| 2260: | $validatedNodes = $XMLDSig->getValidatedNodes(); |
| 2261: | if (isset($validatedNodes[self::TOKEN_NAME])) |
| 2262: | { |
| 2263: | $nodeObject = $validatedNodes[self::TOKEN_NAME]; |
| 2264: | } |
| 2265: | if (is_null($nodeObject) || !$nodeObject->isSameNode($this->xpath->query("/ds:Signature/ds:Object")->item(0))) |
| 2266: | { |
| 2267: | throw new Exception("The digested node is not the node ds:Signature/ds:Object!"); |
| 2268: | } |
| 2269: | |
| 2270: | $this->isDigestValueOk = true; |
| 2271: | } |
| 2272: | catch (Exception $e) |
| 2273: | { |
| 2274: | // ANOMALY: Token hash verification failed! |
| 2275: | $nodeObject = null; |
| 2276: | $this->isDigestValueOk = false; |
| 2277: | $this->anomalies[] = "Token hash verification failed!"; |
| 2278: | } |
| 2279: | |
| 2280: | // Canonicalize the node "ds:Signature/ds:SignedInfo". The signature is |
| 2281: | // verified against this canonical form; the verifier throws an |
| 2282: | // exception if it is empty (see Canonicalization::guardedVerifier()). |
| 2283: | $XMLDSig->canonicalizeSignedInfo(); |
| 2284: | |
| 2285: | // Verifies that the signature held in the node |
| 2286: | // "ds:Signature/ds:SignatureValue" is correct for the node |
| 2287: | // "ds:Signature/ds:SignedInfo" using the key we've just built from the |
| 2288: | // X.509 certificate found in the XML Digital Signature. |
| 2289: | // The verification returns the value of openssl_verify(): 1 (valid), |
| 2290: | // 0 (invalid) or -1 (error), which is TRUE in a boolean context: only a |
| 2291: | // strict 1 makes the signature valid. |
| 2292: | // |
| 2293: | // openssl_verify() takes the key of the certificate with the digest of |
| 2294: | // the declared algorithm, whatever the type of the key: with an EC or |
| 2295: | // DSA key, it verifies an ECDSA or DSA signature, and returns 1 for a |
| 2296: | // token signed so under an RSA algorithm (it returns -1 for an RSA |
| 2297: | // signature). The signature algorithms are RSA ones: the key must be |
| 2298: | // an RSA key, or the signature is not verified. |
| 2299: | $signatureVerification = false; |
| 2300: | $publicKey = @openssl_pkey_get_public($this->x509Certificate->getPem()); |
| 2301: | $publicKeyDetails = false === $publicKey ? false : openssl_pkey_get_details($publicKey); |
| 2302: | if (is_array($publicKeyDetails) && OPENSSL_KEYTYPE_RSA === $publicKeyDetails['type']) |
| 2303: | { |
| 2304: | try |
| 2305: | { |
| 2306: | $signatureVerification = $XMLDSig->verify($objKeyX509); |
| 2307: | } |
| 2308: | catch (\Throwable $e) |
| 2309: | { |
| 2310: | $signatureVerification = false; |
| 2311: | } |
| 2312: | } |
| 2313: | |
| 2314: | if (1 === $signatureVerification) |
| 2315: | { |
| 2316: | // Token signature is valid. |
| 2317: | $this->isSignatureValueOk = true; |
| 2318: | } |
| 2319: | else |
| 2320: | { |
| 2321: | // ANOMALY: Token hash signature verification failed! |
| 2322: | $this->isSignatureValueOk = false; |
| 2323: | $this->anomalies[] = "Token hash signature verification failed!"; |
| 2324: | } |
| 2325: | |
| 2326: | // Neither decrypt nor read a token whose hash or hash signature is not |
| 2327: | // valid: its content is not the signed one. |
| 2328: | if (!$this->isDigestValueOk || !$this->isSignatureValueOk) |
| 2329: | { |
| 2330: | $this->_throwAnomalies(); |
| 2331: | } |
| 2332: | |
| 2333: | // The signature has only been verified with the certificate the token |
| 2334: | // carries, which anyone can produce. Neither decrypt nor read a token |
| 2335: | // whose certificate is not trusted. |
| 2336: | $this->_verifyCertTrust(); |
| 2337: | |
| 2338: | // Check if the content of the node "ds:Object" is ciphered. |
| 2339: | $encryptedDataNode = $this->xpath->query("xenc:EncryptedData", $nodeObject)->item(0); |
| 2340: | |
| 2341: | if (is_null($encryptedDataNode)) |
| 2342: | { |
| 2343: | // The node "ds:Object" is not ciphered. |
| 2344: | // Set encryption flag to FALSE. |
| 2345: | $this->isDataEncrypted = false; |
| 2346: | } |
| 2347: | else |
| 2348: | { |
| 2349: | // The node "ds:Object" is ciphered. |
| 2350: | // Set encryption flag to TRUE. |
| 2351: | $this->isDataEncrypted = true; |
| 2352: | |
| 2353: | // Do not decrypt a token encrypted with other algorithms than |
| 2354: | // the expected ones: the decryption itself is what an attacker |
| 2355: | // submitting altered tokens probes (see |
| 2356: | // _isValidKeyTransportAlgorithm() and |
| 2357: | // _isAuthenticatedCipheringAlgorithm()). |
| 2358: | if (!empty($this->anomalies)) |
| 2359: | { |
| 2360: | $this->_throwAnomalies(); |
| 2361: | } |
| 2362: | |
| 2363: | // A token created without the private key of the recipient |
| 2364: | // cannot be decrypted: everything that can be checked without |
| 2365: | // decrypting it has been, and its content is left unread. |
| 2366: | if ($isCreation && is_null($this->cryptKey)) |
| 2367: | { |
| 2368: | return; |
| 2369: | } |
| 2370: | |
| 2371: | // Decrypt it now. |
| 2372: | $this->_decryptToken($encryptedDataNode); |
| 2373: | } |
| 2374: | |
| 2375: | // Verify that the token data is well formed. The token is read from the |
| 2376: | // digested node "ds:Signature/ds:Object" (see above). |
| 2377: | $queries = array( |
| 2378: | self::TOKEN_NAME, |
| 2379: | self::TOKEN_NAME . "/" . self::TOKEN_TIMESTAMP_NAME, |
| 2380: | self::TOKEN_NAME . "/" . self::TOKEN_DATA_NAME, |
| 2381: | ); |
| 2382: | |
| 2383: | foreach ($queries as $query) |
| 2384: | { |
| 2385: | if ($this->xpath->query($query, $nodeObject)->length !== 1) |
| 2386: | { |
| 2387: | // ERROR: Malformed token! The structure of an encrypted |
| 2388: | // token is that of its decrypted content: it fails as the |
| 2389: | // decryption does (see _decryptToken()). |
| 2390: | throw new Exception($this->isDataEncrypted ? self::DECRYPTION_FAILED : "Malformed token!"); |
| 2391: | } |
| 2392: | } |
| 2393: | |
| 2394: | // Get the node "ds:Signature/ds:Object/Token/TokenTimestamp". |
| 2395: | $query = self::TOKEN_NAME . "/" . self::TOKEN_TIMESTAMP_NAME; |
| 2396: | $nodeTokenTimestamp = $this->xpath->query($query, $nodeObject)->item(0); |
| 2397: | |
| 2398: | // Check that token timestamp node is a DOM element that contains solely |
| 2399: | // a text node. |
| 2400: | if (XML_ELEMENT_NODE === $nodeTokenTimestamp->nodeType |
| 2401: | && $nodeTokenTimestamp->hasChildNodes() |
| 2402: | && 1 === $nodeTokenTimestamp->childNodes->length |
| 2403: | && XML_TEXT_NODE === $nodeTokenTimestamp->childNodes->item(0)->nodeType) |
| 2404: | { |
| 2405: | // Compute the UTC UNIX timestamp from the token timestamp string. |
| 2406: | $timezone = new DateTimeZone('UTC'); |
| 2407: | $UTCDate = DateTime::createFromFormat(self::TOKEN_TIMESTAMP_FORMAT, $nodeTokenTimestamp->nodeValue, $timezone); |
| 2408: | if (false !== $UTCDate) |
| 2409: | { |
| 2410: | // Store token timestamp. |
| 2411: | $this->timestamp = $nodeTokenTimestamp->nodeValue; |
| 2412: | } |
| 2413: | else |
| 2414: | { |
| 2415: | // ANOMALY: Token timestamp format is incorrect! |
| 2416: | $this->anomalies[] = "Token timestamp format is invalid!"; |
| 2417: | } |
| 2418: | } |
| 2419: | else |
| 2420: | { |
| 2421: | // ANOMALY: Malformed token timestamp. |
| 2422: | $this->anomalies[] = "Token timestamp is malformed!"; |
| 2423: | } |
| 2424: | |
| 2425: | // Get the node "ds:Signature/ds:Object/Token/TokenId". A token without |
| 2426: | // identifier (as created by the 0.x versions) is rejected: the |
| 2427: | // receiver could not tell it from a replayed one (see getTokenId()). |
| 2428: | $query = self::TOKEN_NAME . "/" . self::TOKEN_ID_NAME; |
| 2429: | $nodeTokenIds = $this->xpath->query($query, $nodeObject); |
| 2430: | if (0 === $nodeTokenIds->length) |
| 2431: | { |
| 2432: | // ANOMALY: Missing token identifier. |
| 2433: | $this->anomalies[] = "Token identifier is missing!"; |
| 2434: | } |
| 2435: | elseif (1 === $nodeTokenIds->length |
| 2436: | && 1 === $nodeTokenIds->item(0)->childNodes->length |
| 2437: | && XML_TEXT_NODE === $nodeTokenIds->item(0)->firstChild->nodeType |
| 2438: | && preg_match('/\A[0-9a-f]{' . (2 * self::TOKEN_ID_BYTES) . '}\z/', $nodeTokenIds->item(0)->nodeValue)) |
| 2439: | { |
| 2440: | // Store token identifier. |
| 2441: | $this->tokenId = $nodeTokenIds->item(0)->nodeValue; |
| 2442: | } |
| 2443: | else |
| 2444: | { |
| 2445: | // ANOMALY: Malformed token identifier. |
| 2446: | $this->anomalies[] = "Token identifier is malformed!"; |
| 2447: | } |
| 2448: | |
| 2449: | // Get the node "ds:Signature/ds:Object/Token/TokenExpiry", if any: a |
| 2450: | // token created without the option "validity" has none. |
| 2451: | $query = self::TOKEN_NAME . "/" . self::TOKEN_EXPIRY_NAME; |
| 2452: | $nodeTokenExpiries = $this->xpath->query($query, $nodeObject); |
| 2453: | $this->hasExpiryNode = 0 < $nodeTokenExpiries->length; |
| 2454: | if ($this->hasExpiryNode) |
| 2455: | { |
| 2456: | $timezone = new DateTimeZone('UTC'); |
| 2457: | $expiryDate = (1 === $nodeTokenExpiries->length && 1 === $nodeTokenExpiries->item(0)->childNodes->length && XML_TEXT_NODE === $nodeTokenExpiries->item(0)->firstChild->nodeType) |
| 2458: | ? DateTime::createFromFormat(self::TOKEN_TIMESTAMP_FORMAT, $nodeTokenExpiries->item(0)->nodeValue, $timezone) |
| 2459: | : false; |
| 2460: | $timestampDate = is_null($this->timestamp) ? false : DateTime::createFromFormat(self::TOKEN_TIMESTAMP_FORMAT, $this->timestamp, $timezone); |
| 2461: | if (false === $expiryDate || $expiryDate->format(self::TOKEN_TIMESTAMP_FORMAT) !== $nodeTokenExpiries->item(0)->nodeValue) |
| 2462: | { |
| 2463: | // ANOMALY: Malformed token expiry. |
| 2464: | $this->anomalies[] = "Token expiry is malformed!"; |
| 2465: | } |
| 2466: | elseif (false !== $timestampDate && $expiryDate <= $timestampDate) |
| 2467: | { |
| 2468: | // ANOMALY: Token expiring before it was issued. |
| 2469: | $this->anomalies[] = "Token expiry is not after its timestamp!"; |
| 2470: | } |
| 2471: | else |
| 2472: | { |
| 2473: | // Store token expiry. |
| 2474: | $this->expiry = $nodeTokenExpiries->item(0)->nodeValue; |
| 2475: | } |
| 2476: | } |
| 2477: | |
| 2478: | // Get the nodes "ds:Signature/ds:Object/Token/TokenAudience", if any, |
| 2479: | // and check them against the expected audience (see |
| 2480: | // _verifyAudience()) before the token data are read. |
| 2481: | $query = self::TOKEN_NAME . "/" . self::TOKEN_AUDIENCE_NAME; |
| 2482: | $nodeTokenAudiences = $this->xpath->query($query, $nodeObject); |
| 2483: | if (0 < $nodeTokenAudiences->length) |
| 2484: | { |
| 2485: | $audiences = []; |
| 2486: | foreach ($nodeTokenAudiences as $nodeTokenAudience) |
| 2487: | { |
| 2488: | if (1 !== $nodeTokenAudience->childNodes->length |
| 2489: | || XML_TEXT_NODE !== $nodeTokenAudience->firstChild->nodeType |
| 2490: | || !self::_isValidAudience($nodeTokenAudience->nodeValue)) |
| 2491: | { |
| 2492: | // ANOMALY: Malformed token audience. The token is |
| 2493: | // rejected before its data are read: a malformed |
| 2494: | // audience is not one the receiver can be sure of. |
| 2495: | $this->anomalies[] = "Token audience is malformed!"; |
| 2496: | $this->_throwAnomalies(); |
| 2497: | } |
| 2498: | $audiences[] = $nodeTokenAudience->nodeValue; |
| 2499: | } |
| 2500: | $this->audience = $audiences; |
| 2501: | } |
| 2502: | |
| 2503: | // A token whose timestamp, identifier or expiry is malformed is |
| 2504: | // rejected here, before its data are read and before its audience is |
| 2505: | // checked, so that the error lists these anomalies. |
| 2506: | if (!empty($this->anomalies)) |
| 2507: | { |
| 2508: | $this->_throwAnomalies(); |
| 2509: | } |
| 2510: | |
| 2511: | $this->_verifyAudience($isCreation); |
| 2512: | |
| 2513: | // Get the node "ds:Signature/ds:Object/Token/TokenData". |
| 2514: | $query = self::TOKEN_NAME . "/" . self::TOKEN_DATA_NAME; |
| 2515: | $nodeTokenData = $this->xpath->query($query, $nodeObject)->item(0); |
| 2516: | |
| 2517: | /** |
| 2518: | * Inline function to build a flat or multi-dimensional associative |
| 2519: | * array from a node tree whose leaf values are base64 encoded. The |
| 2520: | * values of the leaves are base64 decoded by this function. |
| 2521: | * |
| 2522: | * NOTE: This function is called recursively if the node tree is more |
| 2523: | * than one level deep. |
| 2524: | * |
| 2525: | * @param string $rootNode The node that holds the node tree. |
| 2526: | * |
| 2527: | * @param array $data The array to fill up with decoded data. |
| 2528: | */ |
| 2529: | $nodeTreeToData = function($rootNode, &$data) use (&$nodeTreeToData) |
| 2530: | { |
| 2531: | if (!$rootNode->hasChildNodes()) |
| 2532: | { |
| 2533: | // ANOMALY: Empty token data. |
| 2534: | $this->anomalies[] = "Token data is empty!"; |
| 2535: | } |
| 2536: | else |
| 2537: | { |
| 2538: | foreach ($rootNode->childNodes as $node) |
| 2539: | { |
| 2540: | if ((XML_TEXT_NODE === $node->nodeType && 1 !== $node->parentNode->childNodes->length)) |
| 2541: | { |
| 2542: | // ANOMALY: Malformed token data. |
| 2543: | $this->anomalies[] = "Token data is malformed!"; |
| 2544: | } |
| 2545: | if (XML_ELEMENT_NODE === $node->nodeType && $node->hasChildNodes()) |
| 2546: | { |
| 2547: | if (1 === $node->childNodes->length && XML_TEXT_NODE === $node->childNodes->item(0)->nodeType) |
| 2548: | { |
| 2549: | $decode = ("base64" === $node->getAttribute('Algorithm')) ? true : false; |
| 2550: | $data[$node->nodeName] = $decode ? base64_decode($node->childNodes->item(0)->nodeValue) : $node->childNodes->item(0)->nodeValue; |
| 2551: | } |
| 2552: | else |
| 2553: | { |
| 2554: | $data[$node->nodeName] = array(); |
| 2555: | |
| 2556: | // Recursive call. |
| 2557: | $nodeTreeToData($node, $data[$node->nodeName]); |
| 2558: | } |
| 2559: | } |
| 2560: | } |
| 2561: | } |
| 2562: | }; |
| 2563: | |
| 2564: | // Check that token data is well formed and extract data. |
| 2565: | $tokenData = array(); |
| 2566: | $nodeTreeToData($nodeTokenData, $tokenData); |
| 2567: | |
| 2568: | // Store token data. |
| 2569: | $this->data = $tokenData; |
| 2570: | |
| 2571: | // If any anomaly has been detected during analysis, set an error |
| 2572: | // message. |
| 2573: | if (!empty($this->anomalies)) |
| 2574: | { |
| 2575: | $this->_throwAnomalies(); |
| 2576: | } |
| 2577: | } |
| 2578: | |
| 2579: | |
| 2580: | /** |
| 2581: | * Decrypt the content of the node "ds:Object" in place. |
| 2582: | * |
| 2583: | * The failures that do not depend on the token content (no decryption |
| 2584: | * key, a key that cannot be loaded) or only on its structure have their |
| 2585: | * own message. Every failure that depends on the decrypted content |
| 2586: | * (session key, token data, parsing of the decrypted XML) gives the same |
| 2587: | * error, `DECRYPTION_FAILED`, without its reason, and raises no PHP |
| 2588: | * warning: a message or a warning per failure would tell an attacker who |
| 2589: | * can submit altered tokens which step failed, which is how padding |
| 2590: | * oracles (Bleichenbacher on RSA 1.5, Jager-Somorovsky on CBC) decrypt a |
| 2591: | * token step by step. `_readXML()` only calls this function once the |
| 2592: | * digest, the signature, the certificate and the algorithms of the token |
| 2593: | * have been verified. |
| 2594: | * |
| 2595: | * @param DOMElement $encryptedDataNode The node "xenc:EncryptedData", |
| 2596: | * child of the digested node "ds:Signature/ds:Object". |
| 2597: | * |
| 2598: | * @throws Exception |
| 2599: | */ |
| 2600: | private function _decryptToken($encryptedDataNode) |
| 2601: | { |
| 2602: | // Check that we have a private key to perform decryption. |
| 2603: | if (is_null($this->cryptKey)) |
| 2604: | { |
| 2605: | // ERROR: No private key provided for decryption. |
| 2606: | throw new Exception("Token is encrypted but no private key is provided for decryption!"); |
| 2607: | } |
| 2608: | |
| 2609: | // Passes the node containing the ciphered token to an XMLSecEnc |
| 2610: | // object. Its type, Element or Content (checked by _readXML()), is |
| 2611: | // not passed: the plaintext is inserted below the same way for both. |
| 2612: | $objXMLSecEnc = new XMLSecEnc(); |
| 2613: | $objXMLSecEnc->setNode($encryptedDataNode); |
| 2614: | |
| 2615: | // Get an XMLSecurityKey object already configured with the algorithm |
| 2616: | // which was used to encrypt the token data with the session key. |
| 2617: | $objKeyCrypt = $objXMLSecEnc->locateKey(); |
| 2618: | if (is_null($objKeyCrypt)) |
| 2619: | { |
| 2620: | // ERROR: The algorithm cannot be found. |
| 2621: | throw new Exception("Cannot locate session key ciphering algorithm!"); |
| 2622: | } |
| 2623: | |
| 2624: | // Retrieve the encrypted session key. |
| 2625: | $objKeyInfoCrypt = $objXMLSecEnc->locateKeyInfo($objKeyCrypt); |
| 2626: | if (is_null($objKeyInfoCrypt)) |
| 2627: | { |
| 2628: | // ERROR: Session key cannot be found. |
| 2629: | throw new Exception("Cannot locate session key!"); |
| 2630: | } |
| 2631: | if (!$objKeyInfoCrypt->isEncrypted) |
| 2632: | { |
| 2633: | // ERROR: Session key found but it is not encrypted. |
| 2634: | throw new Exception("Session key is not encrypted!"); |
| 2635: | } |
| 2636: | |
| 2637: | // Loads the private key to be used for deciphering the encrypted |
| 2638: | // session key. If a password is provided, use it to access the |
| 2639: | // private key. |
| 2640: | if (!is_null($this->cryptKeyPassword)) |
| 2641: | { |
| 2642: | $objKeyInfoCrypt->passphrase = $this->cryptKeyPassword; |
| 2643: | } |
| 2644: | $objKeyInfoCrypt->loadKey($this->cryptKey, false); |
| 2645: | if (empty($objKeyInfoCrypt->key)) |
| 2646: | { |
| 2647: | // ERROR: Failed loading private key to decrypt session key! |
| 2648: | throw new Exception("Failed loading private key to decrypt session key!"); |
| 2649: | } |
| 2650: | |
| 2651: | // Decipher the session key, then the token data with it, in place. |
| 2652: | // From here on, every failure gives the same error: exceptions are |
| 2653: | // caught, libxml errors are kept internal and PHP warnings are |
| 2654: | // intercepted (see above). |
| 2655: | $failed = false; |
| 2656: | $prevState = libxml_use_internal_errors(true); |
| 2657: | libxml_clear_errors(); |
| 2658: | set_error_handler(function () use (&$failed) { |
| 2659: | $failed = true; |
| 2660: | return true; |
| 2661: | }, E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED); |
| 2662: | try |
| 2663: | { |
| 2664: | $sessionKey = $objKeyInfoCrypt->encryptedCtx->decryptKey($objKeyInfoCrypt); |
| 2665: | $objKeyCrypt->loadKey($sessionKey); |
| 2666: | $plaintext = $objXMLSecEnc->decryptNode($objKeyCrypt, false); |
| 2667: | |
| 2668: | // The plaintext replaces the node "xenc:EncryptedData" as an XML |
| 2669: | // fragment, for the type Element as for the type Content: an |
| 2670: | // element is a valid content. XMLSecEnc would parse an Element |
| 2671: | // plaintext as a whole document instead, which may hold a |
| 2672: | // document type declaration (DOCTYPE) with its entities, refused |
| 2673: | // everywhere else (see Xml::load()); a fragment cannot hold one. |
| 2674: | $fragment = $encryptedDataNode->ownerDocument->createDocumentFragment(); |
| 2675: | if (!is_string($plaintext) || '' === $plaintext || !$fragment->appendXML($plaintext)) |
| 2676: | { |
| 2677: | $failed = true; |
| 2678: | } |
| 2679: | else |
| 2680: | { |
| 2681: | $encryptedDataNode->parentNode->replaceChild($fragment, $encryptedDataNode); |
| 2682: | } |
| 2683: | if (count(libxml_get_errors()) > 0) |
| 2684: | { |
| 2685: | $failed = true; |
| 2686: | } |
| 2687: | } |
| 2688: | catch (\Throwable $e) |
| 2689: | { |
| 2690: | $failed = true; |
| 2691: | } |
| 2692: | finally |
| 2693: | { |
| 2694: | restore_error_handler(); |
| 2695: | libxml_clear_errors(); |
| 2696: | libxml_use_internal_errors($prevState); |
| 2697: | } |
| 2698: | |
| 2699: | if ($failed) |
| 2700: | { |
| 2701: | // ERROR: Token decryption failed. |
| 2702: | throw new Exception(self::DECRYPTION_FAILED); |
| 2703: | } |
| 2704: | } |
| 2705: | |
| 2706: | |
| 2707: | /** |
| 2708: | * Verify that the X.509 certificate included in the XML token is trusted. |
| 2709: | * |
| 2710: | * The signature of the token is verified with the certificate the token |
| 2711: | * carries: any key pair can produce a valid one, with a certificate that |
| 2712: | * copies the names of a legitimate one. The token is only valid if the |
| 2713: | * certificate is also trusted: |
| 2714: | * |
| 2715: | * - A trust anchor is required: CA certificates (option `caCertPath`) |
| 2716: | * and/or a pinned certificate (option `signerCertPath`). Without it, no |
| 2717: | * certificate is trusted. |
| 2718: | * |
| 2719: | * - The certificate must be valid at the current date and its key usage |
| 2720: | * must allow signing (see `X509Cert::canSign()`). |
| 2721: | * |
| 2722: | * - If a certificate is pinned, the certificate must be this very |
| 2723: | * certificate (same fingerprint). |
| 2724: | * |
| 2725: | * - If CA certificates are given, OpenSSL must verify the chain of the |
| 2726: | * certificate up to them (see `X509Cert::isTrustedBy()`). Only the |
| 2727: | * signing certificate is taken from the token: the token cannot supply |
| 2728: | * intermediate certificates. |
| 2729: | * |
| 2730: | * - If a subject is expected (option `expectedSubject`), the subject of |
| 2731: | * the certificate must match it. |
| 2732: | * |
| 2733: | * Sets the flag returned by `isCertTrusted()`. |
| 2734: | * |
| 2735: | * @throws Exception If the certificate is not trusted, with the reason. |
| 2736: | */ |
| 2737: | private function _verifyCertTrust() |
| 2738: | { |
| 2739: | $this->isCertTrusted = false; |
| 2740: | $cert = $this->x509Certificate; |
| 2741: | |
| 2742: | if (is_null($this->trustedCACertPaths) && is_null($this->pinnedSignerCert)) |
| 2743: | { |
| 2744: | throw new Exception("No trust anchor! Pass the option 'caCertPath' (trusted CA certificates) and/or 'signerCertPath' (pinned signing certificate) to analyze a token: without them, no signing certificate can be trusted."); |
| 2745: | } |
| 2746: | |
| 2747: | if ($cert->isOutOfDate()) |
| 2748: | { |
| 2749: | throw new Exception("Signing certificate is not valid at the current date (valid from " . $cert->getValidFrom(self::TOKEN_TIMESTAMP_FORMAT) . " to " . $cert->getValidTo(self::TOKEN_TIMESTAMP_FORMAT) . ")!"); |
| 2750: | } |
| 2751: | |
| 2752: | if (!$cert->canSign()) |
| 2753: | { |
| 2754: | throw new Exception("Signing certificate is not allowed to sign (key usage)!"); |
| 2755: | } |
| 2756: | |
| 2757: | if (!is_null($this->pinnedSignerCert)) |
| 2758: | { |
| 2759: | $pinned = new X509Cert($this->pinnedSignerCert); |
| 2760: | if (!hash_equals($pinned->getFingerprint(), $cert->getFingerprint())) |
| 2761: | { |
| 2762: | throw new Exception("Signing certificate is not the pinned certificate!"); |
| 2763: | } |
| 2764: | } |
| 2765: | |
| 2766: | if (!is_null($this->trustedCACertPaths) && !$cert->isTrustedBy($this->trustedCACertPaths)) |
| 2767: | { |
| 2768: | throw new Exception("Signing certificate is not issued by a trusted CA: its chain could not be verified up to the CA certificates of the option 'caCertPath', which must hold the issuing CA and the certificates up to its root!"); |
| 2769: | } |
| 2770: | |
| 2771: | if (!is_null($this->expectedSubject)) |
| 2772: | { |
| 2773: | $matches = is_string($this->expectedSubject) |
| 2774: | ? $cert->getDN() === $this->expectedSubject |
| 2775: | : X509Cert::matchesName($cert->getSubject(), $this->expectedSubject); |
| 2776: | if (!$matches) |
| 2777: | { |
| 2778: | throw new Exception("Subject of the signing certificate is not the expected one! Subject: " . $cert->getDN() . "."); |
| 2779: | } |
| 2780: | } |
| 2781: | |
| 2782: | $this->isCertTrusted = true; |
| 2783: | } |
| 2784: | |
| 2785: | |
| 2786: | /** |
| 2787: | * Verify that the token is addressed to the expected audience. |
| 2788: | * |
| 2789: | * A token signed by a trusted issuer is valid for every receiver that |
| 2790: | * trusts this issuer: without an audience, a token issued for one |
| 2791: | * receiver is accepted by another. A token may therefore name the |
| 2792: | * receivers it is addressed to (option "audience" of its creation), and |
| 2793: | * the analysis then requires the receiver to say who it is (option |
| 2794: | * "expectedAudience"): |
| 2795: | * |
| 2796: | * - A token that names audiences is rejected unless `expectedAudience` |
| 2797: | * is given and is one of them. Accepting it without this option would |
| 2798: | * let any receiver of the issuer accept a token that is not addressed |
| 2799: | * to it. |
| 2800: | * |
| 2801: | * - A token that names no audience is rejected when `expectedAudience` is |
| 2802: | * given: the receiver asked for a token addressed to it. |
| 2803: | * |
| 2804: | * - A token that names no audience is accepted when `expectedAudience` is |
| 2805: | * not given, as are the tokens of version 1.0, which have none. |
| 2806: | * |
| 2807: | * When the object has just created the token, the audiences read must be |
| 2808: | * those it wrote. |
| 2809: | * |
| 2810: | * @param boolean $isCreation TRUE if the object has just created the |
| 2811: | * token, FALSE if it analyzes a given one. |
| 2812: | * |
| 2813: | * @throws Exception If the token is not addressed to the expected |
| 2814: | * audience, with the reason. |
| 2815: | */ |
| 2816: | private function _verifyAudience($isCreation) |
| 2817: | { |
| 2818: | $audiences = is_null($this->audience) ? [] : $this->audience; |
| 2819: | |
| 2820: | if ($isCreation) |
| 2821: | { |
| 2822: | if ($audiences !== (is_null($this->audienceToWrite) ? [] : $this->audienceToWrite)) |
| 2823: | { |
| 2824: | throw new Exception("Token audience is not the one written!"); |
| 2825: | } |
| 2826: | return; |
| 2827: | } |
| 2828: | |
| 2829: | if (is_null($this->expectedAudience)) |
| 2830: | { |
| 2831: | if (!empty($audiences)) |
| 2832: | { |
| 2833: | throw new Exception("Token is addressed to an audience ('" . implode("', '", $audiences) . "'), but the option 'expectedAudience' is not given: pass the audience of this receiver to accept it!"); |
| 2834: | } |
| 2835: | return; |
| 2836: | } |
| 2837: | |
| 2838: | if (empty($audiences)) |
| 2839: | { |
| 2840: | throw new Exception("Token is not addressed to any audience, but the audience '" . $this->expectedAudience . "' is expected!"); |
| 2841: | } |
| 2842: | |
| 2843: | if (!in_array($this->expectedAudience, $audiences, true)) |
| 2844: | { |
| 2845: | throw new Exception("Token is not addressed to the expected audience! Expected: '" . $this->expectedAudience . "'. Token audience: '" . implode("', '", $audiences) . "'."); |
| 2846: | } |
| 2847: | } |
| 2848: | |
| 2849: | |
| 2850: | /** |
| 2851: | * Throw an exception whose message lists the anomalies detected during |
| 2852: | * the analysis of the XML token. |
| 2853: | * |
| 2854: | * @throws Exception |
| 2855: | */ |
| 2856: | private function _throwAnomalies() |
| 2857: | { |
| 2858: | $nb = count($this->anomalies); |
| 2859: | throw new Exception($nb . ($nb === 1 ? " anomaly" : " anomalies") . " detected: " . implode(" ; ", $this->anomalies)); |
| 2860: | } |
| 2861: | |
| 2862: | |
| 2863: | /** |
| 2864: | * Indicates whether XML token signature is valid or not. |
| 2865: | * |
| 2866: | * This means that: |
| 2867: | * |
| 2868: | * - No error occurred during the analysis of the XML digital signature. |
| 2869: | * |
| 2870: | * - No anomaly detected during the analysis of the XML digital signature. |
| 2871: | * |
| 2872: | * - The token hash has been verified and is valid. |
| 2873: | * |
| 2874: | * - The token hash signature has been verified and is valid. |
| 2875: | * |
| 2876: | * - The X.509 certificate included in the XML token is trusted: it is |
| 2877: | * valid at the current date, it is the pinned certificate and/or its |
| 2878: | * chain has been verified up to the trusted CA certificates, and its |
| 2879: | * subject is the expected one, if any (see `isCertTrusted()`). |
| 2880: | * |
| 2881: | * - The token is addressed to the audience given by the option |
| 2882: | * `expectedAudience`, if it names audiences or if this option is given |
| 2883: | * (see `getAudience()`). |
| 2884: | * |
| 2885: | * Without a trust anchor given to the analysis, it returns FALSE. |
| 2886: | * |
| 2887: | * **It checks neither the freshness of the token nor whether it is |
| 2888: | * replayed.** A token that was valid once stays valid here, however old |
| 2889: | * it is and however many times it is submitted. Before trusting the data |
| 2890: | * of a received token, the caller must check that: |
| 2891: | * |
| 2892: | * - `isSignatureValid()` returns TRUE; |
| 2893: | * |
| 2894: | * - `isOutOfDate($ttl)` returns FALSE, for the time to live the |
| 2895: | * application accepts (it also checks the expiry of the token, if |
| 2896: | * any); |
| 2897: | * |
| 2898: | * - the identifier returned by `getTokenId()` has not been accepted |
| 2899: | * before: store it atomically, and refuse the token if it already is. |
| 2900: | * |
| 2901: | * The trust anchor `caCertPath` accepts any certificate its CA issues: if |
| 2902: | * this CA also issues certificates to others than the expected sender, |
| 2903: | * any of them can sign a token that passes this check. Restrict it then |
| 2904: | * to the sender with the option `expectedSubject`, or pin its certificate |
| 2905: | * with `signerCertPath`. |
| 2906: | * |
| 2907: | * For a token created encrypted without the private key of the |
| 2908: | * recipient, it tells whether the checks made without decrypting the |
| 2909: | * token passed (see `createSecureXMLToken()`). |
| 2910: | * |
| 2911: | * @return boolean TRUE if XML token is valid, FALSE otherwise. |
| 2912: | */ |
| 2913: | public function isSignatureValid() |
| 2914: | { |
| 2915: | return true === $this->isDigestValueOk |
| 2916: | && true === $this->isSignatureValueOk |
| 2917: | && true === $this->isCertTrusted |
| 2918: | && is_null($this->error); |
| 2919: | } |
| 2920: | |
| 2921: | |
| 2922: | /** |
| 2923: | * Indicates whether the X.509 certificate included in the XML token is |
| 2924: | * trusted or not, according to the trust anchor given to the analysis |
| 2925: | * (options `caCertPath`, `signerCertPath` and `expectedSubject`). |
| 2926: | * |
| 2927: | * NOTE: If not evaluated (because an error occurred before), this function |
| 2928: | * returns NULL. When it returns FALSE, `getError()` gives the reason. |
| 2929: | * |
| 2930: | * @return boolean|null TRUE if the certificate is trusted, FALSE |
| 2931: | * otherwise, NULL if cannot be evaluated. |
| 2932: | */ |
| 2933: | public function isCertTrusted() |
| 2934: | { |
| 2935: | return $this->isCertTrusted; |
| 2936: | } |
| 2937: | |
| 2938: | |
| 2939: | /** |
| 2940: | * Indicates whether the XML token is out of date or not. |
| 2941: | * |
| 2942: | * The token is out of date if its timestamp is more than `$ttl` seconds |
| 2943: | * in the past, or more than `DESYNC_TOLERANCE` seconds in the future |
| 2944: | * (clocks of sender and receiver out of sync), or if it has no valid |
| 2945: | * timestamp. A token created with the option `validity` is also out of |
| 2946: | * date once its expiry is passed (see `getExpiry()`): the shorter of the |
| 2947: | * validity set by the issuer and the `$ttl` set by the receiver applies. |
| 2948: | * |
| 2949: | * The expiry is only checked here, with the timestamp: like the time to |
| 2950: | * live, it is a check left to the caller, and `isSignatureValid()` does |
| 2951: | * not make it. `DESYNC_TOLERANCE` does not apply to the expiry: a |
| 2952: | * receiver whose clock is ahead rejects the token a little earlier. |
| 2953: | * Version 1.0 of this class ignores the expiry: a receiver that has not |
| 2954: | * upgraded only applies its own `$ttl`. |
| 2955: | * |
| 2956: | * NOTE: A token that is not out of date can still be a replayed one: see |
| 2957: | * `getTokenId()`. |
| 2958: | * |
| 2959: | * @param int $ttl The time to live (in seconds) allowed for the token. |
| 2960: | * |
| 2961: | * @return boolean TRUE if token is out of date, FALSE otherwise. |
| 2962: | */ |
| 2963: | public function isOutOfDate($ttl = self::TOKEN_DEFAULT_TTL) |
| 2964: | { |
| 2965: | if (is_null($this->timestamp)) |
| 2966: | { |
| 2967: | // Timestamp is missing! So we assume token is expired. |
| 2968: | return true; |
| 2969: | } |
| 2970: | |
| 2971: | // We will compare date using UTC timezone. |
| 2972: | $timezone = new DateTimeZone('UTC'); |
| 2973: | |
| 2974: | // Compute the UTC UNIX timestamp from the token timestamp string. |
| 2975: | $tokenUTCDate = DateTime::createFromFormat(self::TOKEN_TIMESTAMP_FORMAT, $this->timestamp, $timezone); |
| 2976: | if (false === $tokenUTCDate) |
| 2977: | { |
| 2978: | // Token timestamp format is incorrect! So we assume token is |
| 2979: | // expired. |
| 2980: | return true; |
| 2981: | } |
| 2982: | $tokenUTCTimestamp = $tokenUTCDate->getTimestamp(); |
| 2983: | |
| 2984: | // Compute the UTC UNIX timestamp for the current date/time. |
| 2985: | $curUTCDate = new DateTime('now', $timezone); |
| 2986: | $curUTCTimestamp = $curUTCDate->getTimestamp(); |
| 2987: | |
| 2988: | // A token whose expiry is passed is out of date, whatever $ttl. So |
| 2989: | // is a token whose expiry could not be read: it is not valid either |
| 2990: | // (see isSignatureValid()), but a caller that only calls this |
| 2991: | // function must not take it for a token without expiry. |
| 2992: | if ($this->hasExpiryNode && is_null($this->expiry)) |
| 2993: | { |
| 2994: | return true; |
| 2995: | } |
| 2996: | if (!is_null($this->expiry)) |
| 2997: | { |
| 2998: | $tokenUTCExpiry = DateTime::createFromFormat(self::TOKEN_TIMESTAMP_FORMAT, $this->expiry, $timezone); |
| 2999: | if (false === $tokenUTCExpiry || $tokenUTCExpiry->getTimestamp() < $curUTCTimestamp) |
| 3000: | { |
| 3001: | return true; |
| 3002: | } |
| 3003: | } |
| 3004: | |
| 3005: | // Return timestamps comparison result. |
| 3006: | return $tokenUTCTimestamp > ($curUTCTimestamp + self::DESYNC_TOLERANCE) || ($tokenUTCTimestamp + $ttl) < $curUTCTimestamp; |
| 3007: | } |
| 3008: | |
| 3009: | |
| 3010: | /** |
| 3011: | * Indicates whether token data is encrypted or not. |
| 3012: | * |
| 3013: | * For a token created encrypted, it returns TRUE, whether or not the |
| 3014: | * private key of the recipient was given (see `createSecureXMLToken()`). |
| 3015: | * |
| 3016: | * NOTE: If not evaluated (because an error occurred before), this function |
| 3017: | * returns NULL. |
| 3018: | * |
| 3019: | * @return boolean|null TRUE if token data is encrypted, FALSE otherwise, |
| 3020: | * NULL if cannot be evaluated. |
| 3021: | */ |
| 3022: | public function isDataEncrypted() |
| 3023: | { |
| 3024: | return $this->isDataEncrypted; |
| 3025: | } |
| 3026: | |
| 3027: | |
| 3028: | /** |
| 3029: | * Indicates whether the digest of token data (a hash) has been verified and |
| 3030: | * is valid or not. |
| 3031: | * |
| 3032: | * NOTE: If not evaluated (because an error occurred before), this function |
| 3033: | * returns NULL. |
| 3034: | * |
| 3035: | * @return boolean|null TRUE if token hash has been verified and is valid, |
| 3036: | * FALSE otherwise, NULL if cannot be evaluated. |
| 3037: | */ |
| 3038: | public function isDigestValueOk() |
| 3039: | { |
| 3040: | return $this->isDigestValueOk; |
| 3041: | } |
| 3042: | |
| 3043: | |
| 3044: | /** |
| 3045: | * Indicates whether signature of the digest of the token data has been |
| 3046: | * verified and is valid or not. |
| 3047: | * |
| 3048: | * NOTE: If not evaluated (because an error occurred before), this function |
| 3049: | * returns NULL. |
| 3050: | * |
| 3051: | * @return boolean|null TRUE if token hash signature has been verified and |
| 3052: | * is valid, FALSE otherwise, NULL if cannot be evaluated. |
| 3053: | */ |
| 3054: | public function isSignatureValueOk() |
| 3055: | { |
| 3056: | return $this->isSignatureValueOk; |
| 3057: | } |
| 3058: | |
| 3059: | |
| 3060: | /** |
| 3061: | * Get the XML token. |
| 3062: | * |
| 3063: | * @return string|null The XML token, NULL if not available. |
| 3064: | */ |
| 3065: | public function getXML() |
| 3066: | { |
| 3067: | return $this->xml; |
| 3068: | } |
| 3069: | |
| 3070: | |
| 3071: | /** |
| 3072: | * Get the user data contained in the XML token. |
| 3073: | * |
| 3074: | * The data can only be trusted if `isSignatureValid()` returns TRUE (and |
| 3075: | * the token is neither out of date nor replayed). They are only read |
| 3076: | * once the digest, the signature and the signing certificate have been |
| 3077: | * verified. |
| 3078: | * |
| 3079: | * A token created encrypted without the private key of the recipient is |
| 3080: | * not decrypted: its data are not available (see |
| 3081: | * `createSecureXMLToken()`). |
| 3082: | * |
| 3083: | * @return array|null The associative array containing token data, NULL if |
| 3084: | * not available. |
| 3085: | */ |
| 3086: | public function getData() |
| 3087: | { |
| 3088: | return $this->data; |
| 3089: | } |
| 3090: | |
| 3091: | |
| 3092: | /** |
| 3093: | * Get the timestamp of the XML token. |
| 3094: | * |
| 3095: | * The timestamp of a token that is not valid is not given: nothing read |
| 3096: | * from such a token can be trusted. `isOutOfDate()` still reads it, and |
| 3097: | * rejects such a token anyway when its timestamp could not be read. |
| 3098: | * |
| 3099: | * @return string|null The token timestamp, NULL if the token is not |
| 3100: | * valid (see `isSignatureValid()`), or if it was created encrypted |
| 3101: | * without the private key of the recipient, which leaves its content |
| 3102: | * unread (see `createSecureXMLToken()`). |
| 3103: | */ |
| 3104: | public function getTimestamp() |
| 3105: | { |
| 3106: | return $this->isSignatureValid() ? $this->timestamp : null; |
| 3107: | } |
| 3108: | |
| 3109: | |
| 3110: | /** |
| 3111: | * Get the identifier of the XML token. |
| 3112: | * |
| 3113: | * Each token created by this class holds a random identifier of 128 bits |
| 3114: | * (32 hexadecimal characters), generated with `random_bytes()` and |
| 3115: | * covered by the signature. A valid token can be submitted again for as |
| 3116: | * long as `isOutOfDate()` accepts it: the class keeps no list of the |
| 3117: | * tokens it has analyzed, so the caller must refuse a token whose |
| 3118: | * identifier it has already accepted. A token is accepted from |
| 3119: | * `DESYNC_TOLERANCE` seconds before its timestamp to `$ttl` seconds after |
| 3120: | * it (see `isOutOfDate()`): keep each accepted identifier for at least |
| 3121: | * `$ttl + XMLDSigToken::DESYNC_TOLERANCE` seconds after accepting it. |
| 3122: | * |
| 3123: | * A token without identifier (as created by the 0.x versions) is not |
| 3124: | * valid. |
| 3125: | * |
| 3126: | * @return string|null The token identifier, NULL if the token is not |
| 3127: | * valid (see `isSignatureValid()`), or if it was created encrypted |
| 3128: | * without the private key of the recipient, which leaves its content |
| 3129: | * unread (see `createSecureXMLToken()`). |
| 3130: | */ |
| 3131: | public function getTokenId() |
| 3132: | { |
| 3133: | return $this->isSignatureValid() ? $this->tokenId : null; |
| 3134: | } |
| 3135: | |
| 3136: | |
| 3137: | /** |
| 3138: | * Get the audiences the XML token is addressed to. |
| 3139: | * |
| 3140: | * A token created with the option `audience` names the receivers it is |
| 3141: | * addressed to, and `isSignatureValid()` only accepts it if the analysis |
| 3142: | * gives one of them with the option `expectedAudience` (see |
| 3143: | * `__construct()`). |
| 3144: | * |
| 3145: | * @return array|null The list of the audiences of the token, NULL if the |
| 3146: | * token is not valid (see `isSignatureValid()`), if it names no |
| 3147: | * audience, or if it was created encrypted without the private key of |
| 3148: | * the recipient, which leaves its content unread (see |
| 3149: | * `createSecureXMLToken()`). |
| 3150: | */ |
| 3151: | public function getAudience() |
| 3152: | { |
| 3153: | return $this->isSignatureValid() ? $this->audience : null; |
| 3154: | } |
| 3155: | |
| 3156: | |
| 3157: | /** |
| 3158: | * Get the expiry of the XML token. |
| 3159: | * |
| 3160: | * A token created with the option `validity` holds the date after which |
| 3161: | * it is out of date (see `isOutOfDate()`), in the format of the timestamp |
| 3162: | * (`TOKEN_TIMESTAMP_FORMAT`, UTC). |
| 3163: | * |
| 3164: | * @return string|null The token expiry, NULL if the token is not valid |
| 3165: | * (see `isSignatureValid()`), if it has no expiry, or if it was |
| 3166: | * created encrypted without the private key of the recipient, which |
| 3167: | * leaves its content unread (see `createSecureXMLToken()`). |
| 3168: | */ |
| 3169: | public function getExpiry() |
| 3170: | { |
| 3171: | return $this->isSignatureValid() ? $this->expiry : null; |
| 3172: | } |
| 3173: | |
| 3174: | |
| 3175: | /** |
| 3176: | * Get the message of the error that occurred while parsing the XML token. |
| 3177: | * |
| 3178: | * @return string|null The error message. If no error, NULL is returned. |
| 3179: | */ |
| 3180: | public function getError() |
| 3181: | { |
| 3182: | return $this->error; |
| 3183: | } |
| 3184: | |
| 3185: | |
| 3186: | /** |
| 3187: | * Get the list of anomalies that occurred while parsing the XML token. |
| 3188: | * |
| 3189: | * @return array The list of anomalies, empty if none. |
| 3190: | */ |
| 3191: | public function getAnomalies() |
| 3192: | { |
| 3193: | return $this->anomalies; |
| 3194: | } |
| 3195: | |
| 3196: | |
| 3197: | /** |
| 3198: | * Get the X.509 certificate that is included in the XML token (PEM format). |
| 3199: | * |
| 3200: | * @return string|null The content of the X.509 certificate, NULL if not |
| 3201: | * available. |
| 3202: | */ |
| 3203: | public function getCertificate() |
| 3204: | { |
| 3205: | if (is_null($this->x509Certificate)) |
| 3206: | { |
| 3207: | return null; |
| 3208: | } |
| 3209: | |
| 3210: | return $this->x509Certificate->getPem(); |
| 3211: | } |
| 3212: | |
| 3213: | |
| 3214: | /** |
| 3215: | * Get the issuer information of the X.509 certificate that is included in |
| 3216: | * the XML token. |
| 3217: | * |
| 3218: | * @return array|null The issuer information of the X.509 certificate, NULL |
| 3219: | * if not available. |
| 3220: | */ |
| 3221: | public function getCertIssuer() |
| 3222: | { |
| 3223: | if (is_null($this->x509Certificate)) |
| 3224: | { |
| 3225: | return null; |
| 3226: | } |
| 3227: | |
| 3228: | return $this->x509Certificate->getIssuer(); |
| 3229: | } |
| 3230: | |
| 3231: | |
| 3232: | /** |
| 3233: | * Get the subject information of the X.509 certificate that is included in |
| 3234: | * the XML token. |
| 3235: | * |
| 3236: | * @return array|null The subject information of the X.509 certificate, NULL |
| 3237: | * if not available. |
| 3238: | */ |
| 3239: | public function getCertSubject() |
| 3240: | { |
| 3241: | if (is_null($this->x509Certificate)) |
| 3242: | { |
| 3243: | return null; |
| 3244: | } |
| 3245: | |
| 3246: | return $this->x509Certificate->getSubject(); |
| 3247: | } |
| 3248: | |
| 3249: | |
| 3250: | /** |
| 3251: | * Get the Distinguished Name of the X.509 certificate that is included in |
| 3252: | * the XML token. |
| 3253: | * |
| 3254: | * @return string|null The Distinguished Name of the X.509 certificate, NULL |
| 3255: | * if not available. |
| 3256: | */ |
| 3257: | public function getCertDN() |
| 3258: | { |
| 3259: | if (is_null($this->x509Certificate)) |
| 3260: | { |
| 3261: | return null; |
| 3262: | } |
| 3263: | |
| 3264: | return $this->x509Certificate->getDN(); |
| 3265: | } |
| 3266: | |
| 3267: | |
| 3268: | /** |
| 3269: | * Get the UTC date from which the X.509 certificate that is included in the |
| 3270: | * XML token is valid. |
| 3271: | * |
| 3272: | * @param string $dateFormat The format of the returned date (Default: |
| 3273: | * XMLDSigToken::TOKEN_TIMESTAMP_FORMAT). |
| 3274: | * |
| 3275: | * @return string|null|false The date from which the X.509 certificate is |
| 3276: | * valid, NULL if not available, FALSE if $dateFormat is invalid. |
| 3277: | */ |
| 3278: | public function getCertValidFrom($dateFormat = self::TOKEN_TIMESTAMP_FORMAT) |
| 3279: | { |
| 3280: | if (is_null($this->x509Certificate)) |
| 3281: | { |
| 3282: | return null; |
| 3283: | } |
| 3284: | |
| 3285: | return $this->x509Certificate->getValidFrom($dateFormat); |
| 3286: | } |
| 3287: | |
| 3288: | |
| 3289: | /** |
| 3290: | * Get the UTC date to which the X.509 certificate that is included in the |
| 3291: | * XML token is valid. |
| 3292: | * |
| 3293: | * @param string $dateFormat The format of the returned date (Default: |
| 3294: | * XMLDSigToken::TOKEN_TIMESTAMP_FORMAT). |
| 3295: | * |
| 3296: | * @return string|null|false The date to which the X.509 certificate is |
| 3297: | * valid, NULL if |
| 3298: | * not available, FALSE if $dateFormat is invalid. |
| 3299: | */ |
| 3300: | public function getCertValidTo($dateFormat = self::TOKEN_TIMESTAMP_FORMAT) |
| 3301: | { |
| 3302: | if (is_null($this->x509Certificate)) |
| 3303: | { |
| 3304: | return null; |
| 3305: | } |
| 3306: | |
| 3307: | return $this->x509Certificate->getValidTo($dateFormat); |
| 3308: | } |
| 3309: | |
| 3310: | |
| 3311: | /** |
| 3312: | * Indicates whether the X.509 certificate included in the XML token is out |
| 3313: | * of date or not. |
| 3314: | * |
| 3315: | * @return boolean TRUE if X.509 certificate is out of date, FALSE |
| 3316: | * otherwise. |
| 3317: | */ |
| 3318: | public function isCertOutOfDate() |
| 3319: | { |
| 3320: | if (is_null($this->x509Certificate)) |
| 3321: | { |
| 3322: | return true; |
| 3323: | } |
| 3324: | |
| 3325: | return $this->x509Certificate->isOutOfDate(); |
| 3326: | } |
| 3327: | |
| 3328: | |
| 3329: | /** |
| 3330: | * Check that the issuer information of the X.509 certificate that is |
| 3331: | * included in the XML token matches the expected one. |
| 3332: | * |
| 3333: | * The expected issuer information must be passed as an array to the |
| 3334: | * function: |
| 3335: | * |
| 3336: | * ```php |
| 3337: | * $ExpectedIssuerInfo = [ |
| 3338: | * 'C' => 'DK', |
| 3339: | * 'ST' => 'Jylland', |
| 3340: | * 'O' => 'Lothbrok Ltd', |
| 3341: | * 'OU' => 'Jarl Dept', |
| 3342: | * 'CN' => 'www.Lothbrok.dk', |
| 3343: | * 'emailAddress' => 'ragnar@Lothbrok.dk' |
| 3344: | * ]; |
| 3345: | * ``` |
| 3346: | * |
| 3347: | * NOTE: Character case of data is significant. |
| 3348: | * |
| 3349: | * NOTE: This only compares names, which any certificate can copy: it |
| 3350: | * tells nothing about who issued the certificate. `isSignatureValid()` |
| 3351: | * verifies the certificate against the trust anchor of the analysis. |
| 3352: | * |
| 3353: | * @param array $expectedIssuerInfo The issuer information that the X.509 |
| 3354: | * certificate should match. |
| 3355: | * |
| 3356: | * @return boolean TRUE if the issuer of the X.509 certificate holds the |
| 3357: | * expected information, FALSE otherwise. |
| 3358: | * |
| 3359: | * @throws Exception |
| 3360: | */ |
| 3361: | public function isValidCertIssuer($expectedIssuerInfo) |
| 3362: | { |
| 3363: | // Check if the expected issuer information is an array. |
| 3364: | if (!is_array($expectedIssuerInfo)) |
| 3365: | { |
| 3366: | throw new Exception("Invalid parameter 'issuerInfo'! Issuer information should be an array."); |
| 3367: | } |
| 3368: | |
| 3369: | // Verify that the information of the X.509 certificate matches the |
| 3370: | // expected one. |
| 3371: | $certIssuerInfo = $this->getCertIssuer(); |
| 3372: | if (is_null($certIssuerInfo)) |
| 3373: | { |
| 3374: | return false; |
| 3375: | } |
| 3376: | |
| 3377: | return X509Cert::matchesName($certIssuerInfo, $expectedIssuerInfo); |
| 3378: | } |
| 3379: | |
| 3380: | |
| 3381: | /** |
| 3382: | * Check that the X.509 certificate included in the XML token comes from the |
| 3383: | * expected CA. |
| 3384: | * |
| 3385: | * Note that more than one CA certificate can give a positive result, some |
| 3386: | * CAs re-issue signing certificates after having only changed the |
| 3387: | * expiration dates. |
| 3388: | * |
| 3389: | * Note that it also works with self-signed certificates. In this case, |
| 3390: | * pass the X.509 certificate that is supposed to be included in the XML |
| 3391: | * token to the function. |
| 3392: | * |
| 3393: | * Only the link between the certificate and the given CA certificate is |
| 3394: | * checked (see `X509Cert::isValidCA()`). `isSignatureValid()` verifies the |
| 3395: | * whole chain against the trust anchor of the analysis. |
| 3396: | * |
| 3397: | * @param string $caCertPath The PEM certificate (public key) that is |
| 3398: | * supposed to be used by the CA to sign the X.509 certificate included in |
| 3399: | * the XML token. |
| 3400: | * |
| 3401: | * @return boolean TRUE if the X.509 certificate has been signed by the |
| 3402: | * expected CA, FALSE otherwise (and when no certificate has been read |
| 3403: | * from the token). |
| 3404: | * |
| 3405: | * @throws Exception |
| 3406: | */ |
| 3407: | public function isValidCertCA($caCertPath) |
| 3408: | { |
| 3409: | if (is_null($this->x509Certificate)) |
| 3410: | { |
| 3411: | return false; |
| 3412: | } |
| 3413: | |
| 3414: | // Get the CA public key that is supposed to be used to sign the X.509 |
| 3415: | // certificate. |
| 3416: | $caCert = @file_get_contents($caCertPath); |
| 3417: | if (false === $caCert) |
| 3418: | { |
| 3419: | throw new Exception("Cannot read CA certificate to perform signer check! File: " . $caCertPath); |
| 3420: | } |
| 3421: | |
| 3422: | return $this->x509Certificate->isValidCA($caCert); |
| 3423: | } |
| 3424: | |
| 3425: | |
| 3426: | /** |
| 3427: | * Check if an algorithm is valid to perform XML canonicalization |
| 3428: | * operations. |
| 3429: | * |
| 3430: | * @param string $algorithm The algorithm reference (URL). |
| 3431: | * |
| 3432: | * @return boolean TRUE if valid, FALSE otherwise. |
| 3433: | */ |
| 3434: | static private function _isValidCanonicalizationAlgorithm($algorithm) |
| 3435: | { |
| 3436: | // switch compares loosely: TRUE would match any algorithm. |
| 3437: | if (!is_string($algorithm)) |
| 3438: | { |
| 3439: | return(false); |
| 3440: | } |
| 3441: | |
| 3442: | switch ($algorithm) |
| 3443: | { |
| 3444: | case (self::C14N): |
| 3445: | case (self::C14N_COMMENTS): |
| 3446: | case (self::EXC_C14N): |
| 3447: | case (self::EXC_C14N_COMMENTS): |
| 3448: | return(true); |
| 3449: | default: |
| 3450: | return(false); |
| 3451: | } |
| 3452: | } |
| 3453: | |
| 3454: | |
| 3455: | /** |
| 3456: | * Check if an algorithm is valid to perform hash operations. |
| 3457: | * |
| 3458: | * @param string $algorithm The algorithm reference (URL). |
| 3459: | * |
| 3460: | * @return boolean TRUE if valid, FALSE otherwise. |
| 3461: | */ |
| 3462: | static private function _isValidHashAlgorithm($algorithm) |
| 3463: | { |
| 3464: | // switch compares loosely: TRUE would match any algorithm. |
| 3465: | if (!is_string($algorithm)) |
| 3466: | { |
| 3467: | return(false); |
| 3468: | } |
| 3469: | |
| 3470: | switch ($algorithm) |
| 3471: | { |
| 3472: | case (self::SHA1): |
| 3473: | case (self::SHA256): |
| 3474: | case (self::SHA384): |
| 3475: | case (self::SHA512): |
| 3476: | case (self::RIPEMD160): |
| 3477: | return(true); |
| 3478: | default: |
| 3479: | return(false); |
| 3480: | } |
| 3481: | } |
| 3482: | |
| 3483: | |
| 3484: | /** |
| 3485: | * Check if an algorithm is valid to sign the node "ds:SignedInfo". |
| 3486: | * |
| 3487: | * Signature and key transport algorithms (see |
| 3488: | * `_isValidKeyTransportAlgorithm()`) are both asymmetric, but each list |
| 3489: | * only holds its own: a key transport algorithm is not a signature |
| 3490: | * algorithm, and the reverse. |
| 3491: | * |
| 3492: | * @param string $algorithm The algorithm reference (URL). |
| 3493: | * |
| 3494: | * @return boolean TRUE if valid, FALSE otherwise. |
| 3495: | */ |
| 3496: | static private function _isValidSignatureAlgorithm($algorithm) |
| 3497: | { |
| 3498: | // switch compares loosely: TRUE would match any algorithm. |
| 3499: | if (!is_string($algorithm)) |
| 3500: | { |
| 3501: | return(false); |
| 3502: | } |
| 3503: | |
| 3504: | switch ($algorithm) |
| 3505: | { |
| 3506: | // case (self::DSA_SHA1): // Does not work. |
| 3507: | case (self::RSA_SHA1): |
| 3508: | case (self::RSA_SHA256): |
| 3509: | case (self::RSA_SHA384): |
| 3510: | case (self::RSA_SHA512): |
| 3511: | // case (self::HMAC_SHA1): // Does not work. |
| 3512: | return(true); |
| 3513: | default: |
| 3514: | return(false); |
| 3515: | } |
| 3516: | } |
| 3517: | |
| 3518: | |
| 3519: | /** |
| 3520: | * Check if an algorithm is valid to encrypt the session key that encrypts |
| 3521: | * the token (key transport). |
| 3522: | * |
| 3523: | * RSA 1.5 (PKCS #1 v1.5 padding) is not valid, neither to create nor to |
| 3524: | * analyze a token: whether the padding of a submitted session key is |
| 3525: | * valid can be told from the decryption (Bleichenbacher), which lets an |
| 3526: | * attacker who can submit altered tokens decrypt a session key. |
| 3527: | * |
| 3528: | * @param string $algorithm The algorithm reference (URL). |
| 3529: | * |
| 3530: | * @return boolean TRUE if valid, FALSE otherwise. |
| 3531: | * |
| 3532: | * @see _isValidSignatureAlgorithm() |
| 3533: | */ |
| 3534: | static private function _isValidKeyTransportAlgorithm($algorithm) |
| 3535: | { |
| 3536: | // switch compares loosely: TRUE would match any algorithm. |
| 3537: | if (!is_string($algorithm)) |
| 3538: | { |
| 3539: | return(false); |
| 3540: | } |
| 3541: | |
| 3542: | switch ($algorithm) |
| 3543: | { |
| 3544: | case (self::RSA_OAEP_MGF1P): |
| 3545: | return(true); |
| 3546: | default: |
| 3547: | return(false); |
| 3548: | } |
| 3549: | } |
| 3550: | |
| 3551: | |
| 3552: | /** |
| 3553: | * Check if an algorithm is valid to perform symmetric ciphering operations. |
| 3554: | * |
| 3555: | * @param string $algorithm The algorithm reference (URL). |
| 3556: | * |
| 3557: | * @return boolean TRUE if valid, FALSE otherwise. |
| 3558: | */ |
| 3559: | static private function _isValidSymmetricCipheringAlgorithm($algorithm) |
| 3560: | { |
| 3561: | // switch compares loosely: TRUE would match any algorithm. |
| 3562: | if (!is_string($algorithm)) |
| 3563: | { |
| 3564: | return(false); |
| 3565: | } |
| 3566: | |
| 3567: | switch ($algorithm) |
| 3568: | { |
| 3569: | case (self::TRIPLEDES_CBC): |
| 3570: | case (self::AES128_CBC): |
| 3571: | case (self::AES192_CBC): |
| 3572: | case (self::AES256_CBC): |
| 3573: | case (self::AES128_GCM): |
| 3574: | case (self::AES192_GCM): |
| 3575: | case (self::AES256_GCM): |
| 3576: | return(true); |
| 3577: | default: |
| 3578: | return(false); |
| 3579: | } |
| 3580: | } |
| 3581: | |
| 3582: | |
| 3583: | /** |
| 3584: | * Check if a symmetric algorithm authenticates the data it decrypts. |
| 3585: | * |
| 3586: | * AES-GCM checks an authentication tag before returning any decrypted |
| 3587: | * data: altered data fails as a whole. CBC has no integrity: altered |
| 3588: | * data is decrypted all the same, and how the decrypted content then |
| 3589: | * fails (padding, XML parsing) can tell an attacker who can submit |
| 3590: | * altered tokens what it holds (Jager-Somorovsky). A token encrypted |
| 3591: | * with CBC is therefore only decrypted if the analysis declares this |
| 3592: | * algorithm (option `sessionKeyCipheringAlgorithm`), whatever |
| 3593: | * `checkCryptingAlgorithms`. |
| 3594: | * |
| 3595: | * @param string $algorithm The algorithm reference (URL). |
| 3596: | * |
| 3597: | * @return boolean TRUE if the algorithm is authenticated, FALSE otherwise. |
| 3598: | */ |
| 3599: | static private function _isAuthenticatedCipheringAlgorithm($algorithm) |
| 3600: | { |
| 3601: | return in_array($algorithm, [self::AES128_GCM, self::AES192_GCM, self::AES256_GCM], true); |
| 3602: | } |
| 3603: | |
| 3604: | |
| 3605: | /** |
| 3606: | * Utility function for modifying a node of an XML content. |
| 3607: | * |
| 3608: | * The XML content is loaded as an XML token is: a document with a |
| 3609: | * document type declaration (DOCTYPE), or not encoded in UTF-8, is |
| 3610: | * refused before it is parsed, and the parser never accesses the network |
| 3611: | * (see `Xml::load()`). A refused or invalid document is left unchanged and |
| 3612: | * the function returns FALSE. |
| 3613: | * |
| 3614: | * @param string $xml XML content, passed by reference. |
| 3615: | * |
| 3616: | * @param string $nodePath The xpath query to select the node to modify. |
| 3617: | * This should be a full path that identifies a single node. |
| 3618: | * |
| 3619: | * @param string $nodeAttribute In case you want to modify an attribute of |
| 3620: | * the specified node, provide its name here, otherwise set this |
| 3621: | * parameter to NULL. |
| 3622: | * |
| 3623: | * @param string $newValue The value that will replace the original value of |
| 3624: | * the node or of the attribute of the node if $nodeAttribute parameter |
| 3625: | * is provided. |
| 3626: | * |
| 3627: | * @param boolean $delete If TRUE delete the specified node or attribute. |
| 3628: | * |
| 3629: | * @return string|false The value of the node or attribute before |
| 3630: | * modification or deletion, FALSE otherwise. |
| 3631: | */ |
| 3632: | static public function alterXML(&$xml, $nodePath, $nodeAttribute, $newValue, $delete = false) |
| 3633: | { |
| 3634: | // Assume modification will fail. |
| 3635: | $oldValue = false; |
| 3636: | |
| 3637: | // Load the XML content into a DOM document. |
| 3638: | try |
| 3639: | { |
| 3640: | $xmlDoc = Xml::load($xml, "XML content"); |
| 3641: | } |
| 3642: | catch (Exception $e) |
| 3643: | { |
| 3644: | return false; |
| 3645: | } |
| 3646: | $xmlDoc->formatOutput = false; |
| 3647: | |
| 3648: | // Instantiate a DOMXpath object to navigate in the XML document. |
| 3649: | $xpath = new DOMXPath($xmlDoc); |
| 3650: | $xpath->registerNamespace('ds', XMLSecurityDSig::XMLDSIGNS); |
| 3651: | $xpath->registerNamespace('xenc', XMLSecEnc::XMLENCNS); |
| 3652: | |
| 3653: | // Locate the node. |
| 3654: | $nodeList = $xpath->query($nodePath); |
| 3655: | if (1 <= $nodeList->length) |
| 3656: | { |
| 3657: | // Node found. |
| 3658: | $node = $nodeList->item(0); |
| 3659: | |
| 3660: | if (is_null($nodeAttribute)) |
| 3661: | { |
| 3662: | if ($delete) |
| 3663: | { |
| 3664: | // Delete the node. |
| 3665: | $oldValue = $node->nodeValue; |
| 3666: | $node->parentNode->removeChild($node); |
| 3667: | } |
| 3668: | else |
| 3669: | { |
| 3670: | // Replace node value with the given one. |
| 3671: | $oldValue = $node->nodeValue; |
| 3672: | $node->nodeValue = $newValue; |
| 3673: | } |
| 3674: | } |
| 3675: | else |
| 3676: | { |
| 3677: | if ($node->hasAttribute($nodeAttribute)) |
| 3678: | { |
| 3679: | if ($delete) |
| 3680: | { |
| 3681: | // Delete attribute. |
| 3682: | $oldValue = $node->getAttribute($nodeAttribute); |
| 3683: | $node->removeAttribute($nodeAttribute); |
| 3684: | } |
| 3685: | else |
| 3686: | { |
| 3687: | // Replace attribute value with the given one. |
| 3688: | $oldValue = $node->getAttribute($nodeAttribute); |
| 3689: | $node->removeAttribute($nodeAttribute); |
| 3690: | $node->setAttribute($nodeAttribute, $newValue); |
| 3691: | } |
| 3692: | } |
| 3693: | } |
| 3694: | } |
| 3695: | |
| 3696: | // Update the XML content with its modified version. |
| 3697: | if ($oldValue) |
| 3698: | { |
| 3699: | $xml = $xmlDoc->saveXML(); |
| 3700: | } |
| 3701: | |
| 3702: | // Return the old value of the modified or deleted element (a node or |
| 3703: | // an attribute) or false on failure. |
| 3704: | return $oldValue; |
| 3705: | } |
| 3706: | |
| 3707: | |
| 3708: | /** |
| 3709: | * Return the XML token in a pretty readable format. |
| 3710: | * |
| 3711: | * This function is intended for display purposes only. Use the `getXML()` |
| 3712: | * function to obtain the raw XML token you want to work with. |
| 3713: | * |
| 3714: | * @return string The pretty formatted XMLDSigToken signature. |
| 3715: | */ |
| 3716: | public function getPrettyXML() |
| 3717: | { |
| 3718: | $xml = $this->xml; |
| 3719: | $formatted = ''; |
| 3720: | $pad = 0; |
| 3721: | $indent_size = 2; |
| 3722: | $matches = array(); |
| 3723: | |
| 3724: | // Inline function that splits the value of a node |
| 3725: | // into multiple lines of 64 characters. |
| 3726: | $splitNodeValue = function(&$xml, $prefix, $xpathQuery) |
| 3727: | { |
| 3728: | $xpathQuery = str_replace('ds:', $prefix, $xpathQuery); |
| 3729: | $nodeValue = XMLDSigToken::alterXML($xml, $xpathQuery, null, 'placeholer', false); |
| 3730: | if (false === $nodeValue) |
| 3731: | { |
| 3732: | // No such node, or the XML token is not a valid XML document. |
| 3733: | return; |
| 3734: | } |
| 3735: | $nodeValue = PHP_EOL . implode(PHP_EOL, str_split($nodeValue, 64)) . PHP_EOL; |
| 3736: | XMLDSigToken::alterXML($xml, $xpathQuery, null, $nodeValue, false); |
| 3737: | // Remove XML encoded carriage return introduced when splitting node |
| 3738: | // value. |
| 3739: | $xml = str_replace('
', '', $xml); |
| 3740: | }; |
| 3741: | |
| 3742: | // Split node values that are too long. |
| 3743: | $prefix = $this->xmldsigNsPrefix ? $this->xmldsigNsPrefix . ':' : ''; |
| 3744: | $splitNodeValue($xml, $prefix, '//ds:Signature/ds:SignatureValue'); |
| 3745: | $splitNodeValue($xml, $prefix, '//ds:Signature/ds:KeyInfo/ds:X509Data/ds:X509Certificate'); |
| 3746: | $splitNodeValue($xml, $prefix, '//ds:Signature/ds:Object/xenc:EncryptedData/ds:KeyInfo/xenc:EncryptedKey/xenc:CipherData/xenc:CipherValue'); |
| 3747: | $splitNodeValue($xml, $prefix, '//ds:Signature/ds:Object/xenc:EncryptedData/xenc:CipherData/xenc:CipherValue'); |
| 3748: | |
| 3749: | // Tokenise the XML string. |
| 3750: | $xml = preg_replace('/(>)[\s]*(<)(\/*)/', "$1\n$2$3", $xml); |
| 3751: | |
| 3752: | // Get the first token. |
| 3753: | $tok = strtok($xml, "\n"); |
| 3754: | |
| 3755: | // Scan each token and adjust indent based on opening/closing tags. |
| 3756: | while ($tok !== false) |
| 3757: | { |
| 3758: | // Test for the various tag states |
| 3759: | if (preg_match('/.+<\/\w[^>]*>$/', $tok, $matches)) |
| 3760: | { |
| 3761: | // Opening and closing tags on same line: no change. |
| 3762: | $indent = 0; |
| 3763: | } |
| 3764: | elseif (preg_match('/^<\/\w/', $tok, $matches)) |
| 3765: | { |
| 3766: | // Closing tag: outdent now. |
| 3767: | $pad = $pad - $indent_size; |
| 3768: | } |
| 3769: | elseif (preg_match('/^<\w[^>]*[^\/]>.*$/', $tok, $matches)) |
| 3770: | { |
| 3771: | // Opening tag: don't pad this one, only subsequent tags. |
| 3772: | $indent = $indent_size; |
| 3773: | } |
| 3774: | else |
| 3775: | { |
| 3776: | // No indentation needed. |
| 3777: | $indent = 0; |
| 3778: | } |
| 3779: | |
| 3780: | // Pad the line with the required number of leading spaces. |
| 3781: | $prettyLine = str_pad($tok, strlen($tok) + $pad, ' ', STR_PAD_LEFT); |
| 3782: | $formatted .= $prettyLine . "\n"; |
| 3783: | |
| 3784: | // Get the next token |
| 3785: | $tok = strtok("\n"); |
| 3786: | |
| 3787: | // Update the pad size for subsequent token. |
| 3788: | $pad += $indent; |
| 3789: | } |
| 3790: | |
| 3791: | // Return formatted XML string. |
| 3792: | return $formatted; |
| 3793: | } |
| 3794: | |
| 3795: | |
| 3796: | /** |
| 3797: | * Utility function that returns information on the XML token in HTML |
| 3798: | * format. |
| 3799: | * |
| 3800: | * The output shows what the token carries, valid or not: data, |
| 3801: | * certificate fields and error messages come from whoever sent the token. |
| 3802: | * Every value is therefore escaped with `htmlspecialchars()` |
| 3803: | * (`ENT_QUOTES | ENT_SUBSTITUTE`, UTF-8), the outputs of `var_dump()` |
| 3804: | * included, so that it can be displayed as is in an HTML page. The output |
| 3805: | * loads no external resource (script, style sheet, image). |
| 3806: | * |
| 3807: | * @return string An HTML fragment. |
| 3808: | */ |
| 3809: | public function getHTMLDump() |
| 3810: | { |
| 3811: | // Inline function to escape a value for HTML output. |
| 3812: | $escape = function($value) |
| 3813: | { |
| 3814: | return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); |
| 3815: | }; |
| 3816: | |
| 3817: | // Inline function to output var_dump() into a string. |
| 3818: | $dumpToString = function($var) |
| 3819: | { |
| 3820: | // Capture var_dump() output. When Xdebug overloads var_dump(), it |
| 3821: | // writes HTML if html_errors is on: turn it off so that the |
| 3822: | // output is plain text, which is then escaped like any value. |
| 3823: | $htmlErrors = ini_set('html_errors', '0'); |
| 3824: | ob_start(); |
| 3825: | var_dump($var); |
| 3826: | $res = ob_get_clean(); |
| 3827: | if (false !== $htmlErrors) |
| 3828: | { |
| 3829: | ini_set('html_errors', $htmlErrors); |
| 3830: | } |
| 3831: | |
| 3832: | // Remove the location ("file:line:") Xdebug writes first. |
| 3833: | if (extension_loaded('xdebug')) |
| 3834: | { |
| 3835: | $res = preg_replace('@\A[^\n]*:\d+:\n@', '', $res, 1); |
| 3836: | } |
| 3837: | |
| 3838: | // Return result. |
| 3839: | return $res; |
| 3840: | }; |
| 3841: | |
| 3842: | $results = array(); |
| 3843: | $results['isSignatureValid()'] = $this->isSignatureValid() ? 'TRUE' : 'FALSE'; |
| 3844: | $results['isDataEncrypted()'] = $this->isDataEncrypted() ? 'TRUE' : 'FALSE'; |
| 3845: | $results['getTimestamp()'] = $this->getTimestamp(); |
| 3846: | $results['getTokenId()'] = is_null($this->getTokenId()) ? 'NULL' : $this->getTokenId(); |
| 3847: | $results['getAudience()'] = $dumpToString($this->getAudience()); |
| 3848: | $results['getExpiry()'] = is_null($this->getExpiry()) ? 'NULL' : $this->getExpiry(); |
| 3849: | $results['getData()'] = $dumpToString($this->getData()); |
| 3850: | $results['getError()'] = is_null($this->getError()) ? 'NULL' : $this->getError(); |
| 3851: | $results['getAnomalies()'] = $dumpToString($this->getAnomalies()); |
| 3852: | $results['getCertDN()'] = $this->getCertDN(); |
| 3853: | $results['getCertSubject()'] = $dumpToString($this->getCertSubject()); |
| 3854: | $results['getCertIssuer()'] = $dumpToString($this->getCertIssuer()); |
| 3855: | $results['getCertValidFrom()'] = $this->getCertValidFrom(); |
| 3856: | $results['getCertValidTo()'] = $this->getCertValidTo(); |
| 3857: | $results['isCertOutOfDate()'] = $this->isCertOutOfDate() ? 'TRUE' : 'FALSE'; |
| 3858: | |
| 3859: | $html = '<table cellpadding="5">'; |
| 3860: | $html .= '<tr><td colspan="2"><pre class="xdebug-var-dump"><b><span style="color: red">XML Digital Signature</span></b></pre></td></tr>'; |
| 3861: | $html .= '<tr><td colspan="2"><pre>' . $escape($this->getPrettyXML()) . '</pre></td></tr>'; |
| 3862: | $html .= '<tr><td width="1%"><pre><b><span style="color: red">METHOD CALLS</span></b></pre></td>'; |
| 3863: | $html .= '<td valign="top" width="99%"><pre><b><span style="color: red">RESULTS</span></b></pre></td></tr>'; |
| 3864: | foreach ($results as $key => $value) { |
| 3865: | $html .= '<tr><td valign="top"><pre><b>' . $escape($key) . '</b></pre></td>'; |
| 3866: | $html .= '<td valign="top"><pre>' . $escape($value) . '</pre></td></tr>'; |
| 3867: | } |
| 3868: | $html .= '</table>'; |
| 3869: | |
| 3870: | return $html; |
| 3871: | } |
| 3872: | } |
| 3873: |