Completed
Push — feature/use-authn-request-acs-... ( 994cc5...dc9b8d )
by
unknown
02:32
created

SamlProxyController::getServiceProvider()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 1
eloc 3
nc 1
nop 1
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())
0 ignored issues
show
Bug introduced by
The method getAssertionConsumerServiceURL() does not seem to exist on object<Surfnet\SamlBundle\SAML2\AuthnRequest>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
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($provider);
224
225
            return $this->renderSamlResponse('unprocessableResponse', $stateHandler, $response);
226
        }
227
228
        $adaptedAssertion = new AssertionAdapter($assertion);
229
        $expectedResponse = $stateHandler->getGatewayRequestId();
230
        if (!$adaptedAssertion->inResponseToMatches($expectedResponse)) {
231
            throw new UnknownInResponseToException(
232
                $adaptedAssertion->getInResponseTo(),
233
                $expectedResponse
234
            );
235
        }
236
237
        $authenticatedNameId = $assertion->getNameId();
238
        $isSubjectRequested = $stateHandler->hasSubject();
239
        if ($isSubjectRequested && ($stateHandler->getSubject() !== $authenticatedNameId->value)) {
240
            $logger->critical(sprintf(
241
                'Requested Subject NameID "%s" and Response NameID "%s" do not match',
242
                $stateHandler->getSubject(),
243
                $authenticatedNameId->value
244
            ));
245
246
            if ($stateHandler->secondFactorVerificationRequested()) {
247
                // The error should go to the original requesting service provider.
248
                //
249
                // To achieve this, we need to get the context of the "outer" SAML request: the original
250
                // request as received by the GatewayController, and not the "inner" GSSP request.
251
252
                /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseContext $context */
253
                $context = $this->get('gateway.proxy.response_context');
254
                $targetServiceProvider = $context->getServiceProvider();
255
                $stateHandler->setRequestServiceProvider($targetServiceProvider->getEntityId());
256
                $stateHandler->setRequestAssertionConsumerServiceUrl(
257
                    $context->getUnvalidatedRequestAssertionConsumerServiceUrl()
258
                );
259
            }
260
261
            return $this->renderSamlResponse(
262
                'recoverableError',
263
                $stateHandler,
264
                $this->createAuthnFailedResponse($provider)
265
            );
266
        }
267
268
        $logger->notice('Successfully processed SAMLResponse');
269
270
        if ($stateHandler->secondFactorVerificationRequested()) {
271
            $logger->notice(
272
                'Second Factor verification was requested and was successful, forwarding to SecondFactor handling'
273
            );
274
275
            return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:gssfVerified');
276
        }
277
278
        /** @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Saml\ProxyResponseFactory $proxyResponseFactory */
279
        $proxyResponseFactory  = $this->get('gssp.provider.' . $provider->getName() . '.response_proxy');
280
        $targetServiceProvider = $this->getServiceProvider($stateHandler->getRequestServiceProvider());
281
282
        $response = $proxyResponseFactory->createProxyResponse(
283
            $assertion,
284
            $targetServiceProvider->determineAcsLocation(
285
                $stateHandler->getRequestAssertionConsumerServiceUrl(),
286
                $this->get('logger')
287
            )
288
        );
289
290
        $logger->notice(sprintf(
291
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
292
            $stateHandler->getRequestId(),
293
            $response->getId()
294
        ));
295
296
        return $this->renderSamlResponse('consumeAssertion', $stateHandler, $response);
297
    }
298
299
    /**
300
     * @param string $provider
301
     * @return XMLResponse
302
     */
303
    public function metadataAction($provider)
304
    {
305
        $provider = $this->getProvider($provider);
306
307
        /** @var \Surfnet\SamlBundle\Metadata\MetadataFactory $factory */
308
        $factory = $this->get('gssp.provider.' . $provider->getName() . '.metadata.factory');
309
310
        return new XMLResponse($factory->generate());
311
    }
312
313
    /**
314
     * @param string $provider
315
     * @return \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\Provider
316
     */
317
    private function getProvider($provider)
318
    {
319
        /** @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\ProviderRepository $providerRepository */
320
        $providerRepository = $this->get('gssp.provider_repository');
321
322
        if (!$providerRepository->has($provider)) {
323
            throw new NotFoundHttpException(
324
                sprintf('Requested GSSP "%s" does not exist or is not registered', $provider)
325
            );
326
        }
327
328
        return $providerRepository->get($provider);
329
    }
330
331
    /**
332
     * @param string         $view
333
     * @param StateHandler   $stateHandler
334
     * @param SAMLResponse $response
335
     * @return Response
336
     */
337 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...
338
    {
339
        $response = $this->render($view, [
340
            'acu'        => $response->getDestination(),
341
            'response'   => $this->getResponseAsXML($response),
342
            'relayState' => $stateHandler->getRelayState()
343
        ]);
344
345
        // clear the state so we can call again :)
346
        $stateHandler->clear();
347
348
        return $response;
349
    }
350
351
    /**
352
     * @param string   $view
353
     * @param array    $parameters
354
     * @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...
355
     * @return Response
356
     */
357
    public function render($view, array $parameters = array(), Response $response = null)
358
    {
359
        return parent::render(
360
            'SurfnetStepupGatewaySamlStepupProviderBundle:SamlProxy:' . $view . '.html.twig',
361
            $parameters,
362
            $response
363
        );
364
    }
365
366
    /**
367
     * @param SAMLResponse $response
368
     * @return string
369
     */
370
    private function getResponseAsXML(SAMLResponse $response)
371
    {
372
        return base64_encode($response->toUnsignedXML()->ownerDocument->saveXML());
373
    }
374
375
    /**
376
     * Response that indicates that an error occurred in the responder (the gateway). Used to indicate that we could
377
     * not process the response we received from the upstream GSSP
378
     *
379
     * @param Provider $provider
380
     * @return SAMLResponse
381
     */
382
    private function createResponseFailureResponse(Provider $provider)
383
    {
384
        $response = $this->createResponse($provider);
385
        $response->setStatus(['Code' => Constants::STATUS_RESPONDER]);
386
387
        return $response;
388
    }
389
390
    /**
391
     * Response that indicates that the authentication could not be performed correctly. In this context it means
392
     * that the upstream GSSP did not responsd with the same NameID as we request to authenticate in the AuthnRequest
393
     *
394
     * @param Provider $provider
395
     * @return SAMLResponse
396
     */
397
    private function createAuthnFailedResponse(Provider $provider)
398
    {
399
        $response = $this->createResponse($provider);
400
        $response->setStatus([
401
            'Code'    => Constants::STATUS_RESPONDER,
402
            'SubCode' => Constants::STATUS_AUTHN_FAILED
403
        ]);
404
405
        return $response;
406
    }
407
408
    /**
409
     * Creates a standard response with default status Code (success)
410
     *
411
     * @param Provider $provider
412
     * @return SAMLResponse
413
     */
414
    private function createResponse(Provider $provider)
415
    {
416
        $stateHandler = $provider->getStateHandler();
417
        $serviceProvider = $this->getServiceProvider($stateHandler->getRequestServiceProvider());
418
419
        $response = new SAMLResponse();
420
        $response->setDestination(
421
            $serviceProvider->determineAcsLocation(
422
                $stateHandler->getRequestAssertionConsumerServiceUrl(),
423
                $this->get('logger')
424
            )
425
        );
426
        $response->setIssuer($provider->getIdentityProvider()->getEntityId());
427
        $response->setIssueInstant((new DateTime('now'))->getTimestamp());
428
        $response->setInResponseTo($provider->getStateHandler()->getRequestId());
429
430
        return $response;
431
    }
432
433
    /**
434
     * @param string $serviceProvider
435
     * @return \Surfnet\StepupGateway\GatewayBundle\Entity\ServiceProvider
436
     */
437
    private function getServiceProvider($serviceProvider)
438
    {
439
        /**
440
         * @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...
441
         */
442
        $connectedServiceProviders = $this->get('gssp.connected_service_providers');
443
        return $connectedServiceProviders->getConfigurationOf($serviceProvider);
444
    }
445
}
446