Completed
Push — master ( e96383...13486f )
by
unknown
06:11
created

SamlProxyController::singleSignOnAction()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 74
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 74
rs 9.0335
cc 3
eloc 42
nc 3
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Copyright 2014 SURFnet bv
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License");
7
 * you may not use this file except in compliance with the License.
8
 * You may obtain a copy of the License at
9
 *
10
 *     http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS,
14
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
 * See the License for the specific language governing permissions and
16
 * limitations under the License.
17
 */
18
19
namespace Surfnet\StepupGateway\SamlStepupProviderBundle\Controller;
20
21
use DateTime;
22
use Exception;
23
use SAML2\Constants;
24
use SAML2\Response as SAMLResponse;
25
use Surfnet\SamlBundle\Http\XMLResponse;
26
use Surfnet\SamlBundle\SAML2\AuthnRequest;
27
use Surfnet\SamlBundle\SAML2\AuthnRequestFactory;
28
use Surfnet\StepupGateway\GatewayBundle\Saml\AssertionAdapter;
29
use Surfnet\StepupGateway\GatewayBundle\Saml\Exception\UnknownInResponseToException;
30
use Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\Provider;
31
use Surfnet\StepupGateway\SamlStepupProviderBundle\Saml\StateHandler;
32
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpFoundation\Response;
35
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
36
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
37
38
/**
39
 * Handling of GSSP registration and verification.
40
 *
41
 * See docs/GatewayState.md for a high-level diagram on how this controller
42
 * interacts with outside actors and other parts of Stepup.
43
 *
44
 * Should be refactored, {@see https://www.pivotaltracker.com/story/show/90169776}
45
 *
46
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
47
 * @SuppressWarnings(PHPMD.NPathComplexity)
48
 */
49
class SamlProxyController extends Controller
50
{
51
    /**
52
     * Proxy a GSSP authentication request to the remote GSSP SSO endpoint.
53
     *
54
     * The user is about to be sent to the remote GSSP application for
55
     * registration. Verification is not initiated with a SAML AUthnRequest,
56
     * see sendSecondFactorVerificationAuthnRequestAction().
57
     *
58
     * The service provider in this context is SelfService.
59
     *
60
     * @param string  $provider
61
     * @param Request $httpRequest
62
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
63
     */
64
    public function singleSignOnAction($provider, Request $httpRequest)
65
    {
66
        $provider = $this->getProvider($provider);
67
68
        $logger = $this->get('logger');
69
        $logger->notice('Received AuthnRequest, started processing');
70
71
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
72
        $redirectBinding = $this->get('surfnet_saml.http.redirect_binding');
73
74
        $originalRequest = $redirectBinding->processSignedRequest($httpRequest);
75
76
        $originalRequestId = $originalRequest->getRequestId();
77
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
78
        $logger->notice(sprintf(
79
            'AuthnRequest processing complete, received AuthnRequest from "%s", request ID: "%s"',
80
            $originalRequest->getServiceProvider(),
81
            $originalRequest->getRequestId()
82
        ));
83
84
        $logger->debug('Checking if SP "%s" is supported');
85
        /**
86
         * @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\ConnectedServiceProviders $connectedServiceProviders
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 125 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
87
         */
88
        $connectedServiceProviders = $this->get('gssp.connected_service_providers');
89
        if (!$connectedServiceProviders->isConnected($originalRequest->getServiceProvider())) {
0 ignored issues
show
Bug introduced by
It seems like $originalRequest->getServiceProvider() targeting Surfnet\SamlBundle\SAML2...t::getServiceProvider() can also be of type null or object<SAML2\XML\saml\Issuer>; however, Surfnet\StepupGateway\Sa...roviders::isConnected() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
90
            $logger->warning(sprintf(
91
                'Received AuthnRequest from SP "%s", while SP is not allowed to use this for SSO',
92
                $originalRequest->getServiceProvider()
93
            ));
94
95
            throw new AccessDeniedHttpException();
96
        }
97
98
        /** @var StateHandler $stateHandler */
99
        $stateHandler = $provider->getStateHandler();
100
101
        // Clear the state of the previous SSO action. Request data of
102
        // previous SSO actions should not have any effect in subsequent SSO
103
        // actions.
104
        $stateHandler->clear();
105
106
        $stateHandler
107
            ->setRequestId($originalRequestId)
108
            ->setRequestServiceProvider($originalRequest->getServiceProvider())
0 ignored issues
show
Bug introduced by
It seems like $originalRequest->getServiceProvider() targeting Surfnet\SamlBundle\SAML2...t::getServiceProvider() can also be of type null or object<SAML2\XML\saml\Issuer>; however, Surfnet\StepupGateway\Ga...equestServiceProvider() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
109
            ->setRequestAssertionConsumerServiceUrl($originalRequest->getAssertionConsumerServiceURL())
110
            ->setRelayState($httpRequest->get(AuthnRequest::PARAMETER_RELAY_STATE, ''));
111
112
        $proxyRequest = AuthnRequestFactory::createNewRequest(
113
            $provider->getServiceProvider(),
114
            $provider->getRemoteIdentityProvider()
115
        );
116
117
        // if a Specific subject is given to authenticate we should proxy that and verify in the response
118
        // that that subject indeed was authenticated
119
        $nameId = $originalRequest->getNameId();
120
        if ($nameId) {
121
            $proxyRequest->setSubject($nameId, $originalRequest->getNameIdFormat());
122
            $stateHandler->setSubject($nameId);
123
        }
124
125
        $proxyRequest->setScoping([$originalRequest->getServiceProvider()]);
126
        $stateHandler->setGatewayRequestId($proxyRequest->getRequestId());
127
128
        $logger->notice(sprintf(
129
            'Sending Proxy AuthnRequest with request ID: "%s" for original AuthnRequest "%s" to GSSP "%s" at "%s"',
130
            $proxyRequest->getRequestId(),
131
            $originalRequest->getRequestId(),
132
            $provider->getName(),
133
            $provider->getRemoteIdentityProvider()->getSsoUrl()
134
        ));
135
136
        return $redirectBinding->createResponseFor($proxyRequest);
137
    }
138
139
    /**
140
     * Start a GSSP single sign-on.
141
     *
142
     * The user has selected a second factor token and the token happens to be
143
     * a GSSP token. The SecondFactorController therefor did an internal
144
     * redirect (see SecondFactorController::verifyGssfAction) to this method.
145
     *
146
     * In this method, an authn request is created. This authn request is sent
147
     * directly to the remote GSSP SSO URL, and the response is handled in
148
     * consumeAssertionAction().
149
     *
150
     * @param $provider
151
     * @param $subjectNameId
152
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
153
     */
154
    public function sendSecondFactorVerificationAuthnRequestAction($provider, $subjectNameId)
155
    {
156
        $provider = $this->getProvider($provider);
157
        $stateHandler = $provider->getStateHandler();
158
159
        $originalRequestId = $this->get('gateway.proxy.response_context')->getInResponseTo();
160
161
        $authnRequest = AuthnRequestFactory::createNewRequest(
162
            $provider->getServiceProvider(),
163
            $provider->getRemoteIdentityProvider()
164
        );
165
        $authnRequest->setSubject($subjectNameId);
166
167
        $stateHandler
168
            ->setRequestId($originalRequestId)
169
            ->setGatewayRequestId($authnRequest->getRequestId())
170
            ->setSubject($subjectNameId)
171
            ->markRequestAsSecondFactorVerification();
172
173
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
174
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
175
        $logger->notice(sprintf(
176
            'Sending AuthnRequest to verify Second Factor with request ID: "%s" to GSSP "%s" at "%s" for subject "%s"',
177
            $authnRequest->getRequestId(),
178
            $provider->getName(),
179
            $provider->getRemoteIdentityProvider()->getSsoUrl(),
180
            $subjectNameId
181
        ));
182
183
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
184
        $redirectBinding = $this->get('surfnet_saml.http.redirect_binding');
185
186
        return $redirectBinding->createResponseFor($authnRequest);
187
    }
188
189
    /**
190
     * Process an assertion received from the remote GSSP application.
191
     *
192
     * The GSSP application sent an assertion back to the gateway. When
193
     * successful, the user is sent back to:
194
     *
195
     *  1. in case of registration: back to the originating SP (SelfService)
196
     *  2. in case of verification: internal redirect to SecondFactorController
197
     *
198
     * @param string  $provider
199
     * @param Request $httpRequest
200
     * @return \Symfony\Component\HttpFoundation\Response
201
     */
202
    public function consumeAssertionAction($provider, Request $httpRequest)
203
    {
204
        $provider = $this->getProvider($provider);
205
        $stateHandler = $provider->getStateHandler();
206
        $originalRequestId = $stateHandler->getRequestId();
207
208
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
209
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
210
211
        $action = $stateHandler->hasSubject() ? 'Second Factor Verification' : 'Proxy Response';
212
        $logger->notice(
213
            sprintf('Received SAMLResponse, attempting to process for %s', $action)
214
        );
215
216
        try {
217
            /** @var \SAML2\Assertion $assertion */
218
            $assertion = $this->get('surfnet_saml.http.post_binding')->processResponse(
219
                $httpRequest,
220
                $provider->getRemoteIdentityProvider(),
221
                $provider->getServiceProvider()
222
            );
223
        } catch (Exception $exception) {
224
            $logger->error(sprintf('Could not process received Response, error: "%s"', $exception->getMessage()));
225
226
            $response = $this->createResponseFailureResponse(
227
                $provider,
228
                $this->getDestination($provider->getStateHandler())
229
            );
230
231
            return $this->renderSamlResponse('consumeAssertion', $stateHandler, $response);
232
        }
233
234
        $adaptedAssertion = new AssertionAdapter($assertion);
235
        $expectedResponse = $stateHandler->getGatewayRequestId();
236
        if (!$adaptedAssertion->inResponseToMatches($expectedResponse)) {
237
            throw new UnknownInResponseToException(
238
                $adaptedAssertion->getInResponseTo(),
239
                $expectedResponse
240
            );
241
        }
242
243
        $authenticatedNameId = $assertion->getNameId();
244
        $isSubjectRequested = $stateHandler->hasSubject();
245
        if ($isSubjectRequested && ($stateHandler->getSubject() !== $authenticatedNameId->value)) {
246
            $logger->critical(sprintf(
247
                'Requested Subject NameID "%s" and Response NameID "%s" do not match',
248
                $stateHandler->getSubject(),
249
                $authenticatedNameId->value
250
            ));
251
252
            return $this->renderSamlResponse(
253
                'recoverableError',
254
                $stateHandler,
255
                $this->createAuthnFailedResponse(
256
                    $provider,
257
                    $this->getDestination($provider->getStateHandler())
258
                )
259
            );
260
        }
261
262
        $logger->notice('Successfully processed SAMLResponse');
263
264
        if ($stateHandler->secondFactorVerificationRequested()) {
265
            $logger->notice(
266
                'Second Factor verification was requested and was successful, forwarding to SecondFactor handling'
267
            );
268
269
            return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:gssfVerified');
270
        }
271
272
        /** @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Saml\ProxyResponseFactory $proxyResponseFactory */
273
        $proxyResponseFactory  = $this->get('gssp.provider.' . $provider->getName() . '.response_proxy');
274
        $targetServiceProvider = $this->getServiceProvider($stateHandler->getRequestServiceProvider());
275
276
        $response = $proxyResponseFactory->createProxyResponse(
277
            $assertion,
278
            $targetServiceProvider->determineAcsLocation(
279
                $stateHandler->getRequestAssertionConsumerServiceUrl(),
280
                $this->get('logger')
281
            )
282
        );
283
284
        $logger->notice(sprintf(
285
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
286
            $stateHandler->getRequestId(),
287
            $response->getId()
288
        ));
289
290
        return $this->renderSamlResponse('consumeAssertion', $stateHandler, $response);
291
    }
292
293
    /**
294
     * @param string $provider
295
     * @return XMLResponse
296
     */
297
    public function metadataAction($provider)
298
    {
299
        $provider = $this->getProvider($provider);
300
301
        /** @var \Surfnet\SamlBundle\Metadata\MetadataFactory $factory */
302
        $factory = $this->get('gssp.provider.' . $provider->getName() . '.metadata.factory');
303
304
        return new XMLResponse($factory->generate());
305
    }
306
307
    /**
308
     * @param string $provider
309
     * @return \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\Provider
310
     */
311
    private function getProvider($provider)
312
    {
313
        /** @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\ProviderRepository $providerRepository */
314
        $providerRepository = $this->get('gssp.provider_repository');
315
316
        if (!$providerRepository->has($provider)) {
317
            throw new NotFoundHttpException(
318
                sprintf('Requested GSSP "%s" does not exist or is not registered', $provider)
319
            );
320
        }
321
322
        return $providerRepository->get($provider);
323
    }
324
325
    /**
326
     * @param StateHandler $stateHandler
327
     * @return string
328
     */
329
    private function getDestination(StateHandler $stateHandler)
330
    {
331
        if ($stateHandler->secondFactorVerificationRequested()) {
332
            // GSSP verification action, return to SP from GatewayController state!
333
            $destination = $this->get('gateway.proxy.response_context')->getDestination();
334
        } else {
335
            // GSSP registration action, return to SP remembered in ssoAction().
336
            $serviceProvider = $this->getServiceProvider(
337
                $stateHandler->getRequestServiceProvider()
338
            );
339
340
            $destination = $serviceProvider->determineAcsLocation(
341
                $stateHandler->getRequestAssertionConsumerServiceUrl(),
342
                $this->get('logger')
343
            );
344
        }
345
346
        return $destination;
347
    }
348
349
    /**
350
     * @param string         $view
351
     * @param StateHandler   $stateHandler
352
     * @param SAMLResponse $response
353
     * @return Response
354
     */
355 View Code Duplication
    public function renderSamlResponse($view, StateHandler $stateHandler, SAMLResponse $response)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
356
    {
357
        $response = $this->render($view, [
358
            'acu'        => $response->getDestination(),
359
            'response'   => $this->getResponseAsXML($response),
360
            'relayState' => $stateHandler->getRelayState()
361
        ]);
362
363
        // clear the state so we can call again :)
364
        $stateHandler->clear();
365
366
        return $response;
367
    }
368
369
    /**
370
     * @param string   $view
371
     * @param array    $parameters
372
     * @param Response $response
0 ignored issues
show
Documentation introduced by
Should the type for parameter $response not be null|Response?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
373
     * @return Response
374
     */
375
    public function render($view, array $parameters = array(), Response $response = null)
376
    {
377
        return parent::render(
378
            'SurfnetStepupGatewaySamlStepupProviderBundle:SamlProxy:' . $view . '.html.twig',
379
            $parameters,
380
            $response
381
        );
382
    }
383
384
    /**
385
     * @param SAMLResponse $response
386
     * @return string
387
     */
388
    private function getResponseAsXML(SAMLResponse $response)
389
    {
390
        return base64_encode($response->toUnsignedXML()->ownerDocument->saveXML());
391
    }
392
393
    /**
394
     * Response that indicates that an error occurred in the responder (the gateway). Used to indicate that we could
395
     * not process the response we received from the upstream GSSP
396
     *
397
     * @param Provider $provider
398
     * @param string $destination
399
     * @return SAMLResponse
400
     */
401
    private function createResponseFailureResponse(Provider $provider, $destination)
402
    {
403
        $response = $this->createResponse($provider, $destination);
404
        $response->setStatus(['Code' => Constants::STATUS_RESPONDER]);
405
406
        return $response;
407
    }
408
409
    /**
410
     * Response that indicates that the authentication could not be performed correctly. In this context it means
411
     * that the upstream GSSP did not responsd with the same NameID as we request to authenticate in the AuthnRequest
412
     *
413
     * @param Provider $provider
414
     * @param string $destination
415
     * @return SAMLResponse
416
     */
417
    private function createAuthnFailedResponse(Provider $provider, $destination)
418
    {
419
        $response = $this->createResponse($provider, $destination);
420
        $response->setStatus([
421
            'Code'    => Constants::STATUS_RESPONDER,
422
            'SubCode' => Constants::STATUS_AUTHN_FAILED
423
        ]);
424
425
        return $response;
426
    }
427
428
    /**
429
     * Creates a standard response with default status Code (success)
430
     *
431
     * @param Provider $provider
432
     * @param string $destination
433
     * @return SAMLResponse
434
     */
435
    private function createResponse(Provider $provider, $destination)
436
    {
437
        $response = new SAMLResponse();
438
        $response->setDestination($destination);
439
        $response->setIssuer($provider->getIdentityProvider()->getEntityId());
440
        $response->setIssueInstant((new DateTime('now'))->getTimestamp());
441
        $response->setInResponseTo($provider->getStateHandler()->getRequestId());
442
443
        return $response;
444
    }
445
446
    /**
447
     * @param string $serviceProvider
448
     * @return \Surfnet\StepupGateway\GatewayBundle\Entity\ServiceProvider
449
     */
450
    private function getServiceProvider($serviceProvider)
451
    {
452
        /**
453
         * @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\ConnectedServiceProviders $connectedServiceProviders
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 125 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
454
         */
455
        $connectedServiceProviders = $this->get('gssp.connected_service_providers');
456
        return $connectedServiceProviders->getConfigurationOf($serviceProvider);
457
    }
458
}
459