-
-
Notifications
You must be signed in to change notification settings - Fork 462
/
Auth.php
539 lines (480 loc) · 17.6 KB
/
Auth.php
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
<?php
/**
* Main class of OneLogin's PHP Toolkit
*
*/
class OneLogin_Saml2_Auth
{
/**
* Settings data.
*
* @var OneLogin_Saml2_Settings
*/
private $_settings;
/**
* User attributes data.
*
* @var array
*/
private $_attributes = array();
/**
* NameID
*
* @var string
*/
private $_nameid;
/**
* If user is authenticated.
*
* @var bool
*/
private $_authenticated = false;
/**
* SessionIndex. When the user is logged, this stored it
* from the AuthnStatement of the SAML Response
*
* @var string
*/
private $_sessionIndex;
/**
* SessionNotOnOrAfter. When the user is logged, this stored it
* from the AuthnStatement of the SAML Response
*
* @var DateTime
*/
private $_sessionExpiration;
/**
* If any error.
*
* @var array
*/
private $_errors = array();
/**
* Reason of the last error.
*
* @var string
*/
private $_errorReason;
/**
* Last AuthNRequest ID or LogoutRequest ID generated by this Service Provider
*
* @var string
*/
private $_lastRequestID;
/**
* Initializes the SP SAML instance.
*
* @param array|object|null $oldSettings Setting data (You can provide a OneLogin_Saml_Settings, the settings object of the Saml folder implementation)
*/
public function __construct($oldSettings = null)
{
$this->_settings = new OneLogin_Saml2_Settings($oldSettings);
}
/**
* Returns the settings info
*
* @return OneLogin_Saml2_Settings The settings data.
*/
public function getSettings()
{
return $this->_settings;
}
/**
* Set the strict mode active/disable
*
* @param bool $value Strict parameter
*
* @return array The settings data.
*/
public function setStrict($value)
{
if (! (is_bool($value))) {
throw new Exception('Invalid value passed to setStrict()');
}
$this->_settings->setStrict($value);
}
/**
* Process the SAML Response sent by the IdP.
*
* @param string|null $requestId The ID of the AuthNRequest sent by this SP to the IdP
*
* @throws OneLogin_Saml2_Error
*/
public function processResponse($requestId = null)
{
$this->_errors = array();
if (isset($_POST) && isset($_POST['SAMLResponse'])) {
// AuthnResponse -- HTTP_POST Binding
$response = new OneLogin_Saml2_Response($this->_settings, $_POST['SAMLResponse']);
if ($response->isValid($requestId)) {
$this->_attributes = $response->getAttributes();
$this->_nameid = $response->getNameId();
$this->_authenticated = true;
$this->_sessionIndex = $response->getSessionIndex();
$this->_sessionExpiration = $response->getSessionNotOnOrAfter();
} else {
$this->_errors[] = 'invalid_response';
$this->_errorReason = $response->getError();
}
} else {
$this->_errors[] = 'invalid_binding';
throw new OneLogin_Saml2_Error(
'SAML Response not found, Only supported HTTP_POST Binding',
OneLogin_Saml2_Error::SAML_RESPONSE_NOT_FOUND
);
}
}
/**
* Process the SAML Logout Response / Logout Request sent by the IdP.
*
* @param bool $keepLocalSession When false will destroy the local session, otherwise will keep it
* @param string|null $requestId The ID of the LogoutRequest sent by this SP to the IdP
* @param bool $retrieveParametersFromServer
* @param callable $cbDeleteSession
* @param bool $stay True if we want to stay (returns the url string) False to redirect
*
* @return string|void
*
* @throws OneLogin_Saml2_Error
*/
public function processSLO($keepLocalSession = false, $requestId = null, $retrieveParametersFromServer = false, $cbDeleteSession = null, $stay=false)
{
$this->_errors = array();
if (isset($_GET) && isset($_GET['SAMLResponse'])) {
$logoutResponse = new OneLogin_Saml2_LogoutResponse($this->_settings, $_GET['SAMLResponse']);
if (!$logoutResponse->isValid($requestId, $retrieveParametersFromServer)) {
$this->_errors[] = 'invalid_logout_response';
$this->_errorReason = $logoutResponse->getError();
} else if ($logoutResponse->getStatus() !== OneLogin_Saml2_Constants::STATUS_SUCCESS) {
$this->_errors[] = 'logout_not_success';
} else {
if (!$keepLocalSession) {
if ($cbDeleteSession === null) {
OneLogin_Saml2_Utils::deleteLocalSession();
} else {
call_user_func($cbDeleteSession);
}
}
}
} else if (isset($_GET) && isset($_GET['SAMLRequest'])) {
$logoutRequest = new OneLogin_Saml2_LogoutRequest($this->_settings, $_GET['SAMLRequest']);
if (!$logoutRequest->isValid($retrieveParametersFromServer)) {
$this->_errors[] = 'invalid_logout_request';
$this->_errorReason = $logoutRequest->getError();
} else {
if (!$keepLocalSession) {
if ($cbDeleteSession === null) {
OneLogin_Saml2_Utils::deleteLocalSession();
} else {
call_user_func($cbDeleteSession);
}
}
$inResponseTo = $logoutRequest->id;
$responseBuilder = new OneLogin_Saml2_LogoutResponse($this->_settings);
$responseBuilder->build($inResponseTo);
$logoutResponse = $responseBuilder->getResponse();
$parameters = array('SAMLResponse' => $logoutResponse);
if (isset($_GET['RelayState'])) {
$parameters['RelayState'] = $_GET['RelayState'];
}
$security = $this->_settings->getSecurityData();
if (isset($security['logoutResponseSigned']) && $security['logoutResponseSigned']) {
$signature = $this->buildResponseSignature($logoutResponse, isset($parameters['RelayState'])? $parameters['RelayState']: null, $security['signatureAlgorithm']);
$parameters['SigAlg'] = $security['signatureAlgorithm'];
$parameters['Signature'] = $signature;
}
return $this->redirectTo($this->getSLOurl(), $parameters, $stay);
}
} else {
$this->_errors[] = 'invalid_binding';
throw new OneLogin_Saml2_Error(
'SAML LogoutRequest/LogoutResponse not found. Only supported HTTP_REDIRECT Binding',
OneLogin_Saml2_Error::SAML_LOGOUTMESSAGE_NOT_FOUND
);
}
}
/**
* Redirects the user to the url past by parameter
* or to the url that we defined in our SSO Request.
*
* @param string $url The target URL to redirect the user.
* @param array $parameters Extra parameters to be passed as part of the url
* @param bool $stay True if we want to stay (returns the url string) False to redirect
*/
public function redirectTo($url = '', $parameters = array(), $stay = false)
{
assert('is_string($url)');
assert('is_array($parameters)');
if (empty($url) && isset($_REQUEST['RelayState'])) {
$url = $_REQUEST['RelayState'];
}
return OneLogin_Saml2_Utils::redirect($url, $parameters, $stay);
}
/**
* Checks if the user is authenticated or not.
*
* @return bool True if the user is authenticated
*/
public function isAuthenticated()
{
return $this->_authenticated;
}
/**
* Returns the set of SAML attributes.
*
* @return array Attributes of the user.
*/
public function getAttributes()
{
return $this->_attributes;
}
/**
* Returns the nameID
*
* @return string The nameID of the assertion
*/
public function getNameId()
{
return $this->_nameid;
}
/**
* Returns the SessionIndex
*
* @return string|null The SessionIndex of the assertion
*/
public function getSessionIndex()
{
return $this->_sessionIndex;
}
/**
* Returns the SessionNotOnOrAfter
*
* @return DateTime|null The SessionNotOnOrAfter of the assertion
*/
public function getSessionExpiration()
{
return $this->_sessionExpiration;
}
/**
* Returns if there were any error
*
* @return array Errors
*/
public function getErrors()
{
return $this->_errors;
}
/**
* Returns the reason for the last error
*
* @return string Error reason
*/
public function getLastErrorReason()
{
return $this->_errorReason;
}
/**
* Returns the requested SAML attribute
*
* @param string $name The requested attribute of the user.
*
* @return array|null Requested SAML attribute ($name).
*/
public function getAttribute($name)
{
assert('is_string($name)');
$value = null;
if (isset($this->_attributes[$name])) {
return $this->_attributes[$name];
}
return $value;
}
/**
* Initiates the SSO process.
*
* @param string|null $returnTo The target URL the user should be returned to after login.
* @param array $parameters Extra parameters to be added to the GET
* @param bool $forceAuthn When true the AuthNReuqest will set the ForceAuthn='true'
* @param bool $isPassive When true the AuthNReuqest will set the Ispassive='true'
* @param bool $stay True if we want to stay (returns the url string) False to redirect
* @param bool $setNameIdPolicy When true the AuthNReuqest will set a nameIdPolicy element
*
* @return If $stay is True, it return a string with the SLO URL + LogoutRequest + parameters
*/
public function login($returnTo = null, $parameters = array(), $forceAuthn = false, $isPassive = false, $stay=false, $setNameIdPolicy = true)
{
assert('is_array($parameters)');
$authnRequest = new OneLogin_Saml2_AuthnRequest($this->_settings, $forceAuthn, $isPassive, $setNameIdPolicy);
$this->_lastRequestID = $authnRequest->getId();
$samlRequest = $authnRequest->getRequest();
$parameters['SAMLRequest'] = $samlRequest;
if (!empty($returnTo)) {
$parameters['RelayState'] = $returnTo;
} else {
$parameters['RelayState'] = OneLogin_Saml2_Utils::getSelfRoutedURLNoQuery();
}
$security = $this->_settings->getSecurityData();
if (isset($security['authnRequestsSigned']) && $security['authnRequestsSigned']) {
$signature = $this->buildRequestSignature($samlRequest, $parameters['RelayState'], $security['signatureAlgorithm']);
$parameters['SigAlg'] = $security['signatureAlgorithm'];
$parameters['Signature'] = $signature;
}
return $this->redirectTo($this->getSSOurl(), $parameters, $stay);
}
/**
* Initiates the SLO process.
*
* @param string|null $returnTo The target URL the user should be returned to after logout.
* @param array $parameters Extra parameters to be added to the GET
* @param string|null $nameId The NameID that will be set in the LogoutRequest.
* @param string|null $sessionIndex The SessionIndex (taken from the SAML Response in the SSO process).
* @param bool $stay True if we want to stay (returns the url string) False to redirect
*
* @return If $stay is True, it return a string with the SLO URL + LogoutRequest + parameters
*
* @throws OneLogin_Saml2_Error
*/
public function logout($returnTo = null, $parameters = array(), $nameId = null, $sessionIndex = null, $stay=false)
{
assert('is_array($parameters)');
$sloUrl = $this->getSLOurl();
if (empty($sloUrl)) {
throw new OneLogin_Saml2_Error(
'The IdP does not support Single Log Out',
OneLogin_Saml2_Error::SAML_SINGLE_LOGOUT_NOT_SUPPORTED
);
}
if (empty($nameId) && !empty($this->_nameid)) {
$nameId = $this->_nameid;
}
$logoutRequest = new OneLogin_Saml2_LogoutRequest($this->_settings, null, $nameId, $sessionIndex);
$this->_lastRequestID = $logoutRequest->id;
$samlRequest = $logoutRequest->getRequest();
$parameters['SAMLRequest'] = $samlRequest;
if (!empty($returnTo)) {
$parameters['RelayState'] = $returnTo;
} else {
$parameters['RelayState'] = OneLogin_Saml2_Utils::getSelfRoutedURLNoQuery();
}
$security = $this->_settings->getSecurityData();
if (isset($security['logoutRequestSigned']) && $security['logoutRequestSigned']) {
$signature = $this->buildRequestSignature($samlRequest, $parameters['RelayState'], $security['signatureAlgorithm']);
$parameters['SigAlg'] = $security['signatureAlgorithm'];
$parameters['Signature'] = $signature;
}
return $this->redirectTo($sloUrl, $parameters, $stay);
}
/**
* Gets the SSO url.
*
* @return string The url of the Single Sign On Service
*/
public function getSSOurl()
{
$idpData = $this->_settings->getIdPData();
return $idpData['singleSignOnService']['url'];
}
/**
* Gets the SLO url.
*
* @return string The url of the Single Logout Service
*/
public function getSLOurl()
{
$url = null;
$idpData = $this->_settings->getIdPData();
if (isset($idpData['singleLogoutService']) && isset($idpData['singleLogoutService']['url'])) {
$url = $idpData['singleLogoutService']['url'];
}
return $url;
}
/**
* Gets the ID of the last AuthNRequest or LogoutRequest generated by the Service Provider.
*
* @return string The ID of the Request SAML message.
*/
public function getLastRequestID()
{
return $this->_lastRequestID;
}
/**
* Generates the Signature for a SAML Request
*
* @param string $samlRequest The SAML Request
* @param string $relayState The RelayState
* @param string $signAlgorithm Signature algorithm method
*
* @return string A base64 encoded signature
*
* @throws Exception
* @throws OneLogin_Saml2_Error
*/
public function buildRequestSignature($samlRequest, $relayState, $signAlgorithm = XMLSecurityKey::RSA_SHA1)
{
if (!$this->_settings->checkSPCerts()) {
throw new OneLogin_Saml2_Error(
"Trying to sign the SAML Request but can't load the SP certs",
OneLogin_Saml2_Error::SP_CERTS_NOT_FOUND
);
}
$key = $this->_settings->getSPkey();
$objKey = new XMLSecurityKey($signAlgorithm, array('type' => 'private'));
$objKey->loadKey($key, false);
$security = $this->_settings->getSecurityData();
if ($security['lowercaseUrlencoding']) {
$msg = 'SAMLRequest='.rawurlencode($samlRequest);
if (isset($relayState)) {
$msg .= '&RelayState='.rawurlencode($relayState);
}
$msg .= '&SigAlg=' . rawurlencode($signAlgorithm);
} else {
$msg = 'SAMLRequest='.urlencode($samlRequest);
if (isset($relayState)) {
$msg .= '&RelayState='.urlencode($relayState);
}
$msg .= '&SigAlg=' . urlencode($signAlgorithm);
}
$signature = $objKey->signData($msg);
return base64_encode($signature);
}
/**
* Generates the Signature for a SAML Response
*
* @param string $samlResponse The SAML Response
* @param string $relayState The RelayState
* @param string $signAlgorithm Signature algorithm method
*
* @return string A base64 encoded signature
*
* @throws Exception
* @throws OneLogin_Saml2_Error
*/
public function buildResponseSignature($samlResponse, $relayState, $signAlgorithm = XMLSecurityKey::RSA_SHA1)
{
if (!$this->_settings->checkSPCerts()) {
throw new OneLogin_Saml2_Error(
"Trying to sign the SAML Response but can't load the SP certs",
OneLogin_Saml2_Error::SP_CERTS_NOT_FOUND
);
}
$key = $this->_settings->getSPkey();
$objKey = new XMLSecurityKey($signAlgorithm, array('type' => 'private'));
$objKey->loadKey($key, false);
$security = $this->_settings->getSecurityData();
if ($security['lowercaseUrlencoding']) {
$msg = 'SAMLResponse='.rawurlencode($samlResponse);
if (isset($relayState)) {
$msg .= '&RelayState='.rawurlencode($relayState);
}
$msg .= '&SigAlg=' . rawurlencode($signAlgorithm);
} else {
$msg = 'SAMLResponse='.urlencode($samlResponse);
if (isset($relayState)) {
$msg .= '&RelayState='.urlencode($relayState);
}
$msg .= '&SigAlg=' . urlencode($signAlgorithm);
}
$signature = $objKey->signData($msg);
return base64_encode($signature);
}
}