Top Banner
XML Security XML Security September 13, 2006 September 13, 2006 Robert Richards Robert Richards [email protected] [email protected]
52
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • XML SecuritySeptember 13, 2006Robert [email protected]

  • Digital Signatures and EncryptionCanonicalizationA standard form of dataDigital SignaturesProvides proof of identity and authenticity which the sender cannot deny.EncryptionProtection of data from being accessed by unauthorized parties.

  • Existing Tools/TechnologiesSecure Sockets Layer (SSL)Transport Layer Security (TLS)Pretty Good Privacy (PGP)GNU Privacy Guard (GnuPG)OpenPGPS/MIMEx.509

  • XML Security StandardsCanonical XMLhttp://www.w3.org/TR/xml-c14n/

    Exclusive XML Canonicalizationhttp://www.w3.org/TR/xml-exc-c14n/

    XML Signaturehttp://www.w3.org/TR/xmldsig-core/

    XML Encryptionhttp://www.w3.org/TR/xmlenc-core/

    XML Key Managementhttp://www.w3.org/TR/xkms2/

  • Transmitting Data Over SSL/TLS

  • XML Security in PHPA library based on the xmlsec library is currently in the workshttp://www.aleksey.com/xmlsec/Provides granular control for working with XML Digital Signatures and XML EncryptionPHP based libraries are availableModel libraries for designing xmlsec wrapperNot officially mainitained and may not be backwards compatible with xmlsec based extensionRequires PHP 5.1+ (5.2 is recommended)Requires DOM, OpenSSL and Mcrypthttp://www.cdatazone.org/files/xmlseclibs.phpshttp://www.cdatazone.org/files/soap-wsse.phpshttp://www.cdatazone.org/files/ws-amazon.phpshttp://www.cdatazone.org/infocard/infocard-lib.phpshttp://www.cdatazone.org/infocard/infocard.phps

  • Benefits of XML Security StandardsXML is a structured formatAllows for secure storage of documentsLeverages existing technologiesProvides granularity

  • XML CanonicalizationA standard serialization of an XML document or XPath node set

  • Canonical XML (C14N)XML declaration and DTD are removedThe document is encoded in UTF-8Line breaks normalized to #xA (linefeed) on input, before parsingEmpty elements are converted to start-end tag pairsWhitespace outside of the document element and within start and end tags is normalizedAttribute value delimiters are set to double quotesSuperfluous namespace declarations are removed from each elementLexicographic order is imposed on the namespace declarations and attributes of each elementhttp://www.w3.org/TR/2001/REC-xml-c14n-20010315http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments

  • Canonical XML Example #1

    Canonical Form of Document (uncommented)

  • Canonical XML Example #1

    Canonical Form of Document (uncommented)

  • Canonical XML Example #1

    Canonical Form of Document (uncommented)

  • Canonical XML Example #1

    Canonical Form of Document (uncommented)

  • Canonical XML Example #2

    Canonical Form of Nodeset (uncommented)(//. | //@* | //namespace::*)[ancestor-or-self::d:e2]

  • Canonical XML Example #2

    Canonical Form of Nodeset (uncommented)(//. | //@* | //namespace::*)[ancestor-or-self::d:e2]

  • Canonical XML Example #2

    Canonical Form of Nodeset (uncommented)(//. | //@* | //namespace::*)[ancestor-or-self::d:e2]

  • Problem with Re-Envelopingcontent

    content

    content

    content

    content

  • Exclusive XML CanonicalizationFollows the same rules as Canonical XML, exceptAttributes in the xml namespace are not imported into orphan nodesNamespaces not specially told to be added are only added on the starting element for which they are visible and not currently in scope within the output.http://www.w3.org/2001/10/xml-exc-c14n#http://www.w3.org/2001/10/xml-exc-c14n#WithComments

  • Re-Enveloping using Exclusivecontent

    content

    content

    content

    content

  • Exclusive Canonical XML Example

    Exclusive Canonical Form of Nodeset (uncommented)(//. | //@* | //namespace::*)[ancestor-or-self::d:e2]

  • XML Digital Signature (XMLDSIG)Insure that a message has not been altered or tampered with. (integrity)Protection against attacks that alter a message but maintain integrity. (message authentication)Provide a means for message auditing so that messages may not be repudiated. (signer authenticity)

  • XML Signature Structure ( ()? )+ ()? ()*

    xmlns="http://www.w3.org/2000/09/xmldsig#"

  • XML Signature: Types of SignaturesEnveloping SignatureData lives within the XML Signature structureGood for signing data being packaged within an XML payloadEnveloped SignatureData lives outside of and contains the XML Signature structureGood for signing portions or all of an XML documentDetached SignatureData lives outside and DOES NOT contain the XML Signature structureData may reside at a remote location addressable by URI

  • Enveloping Signature

    C2g9BLcGyGPCVKuF2byR1Ym+6pE= +R/XEOHDvR/jbmmpiuH4ZcRqC6c= Hello World!

  • Enveloped Signature

    content

    MMMkB0ZPp82XrUvJMFqDIEuXy0o= mVPvfcVSXi9elKL+IcSCAzD4Jbk=

  • Detached Signature

    oLZZOWcLwsAQ9NXWoLPk5FkPuSs= O9ykpFMXmkddzJ3CySrpzHBUW/Q=

  • XML Signature GenerationApply any transforms to the dataCalculate the digest valueCreate the Reference ElementRepeat steps 1 3 for each piece of data to be includedCreate SignedInfo element with SignatureMethod, CanonicalizationMethod and Reference elementsCanonicalize the SignedInfo elementCalculate the SignatureValue over the canonicalized SignedInfo based the SignatureMethodAssemble the Signature element

  • SOAP Request

    tel:1234567890 xx yy

  • SOAP Request: WS-Security (Signature)

    MIIE3zCCBEigAwIBAg . . . . . . . . . Yd1TGIjOb3q4UcQkUBuM3Q6Zs3G... . . .

  • SOAP Request: WS-Security Generationrequire('soap-wsse.php');

    define('PRIVATE_KEY', 'private_key.pem');define('CERT_FILE', 'cert.pem');

    class mySoap extends SoapClient {

    public function __doRequest($request, $location, $saction, $version) {$doc = new DOMDocument('1.0');$doc->loadXML($request);

    /* WS-Security Specific code here */

    return parent::__doRequest($wsseRequest, $location, $saction, $version); }}

  • SOAP Request: WS-Security Generation$objWSSE = new WSSESoap($doc->loadXML($request));

    /* add Timestamp with default expiration timestamp */ $objWSSE->addTimestamp();/* $objWSSE->addUserToken('username', 'password', TRUE); */

    /* create new XMLSec Key using RSA SHA-1 and type is private key */$objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA1, array('type'=>'private'));

    /* load private key from file - last arg is bool if key in file (TRUE) or is string (FALSE) */$objKey->loadKey(PRIVATE_KEY, TRUE);

    /* Sign the message - also signs appropraite WS-Security items */$objWSSE->signSoapDoc($objKey);

    /* Add certificate (BinarySecurityToken) to the message and attach pointer to Signature */$token = $objWSSE->addBinaryToken(file_get_contents(CERT_FILE));$objWSSE->attachTokentoSig($token);

    $wsseRequest = $objWSSE->saveXML();

  • SOAP Request: signSoapDoc()$objDSig = new XMLSecurityDSig();$objDSig->setCanonicalMethod(XMLSecurityDSig::EXC_C14N);

    $arNodes = array();/* $this->secNode refers to wsse:Security node within tree */foreach ($this->secNode->childNodes AS $node) {if ($node->nodeType == XML_ELEMENT_NODE) $arNodes[] = $node;}

    foreach ($this->envelope->childNodes AS $node) {if ($node->namespaceURI == $this->soapNS && $node->localName == 'Body') {$arNodes[] = $node;break;}}

    $arOptions = array('prefix'=>WSSESoap::WSUPFX, 'prefix_ns'=>WSSESoap::WSUNS);$objDSig->addReferenceList($arNodes, XMLSecurityDSig::SHA1, NULL, $arOptions);

    $objDSig->sign($objKey);

    $objDSig->appendSignature($this->secNode, TRUE);

  • XML Signature ValidationObtain the verification keying informationApply the CanonicalizationMethod to the SignedInfo elementVerify the SignatureValue using the canonical form of the SignatureMethodFor each Reference element within SignedInfo:Obtain the data to be digestedDigest the data using the DigestMethod within its Referece elementCompare the computed value to that of the un-encoded value from the DigestValue element

  • XML Encryption (XMLENC)Encrypted data is maintained.All information needed to decrypt a document is contained within the document.Session can be secured on the document level and shared between multiple parties.Sensitive data is easily interchanged between applications.

  • XML Encryption Structure

    ? ? ? ? ?

    xmlns:enc="http://www.w3.org/2001/04/xmlenc#"

  • XML Encryption: EncryptingSelect the algorithm (and parameters) to use in encrypting the item.Obtain the key and create ds:KeyInfo if necessaryEncrypt the data and prepend any appropriate initialization vector (IV).Build CipherData elementIf to be stored within CipherValue element, then encrypted data is base64 encoded.If encrypted data is external, then create CipherReference with URI and any transforms.Build EncryptedData or EncryptedKey structure

  • XML Encryption Example

    1001 Joe Smith 4111 1111 1111 1111 01 2007 123

  • XML Encryption ExampleElement / Shared Secret Key

    1001 Joe Smith C5X1I65RCX

  • XML Encryption Example: Coderequire('xmlseclibs.php');/* Using a shared secret key for encryption */$key = 'secret';

    $doc = new DOMDocument();$xpath = new DOMXPath($doc ->load('payment.xml'));$creditcard = $xpath->query("//creditcard")->item(0);

    $enc = new XMLSecEnc();$enc->setNode($creditcard);$enc->type = XMLSecEnc::Element;

    /* Use the libraries to encrypt the credit card element within the document */$objKey = new XMLSecurityKey(XMLSecurityKey::TRIPLEDES_CBC);$objKey->loadKey($key);

    $encNode = $enc->encryptNode($objKey);

    print $encNode->ownerDocument->saveXML();

  • XML Encryption ExampleElement Content / Shared Secret Key

    1001 Joe Smith C5X1I65RCX

  • XML Encryption ExampleArbitrary Data with Shared Secret Key

    ...C5X1I65RCX...

  • XML Encryption: DecryptingDetermine encryption algorithm and parameters.Obtain the decryption key information.Obtain the data to decrypt.If CipherData has a CipherValue child then base-64 decode its contents.If CipherData has a CipherReference child, retrieve the data and apply any Transforms.Depending upon algorithm and parameters, strip any IV from the data to use for decryption.Decrypt the cipher data with the encryption algorithm, parameters, and keying material.

  • XML Encryption: Decrypting Example (Infocard)

    . . . kXja26CSDKssMeqJcsJttLg

    eIreM+S35Q+=

  • XML Encryption: Code (Infocard)require('xmlseclibs.php');

    define('PRIVATE_KEY', 'site_sslprivate.key');define('SAML_ASSERT_NS', 'urn:oasis:names:tc:SAML:1.0:assertion');

    $encdom = new DOMDocument();$encdom->loadXML($xmlToken);

    $objenc = new XMLSecEnc();$encData = $objenc->locateEncryptedData($encdom);if (! $encData) {throw new Exception("Cannot locate Encrypted Data");}$objenc->setNode($encData);$objenc->type = $encData->getAttribute("Type");

  • XML Encryption: Code (Infocard)$key = NULL;$objKey = $objenc->locateKey();if ($objKey)if ($objKeyInfo = $objenc->locateKeyInfo($objKey))if ($objKeyInfo->isEncrypted) {$objencKey = $objKeyInfo->encryptedCtx;$objKeyInfo->loadKey(PRIVATE_KEY, TRUE);$key = $objencKey->decryptKey($objKeyInfo);}if (empty($objKey) || empty($key))throw new Exception("Error loading key to handle Decryption");

    $objKey->loadKey($key);

    $token = NULL;if ($decrypt = $objenc->decryptNode($objKey, FALSE)) {$token = new DOMDocument();$token->loadXML($decrypt);}

  • XML Encryption: Code (Infocard)

    . . . eHLrK4QSEkrDhHXZYHgGJMkPAU4= 0uDR9pr/TusV... 8llAGAvlPuG... AQAB

  • XML Encryption: Code (Infocard)/* Validate the SAML token */$objXMLSecDSig = new XMLSecurityDSig();$objXMLSecDSig->idKeys[] = 'AssertionID';$objDSig = $objXMLSecDSig->locateSignature($token);

    /* Canonicalize the signed info */$objXMLSecDSig->canonicalizeSignedInfo();

    $retVal = NULL;if ($objDSig) { $retVal = $objXMLSecDSig->validateReference(); }

    if (! $retVal) { throw new Exception("SAML Validation Failed"); }

    $objKey = $objXMLSecDSig->locateKey();/* Additional Key handling here */

    if (empty($objKey)) throw new Exception("Error loading key to handle Signature");

    if (! $objXMLSecDSig->verify($objKey))throw new Exception("Unable to validate Signature");

  • Signing and EncryptingSign and then EncryptProvides signature protectionAllows for encryption algorithm to be changed without affecting signatureIncurs additional overhead as you must decrypt before you can verifyEncrypt and then SignImmediately know if data has been tampered withDocument can no longer be shared with other parties without revealing decryption keySender identity is revealed

  • Questions?

  • XML Encryption in WS-Security

    ...

  • XML Signature using Digital Certificate

    Hello, World!

    HjY8ilZAIEM2tBbPn5mYO1ieIX4=

    SIaj/6KY3C . . .

    MIIE3zCCBEjAUB9 . . .

  • XML Encryption w/ Digital Certificate

    rsakey.pem IPiEu9Nv+EsGyvV . . .

    xrfPSA+BEI+8 . . .