Completed
Push — feature/use-authn-request-acs-... ( c5e9ea...2f048b )
by
unknown
04:29 queued 02:17
created

SamlProxyController::consumeAssertionAction()   C

Complexity

Conditions 7
Paths 10

Size

Total Lines 90
Code Lines 55

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 90
rs 6.5083
cc 7
eloc 55
nc 10
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. An authn
55
     * request was created in ::sendSecondFactorVerificationAuthnRequestAction() and this method
56
     * proxies the authn request to the remote SSO URL. The remote application
57
     * will send an assertion back to consumeAssertionAction().
58
     *
59
     * @param string  $provider
60
     * @param Request $httpRequest
61
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
62
     */
63
    public function singleSignOnAction($provider, Request $httpRequest)
64
    {
65
        $provider = $this->getProvider($provider);
66
67
        $logger = $this->get('logger');
68
        $logger->notice('Received AuthnRequest, started processing');
69
70
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
71
        $redirectBinding = $this->get('surfnet_saml.http.redirect_binding');
72
73
        $originalRequest = $redirectBinding->processSignedRequest($httpRequest);
74
75
        $originalRequestId = $originalRequest->getRequestId();
76
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
77
        $logger->notice(sprintf(
78
            'AuthnRequest processing complete, received AuthnRequest from "%s", request ID: "%s"',
79
            $originalRequest->getServiceProvider(),
80
            $originalRequest->getRequestId()
81
        ));
82
83
        $logger->debug('Checking if SP "%s" is supported');
84
        /**
85
         * @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...
86
         */
87
        $connectedServiceProviders = $this->get('gssp.connected_service_providers');
88
        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...
89
            $logger->warning(sprintf(
90
                'Received AuthnRequest from SP "%s", while SP is not allowed to use this for SSO',
91
                $originalRequest->getServiceProvider()
92
            ));
93
94
            throw new AccessDeniedHttpException();
95
        }
96
97
        /** @var StateHandler $stateHandler */
98
        $stateHandler = $provider->getStateHandler();
99
100
        // Clear the state of the previous SSO action. Request data of
101
        // previous SSO actions should not have any effect in subsequent SSO
102
        // actions.
103
        $stateHandler->clear();
104
105
        $stateHandler
106
            ->setRequestId($originalRequestId)
107
            ->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...
108
            ->setRequestAssertionConsumerServiceUrl($originalRequest->getAssertionConsumerServiceURL())
109
            ->setRelayState($httpRequest->get(AuthnRequest::PARAMETER_RELAY_STATE, ''));
110
111
        $proxyRequest = AuthnRequestFactory::createNewRequest(
112
            $provider->getServiceProvider(),
113
            $provider->getRemoteIdentityProvider()
114
        );
115
116
        // if a Specific subject is given to authenticate we should proxy that and verify in the response
117
        // that that subject indeed was authenticated
118
        $nameId = $originalRequest->getNameId();
119
        if ($nameId) {
120
            $proxyRequest->setSubject($nameId, $originalRequest->getNameIdFormat());
121
            $stateHandler->setSubject($nameId);
122
        }
123
124
        $proxyRequest->setScoping([$originalRequest->getServiceProvider()]);
125
        $stateHandler->setGatewayRequestId($proxyRequest->getRequestId());
126
127
        $logger->notice(sprintf(
128
            'Sending Proxy AuthnRequest with request ID: "%s" for original AuthnRequest "%s" to GSSP "%s" at "%s"',
129
            $proxyRequest->getRequestId(),
130
            $originalRequest->getRequestId(),
131
            $provider->getName(),
132
            $provider->getRemoteIdentityProvider()->getSsoUrl()
133
        ));
134
135
        return $redirectBinding->createResponseFor($proxyRequest);
136
    }
137
138
    /**
139
     * Start a GSSP single sign-on.
140
     *
141
     * The user has selected a second factor token and the token happens to be
142
     * a GSSP token. The SecondFactorController therefor did an internal
143
     * redirect (see SecondFactorController::verifyGssfAction) to this method.
144
     *
145
     * In this method, an authn request is created. This authn request is not
146
     * sent directly to the GSSP SSO URL, but proxied trough the gateway first
147
     * (see SamlProxyController::ssoAction).
148
     *
149
     * @param $provider
150
     * @param $subjectNameId
151
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
152
     */
153
    public function sendSecondFactorVerificationAuthnRequestAction($provider, $subjectNameId)
154
    {
155
        $provider = $this->getProvider($provider);
156
        $stateHandler = $provider->getStateHandler();
157
158
        $originalRequestId = $this->get('gateway.proxy.response_context')->getInResponseTo();
159
160
        $authnRequest = AuthnRequestFactory::createNewRequest(
161
            $provider->getServiceProvider(),
162
            $provider->getRemoteIdentityProvider()
163
        );
164
        $authnRequest->setSubject($subjectNameId);
165
166
        $stateHandler
167
            ->setRequestId($originalRequestId)
168
            ->setGatewayRequestId($authnRequest->getRequestId())
169
            ->setSubject($subjectNameId)
170
            ->markRequestAsSecondFactorVerification();
171
172
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
173
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
174
        $logger->notice(sprintf(
175
            'Sending AuthnRequest to verify Second Factor with request ID: "%s" to GSSP "%s" at "%s" for subject "%s"',
176
            $authnRequest->getRequestId(),
177
            $provider->getName(),
178
            $provider->getRemoteIdentityProvider()->getSsoUrl(),
179
            $subjectNameId
180
        ));
181
182
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
183
        $redirectBinding = $this->get('surfnet_saml.http.redirect_binding');
184
185
        return $redirectBinding->createResponseFor($authnRequest);
186
    }
187
188
    /**
189
     * Process an assertion received from the remote GSSP application.
190
     *
191
     * The GSSP application sent an assertion back to the gateway. When
192
     * successful, the user is sent back to the
193
     * SecondFactorController:gssfVerifiedAction.
194
     *
195
     * @param string  $provider
196
     * @param Request $httpRequest
197
     * @return \Symfony\Component\HttpFoundation\Response
198
     */
199
    public function consumeAssertionAction($provider, Request $httpRequest)
200
    {
201
        $provider = $this->getProvider($provider);
202
        $stateHandler = $provider->getStateHandler();
203
        $originalRequestId = $stateHandler->getRequestId();
204
205
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
206
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
207
208
        $action = $stateHandler->hasSubject() ? 'Second Factor Verification' : 'Proxy Response';
209
        $logger->notice(
210
            sprintf('Received SAMLResponse, attempting to process for %s', $action)
211
        );
212
213
        try {
214
            /** @var \SAML2\Assertion $assertion */
215
            $assertion = $this->get('surfnet_saml.http.post_binding')->processResponse(
216
                $httpRequest,
217
                $provider->getRemoteIdentityProvider(),
218
                $provider->getServiceProvider()
219
            );
220
        } catch (Exception $exception) {
221
            $logger->error(sprintf('Could not process received Response, error: "%s"', $exception->getMessage()));
222
223
            $response = $this->createResponseFailureResponse(
224
                $provider,
225
                $this->getDestination($provider->getStateHandler())
226
            );
227
228
            return $this->renderSamlResponse('consumeAssertion', $stateHandler, $response);
229
        }
230
231
        $adaptedAssertion = new AssertionAdapter($assertion);
232
        $expectedResponse = $stateHandler->getGatewayRequestId();
233
        if (!$adaptedAssertion->inResponseToMatches($expectedResponse)) {
234
            throw new UnknownInResponseToException(
235
                $adaptedAssertion->getInResponseTo(),
236
                $expectedResponse
237
            );
238
        }
239
240
        $authenticatedNameId = $assertion->getNameId();
241
        $isSubjectRequested = $stateHandler->hasSubject();
242
        if ($isSubjectRequested && ($stateHandler->getSubject() !== $authenticatedNameId->value)) {
243
            $logger->critical(sprintf(
244
                'Requested Subject NameID "%s" and Response NameID "%s" do not match',
245
                $stateHandler->getSubject(),
246
                $authenticatedNameId->value
247
            ));
248
249
            return $this->renderSamlResponse(
250
                'recoverableError',
251
                $stateHandler,
252
                $this->createAuthnFailedResponse(
253
                    $provider,
254
                    $this->getDestination($provider->getStateHandler())
255
                )
256
            );
257
        }
258
259
        $logger->notice('Successfully processed SAMLResponse');
260
261
        if ($stateHandler->secondFactorVerificationRequested()) {
262
            $logger->notice(
263
                'Second Factor verification was requested and was successful, forwarding to SecondFactor handling'
264
            );
265
266
            return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:gssfVerified');
267
        }
268
269
        /** @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Saml\ProxyResponseFactory $proxyResponseFactory */
270
        $proxyResponseFactory  = $this->get('gssp.provider.' . $provider->getName() . '.response_proxy');
271
        $targetServiceProvider = $this->getServiceProvider($stateHandler->getRequestServiceProvider());
272
273
        $response = $proxyResponseFactory->createProxyResponse(
274
            $assertion,
275
            $targetServiceProvider->determineAcsLocation(
276
                $stateHandler->getRequestAssertionConsumerServiceUrl(),
277
                $this->get('logger')
278
            )
279
        );
280
281
        $logger->notice(sprintf(
282
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
283
            $stateHandler->getRequestId(),
284
            $response->getId()
285
        ));
286
287
        return $this->renderSamlResponse('consumeAssertion', $stateHandler, $response);
288
    }
289
290
    /**
291
     * @param string $provider
292
     * @return XMLResponse
293
     */
294
    public function metadataAction($provider)
295
    {
296
        $provider = $this->getProvider($provider);
297
298
        /** @var \Surfnet\SamlBundle\Metadata\MetadataFactory $factory */
299
        $factory = $this->get('gssp.provider.' . $provider->getName() . '.metadata.factory');
300
301
        return new XMLResponse($factory->generate());
302
    }
303
304
    /**
305
     * @param string $provider
306
     * @return \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\Provider
307
     */
308
    private function getProvider($provider)
309
    {
310
        /** @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\ProviderRepository $providerRepository */
311
        $providerRepository = $this->get('gssp.provider_repository');
312
313
        if (!$providerRepository->has($provider)) {
314
            throw new NotFoundHttpException(
315
                sprintf('Requested GSSP "%s" does not exist or is not registered', $provider)
316
            );
317
        }
318
319
        return $providerRepository->get($provider);
320
    }
321
322
    /**
323
     * @param StateHandler $stateHandler
324
     * @return string
325
     */
326
    private function getDestination(StateHandler $stateHandler)
327
    {
328
        if ($stateHandler->secondFactorVerificationRequested()) {
329
            // GSSP verification action, return to SP from GatewayController state!
330
            $destination = $this->get('gateway.proxy.response_context')->getDestination();
331
        } else {
332
            // GSSP registration action, return to SP remembered in ssoAction().
333
            $serviceProvider = $this->getServiceProvider(
334
                $stateHandler->getRequestServiceProvider()
335
            );
336
337
            $destination = $serviceProvider->determineAcsLocation(
338
                $stateHandler->getRequestAssertionConsumerServiceUrl(),
339
                $this->get('logger')
340
            );
341
        }
342
343
        return $destination;
344
    }
345
346
    /**
347
     * @param string         $view
348
     * @param StateHandler   $stateHandler
349
     * @param SAMLResponse $response
350
     * @return Response
351
     */
352 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...
353
    {
354
        $response = $this->render($view, [
355
            'acu'        => $response->getDestination(),
356
            'response'   => $this->getResponseAsXML($response),
357
            'relayState' => $stateHandler->getRelayState()
358
        ]);
359
360
        // clear the state so we can call again :)
361
        $stateHandler->clear();
362
363
        return $response;
364
    }
365
366
    /**
367
     * @param string   $view
368
     * @param array    $parameters
369
     * @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...
370
     * @return Response
371
     */
372
    public function render($view, array $parameters = array(), Response $response = null)
373
    {
374
        return parent::render(
375
            'SurfnetStepupGatewaySamlStepupProviderBundle:SamlProxy:' . $view . '.html.twig',
376
            $parameters,
377
            $response
378
        );
379
    }
380
381
    /**
382
     * @param SAMLResponse $response
383
     * @return string
384
     */
385
    private function getResponseAsXML(SAMLResponse $response)
386
    {
387
        return base64_encode($response->toUnsignedXML()->ownerDocument->saveXML());
388
    }
389
390
    /**
391
     * Response that indicates that an error occurred in the responder (the gateway). Used to indicate that we could
392
     * not process the response we received from the upstream GSSP
393
     *
394
     * @param Provider $provider
395
     * @param string $destination
396
     * @return SAMLResponse
397
     */
398
    private function createResponseFailureResponse(Provider $provider, $destination)
399
    {
400
        $response = $this->createResponse($provider, $destination);
401
        $response->setStatus(['Code' => Constants::STATUS_RESPONDER]);
402
403
        return $response;
404
    }
405
406
    /**
407
     * Response that indicates that the authentication could not be performed correctly. In this context it means
408
     * that the upstream GSSP did not responsd with the same NameID as we request to authenticate in the AuthnRequest
409
     *
410
     * @param Provider $provider
411
     * @param string $destination
412
     * @return SAMLResponse
413
     */
414
    private function createAuthnFailedResponse(Provider $provider, $destination)
415
    {
416
        $response = $this->createResponse($provider, $destination);
417
        $response->setStatus([
418
            'Code'    => Constants::STATUS_RESPONDER,
419
            'SubCode' => Constants::STATUS_AUTHN_FAILED
420
        ]);
421
422
        return $response;
423
    }
424
425
    /**
426
     * Creates a standard response with default status Code (success)
427
     *
428
     * @param Provider $provider
429
     * @param string $destination
430
     * @return SAMLResponse
431
     */
432
    private function createResponse(Provider $provider, $destination)
433
    {
434
        $response = new SAMLResponse();
435
        $response->setDestination($destination);
436
        $response->setIssuer($provider->getIdentityProvider()->getEntityId());
437
        $response->setIssueInstant((new DateTime('now'))->getTimestamp());
438
        $response->setInResponseTo($provider->getStateHandler()->getRequestId());
439
440
        return $response;
441
    }
442
443
    /**
444
     * @param string $serviceProvider
445
     * @return \Surfnet\StepupGateway\GatewayBundle\Entity\ServiceProvider
446
     */
447
    private function getServiceProvider($serviceProvider)
448
    {
449
        /**
450
         * @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...
451
         */
452
        $connectedServiceProviders = $this->get('gssp.connected_service_providers');
453
        return $connectedServiceProviders->getConfigurationOf($serviceProvider);
454
    }
455
}
456