View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Matt Lilley
    4    E-mail:        thetrime@gmail.com
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2004-2016, SWI-Prolog Foundation
    7                              VU University Amsterdam
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36
   37:-module(xmlenc,
   38         [ decrypt_xml/4,   % +EncryptedXML, -DecryptedXML, :KeyCallback, +Options
   39           load_certificate_from_base64_string/2 % +Base64String, -Certificate
   40         ]).   41:- autoload(library(base64),[base64/2]).   42:- autoload(library(crypto),
   43	    [crypto_data_decrypt/6,rsa_private_decrypt/4,hex_bytes/2]).   44:- autoload(library(error),[existence_error/2,domain_error/2]).   45:- autoload(library(lists),[append/3]).   46:- autoload(library(sgml),[load_structure/3]).   47:- autoload(library(ssl),[load_certificate/2]).   48:- autoload(library(option),[option/2]).   49
   50:- meta_predicate
   51    decrypt_xml(+, -, 3, +).

XML encryption library

This library is a partial implementation of the XML encryption standard. It implements the decryption part, which is needed by SAML clients.

See also
- https://www.w3.org/TR/xmlenc-core1/
- https://en.wikipedia.org/wiki/Security_Assertion_Markup_Language
   62%   ssl_algorithm(?URI, ?Algorithm, ?IVSize, ?Mode)
   63%
   64%   Block cipher algorithms.  Note that the CBC modes provide no
   65%   integrity.  Using the GCM modes is advised.
   66
   67ssl_algorithm('http://www.w3.org/2001/04/xmlenc#tripledes-cbc', 'des3',         8, cbc).
   68ssl_algorithm('http://www.w3.org/2001/04/xmlenc#aes128-cbc',    'aes-128-cbc', 16, cbc).
   69ssl_algorithm('http://www.w3.org/2001/04/xmlenc#aes256-cbc',    'aes-256-cbc', 16, cbc).
   70ssl_algorithm('http://www.w3.org/2001/04/xmlenc#aes192-cbc',    'aes-192-cbc', 16, cbc).
   71ssl_algorithm('http://www.w3.org/2009/xmlenc11#aes128-gcm',     'aes-128-gcm', 12, gcm).
   72ssl_algorithm('http://www.w3.org/2009/xmlenc11#aes192-gcm',     'aes-192-gcm', 12, gcm).
   73ssl_algorithm('http://www.w3.org/2009/xmlenc11#aes256-gcm',     'aes-256-gcm', 12, gcm).
   74
   75gcm_tag_length(16).
 decrypt_xml(+DOMIn, -DOMOut, :KeyCallback, +Options) is det
Arguments:
KeyCallback- may be called as follows:
  • call(KeyCallback, name, KeyName, Key)
  • call(KeyCallback, public_key, public_key(RSA), Key)
  • call(KeyCallback, certificate, Certificate, Key)

Options:

weak_algorithms(+Boolean)
If true (default false), accept RSA PKCS#1 v1.5 key transport, which is vulnerable to padding oracle attacks.

The CipherReference element is not supported. Note that the CBC block cipher modes do not protect the integrity of the data. Decryption errors are reported using the same exception to avoid padding oracles.

   95decrypt_xml([], [], _, _):- !.
   96decrypt_xml([element(ns(_, 'http://www.w3.org/2001/04/xmlenc#'):'EncryptedData',
   97                     Attributes, EncryptedData)|Siblings],
   98            [Decrypted|NewSiblings], KeyCallback, Options) :-
   99    !,
  100    decrypt_element(Attributes, EncryptedData, Decrypted, KeyCallback, Options),
  101    decrypt_xml(Siblings, NewSiblings, KeyCallback, Options).
  102
  103decrypt_xml([element(Tag, Attributes, Children)|Siblings],
  104            [element(Tag, Attributes, NewChildren)|NewSiblings], KeyCallback, Options) :-
  105    !,
  106    decrypt_xml(Children, NewChildren, KeyCallback, Options),
  107    decrypt_xml(Siblings, NewSiblings, KeyCallback, Options).
  108decrypt_xml([Other|Siblings], [Other|NewSiblings], KeyCallback, Options):-
  109    decrypt_xml(Siblings, NewSiblings, KeyCallback, Options).
 decrypt_element(+Attributes, +EncryptedData, -DecryptedElement, +Options)
Decrypt an EncryptedData element with Attributes and child EncryptedData DecryptedElement will either be an element/3 term or a string as dictacted by the Type attribute in Attributes. If Attributes does not contain a Type attribute then we assume it is a string
  122:-meta_predicate(decrypt_element(+, +, -, 3, +)).  123
  124decrypt_element(Attributes, EncryptedData, Decrypted, KeyCallback, Options):-
  125    XENC = ns(_, 'http://www.w3.org/2001/04/xmlenc#'),
  126    (  memberchk(element(XENC:'CipherData', _, CipherData), EncryptedData)
  127    -> true
  128    ;  existence_error(cipher_data, EncryptedData)
  129    ),
  130    % The Type attribute is not mandatory. However, 3.1 states that
  131    % "Without this information, the decryptor will be unable to automatically restore the XML document to its original cleartext form."
  132    (  memberchk('Type'=Type, Attributes)
  133    -> true
  134    ;  Type = 'http://www.w3.org/2001/04/xmlenc#Content'
  135    ),
  136
  137    % First of all, determine the algorithm used to encrypt the data
  138    determine_encryption_algorithm(EncryptedData, Algorithm, IVSize, Mode),
  139
  140    % There are now two tasks remaining, and they seem like they ought to be quite simple, but unfortunately they are not
  141    % First, we must determine the key used to encrypt the message
  142    determine_key(EncryptedData, Key, KeyCallback, Options),
  143
  144    % Then, we must determine what the encrypted data even IS
  145    % If the message includes a CipherValue then this is straightfoward - the encrypted data is the base64-encoded child
  146    % of this element.
  147    (  memberchk(element(XENC:'CipherValue', _, CipherValueElement), CipherData)
  148    -> base64_element(CipherValueElement, CipherValueWithIV)
  149    ;  domain_error(supported_cipher_data, CipherData)
  150    ),
  151    string_codes(CipherValueWithIV, CipherValueWithIVCodes),
  152    (   length(IVCodes, IVSize),
  153        append(IVCodes, CipherCodes0, CipherValueWithIVCodes)
  154    ->  true
  155    ;   decryption_failed
  156    ),
  157    string_codes(IV, IVCodes),
  158    (   Mode == gcm
  159    ->  gcm_tag_length(TagLen),
  160        length(Tag, TagLen),
  161        (   append(CipherCodes, Tag, CipherCodes0)
  162        ->  true
  163        ;   decryption_failed
  164        ),
  165        string_codes(CipherText, CipherCodes),
  166        catch(crypto_data_decrypt(CipherText, Algorithm, Key, IV, DecryptedString,
  167                                  [ padding(none), encoding(octet),
  168                                    tag(Tag)
  169                                  ]),
  170              error(_,_), decryption_failed)
  171    ;   string_codes(CipherText, CipherCodes0),
  172        catch(crypto_data_decrypt(CipherText, Algorithm, Key, IV,
  173                                  DecryptedStringWithPadding,
  174                                  [padding(none), encoding(octet)]),
  175              error(_,_), decryption_failed),
  176        % The XML-ENC padding scheme does not comply with RFC-1423.  This
  177        % has been noted a few times by people trying to write XML-ENC
  178        % decryptors backed by OpenSSL, which insists on compliance.  The
  179        % only recourse we have is to disable padding entirely and do it
  180        % in our application
  181        (   xmlenc_padding(DecryptedStringWithPadding, IVSize, DecryptedString)
  182        ->  true
  183        ;   decryption_failed
  184        )
  185    ),
  186    % Now that we have the decrypted data, we can decide whether to turn it into an element or leave it as
  187    % content
  188    (  Type == 'http://www.w3.org/2001/04/xmlenc#Element'
  189    -> setup_call_cleanup(open_string(DecryptedString, StringStream),
  190                          load_structure(StringStream, [Decrypted], [dialect(xmlns), keep_prefix(true)]),
  191                          close(StringStream))
  192    ;  Decrypted = DecryptedString
  193    ).
  194
  195%   xmlenc_padding(+Padded, +BlockSize, -Plain) is semidet.
  196%
  197%   Remove XML-ENC padding.  The last byte gives the number of padding
  198%   bytes, which must be between 1 and BlockSize.
  199
  200xmlenc_padding(DecryptedStringWithPadding, BlockSize, DecryptedString):-
  201    string_length(DecryptedStringWithPadding, Len),
  202    Len > 0,
  203    Len mod BlockSize =:= 0,
  204    string_code(Len, DecryptedStringWithPadding, PadLen),
  205    PadLen >= 1,
  206    PadLen =< BlockSize,
  207    PlainLen is Len - PadLen,
  208    sub_string(DecryptedStringWithPadding, 0, PlainLen, _, DecryptedString).
  209
  210decryption_failed :-
  211    throw(error(xmlenc(decryption_failed), _)).
  212
  213:- meta_predicate determine_key(+,-,3,+).  214determine_key(EncryptedData, Key, KeyCallback, Options):-
  215    DS = ns(_, 'http://www.w3.org/2000/09/xmldsig#'),
  216    (  memberchk(element(DS:'KeyInfo', _, KeyInfo), EncryptedData)
  217    -> true
  218    ;  % Technically the KeyInfo is not mandatory. However, without a key we cannot decrypt
  219           % so raise an error. In the future Options could contain a key if it is agreed upon
  220           % by some other channel
  221           existence_error(key_info, EncryptedData)
  222    ),
  223    resolve_key(KeyInfo, Key, KeyCallback, Options).
  224
  225:- meta_predicate resolve_key(+,-,3,+).  226
  227resolve_key(Info, Key, KeyCallback, Options):-
  228    % EncryptedKey
  229    XENC = 'http://www.w3.org/2001/04/xmlenc#',
  230    memberchk(element(ns(_, XENC):'EncryptedKey', _KeyAttributes, EncryptedKey), Info),
  231    !,
  232    % The EncryptedKey is slightly different to EncryptedData. For a start, the algorithms used to decrypt the
  233    % key are orthogonal to those used for EncryptedData. However we can recursively search for the keys then
  234    % decrypt them using the different algorithms as needed
  235    memberchk(element(ns(_, XENC):'EncryptionMethod', MethodAttributes, EncryptionMethod), EncryptedKey),
  236    memberchk('Algorithm'=Algorithm, MethodAttributes),
  237
  238    % Now find the KeyInfo
  239    determine_key(EncryptedKey, PrivateKey, KeyCallback, Options),
  240
  241    memberchk(element(ns(_, XENC):'CipherData', _, CipherData), EncryptedKey),
  242    memberchk(element(ns(_, XENC):'CipherValue', _, CipherValueElement), CipherData),
  243    base64_element(CipherValueElement, CipherValue),
  244    (  Algorithm == 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p'
  245    -> Padding = pkcs1_oaep
  246    ;  Algorithm == 'http://www.w3.org/2009/xmlenc11#rsa-oaep',
  247           memberchk(element(ns(_, 'http://www.w3.org/2009/xmlenc11#'):'MGF', MGFAttributes, _), EncryptionMethod),
  248           memberchk('Algorithm'='http://www.w3.org/2009/xmlenc11#mgf1sha1', MGFAttributes)   % This is just the same as rsa-oaep-mgf1p!
  249    -> Padding = pkcs1_oaep
  250    ;  Algorithm == 'http://www.w3.org/2001/04/xmlenc#rsa-1_5',
  251       option(weak_algorithms(true), Options)
  252    -> Padding = pkcs1
  253    ;  domain_error(key_transport, Algorithm)
  254    ),
  255    catch(rsa_private_decrypt(PrivateKey, CipherValue, Key,
  256                              [encoding(octet), padding(Padding)]),
  257          error(_,_), decryption_failed).
  258resolve_key(KeyInfo, _Key, _KeyCallback, _Options):-
  259    % AgreementMethod. FIXME: Not implemented
  260    XENC = ns(_, 'http://www.w3.org/2001/04/xmlenc#'),
  261    memberchk(element(XENC:'AgreementMethod', _KeyAttributes, _AgreementMethod), KeyInfo),
  262    !,
  263    throw(not_implemented).
  264% Additionally, we are allowed to use any elements from XML-DSIG
  265resolve_key(KeyInfo, Key, KeyCallback, _Options):-
  266    % KeyName. Use the callback with type=name and hint=KeyName
  267    DS = ns(_, 'http://www.w3.org/2000/09/xmldsig#'),
  268    memberchk(element(DS:'KeyName', _KeyAttributes, [KeyName]), KeyInfo),
  269    !,
  270    call(KeyCallback, name, KeyName, Key).
  271resolve_key(KeyInfo, _Key, _KeyCallback, _Options):-
  272    % RetrievalMethod. FIXME: Not implemented
  273    DS = ns(_, 'http://www.w3.org/2000/09/xmldsig#'),
  274    memberchk(element(DS:'RetrievalMethod', _KeyAttributes, _RetrievalMethod), KeyInfo),
  275    !,
  276    throw(not_implemented).
  277resolve_key(KeyInfo, Key, KeyCallback, _Options):-
  278    % KeyValue.
  279    DS = ns(_, 'http://www.w3.org/2000/09/xmldsig#'),
  280    memberchk(element(DS:'KeyValue', _KeyAttributes, KeyValue), KeyInfo),
  281    !,
  282    (  memberchk(element(DS:'RSAKeyValue', _, RSAKeyValue), KeyValue)
  283    -> memberchk(element(DS:'Modulus', _, [ModulusBase64]), RSAKeyValue),
  284           memberchk(element(DS:'Exponent', _, [ExponentBase64]), RSAKeyValue),
  285           base64_to_hex(ModulusBase64, Modulus),
  286           base64_to_hex(ExponentBase64, Exponent),
  287           call(KeyCallback, public_key, public_key(rsa(Modulus, Exponent, -, -, -, -, -, -)), Key)
  288    ;  memberchk(element(DS:'DSAKeyValue', _, _DSAKeyValue), KeyValue)
  289    -> throw(error(not_implemented(dsa_key), _)) % FIXME: Not implemented
  290    ;  existence_error(usable_key_value, KeyValue)
  291    ).
  292resolve_key(KeyInfo, Key, KeyCallback, _Options):-
  293    % X509Data.
  294    DS = ns(_, 'http://www.w3.org/2000/09/xmldsig#'),
  295    memberchk(element(DS:'X509Data', _, X509Data), KeyInfo),
  296    memberchk(element(DS:'X509Certificate', _, [X509Certificate]), X509Data),
  297    !,
  298    load_certificate_from_base64_string(X509Certificate, Certificate),
  299    call(KeyCallback, certificate, Certificate, Key).
  300resolve_key(KeyInfo, _Key, _KeyCallback, _Options):-
  301    % PGPData. FIXME: Not implemented
  302    DS = ns(_, 'http://www.w3.org/2000/09/xmldsig#'),
  303    memberchk(element(DS:'PGPData', _KeyAttributes, _PGPData), KeyInfo),
  304    !,
  305    throw(not_implemented).
  306resolve_key(KeyInfo, _Key, _KeyCallback, _Options):-
  307    % SPKIData. FIXME: Not implemented
  308    DS = ns(_, 'http://www.w3.org/2000/09/xmldsig#'),
  309    memberchk(element(DS:'SPKIData', _KeyAttributes, _SPKIData), KeyInfo),
  310    !,
  311    throw(not_implemented).
  312resolve_key(KeyInfo, _Key, _KeyCallback, _Options):-
  313    % MgmtData. FIXME: Not implemented
  314    DS = ns(_, 'http://www.w3.org/2000/09/xmldsig#'),
  315    memberchk(element(DS:'MgmtData', _KeyAttributes, _SPKIData), KeyInfo),
  316    !,
  317    throw(not_implemented).
  318resolve_key(Info, _, _, _):-
  319    % The XML-ENC standard allows for arbitrary other means of transmitting keys in application-specific
  320    % protocols. This is not supported here, though. In the future a callback could be provided in Options
  321    % to obtain the key information from a KeyInfo structure.
  322    existence_error(usable_key, Info).
  323
  324
  325base64_to_hex(Base64, Hex):-
  326    base64(Raw, Base64),
  327    atom_codes(Raw, Codes),
  328    hex_bytes(Hex0, Codes),
  329    string_upper(Hex0, Hex).
  330
  331
  332determine_encryption_algorithm(EncryptedData, Algorithm, IVSize, Mode):-
  333    XENC = ns(_, 'http://www.w3.org/2001/04/xmlenc#'),
  334    (  memberchk(element(XENC:'EncryptionMethod', EncryptionMethodAttributes, _), EncryptedData)
  335    -> % This is a mandatory attribute
  336           memberchk('Algorithm'=XMLAlgorithm, EncryptionMethodAttributes),
  337           (  ssl_algorithm(XMLAlgorithm, Algorithm, IVSize, Mode)
  338           -> true
  339           ; domain_error(block_cipher, XMLAlgorithm)
  340           )
  341        % In theory the EncryptionMethod is optional. In pracitse though, if the method is not supplied we
  342        % cannot decrypt the data. In the future we could support encryption_algorithm/1 as an option to
  343        % decrypt_element/3 but for now raise an exception
  344    ; existence_error(encryption_method, EncryptedData)
  345    ).
  346
  347base64_element([CipherValueElement], CipherValue):-
  348    atom_codes(CipherValueElement, Base64Codes),
  349    delete_newlines(Base64Codes, TrimmedCodes),
  350    string_codes(Trimmed, TrimmedCodes),
  351    base64(CipherValue, Trimmed).
  352
  353delete_newlines([], []):- !.
  354delete_newlines([13|As], B):- !, delete_newlines(As, B).
  355delete_newlines([10|As], B):- !, delete_newlines(As, B).
  356delete_newlines([A|As], [A|B]):- !, delete_newlines(As, B).
 load_certificate_from_base64_string(+String, -Certificate) is det
Loads a certificate from a string, adding newlines and header where appropriate so that OpenSSL 1.0.1+ will be able to parse it
  365load_certificate_from_base64_string(UnnormalizedData, Certificate):-
  366    normalize_space(codes(Codes), UnnormalizedData),
  367    % Break into 64-byte chunks
  368    chunk_certificate(Codes, Chunks),
  369    atomics_to_string(["-----BEGIN CERTIFICATE-----"|Chunks], '\n', CompleteCertificate),
  370    setup_call_cleanup(open_string(CompleteCertificate, StringStream),
  371                       load_certificate(StringStream, Certificate),
  372                       close(StringStream)).
  373
  374chunk_certificate(Codes, [Chunk|Chunks]):-
  375    length(ChunkCodes, 64),
  376    append(ChunkCodes, Rest, Codes),
  377    !,
  378    string_codes(Chunk, ChunkCodes),
  379    chunk_certificate(Rest, Chunks).
  380chunk_certificate([], ["-----END CERTIFICATE-----\n"]):- !.
  381chunk_certificate(LastCodes, [LastChunk, "-----END CERTIFICATE-----\n"]):-
  382    string_codes(LastChunk, LastCodes).
  383
  384
  385		 /*******************************
  386		 *           MESSAGES		*
  387		 *******************************/
  388
  389:- multifile
  390    prolog:error_message//1.  391
  392prolog:error_message(xmlenc(decryption_failed)) -->
  393    [ 'XML encryption: decryption failed' ]