forked from simplesamlphp/simplesamlphp-module-casserver
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLoginController.php
More file actions
509 lines (437 loc) · 17.1 KB
/
LoginController.php
File metadata and controls
509 lines (437 loc) · 17.1 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
<?php
declare(strict_types=1);
namespace SimpleSAML\Module\casserver\Controller;
use RuntimeException;
use SimpleSAML\Auth\ProcessingChain;
use SimpleSAML\Auth\Simple;
use SimpleSAML\Configuration;
use SimpleSAML\HTTP\RunnableResponse;
use SimpleSAML\Logger;
use SimpleSAML\Module;
use SimpleSAML\Module\casserver\Cas\AttributeExtractor;
use SimpleSAML\Module\casserver\Cas\Factories\ProcessingChainFactory;
use SimpleSAML\Module\casserver\Cas\Factories\TicketFactory;
use SimpleSAML\Module\casserver\Cas\Protocol\Cas20;
use SimpleSAML\Module\casserver\Cas\Protocol\SamlValidateResponder;
use SimpleSAML\Module\casserver\Cas\ServiceValidator;
use SimpleSAML\Module\casserver\Cas\Ticket\TicketStore;
use SimpleSAML\Module\casserver\Controller\Traits\TicketValidatorTrait;
use SimpleSAML\Module\casserver\Controller\Traits\UrlTrait;
use SimpleSAML\Session;
use SimpleSAML\Utils;
use SimpleSAML\XHTML\Template;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Attribute\MapQueryParameter;
use in_array;
use http_build_query;
use var_export;
#[AsController]
class LoginController
{
use UrlTrait;
use TicketValidatorTrait;
/** @var \SimpleSAML\Logger */
protected Logger $logger;
/** @var \SimpleSAML\Configuration */
protected Configuration $casConfig;
/** @var \SimpleSAML\Module\casserver\Cas\Factories\TicketFactory */
protected TicketFactory $ticketFactory;
/** @var \SimpleSAML\Auth\Simple */
protected Simple $authSource;
/** @var \SimpleSAML\Utils\HTTP */
protected Utils\HTTP $httpUtils;
/** @var \SimpleSAML\Module\casserver\Cas\Protocol\Cas20 */
protected Cas20 $cas20Protocol;
/** @var \SimpleSAML\Module\casserver\Cas\Ticket\TicketStore */
protected TicketStore $ticketStore;
/** @var \SimpleSAML\Module\casserver\Cas\ServiceValidator */
protected ServiceValidator $serviceValidator;
/** @var string[] */
protected array $idpList;
/** @var string|null */
protected ?string $authProcId = null;
/** @var string[] */
protected array $postAuthUrlParameters = [];
/** @var string[] */
private const DEBUG_MODES = ['true', 'samlValidate'];
/** @var \SimpleSAML\Module\casserver\Cas\AttributeExtractor */
protected AttributeExtractor $attributeExtractor;
/** @var \SimpleSAML\Module\casserver\Cas\Protocol\SamlValidateResponder */
private SamlValidateResponder $samlValidateResponder;
/**
* @param \SimpleSAML\Configuration $sspConfig
* @param \SimpleSAML\Configuration|null $casConfig
* @param \SimpleSAML\Auth\Simple|null $source
* @param \SimpleSAML\Utils\HTTP|null $httpUtils
*
* @throws \Exception
*/
public function __construct(
private readonly Configuration $sspConfig,
// Facilitate testing
?Configuration $casConfig = null,
?Simple $source = null,
?Utils\HTTP $httpUtils = null,
) {
$this->casConfig = ($casConfig === null || $casConfig === $sspConfig)
? Configuration::getConfig('module_casserver.php') : $casConfig;
// Saml Validate Responsder
$this->samlValidateResponder = new SamlValidateResponder();
// Service Validator needs the generic casserver configuration.
$this->serviceValidator = new ServiceValidator($this->casConfig);
$this->authSource = $source ?? new Simple($this->casConfig->getValue('authsource'));
$this->httpUtils = $httpUtils ?? new Utils\HTTP();
}
/**
*
* @param \Symfony\Component\HttpFoundation\Request $request
* @param bool $renew
* @param bool $gateway
* @param string|null $service
* @param string|null $TARGET Query parameter name for "service" used by older CAS clients'
* @param string|null $scope
* @param string|null $language
* @param string|null $entityId
* @param string|null $debugMode
* @param string|null $method
*
* @return \SimpleSAML\HTTP\RunnableResponse|\SimpleSAML\XHTML\Template
* @throws \SimpleSAML\Error\ConfigurationError
* @throws \SimpleSAML\Error\NoState
*/
public function login(
Request $request,
#[MapQueryParameter] bool $renew = false,
#[MapQueryParameter] bool $gateway = false,
#[MapQueryParameter] ?string $service = null,
#[MapQueryParameter] ?string $TARGET = null,
#[MapQueryParameter] ?string $scope = null,
#[MapQueryParameter] ?string $language = null,
#[MapQueryParameter] ?string $entityId = null,
#[MapQueryParameter] ?string $debugMode = null,
#[MapQueryParameter] ?string $method = null,
): RunnableResponse|Template {
$forceAuthn = $renew;
$serviceUrl = $service ?? $TARGET ?? null;
$redirect = !(isset($method) && $method === 'POST');
// Set initial configurations, or fail
$this->handleServiceConfiguration($serviceUrl);
// Instantiate the classes that rely on the override configuration.
// We do not do this in the constructor since we do not have the correct values yet.
$this->instantiateClassDependencies();
$this->handleScope($scope);
$this->handleLanguage($language);
// Get the ticket from the session
$session = $this->getSession();
$sessionTicket = $this->ticketStore->getTicket($session->getSessionId());
$sessionRenewId = $sessionTicket['renewId'] ?? null;
$requestRenewId = $this->getRequestParam($request, 'renewId');
// if this parameter is true, single sign-on will be bypassed and authentication will be enforced
$requestForceAuthenticate = $forceAuthn && $sessionRenewId !== $requestRenewId;
if ($request->query->has(ProcessingChain::AUTHPARAM)) {
$this->authProcId = $request->query->get(ProcessingChain::AUTHPARAM);
}
// Construct the ReturnTo URL
// This will be used to come back from the AuthSource login or from the Processing Chain
$returnToUrl = $this->getReturnUrl($request, $sessionTicket);
/*
* CAS gateway behavior:
* If gateway=true, service is valid, and the user is not authenticated,
* redirect immediately to the service URL with NO query parameters or fragment.
*/
if ($gateway === true && $serviceUrl !== null && !$this->authSource->isAuthenticated()) {
$cleanServiceUrl = $this->stripQueryParameters($serviceUrl);
return new RunnableResponse(
[$this->httpUtils, 'redirectTrustedURL'],
[$cleanServiceUrl]
);
}
// Authenticate
if (
$requestForceAuthenticate || !$this->authSource->isAuthenticated()
) {
$params = [
'ForceAuthn' => $forceAuthn,
'isPassive' => $gateway,
'ReturnTo' => $returnToUrl,
];
if (isset($entityId)) {
$params['saml:idp'] = $entityId;
}
if (isset($this->idpList)) {
if (count($this->idpList) > 1) {
$params['saml:IDPList'] = $this->idpList;
} else {
$params['saml:idp'] = $this->idpList[0];
}
}
/*
* REDIRECT TO AUTHSOURCE LOGIN
* */
return new RunnableResponse(
[$this->authSource, 'login'],
[$params],
);
}
// We are Authenticated.
$sessionExpiry = $this->authSource->getAuthData('Expire');
// Create a new ticket if we do not have one alreday, or if we are in a forced Authentitcation mode
if (!\is_array($sessionTicket) || $forceAuthn) {
$sessionTicket = $this->ticketFactory->createSessionTicket($session->getSessionId(), $sessionExpiry);
$this->ticketStore->addTicket($sessionTicket);
}
/*
* We are done. REDIRECT TO LOGGEDIN
* */
if (!isset($serviceUrl) && $this->authProcId === null) {
$loggedInUrl = Module::getModuleURL('casserver/loggedIn');
return new RunnableResponse(
[$this->httpUtils, 'redirectTrustedURL'],
[$loggedInUrl, $this->postAuthUrlParameters],
);
}
// Get the state.
$state = $this->getState();
$state['ReturnTo'] = $returnToUrl;
if ($this->authProcId !== null) {
$state[ProcessingChain::AUTHPARAM] = $this->authProcId;
}
// Attribute Handler
$mappedAttributes = $this->attributeExtractor->extractUserAndAttributes($state);
$serviceTicket = $this->ticketFactory->createServiceTicket([
'service' => $serviceUrl,
'forceAuthn' => $forceAuthn,
'userName' => $mappedAttributes['user'],
'attributes' => $mappedAttributes['attributes'],
'proxies' => [],
'sessionId' => $sessionTicket['id'],
]);
$this->ticketStore->addTicket($serviceTicket);
// Check if we are in debug mode.
if ($debugMode !== null && $this->casConfig->getOptionalBoolean('debugMode', false)) {
[$templateName, $statusCode, $DebugModeXmlString] = $this->handleDebugMode(
$request,
$debugMode,
$serviceTicket,
);
$t = new Template($this->sspConfig, (string)$templateName);
$t->data['debugMode'] = $debugMode === 'true' ? 'Default' : $debugMode;
if (!str_contains('error', (string)$templateName)) {
$t->data['DebugModeXml'] = $DebugModeXmlString;
}
$t->data['statusCode'] = $statusCode;
// Return an HTML View that renders the result
return $t;
}
$ticketName = $this->calculateTicketName($service);
$this->postAuthUrlParameters[$ticketName] = $serviceTicket['id'];
// GET
if ($redirect) {
return new RunnableResponse(
[$this->httpUtils, 'redirectTrustedURL'],
[$serviceUrl, $this->postAuthUrlParameters],
);
}
// POST
return new RunnableResponse(
[$this->httpUtils, 'submitPOSTData'],
[$serviceUrl, $this->postAuthUrlParameters],
);
}
/**
* @param \Symfony\Component\HttpFoundation\Request $request
* @param string|null $debugMode
* @param array $serviceTicket
*
* @return array []
*/
public function handleDebugMode(
Request $request,
?string $debugMode,
array $serviceTicket,
): array {
// Check if the debugMode is supported
if (!in_array($debugMode, self::DEBUG_MODES, true)) {
return ['casserver:error.twig', Response::HTTP_BAD_REQUEST, 'Invalid/Unsupported Debug Mode'];
}
if ($debugMode === 'true') {
// Service validate CAS20
$xmlResponse = $this->validate(
request: $request,
method: 'serviceValidate',
renew: $request->get('renew', false),
target: $request->get('target'),
ticket: $serviceTicket['id'],
service: $request->get('service'),
pgtUrl: $request->get('pgtUrl'),
);
return ['casserver:validate.twig', $xmlResponse->getStatusCode(), $xmlResponse->getContent()];
}
// samlValidate Mode
$samlResponse = $this->samlValidateResponder->convertToSaml($serviceTicket);
return [
'casserver:validate.twig',
Response::HTTP_OK,
(string)$this->samlValidateResponder->wrapInSoap($samlResponse),
];
}
/**
* @return array|null
* @throws \SimpleSAML\Error\NoState
*/
public function getState(): ?array
{
// If we come from an authproc filter, we will load the state from the stateId.
// If not, we will get the state from the AuthSource Data
return $this->authProcId !== null ?
$this->attributeExtractor->manageState($this->authProcId) :
$this->authSource->getAuthDataArray();
}
/**
* Construct the ticket name
*
* @param string|null $service
*
* @return string
*/
public function calculateTicketName(?string $service): string
{
$defaultTicketName = $service !== null ? 'ticket' : 'SAMLart';
return $this->casConfig->getOptionalValue('ticketName', $defaultTicketName);
}
/**
* @param \Symfony\Component\HttpFoundation\Request $request
* @param array|null $sessionTicket
*
* @return string
*/
public function getReturnUrl(Request $request, ?array $sessionTicket): string
{
// Parse the query parameters and return them in an array
$query = $this->parseQueryParameters($request, $sessionTicket);
// Construct the ReturnTo URL
return $this->httpUtils->getSelfURLNoQuery() . '?' . http_build_query($query);
}
/**
* @param string|null $serviceUrl
*
* @return void
* @throws \RuntimeException
*/
public function handleServiceConfiguration(?string $serviceUrl): void
{
if ($serviceUrl === null) {
return;
}
$serviceCasConfig = $this->serviceValidator->checkServiceURL($this->sanitize($serviceUrl));
if (!isset($serviceCasConfig)) {
$message = 'Service parameter provided to CAS server is not listed as a legal service: [service] = ' .
var_export($serviceUrl, true);
Logger::debug('casserver:' . $message);
throw new RuntimeException($message);
}
// Override the cas configuration to use for this service
$this->casConfig = $serviceCasConfig;
}
/**
* @param string|null $language
*
* @return void
*/
public function handleLanguage(?string $language): void
{
// If null, do nothing
if ($language === null) {
return;
}
$this->postAuthUrlParameters['language'] = $language;
}
/**
* @param string|null $scope
*
* @return void
* @throws \RuntimeException
*/
public function handleScope(?string $scope): void
{
// If null, do nothing
if ($scope === null) {
return;
}
// Get the scopes from the configuration
$scopes = $this->casConfig->getOptionalValue('scopes', []);
// Fail
if (!isset($scopes[$scope])) {
$message = 'Scope parameter provided to CAS server is not listed as legal scope: [scope] = ' .
var_export($scope, true);
Logger::debug('casserver:' . $message);
throw new RuntimeException($message);
}
// Set the idplist from the scopes
$this->idpList = $scopes[$scope];
}
/**
* Get the Session
*
* @return \SimpleSAML\Session|null
* @throws \Exception
*/
public function getSession(): ?Session
{
return Session::getSessionFromRequest();
}
/**
* @return \SimpleSAML\Module\casserver\Cas\Ticket\TicketStore
*/
public function getTicketStore(): TicketStore
{
return $this->ticketStore;
}
/**
* @return void
* @throws \Exception
*/
private function instantiateClassDependencies(): void
{
$this->cas20Protocol = new Cas20($this->casConfig);
/* Instantiate ticket factory */
$this->ticketFactory = new TicketFactory($this->casConfig);
/* Instantiate ticket store */
$ticketStoreConfig = $this->casConfig->getOptionalValue(
'ticketstore',
['class' => 'casserver:FileSystemTicketStore'],
);
$ticketStoreClass = Module::resolveClass($ticketStoreConfig['class'], 'Cas\Ticket');
// Ticket Store
$this->ticketStore = new $ticketStoreClass($this->casConfig);
// Processing Chain Factory
$processingChainFactory = new ProcessingChainFactory($this->casConfig);
// Attribute Extractor
$this->attributeExtractor = new AttributeExtractor($this->casConfig, $processingChainFactory);
}
/**
* Remove query string from a URL while preserving scheme, userinfo, host, port, path and fragment.
*
* @param string $url
* @return string
*/
private function stripQueryParameters(string $url): string
{
$parts = parse_url($url);
$scheme = $parts['scheme'] ?? '';
$host = $parts['host'] ?? '';
$port = isset($parts['port']) ? ':' . $parts['port'] : '';
$user = $parts['user'] ?? null;
$pass = $parts['pass'] ?? null;
$userInfo = $user ? $user . ($pass ? ':' . $pass : '') . '@' : '';
$path = $parts['path'] ?? '';
$fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
// Ensure root path is preserved if it was "/"
if ($path === '' && (($parts['path'] ?? '') === '/')) {
$path = '/';
}
return sprintf('%s://%s%s%s%s%s', $scheme, $userInfo, $host, $port, $path, $fragment);
}
}