readMetadata.php 14.1 KB
Newer Older
haemmer's avatar
haemmer committed
1
<?php // Copyright (c) 2011, SWITCH - Serving Swiss Universities
haemmer's avatar
haemmer committed
2
3
4
5

// This file is used to dynamically create the list of IdPs to be 
// displayed for the WAYF/DS service based on the federation metadata.
// Configuration parameters are specified in config.php.
haemmer's avatar
haemmer committed
6
7
8
9
//
// The list of Identity Providers can also be updated by running the script
// readMetadata.php periodically as web server user, e.g. with a cron entry like:
// 5 * * * * /usr/bin/php readMetadata.php > /dev/null
haemmer's avatar
haemmer committed
10

11
12
13
// Init log file
openlog("SWITCHwayf.readMetadata.php", LOG_PID | LOG_PERROR, LOG_LOCAL0);

haemmer's avatar
haemmer committed
14
// Make sure this script is not accessed directly
15
if(isRunViaCLI()){
haemmer's avatar
haemmer committed
16
17
18
	// Run in cli mode.
	// Could be used for testing purposes or to facilitate startup confiduration.
	// Results are dumped in $metadataIDPFile (see config.php)
19
20
21
22
23
	
	// Set dummy server name
	$_SERVER['SERVER_NAME'] = 'localhost';
	
	// Load configuration files
haemmer's avatar
haemmer committed
24
25
26
27
28
29
30
31
32
	require('config.php');
	require($IDPConfigFile);
	
	if (
		!isset($metadataFile) 
		|| !file_exists($metadataFile) 
		|| trim(@file_get_contents($metadataFile)) == '') {
	  exit ("Exiting: File ".$metadataFile." is empty or does not exist\n");
	}
33
	
34
35
36
37
38
39
40
	// Check configuration
	if (!isset($metadataSPFile)){
		$errorMsg = 'Please first define a file $metadataSPFile = \'SProvider.metadata.conf.php\'; in config.php before running this script.';
		syslog(LOG_ERR, $errorMsg);
		die($errorMsg);
	}
	
41
42
43
44
45
46
47
48
49
50
	// Get an exclusive lock to generate our parsed IdP and SP files.
	if (($lockFp = fopen($metadataLockFile, 'a+')) === false) {
		$errorMsg = 'Could not open lock file '.$metadataLockFile;
		die($errorMsg);
	}
	if (flock($lockFp, LOCK_EX) === false) { 
		$errorMsg = 'Could not lock file '.$metadataLockFile;
		die($errorMsg);
	}
	
51
52
	echo 'Parsing metadata file '.$metadataFile."\n";
	list($metadataIDProviders, $metadataSProviders) = parseMetadata($metadataFile, $defaultLanguage);
haemmer's avatar
haemmer committed
53
	
54
	// If $metadataIDProviders is not FALSE, dump results in $metadataIDPFile.
haemmer's avatar
haemmer committed
55
56
	if(is_array($metadataIDProviders)){ 
		
57
58
		echo 'Dumping parsed Identity Providers to file '.$metadataIDPFile."\n";
		dumpFile($metadataIDPFile, $metadataIDProviders, 'metadataIDProviders');
59
60
61
	}
	// If $metadataSProviders is not FALSE, dump results in $metadataSPFile.
	if(is_array($metadataSProviders)){ 
haemmer's avatar
haemmer committed
62
		
63
64
65
66
67
68
69
70
71
72
73
		echo 'Dumping parsed Service Providers to file '.$metadataSPFile."\n";
		dumpFile($metadataSPFile, $metadataSProviders, 'metadataSProviders');
	}

	// Release the lock, and close.
	flock($lockFp, LOCK_UN);
	fclose($lockFp);
		
	// If $metadataIDProviders is not FALSE, update $IDProviders and print the Identity Providers lists.
	if(is_array($metadataIDProviders)){ 

74
		echo 'Merging parsed Identity Providers with data from file '.$IDProviders."\n";
haemmer's avatar
haemmer committed
75
76
77
		$IDProviders = mergeInfo($IDProviders, $metadataIDProviders, $SAML2MetaOverLocalConf, $includeLocalConfEntries);
		
		echo "Printing parsed Identity Providers:\n";
78
79
80
		print_r($metadataIDProviders);
		
		echo "Printing effective Identity Providers:\n";
haemmer's avatar
haemmer committed
81
82
83
		print_r($IDProviders);
	}
	
84
	// If $metadataSProviders is not FALSE, update $SProviders and print the list.
85
86
87
88
89
90
91
92
93
	if(is_array($metadataSProviders)){ 
		
		// Fow now copy the array by reference
		$SProviders = &$metadataSProviders;
		
		echo "Printing parsed Service Providers:\n";
		print_r($metadataSProviders);
	}
	
haemmer's avatar
haemmer committed
94
	
95
} elseif (isRunViaInclude()) {
96
97
98
99
100
101
102
103
	
	// Check configuration
	if (!isset($metadataSPFile)){
		$errorMsg = 'Please first define a file $metadataSPFile = \'SProvider.metadata.conf.php\'; in config.php before running this script.';
		syslog(LOG_ERR, $errorMsg);
		die($errorMsg);
	}
	
haemmer's avatar
haemmer committed
104
105
106
107
108
109
	if (!isset($metadataFile)){
		$errorMsg = 'Please first define a file $metadataFile in config.php before running this script.';
		syslog(LOG_ERR, $errorMsg);
		die($errorMsg);
	}
	
110
111
112
113
114
115
	// Open the metadata lock file.
	if (($lockFp = fopen($metadataLockFile, 'a+')) === false) {
		$errorMsg = 'Could not open lock file '.$metadataLockFile;
		syslog(LOG_ERR, $errorMsg);
	}

116
	// Run as included file
haemmer's avatar
haemmer committed
117
	if(!file_exists($metadataIDPFile) or filemtime($metadataFile) > filemtime($metadataIDPFile)){
118
119
120
121
122
123
124
		// Get an exclusive lock to regenerate the parsed files.
		if ($lockFp !== false) {
			if (flock($lockFp, LOCK_EX) === false) { 
				$errorMsg = 'Could not get exclusive lock on '.$metadataLockFile;
				syslog(LOG_ERR, $errorMsg);
			}
		}
haemmer's avatar
haemmer committed
125
		// Regenerate $metadataIDPFile.
126
		list($metadataIDProviders, $metadataSProviders) = parseMetadata($metadataFile, $defaultLanguage);
haemmer's avatar
haemmer committed
127
128
129
130
		
		// If $metadataIDProviders is not an array (parse error in metadata),
		// $IDProviders from $IDPConfigFile will be used.
		if(is_array($metadataIDProviders)){
131
			dumpFile($metadataIDPFile, $metadataIDProviders, 'metadataIDProviders');
haemmer's avatar
haemmer committed
132
133
			$IDProviders = mergeInfo($IDProviders, $metadataIDProviders, $SAML2MetaOverLocalConf, $includeLocalConfEntries);
		}
134
135
136
137
138
139
		
		if(is_array($metadataSProviders)){
			dumpFile($metadataSPFile, $metadataSProviders, 'metadataSProviders');
			require($metadataSPFile);
		}
		
140
141
142
143
144
		// Release the lock.
		if ($lockFp !== false) {
			flock($lockFp, LOCK_UN);
		}

145
146
147
148
149
150
				// Now merge IDPs from metadata and static file
		$IDProviders = mergeInfo($IDProviders, $metadataIDProviders, $SAML2MetaOverLocalConf, $includeLocalConfEntries);
		
		// Fow now copy the array by reference
		$SProviders = &$metadataSProviders;
		
haemmer's avatar
haemmer committed
151
152
	} elseif (file_exists($metadataIDPFile)){
		
153
154
155
156
157
158
159
160
161
		// Get a shared lock to read the IdP and SP files
		// generated from the metadata file.
		if ($lockFp !== false) {
			if (flock($lockFp, LOCK_SH) === false) { 
				$errorMsg = 'Could not lock file '.$metadataLockFile;
				syslog(LOG_ERR, $errorMsg);
			}
		}

162
		// Read SP and IDP files generated with metadata
haemmer's avatar
haemmer committed
163
		require($metadataIDPFile);
164
		require($metadataSPFile);
haemmer's avatar
haemmer committed
165
	
166
167
168
169
170
		// Release the lock.
		if ($lockFp !== false) {
			flock($lockFp, LOCK_UN);
		}

171
172
173
174
175
176
		// Now merge IDPs from metadata and static file
		$IDProviders = mergeInfo($IDProviders, $metadataIDProviders, $SAML2MetaOverLocalConf, $includeLocalConfEntries);
		
		// Fow now copy the array by reference
		$SProviders = &$metadataSProviders;
	}
177
178
179
180
181

	// Close the metadata lock file.
	if ($lockFp !== false) {
		fclose($lockFp);
	}
182
	
haemmer's avatar
haemmer committed
183
184
185
186
} else {
	exit('No direct script access allowed');
}

haemmer's avatar
haemmer committed
187
188
closelog();

haemmer's avatar
haemmer committed
189
/*****************************************************************************/
190
191
// Function parseMetadata, parses metadata file and returns Array($IdPs, SPs)  or
// Array(false, false) if error occurs while parsing metadata file
haemmer's avatar
haemmer committed
192
193
function parseMetadata($metadataFile, $defaultLanguage){
	
194
	if(!file_exists($metadataFile)){
haemmer's avatar
haemmer committed
195
		$errorMsg = 'File '.$metadataFile." does not exist"; 
196
		if (isRunViaCLI()){
haemmer's avatar
haemmer committed
197
			echo $errorMsg."\n";
198
199
200
201
202
203
204
		} else {
			syslog(LOG_ERR, $errorMsg);
		}
		return Array(false, false);
	}

	if(!is_readable($metadataFile)){
haemmer's avatar
haemmer committed
205
206
207
208
209
210
		$errorMsg = 'File '.$metadataFile." cannot be read due to insufficient permissions"; 
		if (isRunViaCLI()){
			echo $errorMsg."\n";
		} else {
			syslog(LOG_ERR, $errorMsg);
		}
211
212
		return Array(false, false);
	}
haemmer's avatar
haemmer committed
213
	
214
215
	$doc = new DOMDocument();
	if(!$doc->load( $metadataFile )){
haemmer's avatar
haemmer committed
216
217
218
219
220
221
		$errorMsg = 'Could not parse metadata file '.$metadataFile; 
		if (isRunViaCLI()){
			echo $errorMsg."\n";
		} else {
			syslog(LOG_ERR, $errorMsg);
		}
222
223
224
225
226
227
228
229
230
		return Array(false, false);
	}
	
	$EntityDescriptors = $doc->getElementsByTagNameNS( 'urn:oasis:names:tc:SAML:2.0:metadata', 'EntityDescriptor' );
	
	$metadataIDProviders = Array();
	$metadataSProviders = Array();
	foreach( $EntityDescriptors as $EntityDescriptor ){
		$entityID = $EntityDescriptor->getAttribute('entityID');
haemmer's avatar
haemmer committed
231
		
232
		foreach($EntityDescriptor->childNodes as $RoleDescriptor) {
233
234
235
			$nodeName = $RoleDescriptor->nodeName;
 			$nodeName = preg_replace('/^(\w+\:)/', '', $nodeName);
 			switch($nodeName){
236
237
238
239
				case 'IDPSSODescriptor':
					$IDP = processIDPRoleDescriptor($RoleDescriptor);
					if ($IDP){
						$metadataIDProviders[$entityID] = $IDP;
haemmer's avatar
haemmer committed
240
					}
241
242
243
244
245
					break;
				case 'SPSSODescriptor':
					$SP = processSPRoleDescriptor($RoleDescriptor);
					if ($SP){
						$metadataSProviders[$entityID] = $SP;
246
247
					} else {
						$errorMsg = "Failed to load SP with entityID $entityID from metadata file $metadataFile";
haemmer's avatar
haemmer committed
248
249
250
251
252
						if (isRunViaCLI()){
							echo $errorMsg."\n";
						} else {
							syslog(LOG_WARNING, $errorMsg);
						}
253
					}
254
255
					break;
				default:
haemmer's avatar
haemmer committed
256
257
258
259
			}
		}
	}
	
haemmer's avatar
haemmer committed
260
261
262
263
264
265
266
267
268
269
	
	// Output result
	$infoMsg = "Successfully parsed metadata file ".$metadataFile. ". Found ".count($metadataIDProviders)." IdPs and ".count($metadataSProviders)." SPs";
	if (isRunViaCLI()){
		echo $infoMsg."\n";
	} else {
		syslog(LOG_INFO, $infoMsg);
	}
	
	
270
	return Array($metadataIDProviders, $metadataSProviders);
haemmer's avatar
haemmer committed
271
272
273
}

/******************************************************************************/
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Is this script run in CLI mode
function isRunViaCLI(){
	return !isset($_SERVER['REMOTE_ADDR']);
}

/******************************************************************************/
// Is this script run in CLI mode
function isRunViaInclude(){
	return basename($_SERVER['SCRIPT_NAME']) != 'readMetadata.php';
}

/******************************************************************************/
// Processes an IDPRoleDescriptor XML node and returns an IDP entry or false if 
// something went wrong
function processIDPRoleDescriptor($IDPRoleDescriptorNode){
haemmer's avatar
haemmer committed
289
290
	global $defaultLanguage;
	
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
	$IDP = Array();
	
	// Get SSO URL
	$SSOServices = $IDPRoleDescriptorNode->getElementsByTagNameNS( 'urn:oasis:names:tc:SAML:2.0:metadata', 'SingleSignOnService' );
	foreach( $SSOServices as $SSOService ){
		if ($SSOService->getAttribute('Binding') == 'urn:mace:shibboleth:1.0:profiles:AuthnRequest'){
			$IDP['SSO'] =  $SSOService->getAttribute('Location');
		}
	}
	
	// Set a default value for backward compatibility
	if (!isset($IDP['SSO'])){
		$IDP['SSO'] = 'https://no.saml1.sso.url.defined.com/error';
	}
	
	
	// Get Name
	$Orgnization = $IDPRoleDescriptorNode->parentNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'Organization' )->item(0);
	if ($Orgnization){
		// Get DisplayNames
		$DisplayNames = $Orgnization->getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'OrganizationDisplayName');
		foreach ($DisplayNames as $DisplayName){
			$lang = $DisplayName->getAttributeNodeNS('http://www.w3.org/XML/1998/namespace', 'lang')->nodeValue;
			$IDP['Name'] = $DisplayName->nodeValue;
			$IDP[$lang]['Name'] = $DisplayName->nodeValue;
		}
haemmer's avatar
haemmer committed
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
		// Set default name
		if (isset($IDP[$defaultLanguage])){
			$IDP['Name'] = $IDP[$defaultLanguage]['Name'];
		} elseif (isset($IDP['en'])){
			$IDP['Name'] = $IDP['en']['Name'];
		} else {
			$IDP['Name'] = $DisplayNames->item(0)->nodeValue;
		}
	} else {
		// Set entityID as Name if no organization is available
		$IDP['Name'] = $IDPRoleDescriptorNode->parentNode->getAttribute('entityID');
	}
	
	return $IDP;
}

/******************************************************************************/
// Processes an SPRoleDescriptor XML node and returns an SP entry or false if 
// something went wrong
function processSPRoleDescriptor($SPRoleDescriptorNode){
	$SP = Array();
	
	// Get <idpdisc:DiscoveryResponse> extensions
	$DResponses = $SPRoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol', 'DiscoveryResponse');
	foreach( $DResponses as $DResponse ){
		if ($DResponse->getAttribute('Binding') == 'urn:oasis:names:tc:SAML:profiles:SSO:idp-discovery-protocol'){
			$SP['DSURL'][] =  $DResponse->getAttribute('Location');
		}
	}
	
	// Get Assertion Consumer Services and store their hostnames
	$ACServices = $SPRoleDescriptorNode->getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:metadata', 'AssertionConsumerService');
	foreach( $ACServices as $ACService ){
		$SP['ACURL'][] =  $ACService->getAttribute('Location');
	}
	
	return $SP;
}

/******************************************************************************/
// Dump variable to a file 
function dumpFile($dumpFile, $providers, $variableName){
	 
	if(($fp = fopen($dumpFile, 'w')) !== false){
haemmer's avatar
haemmer committed
362
		
363
364
365
		fwrite($fp, "<?php\n\n");
		fwrite($fp, "// This file was automatically generated by readMetadata.php\n");
		fwrite($fp, "// Don't edit!\n\n");
haemmer's avatar
haemmer committed
366
		
367
368
369
370
371
		fwrite($fp, '$'.$variableName.' = ');
		fwrite($fp, var_export($providers,true));
		
		fwrite($fp, "\n?>");
			
372
		fclose($fp);
haemmer's avatar
haemmer committed
373
	} else {
haemmer's avatar
haemmer committed
374
375
376
377
378
379
		$errorMsg = 'Could not open file '.$dumpFile.' for writting';
		if (isRunViaCLI()){
			echo $errorMsg."\n";
		} else {
			syslog(LOG_ERR, $errorMsg);
		}
haemmer's avatar
haemmer committed
380
381
382
383
384
385
386
387
388
389
390
391
392
393
	}
}


/******************************************************************************/
// Function mergeInfo is used to create the effective $IDProviders array.
// For each IDP found in the metadata, merge the values from IDProvider.conf.php.
// If an IDP is found in IDProvider.conf as well as in metadata, use metadata  
// information if $SAML2MetaOverLocalConf is true or else use IDProvider.conf data
function mergeInfo($IDProviders, $metadataIDProviders, $SAML2MetaOverLocalConf, $includeLocalConfEntries){

	// If $includeLocalConfEntries parameter is set to true, mergeInfo() will also consider IDPs
	// not listed in metadataIDProviders but defined in IDProviders file
	// This is required if you need to add local exceptions over the federation metadata
394
395
	$allIDPS = $metadataIDProviders;
	$mergedArray = Array();
haemmer's avatar
haemmer committed
396
	if ($includeLocalConfEntries) {
397
		  $allIDPS = array_merge($metadataIDProviders, $IDProviders);
haemmer's avatar
haemmer committed
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
	
	foreach ($allIDPS as $allIDPsKey => $allIDPsEntry){
		if(isset($IDProviders[$allIDPsKey])){
			// Entry exists also in local IDProviders.conf.php
			if (isset($metadataIDProviders[$allIDPsKey]) && is_array($metadataIDProviders[$allIDPsKey])) {
				
				// Remove IdP if there is a removal rule in local IDProviders.conf.php 
				if (!is_array($IDProviders[$allIDPsKey])){
					unset($metadataIDProviders[$allIDPsKey]);
					continue;
				}
				
				// Entry exists in both IDProviders sources and is an array
				if($SAML2MetaOverLocalConf){
					// Metadata entry overwrite local conf
					$mergedArray[$allIDPsKey] = array_merge($IDProviders[$allIDPsKey], $metadataIDProviders[$allIDPsKey]);
				} else {
					// Local conf overwrites metada entry
					$mergedArray[$allIDPsKey] = array_merge($metadataIDProviders[$allIDPsKey], $IDProviders[$allIDPsKey]);
				}
			  } else {
					// Entry only exists in local IDProviders file
					$mergedArray[$allIDPsKey] = $IDProviders[$allIDPsKey];
			  }
haemmer's avatar
haemmer committed
423
		} else {
424
425
			// Entry doesnt exist in in local IDProviders.conf.php
			$mergedArray[$allIDPsKey] = $metadataIDProviders[$allIDPsKey];
haemmer's avatar
haemmer committed
426
427
428
429
430
431
432
		}
	}
	
	return $mergedArray;
}

?>