35
36
37:-module(xmlenc,
38 [ decrypt_xml/4, 39 load_certificate_from_base64_string/2 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, +).
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).
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).
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 131 132 ( memberchk('Type'=Type, Attributes)
133 -> true
134 ; Type = 'http://www.w3.org/2001/04/xmlenc#Content'
135 ),
136
137 138 determine_encryption_algorithm(EncryptedData, Algorithm, IVSize, Mode),
139
140 141 142 determine_key(EncryptedData, Key, KeyCallback, Options),
143
144 145 146 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 177 178 179 180 181 ( xmlenc_padding(DecryptedStringWithPadding, IVSize, DecryptedString)
182 -> true
183 ; decryption_failed
184 )
185 ),
186 187 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
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 ; 219 220 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 229 XENC = 'http://www.w3.org/2001/04/xmlenc#',
230 memberchk(element(ns(_, XENC):'EncryptedKey', _KeyAttributes, EncryptedKey), Info),
231 !,
232 233 234 235 memberchk(element(ns(_, XENC):'EncryptionMethod', MethodAttributes, EncryptionMethod), EncryptedKey),
236 memberchk('Algorithm'=Algorithm, MethodAttributes),
237
238 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) 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 260 XENC = ns(_, 'http://www.w3.org/2001/04/xmlenc#'),
261 memberchk(element(XENC:'AgreementMethod', _KeyAttributes, _AgreementMethod), KeyInfo),
262 !,
263 throw(not_implemented).
265resolve_key(KeyInfo, Key, KeyCallback, _Options):-
266 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 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 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), _)) 290 ; existence_error(usable_key_value, KeyValue)
291 ).
292resolve_key(KeyInfo, Key, KeyCallback, _Options):-
293 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 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 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 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 320 321 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 -> 336 memberchk('Algorithm'=XMLAlgorithm, EncryptionMethodAttributes),
337 ( ssl_algorithm(XMLAlgorithm, Algorithm, IVSize, Mode)
338 -> true
339 ; domain_error(block_cipher, XMLAlgorithm)
340 )
341 342 343 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).
365load_certificate_from_base64_string(UnnormalizedData, Certificate):-
366 normalize_space(codes(Codes), UnnormalizedData),
367 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 388
389:- multifile
390 prolog:error_message//1. 391
392prolog:error_message(xmlenc(decryption_failed)) -->
393 [ 'XML encryption: decryption failed' ]
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.