Completed
Push — feature/use-authn-request-acs-... ( e65869...994cc5 )
by
unknown
05:35
created

SamlProxyController::renderSamlResponse()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 7

Duplication

Lines 13
Ratio 100 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 13
loc 13
rs 9.4285
cc 1
eloc 7
nc 1
nop 3
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 Psr\Log\LoggerInterface;
24
use SAML2\Constants;
25
use SAML2\Response as SAMLResponse;
26
use Surfnet\SamlBundle\Http\XMLResponse;
27
use Surfnet\SamlBundle\SAML2\AuthnRequest;
28
use Surfnet\SamlBundle\SAML2\AuthnRequestFactory;
29
use Surfnet\StepupGateway\GatewayBundle\Saml\AssertionAdapter;
30
use Surfnet\StepupGateway\GatewayBundle\Saml\Exception\UnknownInResponseToException;
31
use Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\Provider;
32
use Surfnet\StepupGateway\SamlStepupProviderBundle\Saml\StateHandler;
33
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
34
use Symfony\Component\HttpFoundation\Request;
35
use Symfony\Component\HttpFoundation\Response;
36
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
37
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
38
39
/**
40
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
41
 * @SuppressWarnings(PHPMD.NPathComplexity)
42
 *
43
 * Should be refactored, {@see https://www.pivotaltracker.com/story/show/90169776}
44
 */
45
class SamlProxyController extends Controller
46
{
47
    /**
48
     * @param string  $provider
49
     * @param Request $httpRequest
50
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
51
     */
52
    public function singleSignOnAction($provider, Request $httpRequest)
53
    {
54
        $provider = $this->getProvider($provider);
55
56
        $logger = $this->get('logger');
57
        $logger->notice('Received AuthnRequest, started processing');
58
59
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
60
        $redirectBinding = $this->get('surfnet_saml.http.redirect_binding');
61
62
        $originalRequest = $redirectBinding->processSignedRequest($httpRequest);
63
64
        $originalRequestId = $originalRequest->getRequestId();
65
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
66
        $logger->notice(sprintf(
67
            'AuthnRequest processing complete, received AuthnRequest from "%s", request ID: "%s"',
68
            $originalRequest->getServiceProvider(),
69
            $originalRequest->getRequestId()
70
        ));
71
72
        $logger->debug('Checking if SP "%s" is supported');
73
        /**
74
         * @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...
75
         */
76
        $connectedServiceProviders = $this->get('gssp.connected_service_providers');
77
        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...
78
            $logger->warning(sprintf(
79
                'Received AuthnRequest from SP "%s", while SP is not allowed to use this for SSO',
80
                $originalRequest->getServiceProvider()
81
            ));
82
83
            throw new AccessDeniedHttpException();
84
        }
85
86
        /** @var StateHandler $stateHandler */
87
        $stateHandler = $provider->getStateHandler();
88
89
        // Clear the state of the previous SSO action. Request data of
90
        // previous SSO actions should not have any effect in subsequent SSO
91
        // actions.
92
        $stateHandler->clear();
93
94
        $stateHandler
95
            ->setRequestId($originalRequestId)
96
            ->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...
97
            ->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...
98
            ->setRelayState($httpRequest->get(AuthnRequest::PARAMETER_RELAY_STATE, ''));
99
100
        $proxyRequest = AuthnRequestFactory::createNewRequest(
101
            $provider->getServiceProvider(),
102
            $provider->getRemoteIdentityProvider()
103
        );
104
105
        // if a Specific subject is given to authenticate we should proxy that and verify in the response
106
        // that that subject indeed was authenticated
107
        $nameId = $originalRequest->getNameId();
108
        if ($nameId) {
109
            $proxyRequest->setSubject($nameId, $originalRequest->getNameIdFormat());
110
            $stateHandler->setSubject($nameId);
111
        }
112
113
        $proxyRequest->setScoping([$originalRequest->getServiceProvider()]);
114
        $stateHandler->setGatewayRequestId($proxyRequest->getRequestId());
115
116
        $logger->notice(sprintf(
117
            'Sending Proxy AuthnRequest with request ID: "%s" for original AuthnRequest "%s" to GSSP "%s" at "%s"',
118
            $proxyRequest->getRequestId(),
119
            $originalRequest->getRequestId(),
120
            $provider->getName(),
121
            $provider->getRemoteIdentityProvider()->getSsoUrl()
122
        ));
123
124
        return $redirectBinding->createResponseFor($proxyRequest);
125
    }
126
127
    public function sendSecondFactorVerificationAuthnRequestAction($provider, $subjectNameId)
128
    {
129
        $provider = $this->getProvider($provider);
130
        $stateHandler = $provider->getStateHandler();
131
132
        $originalRequestId = $this->get('gateway.proxy.response_context')->getInResponseTo();
133
134
        $authnRequest = AuthnRequestFactory::createNewRequest(
135
            $provider->getServiceProvider(),
136
            $provider->getRemoteIdentityProvider()
137
        );
138
        $authnRequest->setSubject($subjectNameId);
139
140
        $stateHandler
141
            ->setRequestId($originalRequestId)
142
            ->setGatewayRequestId($authnRequest->getRequestId())
143
            ->setSubject($subjectNameId)
144
            ->markRequestAsSecondFactorVerification();
145
146
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
147
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
148
        $logger->notice(sprintf(
149
            'Sending AuthnRequest to verify Second Factor with request ID: "%s" to GSSP "%s" at "%s" for subject "%s"',
150
            $authnRequest->getRequestId(),
151
            $provider->getName(),
152
            $provider->getRemoteIdentityProvider()->getSsoUrl(),
153
            $subjectNameId
154
        ));
155
156
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
157
        $redirectBinding = $this->get('surfnet_saml.http.redirect_binding');
158
159
        return $redirectBinding->createResponseFor($authnRequest);
160
    }
161
162
    /**
163
     * @param string  $provider
164
     * @param Request $httpRequest
165
     * @return \Symfony\Component\HttpFoundation\Response
166
     */
167
    public function consumeAssertionAction($provider, Request $httpRequest)
168
    {
169
        $provider = $this->getProvider($provider);
170
        $stateHandler = $provider->getStateHandler();
171
        $originalRequestId = $stateHandler->getRequestId();
172
173
        /** @var \Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger $logger */
174
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
175
176
        $action = $stateHandler->hasSubject() ? 'Second Factor Verification' : 'Proxy Response';
177
        $logger->notice(
178
            sprintf('Received SAMLResponse, attempting to process for %s', $action)
179
        );
180
181
        try {
182
            /** @var \SAML2\Assertion $assertion */
183
            $assertion = $this->get('surfnet_saml.http.post_binding')->processResponse(
184
                $httpRequest,
185
                $provider->getRemoteIdentityProvider(),
186
                $provider->getServiceProvider()
187
            );
188
        } catch (Exception $exception) {
189
            $logger->error(sprintf('Could not process received Response, error: "%s"', $exception->getMessage()));
190
191
            $response = $this->createResponseFailureResponse($provider);
192
193
            return $this->renderSamlResponse('unprocessableResponse', $stateHandler, $response);
194
        }
195
196
        $adaptedAssertion = new AssertionAdapter($assertion);
197
        $expectedResponse = $stateHandler->getGatewayRequestId();
198
        if (!$adaptedAssertion->inResponseToMatches($expectedResponse)) {
199
            throw new UnknownInResponseToException(
200
                $adaptedAssertion->getInResponseTo(),
201
                $expectedResponse
202
            );
203
        }
204
205
        $authenticatedNameId = $assertion->getNameId();
206
        $isSubjectRequested = $stateHandler->hasSubject();
207
        if ($isSubjectRequested && ($stateHandler->getSubject() !== $authenticatedNameId->value)) {
208
            $logger->critical(sprintf(
209
                'Requested Subject NameID "%s" and Response NameID "%s" do not match',
210
                $stateHandler->getSubject(),
211
                $authenticatedNameId->value
212
            ));
213
214
            if ($stateHandler->secondFactorVerificationRequested()) {
215
                // The error should go to the original requesting service provider.
216
                //
217
                // To achieve this, we need to get the context of the "outer" SAML request: the original
218
                // request as received by the GatewayController, and not the "inner" GSSP request.
219
220
                /** @var \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseContext $context */
221
                $targetServiceProvider = $this->get('gateway.proxy.response_context')->getServiceProvider();
222
                $stateHandler->setRequestServiceProvider($targetServiceProvider->getEntityId());
223
            }
224
225
            return $this->renderSamlResponse(
226
                'recoverableError',
227
                $stateHandler,
228
                $this->createAuthnFailedResponse($provider)
229
            );
230
        }
231
232
        $logger->notice('Successfully processed SAMLResponse');
233
234
        if ($stateHandler->secondFactorVerificationRequested()) {
235
            $logger->notice(
236
                'Second Factor verification was requested and was successful, forwarding to SecondFactor handling'
237
            );
238
239
            return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:gssfVerified');
240
        }
241
242
        /** @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Saml\ProxyResponseFactory $proxyResponseFactory */
243
        $proxyResponseFactory = $this->get('gssp.provider.' . $provider->getName() . '.response_proxy');
244
        $response             = $proxyResponseFactory->createProxyResponse($assertion);
245
246
        $logger->notice(sprintf(
247
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
248
            $stateHandler->getRequestId(),
249
            $response->getId()
250
        ));
251
252
        return $this->renderSamlResponse('consumeAssertion', $stateHandler, $response);
253
    }
254
255
    /**
256
     * @param string $provider
257
     * @return XMLResponse
258
     */
259
    public function metadataAction($provider)
260
    {
261
        $provider = $this->getProvider($provider);
262
263
        /** @var \Surfnet\SamlBundle\Metadata\MetadataFactory $factory */
264
        $factory = $this->get('gssp.provider.' . $provider->getName() . '.metadata.factory');
265
266
        return new XMLResponse($factory->generate());
267
    }
268
269
    /**
270
     * @param string $provider
271
     * @return \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\Provider
272
     */
273
    private function getProvider($provider)
274
    {
275
        /** @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\ProviderRepository $providerRepository */
276
        $providerRepository = $this->get('gssp.provider_repository');
277
278
        if (!$providerRepository->has($provider)) {
279
            throw new NotFoundHttpException(
280
                sprintf('Requested GSSP "%s" does not exist or is not registered', $provider)
281
            );
282
        }
283
284
        return $providerRepository->get($provider);
285
    }
286
287
    /**
288
     * @param string         $view
289
     * @param StateHandler   $stateHandler
290
     * @param SAMLResponse $response
291
     * @return Response
292
     */
293 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...
294
    {
295
        $response = $this->render($view, [
296
            'acu'        => $response->getDestination(),
297
            'response'   => $this->getResponseAsXML($response),
298
            'relayState' => $stateHandler->getRelayState()
299
        ]);
300
301
        // clear the state so we can call again :)
302
        $stateHandler->clear();
303
304
        return $response;
305
    }
306
307
    /**
308
     * @param string   $view
309
     * @param array    $parameters
310
     * @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...
311
     * @return Response
312
     */
313
    public function render($view, array $parameters = array(), Response $response = null)
314
    {
315
        return parent::render(
316
            'SurfnetStepupGatewaySamlStepupProviderBundle:SamlProxy:' . $view . '.html.twig',
317
            $parameters,
318
            $response
319
        );
320
    }
321
322
    /**
323
     * @param SAMLResponse $response
324
     * @return string
325
     */
326
    private function getResponseAsXML(SAMLResponse $response)
327
    {
328
        return base64_encode($response->toUnsignedXML()->ownerDocument->saveXML());
329
    }
330
331
    /**
332
     * Response that indicates that an error occurred in the responder (the gateway). Used to indicate that we could
333
     * not process the response we received from the upstream GSSP
334
     *
335
     * @param Provider $provider
336
     * @return SAMLResponse
337
     */
338
    private function createResponseFailureResponse(Provider $provider)
339
    {
340
        $response = $this->createResponse($provider);
341
        $response->setStatus(['Code' => Constants::STATUS_RESPONDER]);
342
343
        return $response;
344
    }
345
346
    /**
347
     * Response that indicates that the authentication could not be performed correctly. In this context it means
348
     * that the upstream GSSP did not responsd with the same NameID as we request to authenticate in the AuthnRequest
349
     *
350
     * @param Provider $provider
351
     * @return SAMLResponse
352
     */
353
    private function createAuthnFailedResponse(Provider $provider)
354
    {
355
        $response = $this->createResponse($provider);
356
        $response->setStatus([
357
            'Code'    => Constants::STATUS_RESPONDER,
358
            'SubCode' => Constants::STATUS_AUTHN_FAILED
359
        ]);
360
361
        return $response;
362
    }
363
364
    /**
365
     * Creates a standard response with default status Code (success)
366
     *
367
     * @param Provider $provider
368
     * @return SAMLResponse
369
     */
370
    private function createResponse(Provider $provider)
371
    {
372
        $stateHandler = $provider->getStateHandler();
373
374
        $response = new SAMLResponse();
375
        $response->setDestination($stateHandler->getRequestAssertionConsumerServiceUrl());
376
        $response->setIssuer($provider->getIdentityProvider()->getEntityId());
377
        $response->setIssueInstant((new DateTime('now'))->getTimestamp());
378
        $response->setInResponseTo($provider->getStateHandler()->getRequestId());
379
380
        return $response;
381
    }
382
}
383