lib/VOMS/Lite/SAMLHelper.pm untested

filter: Statementstmt 0.0% 0 / 310 Branchbran 0.0% 0 / 114 Conditioncond 0.0% 0 / 117 MC/DCmcdc 0.0% 0 / 71 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 636 CC 58 SCAR 54.7
CC
58
Cov
0%
getSAMLAttributes
552.0
parseElement
210.0
getAttributes
110.0
CRAP 238.4
1 #!/usr/bin/perl
2 package VOMS::Lite::SAMLHelper;
3  
4 use 5.004;
5 use strict;
6 use XML::Parser;
7 use Data::Dumper;
8 require Exporter;
9 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
10 @ISA = qw(Exporter);
11 %EXPORT_TAGS = ( );
12 @EXPORT_OK = qw( );
13 @EXPORT = ( );
14 $VERSION = '0.20';
15  
16 ####
17 # %knownns
18 # namespaces known about and corresponding local naming shorthand
19 #
20 my %knownns=( 'urn:oasis:names:tc:SAML:1.0:assertion' => 'saml1',
21 'urn:oasis:names:tc:SAML:1.0:protocol' => 'saml1p',
22 'http://www.w3.org/2000/09/xmldsig#' => 'ds',
23 'urn:oasis:names:tc:SAML:2.0:assertion' => 'saml2',
24 'urn:oasis:names:tc:SAML:2.0:protocol' => 'saml2p',
25 'http://www.w3.org/2001/04/xmlenc#' => 'xenc'
26 );
27  
28 ####
29 # %attributes
30 # local friendlynames for attributes that might appear in a SAML Assertion
31 #
32 my %attributes = (
33 # eduPerson Attributes
34 qw|
35 urn:oid:1.3.6.1.4.1.5923.1.1.2 eduPerson
36 urn:mace:dir:attribute-def:eduPerson eduPerson
37 urn:oid:1.3.6.1.4.1.5923.1.1.1.1 eduPersonAffiliation
38 urn:mace:dir:attribute-def:eduPersonAffiliation eduPersonAffiliation
39 urn:oid:1.3.6.1.4.1.5923.1.1.1.7 eduPersonEntitlement
40 urn:mace:dir:attribute-def:eduPersonEntitlement eduPersonEntitlement
41 urn:oid:1.3.6.1.4.1.5923.1.1.1.2 eduPersonNickname
42 urn:mace:dir:attribute-def:eduPersonNickname eduPersonNickname
43 urn:oid:1.3.6.1.4.1.5923.1.1.1.3 eduPersonOrgDN
44 urn:mace:dir:attribute-def:eduPersonOrgDN eduPersonOrgDN
45 urn:oid:1.3.6.1.4.1.5923.1.1.1.4 eduPersonOrgUnitDN
46 urn:mace:dir:attribute-def:eduPersonOrgUnitDN eduPersonOrgUnitDN
47 urn:oid:1.3.6.1.4.1.5923.1.1.1.5 eduPersonPrimaryAffiliation
48 urn:mace:dir:attribute-def:eduPersonPrimaryAffiliation eduPersonPrimaryAffiliation
49 urn:oid:1.3.6.1.4.1.5923.1.1.1.8 eduPersonPrimaryOrgUnitDN
50 urn:mace:dir:attribute-def:eduPersonPrimaryOrgUnitDN eduPersonPrimaryOrgUnitDN
51 urn:oid:1.3.6.1.4.1.5923.1.1.1.6 eduPersonPrincipalName
52 urn:mace:dir:attribute-def:eduPersonPrincipalName eduPersonPrincipalName
53 urn:oid:1.3.6.1.4.1.5923.1.1.1.9 eduPersonScopedAffiliation
54 urn:mace:dir:attribute-def:eduPersonScopedAffiliation eduPersonScopedAffiliation
55 urn:oid:1.3.6.1.4.1.5923.1.1.1.10 eduPersonTargetedID
56 urn:mace:dir:attribute-def:eduPersonTargetedID eduPersonTargetedID
57 |,
58 # eduOrg Attributes
59 qw|
60 urn:oid:1.3.6.1.4.1.5923.1.2.2 eduOrg
61 urn:mace:dir:attribute-def:eduOrg eduOrg
62 urn:oid:1.3.6.1.4.1.5923.1.2.1.2 eduOrgHomePageURI
63 urn:mace:dir:attribute-def:eduOrgHomePageURI eduOrgHomePageURI
64 urn:oid:1.3.6.1.4.1.5923.1.2.1.3 eduOrgIdentityAuthNPolicyURI
65 urn:mace:dir:attribute-def:eduOrgIdentityAuthNPolicyURI eduOrgIdentityAuthNPolicyURI
66 urn:oid:1.3.6.1.4.1.5923.1.2.1.4 eduOrgLegalName
67 urn:mace:dir:attribute-def:eduOrgLegalName eduOrgLegalName
68 urn:oid:1.3.6.1.4.1.5923.1.2.1.5 eduOrgSuperiorURI
69 urn:mace:dir:attribute-def:eduOrgSuperiorURI eduOrgSuperiorURI
70 urn:oid:1.3.6.1.4.1.5923.1.2.1.6 eduOrgWhitePagesURI
71 urn:mace:dir:attribute-def:eduOrgWhitePagesURI eduOrgWhitePagesURI
72 |,
73 # VOMS Attributes
74 qw|
75 http://dci-sec.org/saml/attribute/virtual-organization VOMSVO
76 http://authz-interop.org/xacml/subject/voms-fqan VOMSFQAN
77 http://dci-sec.org/saml/attribute/group VOMSGroup
78 http://dci-sec.org/saml/attribute/group/primary VOMSPrimaryGroup
79 http://dci-sec.org/saml/attribute/role VOMSRole
80 |,
81 # Others
82 qw|
83 urn:mace:dir:attribute-def:eduCourseOffering eduCourseOffering
84 urn:oid:1.3.6.1.4.1.5923.1.6.1.1 eduCourseOffering
85 urn:mace:dir:attribute-def:eduCourseMember eduCourseMember
86 urn:oid:1.3.6.1.4.1.5923.1.6.1.2 eduCourseMember
87 urn:mace:dir:attribute-def:cn cn
88 urn:oid:2.5.4.3 cn
89 urn:mace:dir:attribute-def:sn sn
90 urn:oid:2.5.4.4 sn
91 urn:mace:dir:attribute-def:givenName givenName
92 urn:oid:2.5.4.42 givenName
93 urn:mace:dir:attribute-def:mail mail
94 urn:oid:0.9.2342.19200300.100.1.3 mail
95 urn:mace:dir:attribute-def:telephoneNumber telephoneNumber
96 urn:oid:2.5.4.20 telephoneNumber
97 urn:mace:dir:attribute-def:title title
98 urn:oid:2.5.4.12 title
99 urn:mace:dir:attribute-def:initials initials
100 urn:oid:2.5.4.43 initials
101 urn:mace:dir:attribute-def:description description
102 urn:oid:2.5.4.13 description
103 urn:mace:dir:attribute-def:carLicense carLicense
104 urn:oid:2.16.840.1.113730.3.1.1 carLicense
105 urn:mace:dir:attribute-def:departmentNumber departmentNumber
106 urn:oid:2.16.840.1.113730.3.1.2 departmentNumber
107 urn:mace:dir:attribute-def:displayName displayName
108 urn:oid:2.16.840.1.113730.3.1.3 employeeNumber
109 urn:mace:dir:attribute-def:employeeNumber employeeNumber
110 urn:oid:2.16.840.1.113730.3.1.4 employeeType
111 urn:mace:dir:attribute-def:employeeType employeeType
112 urn:oid:2.16.840.1.113730.3.1.39 preferredLanguage
113 urn:mace:dir:attribute-def:preferredLanguage preferredLanguage
114 urn:oid:2.16.840.1.113730.3.1.241 displayName
115 urn:mace:dir:attribute-def:manager manager
116 urn:oid:0.9.2342.19200300.100.1.10 manager
117 urn:mace:dir:attribute-def:seeAlso seeAlso
118 urn:oid:2.5.4.34 seeAlso
119 urn:mace:dir:attribute-def:facsimileTelephoneNumber facsimileTelephoneNumber
120 urn:oid:2.5.4.23 facsimileTelephoneNumber
121 urn:mace:dir:attribute-def:street street
122 urn:oid:2.5.4.9 street
123 urn:mace:dir:attribute-def:postOfficeBox postOfficeBox
124 urn:oid:2.5.4.18 postOfficeBox
125 urn:mace:dir:attribute-def:postalCode postalCode
126 urn:oid:2.5.4.17 postalCode
127 urn:mace:dir:attribute-def:st st
128 urn:oid:2.5.4.8 st
129 urn:mace:dir:attribute-def:l l
130 urn:oid:2.5.4.7 l
131 urn:mace:dir:attribute-def:o o
132 urn:oid:2.5.4.10 o
133 urn:mace:dir:attribute-def:ou ou
134 urn:oid:2.5.4.11 ou
135 urn:mace:dir:attribute-def:businessCategory businessCategory
136 urn:oid:2.5.4.15 businessCategory
137 urn:mace:dir:attribute-def:physicalDeliveryOfficeName physicalDeliveryOfficeName
138 urn:oid:2.5.4.19 physicalDeliveryOfficeName
139 |
140 );
141  
142 ######
143 # %elements
144 # Hash of how to parse XML
145 # (
146 # NameSpace1 =>
147 # {
148 # ElementInNamespace1 =>
149 # {
150 # "Elements" => { ChildElement => /parse|try|dump|text/, ... },
151 # "Attributes" => { AttributeName => /required|optional/, ... },
152 # "RE" => 'RegularExpression for elements (think DTD) NB Namespaces from knownns are expected'
153 # },
154 # ...
155 # },
156 # ...
157 # )
158 #
159 # ideally we'd parse the xsd and create this hash table; for now defined inline below
160 #
161 my %elements = (
162 "urn:oasis:names:tc:SAML:1.0:protocol" => {
163 "Response" =>
164 { Elements => { qw/Status parse Assertion parse Signature dump/ },
165 Attributes => { qw/MajorVersion required MinorVersion required ResponseID required Recipient optional InResponseTo optional IssueInstant required/ },
166 RE => '((ds:Signature )?(saml1p:Status )(saml1:Assertion )*|(saml1p:Status )(saml1:Assertion )*(ds:Signature )?)'
167 },
168 "Status" =>
169 { Elements => { qw/StatusCode parse StatusMessage parse StatusDetail parse/ },
170 RE => '(saml1p:StatusCode )(saml1p:StatusMessage )?(saml1p:StatusDetail )?'
171 },
172 "StatusDetail" =>
173 { Elements => { qw/* dump/ },
174 RE=>'*'
175 },
176 "StatusCode" => { Attributes => { qw/Value required/ } },
177 "StatusMessage" => { Elements => { '' => 'text' } }
178 },
179 'urn:oasis:names:tc:SAML:1.0:assertion' => {
180 "Assertion" =>
181 { Elements => { qw/Conditions parse Advice parse Subject parse AuthenticationStatement parse AuthorisationDecisionStatement parse AttributeStatement parse Signature dump/ },
182 Attributes => { qw/MajorVersion required MinorVersion required AssertionID required Issuer required IssueInstant required/ },
183 RE=>'(saml1:Conditions )?(saml1:Advice )?(saml1:Subject |saml1:AuthenticationStatement |saml1:AuthorisationDecisionStatement |saml1:AttributeStatement )+(ds:Signature )?'
184 },
185 "Conditions" =>
186 { Elements => { qw/AudienceRestrictionCondition parse DoNotCacheCondition parse * dump/ },
187 Attributes => { qw/NotBefore required NotOnOrAfter required/ },
188 RE=>'(saml1:AudienceRestrictionCondition |saml1:DoNotCacheCondition |[\w:]+ | )'
189 },
190 'DoNotCacheCondition' => { }, #Well it's just ziz node you know
191 'AudienceRestrictionCondition' =>
192 { Elements => { qw/Audience parse/ },
193 RE=>'(saml1:Audience )+'
194 },
195 "Subject" =>
196 { Elements => { qw/NameIdentifier parse SubjectConfirmation parse/ },
197 RE=>'(saml1:NameIdentifier |saml1:NameIdentifier saml1:SubjectConfirmation |saml1:SubjectConfirmation )'
198 },
199 'SubjectConfirmation' =>
200 { Elements => { qw/ConfirmationMethod parse SubjectConfirmationData parse KeyInfo dump/ },
201 RE=>'(saml1:ConfirmationMethod )+(saml1:SubjectConfirmationData )?(ds:KeyInfo )?'
202 },
203 'AuthenticationStatement' =>
204 { Elements => { qw/Subject parse SubjectLocality parse AuthorityBinding parse/ },
205 Attributes => { qw/AuthenticationMethod required AuthenticationInstant required/ },
206 RE=>'((saml1:Subject )(saml1:SubjectLocality )?(saml1:AuthorityBinding )*|(saml1:SubjectLocality )?(saml1:AuthorityBinding )*(saml1:Subject ))'
207 },
208 'AuthorisationDecisionStatement' =>
209 { Elements => { qw/Subject parse Action parse Evidence parse/ },
210 Attributes => { qw/Resource required Decision required/ },
211 RE=>'((saml1:Subject )(saml1:Action )*(saml1:Evidence )?|(saml1:Action )*(saml1:Evidence )?(saml1:Subject ))'
212 },
213 'Evidence' =>
214 { Elements => { qw/Assertion parse AssertionIDReference parse/ },
215 RE=>'(saml1:Assertion |saml1:AssertionIDReference )+'
216 },
217 'AssertionIDReference' => { Elements => { '' => 'text' } },
218 'AttributeStatement' =>
219 { Elements => { qw/Subject parse Attribute parse/ },
220 RE=>'((saml1:Subject )(saml1:Attribute )+|(saml1:Attribute )+|(saml1:Subject ))'
221 },
222 'Attribute' =>
223 { Elements => { qw/AttributeValue parse/ },
224 Attributes => { qw/AttributeName required AttributeNamespace required/ },
225 RE=>'(saml1:AttributeValue )+'
226 },
227 'Audience' => { Elements => { '' => 'text' } },
228 'NameIdentifier' =>
229 { Elements => { '' => 'text' },
230 Attributes => { qw/NameQualifier optional Format optional/ }
231 },
232 'ConfirmationMethod' => { Elements => { '' => 'text' } },
233 'AttributeValue' =>
234 { Elements => { qw/* try/ },
235 Attributes => { qw/* optional/ },
236 RE=>'*'
237 },
238 'SubjectLocality' => { Attributes => { qw/IPAddress optional DNSAddress optional/ } }
239 },
240 'urn:oasis:names:tc:SAML:2.0:protocol' => {
241 "Response" =>
242 { Elements => { qw/Issuer parse Signature dump Extension dump Status parse Assertion parse EncryptedAssertion parse/ } ,
243 Attributes => { qw/ID required InResponseTo optional Version required IssueInstant required Destination optional Consent optional/ },
244 RE => '((saml2:Issuer )?(ds:Signature )?(saml2p:Extension )?(saml2p:Status )(saml2:Assertion |saml2:EncryptedAssertion )*'.
245 '|(saml2:Assertion |saml2:EncryptedAssertion )*(saml2:Issuer )?(ds:Signature )?(saml2:Extension )?(saml2:Status ))'
246 },
247 "Status" =>
248 { Elements => { qw/StatusCode parse StatusMessage parse StatusDetail parse/},
249 RE => '(saml2p:StatusCode )(saml2p:StatusMessage )?(saml2p:StatusDetail )?'
250 },
251 "StatusDetail" =>
252 { Elements => { qw/* dump/ },
253 RE => '*'
254 },
255 "StatusCode" =>
256 { Elements => { qw/StatusCode parse/ },
257 Attributes => {qw/Value required/},
258 RE=>'(saml2p:StatusCode | )'
259 },
260 "StatusMessage" => { Elements => { '' => 'text' } }
261 },
262 'urn:oasis:names:tc:SAML:2.0:assertion' => {
263 'EncryptedAssertion' =>
264 { Elements => { qw/EncryptedData dump EncryptedKey dump/ },
265 RE=>'(xenc:EncryptedData )(xenc:EncryptedKey )*'
266 },
267 'Assertion' =>
268 { Elements => { qw/Issuer parse Signature dump Subject parse Conditions parse Advice parse AuthnStatement parse AuthzDecisionStatement parse AttributeStatement parse/ },
269 Attributes => { qw/Version required ID required IssueInstant required/},
270 RE=>'(saml2:Issuer )(ds:Signature )?(saml2:Subject )?(saml2:Conditions )?(saml2:Advice )?(saml2:AuthnStatement |saml2:AuthzDecisionStatement |saml2:AttributeStatement )*'
271 },
272 'Issuer' =>
273 { Elements => { '' => 'text' },
274 Attributes => { qw/Format optional SPProvidedID optional NameQualifier optional SPNameQualifier optional/}
275 },
276 'Subject' =>
277 { Elements => { qw/BaseID parse NameID parse EncryptedID parse SubjectConfirmation parse/ },
278 RE=>'(((saml2:BaseID |saml2:NameID |saml2:EncryptedID )(saml2:SubjectConfirmation )*?)(saml2:SubjectConfirmation )+'.
279 '|(saml2:SubjectConfirmation )+((saml2:BaseID |saml2:NameID |saml2:EncryptedID )(saml2:SubjectConfirmation )*))'
280 },
281 'BaseID' => { Attributes => { qw/NameQualifier optional SPNameQualifier optional/ } },
282 'NameID' =>
283 { Elements => { '' => 'text' },
284 Attributes => { qw/Format optional SPProvidedID optional NameQualifier optional SPNameQualifier optional/ }
285 },
286 'EncryptedID' =>
287 { Elements => { qw/EncryptedData dump EncryptedKey dump/ },
288 RE=>'(xenc:EncryptedData )(xenc:EncryptedKey )*'
289 },
290 'SubjectConfirmation' =>
291 { Attributes => { qw/Method required/ },
292 Elements => { qw/BaseID parse NameID parse EncryptedID parse SubjectConfirmationData parse/ },
293 RE=>'(saml2:BaseID |saml2:NameID |saml2:EncryptedID )?(saml2:SubjectConfirmationData )?'
294 },
295 'SubjectConfirmationData' =>
296 { Attributes => { qw/* optional/ },
297 Elements => { qw/* dump/ },
298 RE=>'*'
299 },
300 'Conditions' =>
301 { Attributes => { qw/NotBefore optional NotOnOrAfter optional/ },
302 Elements => { qw/AudienceRestriction parse OneTimeUse parse ProxyRestriction parse/ },
303 RE=>'(saml2:Condition |saml2:AudienceRestriction |saml2:OneTimeUse |saml2:ProxyRestriction | )*'
304 },
305 'AudienceRestriction' =>
306 { Elements => { qw/Audience parse/ },
307 RE=>'(saml2:Audience )+'
308 },
309 'Audience' => { Elements => { '' => 'text' } },
310 'OneTimeUse' => { RE=>' ' },
311 'ProxyRestriction' =>
312 { Elements => { qw/Audience parse/ },
313 Attributes => { qw/Count optional/ },
314 RE=>'(saml2:Audience )*'
315 },
316 'Advice' =>
317 { Elements => { qw/AssertionIDRef parse AssertionURIRef parse Assertion parse EncryptedAssertion parse * dump/ },
318 RE=>'(saml2:AssertionIDRef |saml2:AssertionURIRef |saml2:Assertion |saml2:EncryptedAssertion |[\w:]* )*'
319 },
320 'AssertionIDRef' => { Elements => { '' => 'text' } },
321 'AssertionURIRef' => { Elements => { '' => 'text' } },
322 'AuthnStatement' =>
323 { Elements => { qw/SubjectLocality parse AuthnContext parse/ },
324 Attributes => { qw/AuthnInstant required SessionIndex optional SessionNotOnOrAfter optional/ },
325 RE=>'(saml2:SubjectLocality )?(saml2:AuthnContext )'
326 },
327 'SubjectLocality' => { Attributes => { qw/Address optional DNSName optional/ } },
328 'AuthnContext' =>
329 { Elements => { qw/AuthnContextClassRef parse AuthnContextDecl parse AuthnContextDeclRef parse AuthenticatingAuthority parse/ },
330 RE=>'((saml2:AuthnContextClassRef )(saml2:AuthnContextDecl |saml2:AuthnContextDeclRef )?|(saml2:AuthnContextDecl |saml2:AuthnContextDeclRef ))(saml2:AuthnticatingAuthority )*'
331 },
332 'AuthnContextClassRef' => { Elements => { '' => 'text' } },
333 'AuthnContextDecl' => { Elements => { qw/* dump/ } },
334 'AuthnContextDeclRef' => { Elements => { '' => 'text' } },
335 'AuthenticatingAuthority' => { Elements => { '' => 'text' } },
336 'AuthzDecisionStatement' =>
337 { Attributes => { qw/Resource required Decision required/ },
338 Elements => { qw/Action parse Evidence parse/ },
339 RE=>'(saml2:Action )+(saml2:Evidence )?'
340 },
341 'Action' => { Attributes => { qw/Namespace required/ } },
342 'Evidence' =>
343 { Elements => { qw/AssertionIDRef parse AssertionURIRef parse Assertion parse EncryptedAssertion parse/ },
344 RE=>'(saml2:AssertionIDRef |saml2:AssertionURIRef |saml2:Assertion |saml2:EncryptedAssertion )+'
345 },
346 'AttributeStatement' =>
347 { Elements => { qw/Attribute parse EncryptedAttribute parse/ },
348 RE=>'(saml2:Attribute |saml2:EncryptedAttribute )+'
349 },
350 'Attribute' =>
351 { Attributes => { qw/Name required NameFormat optional FriendlyName optional * optional/ },
352 Elements => { qw/AttributeValue parse/ },
353 RE=>'(saml2:AttributeValue | )*'
354 },
355 'AttributeValue' =>
356 { Attributes => { qw/* optional/ },
357 Elements => { qw/* try/ },
358 RE=>'*'
359 },
360 'EncryptedAttribute' =>
361 { Elements => { qw/EncryptedData dump EncryptedKey dump/ },
362 RE=>'(xenc:EncryptedData )(xenc:EncryptedKey )*'
363 }
364 }
365 );
366  
367 ##################################################
368 # parseSAML
369 #
370 # Expects serialised xml on in $_[0].
371 # Called in scalar context returns 1 if successfully parsed 0 otherwise.
372 # Called in array context returns a copy of the parsed object array.
373 # If $_[1] is set to an array reference this is used to prime
374 # and pass the parsed object array back.
375 #
376 # Creates new XML::Parser
377 # Uses getNode to abstractly parse root node
378 # Uses parseElement to parse this abstract root node
379 #
380 # Parsed object is represented as an array of XPath-like data stings
381 # (one array element per data value i.e. may contain \n).
382 #
383 # e.g.
384 # /path/to/node (namespace)
385 # /path/to/node{attribute} (attribute.namespace.if.any) = attributevalue
386 # ...
387 # /path/to/node TextContentIfAny
388 # /path/to/node/subnode (namesapce)
389 # /path/to/node/subnode{attribute} (attribute.namespace.if.any) = attributevalue
390 # ...
391 # /path/to/node/subnode TextContentIfAny
392 # /path/to/node/subnode/subsubnode...
393 # /path/to/node2 (namespace)
394 # ...
395 #
396 # namespaces will be consumed and returned only in parenthases
397 #
398  
399 sub parseSAML {
400 my $data = shift;
401 my @elements;
402 my $elements=\@elements;
403 if ( $_[0] && ref($_[0]) eq "ARRAY" ) { $elements = shift; }
404 my $parser = new XML::Parser( Style => 'Tree' );
405 my $tree=$parser->parse($data);
406 my $rootref=getNode($tree);
407 my $ret=parseElement($rootref,$elements);
408 return wantarray ? @$elements : $ret;
409 }
410  
411 ###################
412 # Try to normalise the responces from SAML 1 and SAML2 worlds
413 #
414 sub getSAMLAttributes {
415 my $data = shift;
416 my ($start,$type)=(0,0);
417 my @a;
418 my @b;
419 my $scope="";
420 my @Warnings=();
421  
422 my ($ResponseID,$StatusCodeValue,$NotOnOrAfter,$NotBefore,$NameIdentifier);
423  
424 foreach ( parseSAML($data) ) {
425 if ( m|/Response{ID} \(\) = (.*)| ) {$ResponseID=$1;}
426 elsif ( m|/Response{ResponseID} \(\) = (.*)| ) {$ResponseID=$1;}
427 elsif ( m|/Response/Status/StatusCode\{Value\} \(\) = .*?([^:]*)$| ) {$StatusCodeValue=$1;}
428 elsif ( m|(?:/Response)?/Assertion/Conditions\{NotOnOrAfter\} \(\) = (.*)| ) {$NotOnOrAfter=$1;}
429 elsif ( m|(?:/Response)?/Assertion/Conditions\{NotBefore\} \(\) = (.*)| ) {$NotBefore=$1;}
430 elsif ( m|(?:/Response)?/Assertion/Subject/NameID = (.*)| ) {$NameIdentifier=$1;}
431 elsif ( m|(?:/Response)?/Assertion/(?:AttributeStatement\|AuthenticationStatement)/Subject/NameIdentifier = (.*)| )
432 {$NameIdentifier=$1;}
433  
434 if ( m|^\S+ \*\* Error\: | ) {push @Warnings, $1;}
435  
436 elsif ( m|/Assertion/AttributeStatement/Attribute| ) {
437 if ( m|/Assertion/AttributeStatement/Attribute \(urn:oasis:names:tc:SAML:1.0:assertion\)| ) { $type=1; push @a,{}; }
438 elsif ( m|/Assertion/AttributeStatement/Attribute \(urn:oasis:names:tc:SAML:2.0:assertion\)| ) { $type=2; push @a,{}; }
439  
440 elsif ( $type==2 && m|/Assertion/AttributeStatement/Attribute{Name} \([^)]*\) = (.*)| ) {
441 $a[-1]->{Name}=$1;
442 $a[-1]->{FriendlyName}=(defined $attributes{$a[-1]->{Name}})?"$attributes{$a[-1]->{Name}}":"$a[-1]->{Name}";
443 @{$a[-1]->{Value}}=();
444 }
445 elsif ( $type==2 && m|/Assertion/AttributeStatement/Attribute/AttributeValue \([^)]*\)| ) { push @{$a[-1]->{Value}},undef; }
446 elsif ( $type==2 && m|/Assertion/AttributeStatement/Attribute/AttributeValue = (.*)| ) {
447 ${$a[-1]->{Value}}[-1]=$1;
448 push @b,((defined $attributes{$a[-1]->{Name}})?"$attributes{$a[-1]->{Name}}":"$a[-1]->{Name}")." = $1"; }
449  
450 elsif ( $type==1 && m|/Assertion/AttributeStatement/Attribute{AttributeName} \([^)]*\) = (.*)| ) {
451 $a[-1]->{Name}=$1;
452 $a[-1]->{FriendlyName}=(defined $attributes{$a[-1]->{Name}})?"$attributes{$a[-1]->{Name}}":"$a[-1]->{Name}";
453 @{$a[-1]->{Value}}=();
454 }
455 elsif ( $type==1 && m|/Assertion/AttributeStatement/Attribute/AttributeValue \([^)]*\)| ) { push @{$a[-1]->{Value}},undef; }
456 elsif ( $type==1 && m|/Assertion/AttributeStatement/Attribute/AttributeValue{Scope} \([^)]*\) = (.*)| ) { $scope="\@$1"; }
457 elsif ( $type==1 && m|/Assertion/AttributeStatement/Attribute/AttributeValue = (.*)| ) {
458 $a[-1]->{Value}->[-1]="$1$scope";
459 push @b,((defined $attributes{$a[-1]->{Name}})?"$attributes{$a[-1]->{Name}}":"$a[-1]->{Name}")." = $1$scope";
460 $scope="";
461 }
462 }
463 }
464  
465 my %a;
466 foreach (@a) { push @{ $a{$_->{'FriendlyName'}} },@{ $_->{'Value'} }; }
467  
468 return {
469 Attributes=>\%a,
470 ResponseID=>$ResponseID,
471 Status=>$StatusCodeValue,
472 NotOnOrAfter=>$NotOnOrAfter,
473 NotBefore=>$NotBefore,
474 Subject=>$NameIdentifier,
475 Warnings=>\@Warnings
476 };
477  
478 # return @b;
479 }
480  
481 ###################################################
482  
483 sub getNode {
484 my $in=shift; #Reference to Array
485 my $inns=shift; #Reference to Namespace Array #################
486 my @array=@{$in}; #copy array
487 my $qname=shift(@array); #1st element is the name
488 my $contentsref=shift(@array); #2nd element is the Contents Array in the form: $ref = [ \%Attributes , ($Name, @Contents)* ] -- as per tree parsing of XML
489 my @contents=@$contentsref;
490 # shift the attributes off the array
491 my $attributesref=shift(@contents); #Get the Attributes
492 my %attributes=($attributesref)?%$attributesref:();
493 # Reconstruct Namespase Hierarchy
494 my %NameSpaces=(defined $inns)?%{$inns}:(); # inherit namespaces
495 foreach ( keys %attributes ) { if ( /^xmlns()$/ or /^xmlns:([\w-]+)/ ) {$NameSpaces{$1}=$attributes{$&}; } }
496 my ($NSToken,$name,$namespace) = ("","","");
497 if ( ! $qname ) { $qname = ""; } # just a text node
498 elsif ( $qname =~ /^(?:([\w-]+):)(\w+)$/ ) { ($NSToken,$name) = ($1,$2);}
499 else { ($NSToken,$name) = ("",$qname);}
500 # Infer Namespace for this element
501 $namespace=$NameSpaces{$NSToken};
502 return { Name => $name,
503 QName => $qname,
504 Attributes => \%attributes,
505 Contents => \@contents,
506 NameSpaces => \%NameSpaces,
507 NameSpaceToken => $NSToken,
508 NameSpace => $namespace
509 };
510 }
511  
512 sub getChildNodes {
513 my $in=shift; # Hash as returned by getNode
514 my %hash=%{$in}; # copy hash
515 my @Contents=@{$hash{Contents}}; #
516 my %NameSpaces = %{$hash{NameSpaces}};
517 my @Children;
518 for ( my $i=0;$i<@Contents;$i+=2 ) {
519 if ( $Contents[$i] ) {
520 my @tmp = ( $Contents[$i], $Contents[$i+1] );
521 my $ref = getNode(\@tmp,\%NameSpaces);
522 push @Children,$ref;
523 } else {
524 push @Children, { TextNode => 1, Contents => $Contents[$i+1] };
525 }
526 }
527 return @Children;
528 }
529  
530 #########################################################
531 # CheckNodes
532 #
533 # Given a node $_[0], checks a string constructed from its children element names and namespace tokens against a regular experssion $_[1]
534 # namespace tokens and element names are converted into NameSpaceURI:elementName via lookup in %knownns
535 #
536  
537 sub CheckNodes {
538 my $ref=shift;
539 my $RE=shift;
540 my $name=$knownns{$ref->{NameSpace}}.":".$ref->{Name};
541 my $Children=join(' ', grep { !/^$/ } map { (($_->{Name})?$knownns{$_->{NameSpace}}.":".$_->{Name}:"") } getChildNodes($ref))." ";
542 if ( $Children !~ /^$RE$/ ) { return 0; }
543 return 1;
544 }
545  
546 #########################################################
547 # parseElement
548 #
549 # Expects reference to an element hash in $_[0] (as returned by getNode)
550 # Expects reference to an array $_[1] for output.
551 # Returns 1 if tree parsing was succesful 0 otherwise.
552 #
553 # Consults %elements using the element's $_[0]->{NameSpace} and $_[0]->{Name} values for
554 # A regular expression $RE to be used in CheckNodes subroutine
555 # A hash %Elements to be used in defining how to parse child nodes in subsequent calls to parseElement
556 # A hash %Attributes to be used in getAttributes subroutine
557 #
558 # Checks child elements
559 # Appends statement about namespace to output array
560 # gets/checks attributes of element via call to getChildNodes subrouting
561 # parses child elements via subsequent calls to parseElement
562 # parses text nodes appending details to the output array
563 #
564  
565 sub parseElement {
566 my $ref=shift;
567 my $elements = shift;
568 my $ret=1;
569  
570 my $RE = ($elements{$ref->{NameSpace}}->{$ref->{Name}}->{RE}) ? $elements{$ref->{NameSpace}}->{$ref->{Name}}->{RE} : " ";
571 my %Elements = ($elements{$ref->{NameSpace}}->{$ref->{Name}}->{Elements}) ? %{$elements{$ref->{NameSpace}}->{$ref->{Name}}->{Elements}} : ();
572 my %Attributes = ($elements{$ref->{NameSpace}}->{$ref->{Name}}->{Attributes}) ? %{$elements{$ref->{NameSpace}}->{$ref->{Name}}->{Attributes}} : ();
573  
574 my @elements = (" ($ref->{NameSpace})");
575  
576 unless ( $RE eq '*' || CheckNodes($ref,$RE) ) { push @elements, " ** Error: Unexpected Nodes in $ref->{Name}"; $ret=0; }
577  
578 #Parse Atrributes
579 unless ( getAttributes(\@elements, $ref, %Attributes ) ) { push @elements, " ** Error: Attribute parsing failed in $ref->{Name}"; $ret=0;}
580  
581 #Parse Child Nodes
582 foreach my $cref ( getChildNodes($ref) ) {
583 if ( defined $cref->{TextNode} && defined $Elements{''} && $Elements{''} eq "text" && $cref->{Contents} =~ /^\s*(.*?)\s*$/s ) { push @elements, " = $1";}
584 elsif ( defined $cref->{TextNode} && defined $Elements{'*'} && $Elements{'*'} eq "dump" && $cref->{Contents} =~ /^\s*(\S.*?)\s*$/s ) { push @elements, " = $1";}
585 elsif ( defined $cref->{TextNode} && defined $Elements{'*'} && $Elements{'*'} eq "try" && $cref->{Contents} =~ /^\s*(\S.*?)\s*$/s ) { push @elements, " = $1";}
586 elsif ( defined $cref->{TextNode} && $cref->{Contents} =~ /^\s*$/s ) { next; }
587 elsif ( ( defined $Elements{$cref->{Name}} && $Elements{$cref->{Name}} eq "parse" ) ||
588 ( defined $Elements{'*'} && $Elements{'*'} eq "parse" ) ) { unless ( parseElement($cref,\@elements) ) { $ret=0;} }
589 elsif ( ( defined $Elements{$cref->{Name}} && $Elements{$cref->{Name}} eq "try" ) ||
590 ( defined $Elements{'*'} && $Elements{'*'} eq "try" ) ) { parseElement($cref,\@elements) or push @elements, getNodeAsText($cref); }
591 elsif ( ( defined $Elements{$cref->{Name}} && $Elements{$cref->{Name}} eq "dump" ) ||
592 ( defined $Elements{'*'} && $Elements{'*'} eq "dump" ) ) { push @elements, getNodeAsText($cref); }
593 else { push @elements, " ** Error: $ref->{QName} has Unexpected Child Element $cref->{QName} - $Elements{$cref->{QName}}"; }
594 }
595  
596 push @$elements, map { "/$ref->{Name}$_" } @elements;
597  
598 return $ret;
599 }
600  
601 #########################################################
602 # getAttributes
603 # passed "elements" array by reference for appending to and returning $_[0]
604 # passed node details by reference (not altered) $_[1]
605 # passed hash of parsing rules for node attributes, via list $_[2 .. ]
606 # returns "elements" array with additional elements describing node's arrtibutes
607 #
608  
609 sub getAttributes {
610 my $elements=shift; # elements array to append to
611 my $ref=shift; # reference to element
612 my %req=@_; # hash of all required/optional XML attributes for this element
613 my $ret=1;
614  
615 # Search for each required element
616 foreach ( keys %req ) { if ( $_ eq "required" && ! $ref->{Attributes}->{$_} ) { $ret=0; } }
617  
618 # Handle Attribute Namespace declarations
619 my %NameSpaces=%{ $ref->{NameSpaces} }; # inherit namespaces
620 foreach ( keys %{ $ref->{Attributes} } ) { if ( /^xmlns()$/ or /^xmlns:([\w-]+)/ ) {$NameSpaces{$1}=$ref->{Attributes}->{$&}; } }
621 delete $NameSpaces{""}; # Attributes default namespace is implicite in element context not inherited
622  
623 foreach ( keys %{ $ref->{Attributes} } ) {
624 if ( /^(?:([\w-]+):|)(\w+)$/ && ( ! defined $1 || $1 ne "xmlns" ) && $_ ne "xmlns" ) { # seperate out attributes' namespaces and bypass namespace setting attributes (already handled)
625 my $name;
626 if ( ! $1 ) { $name = "\{$2\} ()"; }
627 elsif ( $NameSpaces{$1} ) { $name = "\{$2\} ($NameSpaces{$1})"; }
628 else { $name = "\{$2\} (Error Undefined Namespace $1)"; }
629  
630 if ( defined $req{$_} && $req{$_} eq "prohibited" ) { push @$elements, " ** Error: Prohibited Attribute $_"; $ret=0; }
631 elsif ( defined $req{'*'} && $req{'*'} eq "optional" ) { push @$elements, "$name = $ref->{Attributes}->{$_}"; }
632 elsif ( defined $req{$_} && $req{$_} eq "optional" ) { push @$elements, "$name = $ref->{Attributes}->{$_}"; }
633 elsif ( defined $req{$_} && $req{$_} eq "required" ) { push @$elements, "$name = $ref->{Attributes}->{$_}"; }
634 else { push @$elements, " ** Error: Unexpected Attribute $_"; $ret=0; }
635 }
636 }
637 return $ret;
638 }
639  
640 #####################################
641 # getNodeAsText
642 #
643 # Given a node returns it in a single element of an array as an XML node i.e. ( 'blah = <node attribute1="..." attribute2="...">[InnerXML]</node>' )
644 #
645  
646 sub getNodeAsText {
647 my $ref=shift;
648 my %ns=();
649 my @element = ( "/$ref->{Name} = ".getNodeContentsAsText($ref->{QName}, [ $ref->{Attributes} , @{$ref->{Contents}} ],\%ns) );
650 return @element;
651 }
652  
653 #####################################
654 # getNodeContentsAsText
655 #
656 # reconstructs (serialises) and returns node given: name [ {} , () ] as per tree parsed from XML::Parser
657 #
658 # *** could perhaps use this to canonicalize node for digest purposes?
659 #
660  
661 sub getNodeContentsAsText {
662 my $name = shift; #must
663 my $ref = shift; #must
664 my $nsref = shift; #may
665 my %ns = %{$nsref};
666 my @array = @{$ref};
667 my %attributes = (%{ shift @array },%ns);
668 my $str = "<$name";
669 if ( %attributes ) { foreach (sort keys %attributes) { $str.=" $_=\"$attributes{$_}\""; } }
670 if (@array) {
671 $str.=">";
672 for(my $i=0;$i<@array;$i+=2) {
673 if ($array[$i]) { $str.=getNodeContentsAsText($array[$i],$array[$i+1],$nsref); }
674 else { $str.=$array[$i+1]; }
675 }
676 $str.="</$name>";
677 }
678 else { $str .= "/>"}
679 return $str;
680 }
681  
682 __END__