Completed
Push — feature/use-authn-request-acs-... ( b0d5b4...6c793d )
by
unknown
03:10
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
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
40
 * @SuppressWarnings(PHPMD.NPathComplexity)
41
 *
42
 * Should be refactored, {@see https://www.pivotaltracker.com/story/show/90169776}
43
 */
44
class SamlProxyController extends Controller
45
{
46
    /**
47
     * @param string  $provider
48
     * @param Request $httpRequest
49
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
50
     */
51
    public function singleSignOnAction($provider, Request $httpRequest)
52
    {
53
        $provider = $this->getProvider($provider);
54
55
        /** @var \Psr\Log\LoggerInterface $logger */
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
                $context = $this->get('gateway.proxy.response_context');
222
223
                $targetServiceProvider = $context->getServiceProvider();
224
                $stateHandler->setRequestServiceProvider($targetServiceProvider->getEntityId());
225
                $stateHandler->setRequestAssertionConsumerServiceUrl($context->getDestination());
226
            }
227
228
            return $this->renderSamlResponse(
229
                'recoverableError',
230
                $stateHandler,
231
                $this->createAuthnFailedResponse($provider)
232
            );
233
        }
234
235
        $logger->notice('Successfully processed SAMLResponse');
236
237
        if ($stateHandler->secondFactorVerificationRequested()) {
238
            $logger->notice(
239
                'Second Factor verification was requested and was successful, forwarding to SecondFactor handling'
240
            );
241
242
            return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:gssfVerified');
243
        }
244
245
        /** @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Saml\ProxyResponseFactory $proxyResponseFactory */
246
        $proxyResponseFactory = $this->get('gssp.provider.' . $provider->getName() . '.response_proxy');
247
        $response             = $proxyResponseFactory->createProxyResponse($assertion);
248
249
        $logger->notice(sprintf(
250
            'Responding to request "%s" with response based on response from the remote IdP with response "%s"',
251
            $stateHandler->getRequestId(),
252
            $response->getId()
253
        ));
254
255
        return $this->renderSamlResponse('consumeAssertion', $stateHandler, $response);
256
    }
257
258
    /**
259
     * @param string $provider
260
     * @return XMLResponse
261
     */
262
    public function metadataAction($provider)
263
    {
264
        $provider = $this->getProvider($provider);
265
266
        /** @var \Surfnet\SamlBundle\Metadata\MetadataFactory $factory */
267
        $factory = $this->get('gssp.provider.' . $provider->getName() . '.metadata.factory');
268
269
        return new XMLResponse($factory->generate());
270
    }
271
272
    /**
273
     * @param string $provider
274
     * @return \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\Provider
275
     */
276
    private function getProvider($provider)
277
    {
278
        /** @var \Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\ProviderRepository $providerRepository */
279
        $providerRepository = $this->get('gssp.provider_repository');
280
281
        if (!$providerRepository->has($provider)) {
282
            throw new NotFoundHttpException(
283
                sprintf('Requested GSSP "%s" does not exist or is not registered', $provider)
284
            );
285
        }
286
287
        return $providerRepository->get($provider);
288
    }
289
290
    /**
291
     * @param string         $view
292
     * @param StateHandler   $stateHandler
293
     * @param SAMLResponse $response
294
     * @return Response
295
     */
296 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...
297
    {
298
        $response = $this->render($view, [
299
            'acu'        => $response->getDestination(),
300
            'response'   => $this->getResponseAsXML($response),
301
            'relayState' => $stateHandler->getRelayState()
302
        ]);
303
304
        // clear the state so we can call again :)
305
        $stateHandler->clear();
306
307
        return $response;
308
    }
309
310
    /**
311
     * @param string   $view
312
     * @param array    $parameters
313
     * @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...
314
     * @return Response
315
     */
316
    public function render($view, array $parameters = array(), Response $response = null)
317
    {
318
        return parent::render(
319
            'SurfnetStepupGatewaySamlStepupProviderBundle:SamlProxy:' . $view . '.html.twig',
320
            $parameters,
321
            $response
322
        );
323
    }
324
325
    /**
326
     * @param SAMLResponse $response
327
     * @return string
328
     */
329
    private function getResponseAsXML(SAMLResponse $response)
330
    {
331
        return base64_encode($response->toUnsignedXML()->ownerDocument->saveXML());
332
    }
333
334
    /**
335
     * Response that indicates that an error occurred in the responder (the gateway). Used to indicate that we could
336
     * not process the response we received from the upstream GSSP
337
     *
338
     * @param Provider $provider
339
     * @return SAMLResponse
340
     */
341
    private function createResponseFailureResponse(Provider $provider)
342
    {
343
        $response = $this->createResponse($provider);
344
        $response->setStatus(['Code' => Constants::STATUS_RESPONDER]);
345
346
        return $response;
347
    }
348
349
    /**
350
     * Response that indicates that the authentication could not be performed correctly. In this context it means
351
     * that the upstream GSSP did not responsd with the same NameID as we request to authenticate in the AuthnRequest
352
     *
353
     * @param Provider $provider
354
     * @return SAMLResponse
355
     */
356
    private function createAuthnFailedResponse(Provider $provider)
357
    {
358
        $response = $this->createResponse($provider);
359
        $response->setStatus([
360
            'Code'    => Constants::STATUS_RESPONDER,
361
            'SubCode' => Constants::STATUS_AUTHN_FAILED
362
        ]);
363
364
        return $response;
365
    }
366
367
    /**
368
     * Creates a standard response with default status Code (success)
369
     *
370
     * @param Provider $provider
371
     * @return SAMLResponse
372
     */
373
    private function createResponse(Provider $provider)
374
    {
375
        $stateHandler = $provider->getStateHandler();
376
377
        $response = new SAMLResponse();
378
        $response->setDestination($stateHandler->getRequestAssertionConsumerServiceUrl());
379
        $response->setIssuer($provider->getIdentityProvider()->getEntityId());
380
        $response->setIssueInstant((new DateTime('now'))->getTimestamp());
381
        $response->setInResponseTo($provider->getStateHandler()->getRequestId());
382
383
        return $response;
384
    }
385
}
386