readMetadata.php 11.2 KB
Newer Older
haemmer's avatar
haemmer committed
1
2
3
4
5
6
7
<?php
/* 
 * 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
8
9
10
11
12
13
14
// 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
15
// Make sure this script is not accessed directly
16
if(isRunViaCLI()){
haemmer's avatar
haemmer committed
17
18
19
20
21
22
23
24
25
26
27
28
	// Run in cli mode.
	// Could be used for testing purposes or to facilitate startup confiduration.
	// Results are dumped in $metadataIDPFile (see config.php)
	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");
	}
29
30
31
	
	echo 'Parsing metadata file '.$metadataFile."\n";
	list($metadataIDProviders, $metadataSProviders) = parseMetadata($metadataFile, $defaultLanguage);
haemmer's avatar
haemmer committed
32
33
34
35
	
	// If $metadataIDProviders is not FALSE update $IDProviders and dump results in $metadataIDPFile, else do nothing.
	if(is_array($metadataIDProviders)){ 
		
36
37
		echo 'Dumping parsed Identity Providers to file '.$metadataIDPFile."\n";
		dumpFile($metadataIDPFile, $metadataIDProviders, 'metadataIDProviders');
haemmer's avatar
haemmer committed
38
		
39
		echo 'Merging parsed Identity Providers with data from file '.$IDProviders."\n";
haemmer's avatar
haemmer committed
40
41
42
		$IDProviders = mergeInfo($IDProviders, $metadataIDProviders, $SAML2MetaOverLocalConf, $includeLocalConfEntries);
		
		echo "Printing parsed Identity Providers:\n";
43
44
45
		print_r($metadataIDProviders);
		
		echo "Printing effective Identity Providers:\n";
haemmer's avatar
haemmer committed
46
47
48
		print_r($IDProviders);
	}
	
49
50
51
52
53
54
55
56
57
58
59
60
61
	// If $metadataSProviders is not FALSE update $SProviders and dump results in $metadataSPFile, else do nothing.
	if(is_array($metadataSProviders)){ 
		
		echo 'Dumping parsed Service Providers to file '.$metadataSPFile."\n";
		dumpFile($metadataSPFile, $metadataSProviders, 'metadataSProviders');
		
		// Fow now copy the array by reference
		$SProviders = &$metadataSProviders;
		
		echo "Printing parsed Service Providers:\n";
		print_r($metadataSProviders);
	}
	
haemmer's avatar
haemmer committed
62
	
63
64
} elseif (isRunViaInclude()) {
	// Run as included file
haemmer's avatar
haemmer committed
65
66
	if(!file_exists($metadataIDPFile) or filemtime($metadataFile) > filemtime($metadataIDPFile)){
		// Regenerate $metadataIDPFile.
67
		list($metadataIDProviders, $metadataSProviders) = parseMetadata($metadataFile, $defaultLanguage);
haemmer's avatar
haemmer committed
68
69
70
71
		
		// If $metadataIDProviders is not an array (parse error in metadata),
		// $IDProviders from $IDPConfigFile will be used.
		if(is_array($metadataIDProviders)){
72
			dumpFile($metadataIDPFile, $metadataIDProviders, 'metadataIDProviders');
haemmer's avatar
haemmer committed
73
74
			$IDProviders = mergeInfo($IDProviders, $metadataIDProviders, $SAML2MetaOverLocalConf, $includeLocalConfEntries);
		}
75
76
77
78
79
80
		
		if(is_array($metadataSProviders)){
			dumpFile($metadataSPFile, $metadataSProviders, 'metadataSProviders');
			require($metadataSPFile);
		}
		
81
82
83
84
85
86
				// 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
87
88
	} elseif (file_exists($metadataIDPFile)){
		
89
		// Read SP and IDP files generated with metadata
haemmer's avatar
haemmer committed
90
		require($metadataIDPFile);
91
		require($metadataSPFile);
haemmer's avatar
haemmer committed
92
	
93
94
95
96
97
98
		// Now merge IDPs from metadata and static file
		$IDProviders = mergeInfo($IDProviders, $metadataIDProviders, $SAML2MetaOverLocalConf, $includeLocalConfEntries);
		
		// Fow now copy the array by reference
		$SProviders = &$metadataSProviders;
	}
99
100
	
	
haemmer's avatar
haemmer committed
101
102
103
104
105
} else {
	exit('No direct script access allowed');
}

/*****************************************************************************/
106
107
// 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
108
109
function parseMetadata($metadataFile, $defaultLanguage){
	
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
	if(!file_exists($metadataFile)){
		$errorMsg = 'File '.$metadataFile." does not exist.\n"; 
		if (isRunViaCLI()){
			echo $errorMsg;
		} else {
			syslog(LOG_ERR, $errorMsg);
		}
		return Array(false, false);
	}

	if(!is_readable($metadataFile)){
		$errorMsg = 'File '.$metadataFile." cannot be read due to insufficient permissions\n"; 
		syslog(LOG_ERR, $errorMsg);
		echo $errorMsg;
		return Array(false, false);
	}
haemmer's avatar
haemmer committed
126
	
127
128
129
	$doc = new DOMDocument();
	if(!$doc->load( $metadataFile )){
		$errorMsg = 'Could not parse metadata file '.$metadataFile.".\n"; 
haemmer's avatar
haemmer committed
130
		syslog(LOG_ERR, $errorMsg);
131
132
133
134
135
136
137
138
139
140
		echo $errorMsg;
		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
141
		
142
143
144
145
146
147
		foreach($EntityDescriptor->childNodes as $RoleDescriptor) {
			switch($RoleDescriptor->nodeName){
				case 'IDPSSODescriptor':
					$IDP = processIDPRoleDescriptor($RoleDescriptor);
					if ($IDP){
						$metadataIDProviders[$entityID] = $IDP;
haemmer's avatar
haemmer committed
148
					}
149
150
151
152
153
					break;
				case 'SPSSODescriptor':
					$SP = processSPRoleDescriptor($RoleDescriptor);
					if ($SP){
						$metadataSProviders[$entityID] = $SP;
haemmer's avatar
haemmer committed
154
					}
155
156
					break;
				default:
haemmer's avatar
haemmer committed
157
158
159
160
			}
		}
	}
	
161
	return Array($metadataIDProviders, $metadataSProviders);
haemmer's avatar
haemmer committed
162
163
164
}

/******************************************************************************/
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// 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
180
181
	global $defaultLanguage;
	
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
	$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
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
		// 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
253
		
254
255
256
257
258
259
260
261
262
263
264
265
266
267
		if (flock($fp, LOCK_EX)) { // do an exclusive lock
			fwrite($fp, "<?php\n\n");
			fwrite($fp, "// This file was automatically generated by readMetadata.php\n");
			fwrite($fp, "// Don't edit!\n\n");
			
			fwrite($fp, '$'.$variableName.' = ');
			fwrite($fp, var_export($providers,true));
			
			fwrite($fp, "\n?>");
			
			// release the lock
			flock($fp, LOCK_UN); 
		} else {
			syslog(LOG_ERR, 'Could not lock file '.$dumpFile.' for writting.');
haemmer's avatar
haemmer committed
268
269
		}
		
270
		fclose($fp);
haemmer's avatar
haemmer committed
271
	} else {
272
		syslog(LOG_ERR, 'Could not open file '.$dumpFile.' for writting.');
haemmer's avatar
haemmer committed
273
274
275
276
277
278
279
280
281
282
283
284
285
286
	}
}


/******************************************************************************/
// 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
287
288
	$allIDPS = $metadataIDProviders;
	$mergedArray = Array();
haemmer's avatar
haemmer committed
289
	if ($includeLocalConfEntries) {
290
		  $allIDPS = array_merge($metadataIDProviders, $IDProviders);
haemmer's avatar
haemmer committed
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
	
	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
316
		} else {
317
318
			// Entry doesnt exist in in local IDProviders.conf.php
			$mergedArray[$allIDPsKey] = $metadataIDProviders[$allIDPsKey];
haemmer's avatar
haemmer committed
319
320
321
322
323
324
325
		}
	}
	
	return $mergedArray;
}

?>