Completed
Pull Request — develop (#121)
by
unknown
04:18 queued 02:14
created

SecondFactorOnlyController::getResponseContext()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
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\SecondFactorOnlyBundle\Controller;
20
21
use Exception;
22
use Surfnet\SamlBundle\SAML2\AuthnRequest;
23
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Saml\ResponseFactory;
24
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\LoaAliasLookupService;
25
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
26
use Symfony\Component\HttpFoundation\Request;
27
use Symfony\Component\HttpFoundation\Response;
28
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
29
30
class SecondFactorOnlyController extends Controller
31
{
32
    /**
33
     * @param Request $httpRequest
34
     * @return Response
35
     */
36
    public function ssoAction(Request $httpRequest)
37
    {
38
        $logger = $this->get('logger');
39
40
        if (!$this->getParameter('second_factor_only')) {
41
            $logger->notice('Access to ssoAction denied, second_factor_only parameter set to false.');
42
43
            throw $this->createAccessDeniedException('Second Factor Only feature is disabled');
44
        }
45
46
        $logger->notice('Received AuthnRequest on second-factor-only endpoint, started processing');
47
48
        /** @var \Surfnet\SamlBundle\Http\RedirectBinding $redirectBinding */
49
        $bindingFactory = $this->get('second_factor_only.http.binding_factory');
50
51
        try {
52
            $logger->notice('Determine what type of Binding is used in the Request');
53
            $binding = $bindingFactory->build($httpRequest);
54
            $originalRequest = $binding->receiveSignedAuthnRequestFrom($httpRequest);
55
        } catch (Exception $e) {
56
            $logger->critical(sprintf('Could not process Request, error: "%s"', $e->getMessage()));
57
58
            return $this->render('SurfnetStepupGatewayGatewayBundle:Gateway:unrecoverableError.html.twig');
59
        }
60
61
        $originalRequestId = $originalRequest->getRequestId();
62
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
63
        $logger->notice(sprintf(
64
            'AuthnRequest processing complete, received AuthnRequest from "%s", request ID: "%s"',
65
            $originalRequest->getServiceProvider(),
66
            $originalRequest->getRequestId()
67
        ));
68
69
        // ADFS support
70
        $adfsHelper = $this->get('second_factor_only.adfs.request_helper');
71
        if ($adfsHelper->isAdfsRequest($httpRequest)) {
72
            $logger->notice('Received AuthnRequest from an ADFS');
73
            try {
74
                $httpRequest = $adfsHelper->transformRequest($httpRequest, $originalRequest->getRequestId());
75
            } catch (Exception $e) {
76
                $logger->critical(sprintf('Could not process ADFS Request, error: "%s"', $e->getMessage()));
77
                return $this->render('SurfnetStepupGatewayGatewayBundle:Gateway:unrecoverableError.html.twig');
78
            }
79
        }
80
81
        $stateHandler = $this->get('gateway.proxy.state_handler');
82
        $stateHandler
83
            ->setRequestId($originalRequestId)
84
            ->setRequestServiceProvider($originalRequest->getServiceProvider())
85
            ->setRelayState($httpRequest->get(AuthnRequest::PARAMETER_RELAY_STATE, ''))
86
            ->setResponseAction('SurfnetStepupGatewaySecondFactorOnlyBundle:SecondFactorOnly:respond')
87
            ->setResponseContextServiceId('second_factor_only.response_context');
88
89
        // Check if the NameID is provided and we may use it.
90
        $nameId = $originalRequest->getNameId();
91
        $secondFactorOnlyNameIdValidator = $this->get('second_factor_only.validate_nameid')->with($logger);
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $secondFactorOnlyNameIdValidator exceeds the maximum configured length of 30.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
92
        $serviceProviderMayUseSecondFactorOnly = $secondFactorOnlyNameIdValidator->validate(
0 ignored issues
show
Comprehensibility Naming introduced by
The variable name $serviceProviderMayUseSecondFactorOnly exceeds the maximum configured length of 30.

Very long variable names usually make code harder to read. It is therefore recommended not to make variable names too verbose.

Loading history...
93
            $originalRequest->getServiceProvider(),
94
            $nameId
95
        );
96
97
        if (!$serviceProviderMayUseSecondFactorOnly) {
98
            /** @var \Surfnet\StepupGateway\GatewayBundle\Service\ResponseRenderingService $responseRendering */
99
            $responseRendering = $this->get('second_factor_only.response_rendering');
100
101
            return $responseRendering->renderRequesterFailureResponse($this->getResponseContext());
102
        }
103
104
        $stateHandler->saveIdentityNameId($nameId);
105
106
        // Check if the requested Loa is provided and supported.
107
        $loaId = $this->get('second_factor_only.loa_resolution')->with($logger)->resolve(
108
            $originalRequest->getAuthenticationContextClassRef()
109
        );
110
111
        if (empty($loaId)) {
112
            /** @var \Surfnet\StepupGateway\GatewayBundle\Service\ResponseRenderingService $responseRendering */
113
            $responseRendering = $this->get('second_factor_only.response_rendering');
114
115
            return $responseRendering->renderRequesterFailureResponse($this->getResponseContext());
116
        }
117
118
        $stateHandler->setRequiredLoaIdentifier($loaId);
119
120
        $logger->notice('Forwarding to second factor controller for loa determination and handling');
121
122
        return $this->forward('SurfnetStepupGatewayGatewayBundle:SecondFactor:selectSecondFactorForVerification');
123
    }
124
125
    /**
126
     * @return Response
127
     */
128
    public function respondAction()
129
    {
130
        $responseContext = $this->getResponseContext();
131
        $originalRequestId = $responseContext->getInResponseTo();
132
133
        $logger = $this->get('surfnet_saml.logger')->forAuthentication($originalRequestId);
134
135
        if (!$this->getParameter('second_factor_only')) {
136
            $logger->notice(sprintf(
137
                'Access to %s denied, second_factor_only parameter set to false.',
138
                __METHOD__
139
            ));
140
            throw $this->createAccessDeniedException('Second Factor Only feature disabled');
141
        }
142
143
        $logger->notice('Creating second-factor-only Response');
144
145
        $selectedSecondFactorUuid = $this->getResponseContext()->getSelectedSecondFactor();
146
        if (!$selectedSecondFactorUuid) {
147
            $logger->error(
148
                'Cannot verify possession of an unknown second factor'
149
            );
150
151
            throw new BadRequestHttpException('Cannot verify possession of an unknown second factor.');
152
        }
153
154
        if (!$responseContext->isSecondFactorVerified()) {
155
            $logger->error('Second factor was not verified');
156
            throw new BadRequestHttpException(
157
                'Cannot verify possession of an unknown second factor.'
158
            );
159
        }
160
161
        $secondFactor = $this->get('gateway.service.second_factor_service')
162
            ->findByUuid($selectedSecondFactorUuid);
163
        $secondFactorTypeService = $this->get('surfnet_stepup.service.second_factor_type');
164
        $grantedLoa = $this->get('surfnet_stepup.service.loa_resolution')
165
            ->getLoaByLevel($secondFactor->getLoaLevel($secondFactorTypeService));
166
167
        /** @var LoaAliasLookupService $loaAliasLookup */
168
        $loaAliasLookup = $this->get('second_factor_only.loa_alias_lookup');
169
        $authnContextClassRef = $loaAliasLookup->findAliasByLoa($grantedLoa);
170
171
        /** @var ResponseFactory $response_factory */
172
        $responseFactory = $this->get('second_factor_only.saml_response_factory');
173
        $response = $responseFactory->createSecondFactorOnlyResponse(
174
            $responseContext->getIdentityNameId(),
175
            $responseContext->getServiceProvider(),
176
            $authnContextClassRef
177
        );
178
179
        $responseContext->responseSent();
180
181
        $logger->notice(sprintf(
182
            'Responding to request "%s" with newly created response "%s"',
183
            $responseContext->getInResponseTo(),
184
            $response->getId()
185
        ));
186
187
        $responseRendering = $this->get('second_factor_only.response_rendering');
188
189
        $adfsHelper = $this->get('second_factor_only.adfs.response_helper');
190
        if ($adfsHelper->isAdfsResponse($originalRequestId)) {
191
            $xmlResponse = $responseRendering->getResponseAsXML($response);
192
            try {
193
                $adfsParameters = $adfsHelper->retrieveAdfsParameters();
194
            } catch (Exception $e) {
195
                $logger->critical(sprintf('Could not process ADFS Response parameters, error: "%s"', $e->getMessage()));
196
                return $this->render('SurfnetStepupGatewayGatewayBundle:Gateway:unrecoverableError.html.twig');
197
            }
198
199
            $logger->notice('Sending ACS Response to ADFS plugin');
200
            return $this->render(
201
                '@SurfnetStepupGatewaySecondFactorOnly/Adfs/consumeAssertion.html.twig',
202
                [
203
                    'acu' => $responseContext->getDestination(),
204
                    'samlResponse' => $xmlResponse,
205
                    'context' => $adfsParameters->getContext(),
206
                    'authMethod' => $adfsParameters->getAuthMethod(),
207
                ]
208
            );
209
        }
210
        return $responseRendering->renderResponse($responseContext, $response);
211
    }
212
213
    /**
214
     * @return \Surfnet\StepupGateway\GatewayBundle\Saml\ResponseContext
215
     */
216
    public function getResponseContext()
217
    {
218
        return $this->get('second_factor_only.response_context');
219
    }
220
}
221