readMetadata.php 10.7 KB
Newer Older
haemmer's avatar
haemmer committed
1
2
3
4
5
6
7
8
<?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.
 */

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

/*****************************************************************************/
93
94
// 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
95
96
function parseMetadata($metadataFile, $defaultLanguage){
	
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
	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
113
	
114
115
116
	$doc = new DOMDocument();
	if(!$doc->load( $metadataFile )){
		$errorMsg = 'Could not parse metadata file '.$metadataFile.".\n"; 
haemmer's avatar
haemmer committed
117
		syslog(LOG_ERR, $errorMsg);
118
119
120
121
122
123
124
125
126
127
		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
128
		
129
130
131
132
133
134
		foreach($EntityDescriptor->childNodes as $RoleDescriptor) {
			switch($RoleDescriptor->nodeName){
				case 'IDPSSODescriptor':
					$IDP = processIDPRoleDescriptor($RoleDescriptor);
					if ($IDP){
						$metadataIDProviders[$entityID] = $IDP;
haemmer's avatar
haemmer committed
135
					}
136
137
138
139
140
					break;
				case 'SPSSODescriptor':
					$SP = processSPRoleDescriptor($RoleDescriptor);
					if ($SP){
						$metadataSProviders[$entityID] = $SP;
haemmer's avatar
haemmer committed
141
					}
142
143
					break;
				default:
haemmer's avatar
haemmer committed
144
145
146
147
			}
		}
	}
	
148
	return Array($metadataIDProviders, $metadataSProviders);
haemmer's avatar
haemmer committed
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
// 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){
	$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
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
		// 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
238
		
239
240
241
242
243
244
245
246
247
248
249
250
251
252
		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
253
254
		}
		
255
		fclose($fp);
haemmer's avatar
haemmer committed
256
	} else {
257
		syslog(LOG_ERR, 'Could not open file '.$dumpFile.' for writting.');
haemmer's avatar
haemmer committed
258
259
260
261
262
263
264
265
266
267
268
269
270
271
	}
}


/******************************************************************************/
// 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
272
273
	$allIDPS = $metadataIDProviders;
	$mergedArray = Array();
haemmer's avatar
haemmer committed
274
	if ($includeLocalConfEntries) {
275
		  $allIDPS = array_merge($metadataIDProviders, $IDProviders);
haemmer's avatar
haemmer committed
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
	
	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
301
		} else {
302
303
			// Entry doesnt exist in in local IDProviders.conf.php
			$mergedArray[$allIDPsKey] = $metadataIDProviders[$allIDPsKey];
haemmer's avatar
haemmer committed
304
305
306
307
308
309
310
		}
	}
	
	return $mergedArray;
}

?>