-
Notifications
You must be signed in to change notification settings - Fork 461
Expand file tree
/
Copy pathsaml-xmlsec1.c
More file actions
1606 lines (1410 loc) · 45.7 KB
/
saml-xmlsec1.c
File metadata and controls
1606 lines (1410 loc) · 45.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*********************************************************
* Copyright (C) 2016-2022 VMware, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation version 2.1 and no later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
*********************************************************/
/**
* @file saml-xmlsec1.c
*
* Code for authenticating users based on SAML tokens.
*/
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
#include <libxml/parser.h>
#include <libxml/catalog.h>
#include <libxml/xmlschemas.h>
#include <libxml/xmlIO.h>
#include <libxml/uri.h>
#include <xmlsec/xmlsec.h>
#include <xmlsec/xmltree.h>
#include <xmlsec/xmldsig.h>
#include <xmlsec/templates.h>
#include <xmlsec/crypto.h>
#include <xmlsec/errors.h>
#include <glib.h>
#include "prefs.h"
#include "serviceInt.h"
#include "certverify.h"
#include "vmxlog.h"
static int gClockSkewAdjustment = VGAUTH_PREF_DEFAULT_CLOCK_SKEW_SECS;
static xmlSchemaPtr gParsedSchemas = NULL;
static xmlSchemaValidCtxtPtr gSchemaValidateCtx = NULL;
#define CATALOG_FILENAME "catalog.xml"
#define SAML_SCHEMA_FILENAME "saml-schema-assertion-2.0.xsd"
/*
******************************************************************************
* UserXmlFileOpen -- */ /**
*
* User defined version of libxml2 export xmlFileOpen.
*
* This function opens a file with its unescaped name only.
*
* xmlInitParser() calls xmlRegisterDefaultInputCallbacks() which calls
* xmlRegisterInputCallbacks(xmlFileMatch, xmlFileOpen,
* xmlFileRead, xmlFileClose)
*
* UserXmlFileOpen is registered at the end of the xmlInputCallback table by
* xmlRegisterInputCallbacks(xmlFileMatch, UserXmlFileOpen,
* xmlFileRead, xmlFileClose)
*
* Based on libxml2 xmlIO.c, precedence is given to user defined handlers.
*
* @param[in] filename The URI file name.
*
* @return A handler or NULL in case of failure.
******************************************************************************
*/
static void *
UserXmlFileOpen(const char *filename)
{
char *unescaped;
void *retval = NULL;
g_debug("%s: Incoming file name is \"%s\"\n", __FUNCTION__, filename);
unescaped = xmlURIUnescapeString(filename, 0, NULL);
if (unescaped != NULL) {
g_debug("%s: Opening file \"%s\"\n", __FUNCTION__, unescaped);
retval = xmlFileOpen(unescaped);
xmlFree(unescaped);
}
if (retval == NULL) {
g_warning("%s: Failed to open file \"%s\"\n", __FUNCTION__, filename);
/*
* Do not retry xmlFileOpen(filename) here.
* Calling system API to open escaped file paths is risky. This can
* cause unexpected not-secured paths being accessed and expose
* privilege escalation vulnerabilities.
*/
}
return retval;
}
/*
* Hack to test expired tokens and by-pass the time checks.
*
* Turning this on allows the VerifySAMLTokenFileTest() unit test
* which reads a token from the file to be fed an old token (eg
* from a log) and not have it fail because of the time-based
* assertions.
*
* Note that setting this *will* cause negative tests looking for
* time checks to fail.
*/
/* #define TEST_VERIFY_SIGN_ONLY 1 */
/*
******************************************************************************
* XmlErrorHandler -- */ /**
*
* Error handler for xml2.
*
* @param[in] ctx Context (unused).
* @param[in] msg The error message in printf format.
* @param[in] ... Any args for the msg.
*
******************************************************************************
*/
static void
XmlErrorHandler(void *ctx,
const char *msg,
...)
{
gchar msgStr[1024];
va_list argPtr;
va_start(argPtr, msg);
vsnprintf(msgStr, sizeof msgStr, msg, argPtr);
va_end(argPtr);
/*
* Treat all as warning.
*/
g_warning("XML Error: %s", msgStr);
VMXLog_Log(VMXLOG_LEVEL_WARNING, "XML Error: %s", msgStr);
}
/*
******************************************************************************
* XmlSecErrorHandler -- */ /**
*
* Error handler for xmlsec.
*
* @param[in] file The name of the file generating the error.
* @param[in] line The line number generating the error.
* @param[in] func The function generating the error.
* @param[in] errorObject The error specific object.
* @param[in] errorSubject The error specific subject.
* @param[in] reason The error code.
* @param[in] msg The additional error message.
*
******************************************************************************
*/
static void
XmlSecErrorHandler(const char *file,
int line,
const char *func,
const char *errorObject,
const char *errorSubject,
int reason,
const char *msg)
{
/*
* Treat all as warning. */
g_warning("XMLSec Error: %s:%s(line %d) object %s"
" subject %s reason: %d, msg: %s",
file, func, line,
errorObject ? errorObject : "<UNSET>",
errorSubject ? errorSubject : "<UNSET>",
reason, msg);
VMXLog_Log(VMXLOG_LEVEL_WARNING,
"XMLSec Error: %s:%s(line %d) object %s"
" subject %s reason: %d, msg: %s",
file, func, line,
errorObject ? errorObject : "<UNSET>",
errorSubject ? errorSubject : "<UNSET>",
reason, msg);
}
/*
******************************************************************************
* LoadCatalogAndSchema -- */ /**
*
* Loads the schemas for validation.
*
* Using a catalog here ala xmllint. Another option would be an
* additional schema acting like a catalog.
*
* @param[in] catPath Path to the catalog file.
* @param[in] schemaPath Path to the SAML schema file.
*
* return TRUE on success
******************************************************************************
*
*/
static gboolean
LoadCatalogAndSchema(void)
{
int ret;
gboolean retVal = FALSE;
xmlSchemaParserCtxtPtr ctx = NULL;
gchar *catalogPath = NULL;
gchar *schemaPath = NULL;
gchar *schemaDir = NULL;
schemaDir = Pref_GetString(gPrefs,
VGAUTH_PREF_SAML_SCHEMA_DIR,
VGAUTH_PREF_GROUP_NAME_SERVICE,
NULL);
if (NULL == schemaDir) {
#ifdef _WIN32
/*
* To make life easier for the Windows installer, assume
* the schema directory is next to the executable. Also
* check in ../ in case we're in a dev environment.
*/
schemaDir = g_build_filename(gInstallDir, "schemas", NULL);
if (!(g_file_test(schemaDir, G_FILE_TEST_EXISTS) &&
g_file_test(schemaDir, G_FILE_TEST_IS_DIR))) {
gchar *newDir = g_build_filename(gInstallDir, "..", "schemas", NULL);
Debug("%s: schemas not found in Windows install loc '%s',"
" trying dev location of '%s'\n", __FUNCTION__, schemaDir, newDir);
g_free(schemaDir);
schemaDir = newDir;
}
#else
/*
* TODO -- clean this up to make a better default for Linux.
*/
schemaDir = g_build_filename(gInstallDir, "..", "schemas", NULL);
#endif
}
Log("%s: Using '%s' for SAML schemas\n", __FUNCTION__, schemaDir);
catalogPath = g_build_filename(schemaDir, CATALOG_FILENAME, NULL);
schemaPath = g_build_filename(schemaDir, SAML_SCHEMA_FILENAME, NULL);
/*
* Skip calling xmlInitializeCatalog().
*
* xmlLoadCatalog() just adds to the default catalog, and won't return an
* error if it doesn't exist so long as a default catalog is set.
*
* So sanity check its existence.
*/
if (!g_file_test(catalogPath, G_FILE_TEST_EXISTS)) {
g_warning("Error: catalog file not found at \"%s\"\n", catalogPath);
retVal = FALSE;
goto done;
}
ret = xmlLoadCatalog(catalogPath);
if (ret < 0) {
g_warning("Error: Failed to load catalog at \"%s\"\n", catalogPath);
retVal = FALSE;
goto done;
}
ctx = xmlSchemaNewParserCtxt(schemaPath);
if (NULL == ctx) {
g_warning("Failed to create schema parser context\n");
retVal = FALSE;
goto done;
}
xmlSchemaSetParserErrors(ctx,
(xmlSchemaValidityErrorFunc) XmlErrorHandler,
(xmlSchemaValidityErrorFunc) XmlErrorHandler,
NULL);
gParsedSchemas = xmlSchemaParse(ctx);
if (NULL == gParsedSchemas) {
/*
* This shouldn't happen. Means somebody mucked with our
* schemas.
*/
g_warning("Error: Failed to parse schemas\n");
retVal = FALSE;
goto done;
}
/*
* Set up the validaton context for later use.
*/
gSchemaValidateCtx = xmlSchemaNewValidCtxt(gParsedSchemas);
if (NULL == gSchemaValidateCtx) {
g_warning("Failed to create schema validation context\n");
retVal = FALSE;
goto done;
}
xmlSchemaSetValidErrors(gSchemaValidateCtx,
XmlErrorHandler,
XmlErrorHandler,
NULL);
retVal = TRUE;
done:
if (NULL != ctx) {
xmlSchemaFreeParserCtxt(ctx);
}
g_free(catalogPath);
g_free(schemaPath);
g_free(schemaDir);
return retVal;
}
/*
******************************************************************************
* FreeSchemas -- */ /**
*
* Frees global schema data.
******************************************************************************
*
*/
static void
FreeSchemas(void)
{
if (NULL != gSchemaValidateCtx) {
xmlSchemaFreeValidCtxt(gSchemaValidateCtx);
gSchemaValidateCtx = NULL;
}
if (NULL != gParsedSchemas) {
xmlSchemaFree(gParsedSchemas);
gParsedSchemas = NULL;
}
}
/*
******************************************************************************
* LoadPrefs -- */ /**
*
* Loads any preferences SAML cares about.
******************************************************************************
*
*/
static void
LoadPrefs(void)
{
gClockSkewAdjustment = Pref_GetInt(gPrefs, VGAUTH_PREF_CLOCK_SKEW_SECS,
VGAUTH_PREF_GROUP_NAME_SERVICE,
VGAUTH_PREF_DEFAULT_CLOCK_SKEW_SECS);
Log("%s: Allowing %d of clock skew for SAML date validation\n",
__FUNCTION__, gClockSkewAdjustment);
}
/*
******************************************************************************
* SAML_Init -- */ /**
*
* Performs any initialization needed for SAML processing.
*
* @return VGAUTH_E_OK on success, VGAuthError on failure
*
******************************************************************************
*/
VGAuthError
SAML_Init(void)
{
int ret;
/*
* Init the xml parser
*/
xmlInitParser();
/*
* Verify the xml2 version -- if this is too old
* its fatal, so we may want to use a different check.
*/
LIBXML_TEST_VERSION
/*
* Tell libxml to do ID/REF lookups
* Tell libxml to complete attributes with defaults from the DTDs
*/
xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
xmlSubstituteEntitiesDefault(1);
/* set up the xml2 error handler */
xmlSetGenericErrorFunc(NULL, XmlErrorHandler);
/*
* Register user defined UserXmlFileOpen
*/
xmlRegisterInputCallbacks(xmlFileMatch, UserXmlFileOpen,
xmlFileRead, xmlFileClose);
/*
* Load schemas
*/
if (!LoadCatalogAndSchema()) {
g_warning("Failed to load schemas\n");
return VGAUTH_E_FAIL;
}
/* init xmlsec */
ret = xmlSecInit();
if (ret < 0) {
g_warning("xmlSecInit() failed %d\n", ret);
return VGAUTH_E_FAIL;
}
/*
* set up the error callback
*/
xmlSecErrorsSetCallback(XmlSecErrorHandler);
/*
* version check xmlsec1
*/
if (xmlSecCheckVersion() != 1) {
g_warning("Error: xmlsec1 lib version mismatch\n");
return VGAUTH_E_FAIL;
}
#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
/*
* Load the openssl crypto engine if we are supporting dynamic
* loading for xmlsec-crypto libraries.
*/
if(xmlSecCryptoDLLoadLibrary("openssl") < 0) {
g_warning("Error: unable to load openssl xmlsec-crypto library.\n "
"Make sure that you have xmlsec1-openssl installed and\n"
"check shared libraries path\n"
"(LD_LIBRARY_PATH) environment variable.\n");
VMXLog_Log(VMXLOG_LEVEL_WARNING,
"Error: unable to load openssl xmlsec-crypto library.\n "
"Make sure that you have xmlsec1-openssl installed and\n"
"check shared libraries path\n"
"(LD_LIBRARY_PATH) environment variable.\n");
return VGAUTH_E_FAIL;
}
#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */
/*
* init the xmlsec1 crypto app layer
*/
ret = xmlSecCryptoAppInit(NULL);
if (ret < 0) {
g_warning("xmlSecCryptoAppInit() failed %d\n", ret);
return VGAUTH_E_FAIL;
}
/*
* Do crypto-engine specific initialization
*/
ret = xmlSecCryptoInit();
if (ret < 0) {
g_warning("xmlSecCryptoInit() failed %d\n", ret);
return VGAUTH_E_FAIL;
}
/*
* Load prefs
*/
LoadPrefs();
Log("%s: Using xmlsec1 %d.%d.%d for XML signature support\n",
__FUNCTION__, XMLSEC_VERSION_MAJOR, XMLSEC_VERSION_MINOR,
XMLSEC_VERSION_SUBMINOR);
VMXLog_Log(VMXLOG_LEVEL_WARNING,
"%s: Using xmlsec1 %d.%d.%d for XML signature support\n",
__FUNCTION__, XMLSEC_VERSION_MAJOR, XMLSEC_VERSION_MINOR,
XMLSEC_VERSION_SUBMINOR);
return VGAUTH_E_OK;
}
/*
******************************************************************************
* SAML_Shutdown -- */ /**
*
* Performs any clean-up of resources allocated by SAML code.
*
******************************************************************************
*/
void
SAML_Shutdown()
{
FreeSchemas();
xmlSecCryptoShutdown();
xmlSecCryptoAppShutdown();
xmlSecShutdown();
#if 0
/*
* This is not thread safe:
* http://0pointer.de/blog/projects/beware-of-xmlCleanupParser
* and should only be called just before exit()
* Because of this, our symbol-checker hates it: See PR 407137
*/
xmlCleanupParser();
#endif
}
/*
******************************************************************************
* SAML_Reload -- */ /**
*
* Reload any in-memory state used by the SAML module.
*
******************************************************************************
*/
void
SAML_Reload()
{
FreeSchemas();
LoadPrefs();
LoadCatalogAndSchema();
}
/*
******************************************************************************
* FreeCertArray -- */ /**
*
* Frees a simple array of pemCert.
*
* @param[in] num Number of certs in array.
* @param[in] certs Array of certs to free.
*
******************************************************************************
*/
static void
FreeCertArray(int num,
gchar **certs)
{
int i;
for (i = 0; i < num; i++) {
g_free(certs[i]);
}
g_free(certs);
}
/*
******************************************************************************
* FindAttrValue -- */ /**
*
* Returns the value of a attribute in an XML node.
*
* @param[in] node XML subtree node.
* @param[in] attrName Name of the attribute.
*
* @return Attribute value if exists. The caller must free this with xmlFree().
*
******************************************************************************
*/
static xmlChar *
FindAttrValue(const xmlNodePtr node,
const gchar *attrName)
{
xmlAttrPtr attr;
xmlChar *name;
/*
* Find the attribute
*/
attr = xmlHasProp(node, attrName);
if ((attr == NULL) || (attr->children == NULL)) {
return NULL;
}
/*
* get the attribute value
*/
name = xmlNodeListGetString(node->doc, attr->children, 1);
return name;
}
/*
******************************************************************************
* RegisterID -- */ /**
*
* Register the document ID with the xml parser.
*
* This needs to be done if the document ID doesn't use the standard.
* Otherwise the signing fails when setting up the reference.
* SAML likes using 'ID' intead of the default 'xml:id', so
* this is needed for both signing and verification.
*
* This is a no-op if the schemas have been loaded since they
* set it up.
*
* See xmlsec1 FAQ 3.2
*
* Based on https://www.aleksey.com/pipermail/xmlsec/2003/001768.html
*
* @param[in] node The XML node on which to set the ID.
* @param[in] idName The name of the ID.
*
* @return TRUE on success.
******************************************************************************
*/
static gboolean
RegisterID(xmlNodePtr node,
const xmlChar *idName)
{
xmlAttrPtr attr;
xmlAttrPtr tmp;
xmlChar *name;
/*
* find pointer to id attribute
*/
attr = xmlHasProp(node, idName);
if ((attr == NULL) || (attr->children == NULL)) {
return FALSE;
}
/*
* get the attribute (id) value
*/
name = xmlNodeListGetString(node->doc, attr->children, 1);
if (name == NULL) {
return FALSE;
}
/*
* check that we don't have the id already registered
*/
tmp = xmlGetID(node->doc, name);
if (tmp != NULL) {
xmlFree(name);
/* no-op if its already there */
return TRUE;
}
/*
* finally register id
*/
xmlAddID(NULL, node->doc, name, attr);
xmlFree(name);
return TRUE;
}
/*
******************************************************************************
* FindNodeByName -- */ /**
*
* Searches under the specified node for one with a matching name.
*
* @param[in] root XML subtree root under which to search.
* @param[in] nodeName Name of node to find.
*
* @return matching xmlNodePtr or NULL. Caller should not free this node.
*
******************************************************************************
*/
static xmlNodePtr
FindNodeByName(xmlNodePtr root,
char *nodeName)
{
xmlNodePtr cur;
cur = root->children;
while (cur != NULL) {
if (cur->type == XML_ELEMENT_NODE) {
if (xmlStrEqual(nodeName, cur->name)) {
break;
}
}
cur = cur->next;
}
return cur;
}
/*
******************************************************************************
* FindAllNodesByName -- */ /**
*
* Searches under the specified node for all with a matching name.
*
* @param[in] root XML subtree root under which to search.
* @param[in] nodeName Name of node to find.
* @param[out] nodeName Array of matches.
*
* @return Number of matching nodes. Caller needs to free the array
* of Nodes, but not the nodes themselves.
*
******************************************************************************
*/
static int
FindAllNodesByName(xmlNodePtr root,
char *nodeName,
xmlNodePtr **nodes)
{
xmlNodePtr cur;
xmlNodePtr *list = NULL;
int count = 0;
cur = root->children;
while (cur != NULL) {
if (cur->type == XML_ELEMENT_NODE) {
if (xmlStrEqual(nodeName, cur->name)) {
list = g_realloc_n(list,
sizeof(xmlNodePtr),
count + 1);
list[count++] = cur;
}
}
cur = cur->next;
}
*nodes = list;
return count;
}
/*
******************************************************************************
* ValidateDoc -- */ /**
*
* Validates the XML document against the schema.
*
* @param[in] doc Parsed XML document.
*
******************************************************************************
*/
static gboolean
ValidateDoc(xmlDocPtr doc)
{
int ret;
ret = xmlSchemaValidateDoc(gSchemaValidateCtx, doc);
if (ret < 0) {
g_warning("Failed to validate doc against schema\n");
}
return (ret == 0) ? TRUE : FALSE;
}
/*
******************************************************************************
* CheckTimeAttr -- */ /**
*
* Checks that the given attribute with the given name is a timestamp and
* compares it against the current time.
*
* @param[in] node The node containing the attribute.
* @param[in] attrName The name of the attribute.
* @param[in] notBefore Whether the condition given by the attribute
* should be in the past or 'now' (TRUE).
*
******************************************************************************
*/
static gboolean
CheckTimeAttr(const xmlNodePtr node,
const gchar *attrName,
gboolean notBefore)
{
xmlChar *timeAttr;
GTimeVal attrTime;
GTimeVal now;
glong diff;
gboolean retVal;
timeAttr = FindAttrValue(node, attrName);
if ((NULL == timeAttr) || (0 == *timeAttr)) {
/*
* The presence of all time restrictions in SAML are optional, so if
* the attribute is not present, that is fine.
*/
retVal = TRUE;
goto done;
}
if (!g_time_val_from_iso8601(timeAttr, &attrTime)) {
g_warning("%s: Could not parse %s value (%s).\n", __FUNCTION__, attrName,
timeAttr);
retVal = FALSE;
goto done;
}
g_get_current_time(&now);
/*
* Check the difference, doing the math so that a positive
* value is bad. Ignore the micros field since precision
* is unnecessary here because we see unsynced clocks in
* the real world.
*/
if (notBefore) {
// expect time <= now
diff = attrTime.tv_sec - now.tv_sec;
} else {
// expect now <= time
diff = now.tv_sec - attrTime.tv_sec;
}
/*
* A negative value is fine, a postive value
* greater than the clock skew range is bad.
*/
if (diff > gClockSkewAdjustment) {
g_warning("%s: FAILED SAML assertion (timeStamp %s, delta %d) %s.\n",
__FUNCTION__, timeAttr, (int) diff,
notBefore ? "is not yet valid" : "has expired");
VMXLog_Log(VMXLOG_LEVEL_WARNING,
"%s: FAILED SAML assertion (timeStamp %s, delta %d) %s.\n",
__FUNCTION__, timeAttr, (int) diff,
notBefore ? "is not yet valid" : "has expired");
retVal = FALSE;
goto done;
}
retVal = TRUE;
done:
if (timeAttr) {
xmlFree(timeAttr);
}
return retVal;
}
/*
******************************************************************************
* CheckAudience -- */ /**
*
* Checks whether the given audience URI refers to this machine.
*
* @param[in] audience An audience URI that a token is targetted for.
*
* @return TRUE if the audience URI refers to this machine, FALSE otherwise.
*
******************************************************************************
*/
static gboolean
CheckAudience(const xmlChar *audience)
{
gboolean ret;
/*
* Our SSO server doesn't set Recipient, so this only gets used by test code
* whch uses a simple hostname check.
*
* Something like a VC UUID might be more accurate in a virtual
* machine.
*/
ret = strstr(audience, g_get_host_name()) != NULL;
g_debug("%s: audience check: token: '%s', host: '%s' ? %d\n",
__FUNCTION__,
audience, g_get_host_name(), ret);
return ret;
}
/*
******************************************************************************
* VerifySubject -- */ /**
*
* Extracts the name of the subject and enforces any conditions in
* SubjectConfirmation elements.
* Subjects are described in section 2.4 of the SAML Core specification.
*
* Example Subject XML:
* <saml:Subject>
* <saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">
* scott@example.org
* </saml:NameID>
* <saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">
* <saml:SubjectConfirmationData NotOnOrAfter="2011-12-08T00:42:10Z">
* </saml:SubjectConfirmationData>
* </saml:SubjectConfirmation>
* </saml:Subject>
*
* @param[in] doc The parsed SAML token.
* @param[out] subjectRet The Subject NameId. Should be g_free()d by
* caller.
*
* @return TRUE if the conditions in at least one SubjectConfirmation is met,
* FALSE otherwise.
*
******************************************************************************
*/
static gboolean
VerifySubject(xmlDocPtr doc,
gchar **subjectRet)
{
xmlNodePtr subjNode;
xmlNodePtr nameIDNode;
xmlNodePtr child;
gchar *subjectVal = NULL;
gboolean validSubjectFound = FALSE;
xmlChar *tmp;
if (NULL != subjectRet) {
*subjectRet = NULL;
}
subjNode = FindNodeByName(xmlDocGetRootElement(doc), "Subject");
if (NULL == subjNode) {
g_warning("No Subject node found\n");
goto done;
}
/*
* Pull out the NameID for later checks elsewhere.
*/
nameIDNode = FindNodeByName(subjNode, "NameID");
if (NULL == nameIDNode) {
g_warning("%s: NameID not found in Subject\n", __FUNCTION__);
goto done;
}
tmp = xmlNodeGetContent(nameIDNode);
subjectVal = g_strdup(tmp);
xmlFree(tmp);
/*
* Find all the SubjectConfirmation nodes and see if at least one
* can be validated.
*/
for (child = subjNode->children; child != NULL; child = child->next) {
xmlChar *method;
xmlNodePtr subjConfirmData;
if (child->type == XML_ELEMENT_NODE) {
if (!xmlStrEqual(child->name, "SubjectConfirmation")) {
continue;
}
method = FindAttrValue(child, "Method");
if ((NULL == method) || (0 == *method)) {
// should not happen since this is required
g_warning("%s: Missing SubjectConfirmation method\n", __FUNCTION__);
xmlFree(method);
goto done;
}
if (!xmlStrEqual(method, "urn:oasis:names:tc:SAML:2.0:cm:bearer")) {
g_warning("%s: method %s not bearer\n", __FUNCTION__, method);
xmlFree(method);
continue;
}
xmlFree(method);
subjConfirmData = FindNodeByName(child, "SubjectConfirmationData");
if (NULL != subjConfirmData) {
xmlChar *recipient;
if (!CheckTimeAttr(subjConfirmData, "NotBefore", TRUE) ||
!CheckTimeAttr(subjConfirmData, "NotOnOrAfter", FALSE)) {
g_warning("%s: subjConfirmData time check failed\n",
__FUNCTION__);
continue;
}
/*
* Recipient isn't always there.