Skip to content

Commit

Permalink
Receive the GSSP SAMLResponse
Browse files Browse the repository at this point in the history
1. To check the preconditions
2. To verify that the Subject NameID matches the SecondFactor Identifier
   used to start the authentication.
  • Loading branch information
MKodde committed Oct 25, 2023
1 parent 011aec5 commit 25c8b8e
Show file tree
Hide file tree
Showing 8 changed files with 375 additions and 24 deletions.
4 changes: 2 additions & 2 deletions config/legacy/parameters.yaml.dist
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ parameters:
mailer_password: ~

# Default locale
default_locale: en_GB
default_locale: en
# Available locales
locales: [nl_NL, en_GB]
locales: [en, nl, nl_NL, en_GB]
# Domain for the locale cookie that is set by the Gateway, SelfService and the RA and that is used to share the
# user's locale preference with other (stepup) components
locale_cookie_domain: openconext.org
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ public function respondAction(Request $request)
}

try {
$response = $this->getSecondFactorRespondService()->respond($responseContext);
$response = $this->getSecondFactorRespondService()->respond($responseContext, $request);
} catch (InvalidSecondFactorMethodException $e) {
throw new BadRequestHttpException($e->getMessage());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

/**
* Copyright 2018 SURFnet bv
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Surfnet\StepupGateway\SecondFactorOnlyBundle\Exception;

use RuntimeException as BaseRuntimeException;

class RuntimeException extends BaseRuntimeException
{

}
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,13 @@ services:
- "@second_factor_only.saml_response_factory"
- "@gateway.service.second_factor_service"
- "@surfnet_stepup.service.second_factor_type"
- '@Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\Gateway\ResponseValidator'

Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\Gateway\ResponseValidator:
arguments:
- "@surfnet_stepup.service.second_factor_type"
- "@gssp.provider_repository"
- "@second_factor_only.http.post_binding"

second_factor_only.adfs_service:
class: Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\Gateway\AdfsService
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Saml\ResponseFactory;
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\LoaAliasLookupService;
use Surfnet\StepupBundle\Service\LoaResolutionService;
use Symfony\Component\HttpFoundation\Request;

class RespondService
{
Expand All @@ -48,29 +49,25 @@ class RespondService
/** @var SecondFactorTypeService */
private $secondFactorTypeService;

/**
* SecondFactorRespondService constructor.
* @param SamlAuthenticationLogger $samlLogger
* @param LoaResolutionService $loaResolutionService
* @param LoaAliasLookupService $loaAliasLookupService
* @param ResponseFactory $responseFactory
* @param SecondFactorService $secondFactorService
* @param SecondFactorTypeService $secondFactorTypeService
*/
/** @var ResponseValidator */
private $responseValidator;

public function __construct(
SamlAuthenticationLogger $samlLogger,
LoaResolutionService $loaResolutionService,
LoaAliasLookupService $loaAliasLookupService,
ResponseFactory $responseFactory,
SecondFactorService $secondFactorService,
SecondFactorTypeService $secondFactorTypeService
SecondFactorTypeService $secondFactorTypeService,
ResponseValidator $responseValidator
) {
$this->samlLogger = $samlLogger;
$this->loaResolutionService = $loaResolutionService;
$this->loaAliasLookupService = $loaAliasLookupService;
$this->responseFactory = $responseFactory;
$this->secondFactorService = $secondFactorService;
$this->secondFactorTypeService = $secondFactorTypeService;
$this->responseValidator = $responseValidator;
}


Expand All @@ -84,7 +81,7 @@ public function __construct(
* @param ResponseContext $responseContext
* @return Response
*/
public function respond(ResponseContext $responseContext)
public function respond(ResponseContext $responseContext, Request $request)
{
$originalRequestId = $responseContext->getInResponseTo();
$logger = $this->samlLogger->forAuthentication($originalRequestId);
Expand All @@ -105,6 +102,8 @@ public function respond(ResponseContext $responseContext)
}

$secondFactor = $this->secondFactorService->findByUuid($selectedSecondFactorUuid);
$this->responseValidator->validate($request, $secondFactor, $responseContext->getIdentityNameId());

$grantedLoa = $this->loaResolutionService
->getLoaByLevel($secondFactor->getLoaLevel($this->secondFactorTypeService));

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

/**
* Copyright 2023 SURFnet bv
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

namespace Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\Gateway;

use Surfnet\SamlBundle\Http\PostBinding;
use Surfnet\StepupBundle\Service\SecondFactorTypeService;
use Surfnet\StepupBundle\Value\SecondFactorType;
use Surfnet\StepupGateway\GatewayBundle\Entity\SecondFactor;
use Surfnet\StepupGateway\SamlStepupProviderBundle\Provider\ProviderRepository;
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Exception\RuntimeException;
use Symfony\Component\HttpFoundation\Request;

class ResponseValidator
{
/** @var SecondFactorTypeService */
private $secondFactorTypeService;

/** @var ProviderRepository */
private $providerRepository;

/** @var PostBinding */
private $postBinding;

public function __construct(
SecondFactorTypeService $secondFactorTypeService,
ProviderRepository $providerRepository,
PostBinding $postBinding
) {
$this->secondFactorTypeService = $secondFactorTypeService;
$this->providerRepository = $providerRepository;
$this->postBinding = $postBinding;
}

/**
*
*/
public function validate(Request $request, SecondFactor $secondFactor, string $nameIdFromState)
{
$secondFactorType = new SecondFactorType($secondFactor->secondFactorType);
$hasSamlResponse = $request->request->has('SAMLResponse');
// When dealing with a GSSP response. It is advised to receive the SAML response through POST Binding,
// testing the preconditions.
if ($hasSamlResponse && $this->secondFactorTypeService->isGssf($secondFactorType)) {
$provider = $this->providerRepository->get($secondFactorType->getSecondFactorType());
// Receive the response via POST Binding, this will test all the regular pre-conditions
$samlResponse = $this->postBinding->processResponse(
$request,
$provider->getRemoteIdentityProvider(),
$provider->getServiceProvider()
);
$nameIdFromResponse = $samlResponse->getNameId()->getValue();
// Additionally test if the name id from the GSSP matches the SF identifier that we have in state
if ($nameIdFromResponse !== $secondFactor->secondFactorIdentifier) {
throw new RuntimeException(
sprintf(
'The nameID recieved from the GSSP (%s) did not match the selected second factor (%s). This '.
'might be an indication someone is tampering with a GSSP. The authentication was started by %s',
$nameIdFromResponse,
$secondFactor->secondFactorIdentifier,
$nameIdFromState
)
);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

use DateTime;
use Mockery;
use Mockery\Mock;
use SAML2\Response;
use Surfnet\SamlBundle\Entity\IdentityProvider;
use Surfnet\SamlBundle\Monolog\SamlAuthenticationLogger;
Expand All @@ -36,37 +37,43 @@
use Surfnet\StepupGateway\GatewayBundle\Tests\TestCase\GatewaySamlTestCase;
use Surfnet\StepupGateway\SamlStepupProviderBundle\Saml\ProxyResponseFactory;
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Exception\InvalidSecondFactorMethodException;
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Exception\RuntimeException;
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Saml\ResponseFactory;
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\Gateway\RespondService;
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\Gateway\ResponseValidator;
use Surfnet\StepupGateway\SecondFactorOnlyBundle\Service\LoaAliasLookupService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;

final class RespondServiceTest extends GatewaySamlTestCase
{
/** @var Mockery\Mock|RespondService */
/** @var Mock|RespondService */
private $gatewayRespondService;

/** @var Mockery\Mock|ProxyStateHandler */
/** @var Mock|ProxyStateHandler */
private $stateHandler;

/** @var ResponseContext */
private $responseContext;

/** @var Mockery\Mock|LoaResolutionService */
/** @var LoaResolutionService */
private $loaResolutionService;

/** @var Mockery\Mock|SamlEntityService */
/** @var Mock|SamlEntityService */
private $samlEntityService;

/** @var IdentityProvider */
private $hostedIdp;

/** @var Mockery\Mock|SecondFactorService */
/** @var Mock|SecondFactorService */
private $secondFactorService;

/** @var ProxyResponseFactory */
private $proxyResponseFactory;

/** @var Mock&ResponseValidator */
private $validator;

public function setUp(): void
{
parent::setUp();
Expand Down Expand Up @@ -139,9 +146,11 @@ public function it_should_return_a_valid_saml_response_and_update_state_when_the
$this->responseContext->saveSelectedSecondFactor($secondFactor);
$this->responseContext->markSecondFactorVerified();

$request = Mockery::mock(Request::class);

$this->validator->shouldReceive('validate');
// Handle respond
$response = $this->gatewayRespondService->respond($this->responseContext);
$response = $this->gatewayRespondService->respond($this->responseContext, $request);

// Assert response
$this->assertInstanceOf(Response::class, $response);
Expand Down Expand Up @@ -205,6 +214,57 @@ public function it_should_return_a_valid_saml_response_and_update_state_when_the
], $this->getSessionData('attributes'));
}

/**
* @test
*/
public function it_halts_execution_when_saml_response_is_invalid()
{

$this->mockSessionData('_sf2_attributes', [
'surfnet/gateway/requestrequest_id' => '_7179b234fc69f75724c83cab795fc87475d2f6d88e97e43368c3966e398c',
'surfnet/gateway/requestservice_provider' => 'https://gateway.tld/gssp/tiqr/metadata',
'surfnet/gateway/requestassertion_consumer_service_url' => 'https://gateway.tld/gssp/tiqr/consume-assertion',
'surfnet/gateway/requestrelay_state' => '',
'surfnet/gateway/requestresponse_controller' => 'SurfnetStepupGatewaySecondFactorOnlyBundle:SecondFactorOnly:respond',
'surfnet/gateway/requestresponse_context_service_id' => 'second_factor_only.response_context',
'surfnet/gateway/requestname_id' => 'oom60v-3art',
'surfnet/gateway/requestloa_identifier' => 'http://stepup.example.com/assurance/loa2',
]);

// Mock service provider
$serviceProvider = Mockery::mock(ServiceProvider::class)
->shouldReceive('determineAcsLocation')
->with('https://gateway.tld/gssp/tiqr/consume-assertion', $this->logger)
->getMock();

$this->samlEntityService->shouldReceive('getServiceProvider')
->with('https://gateway.tld/gssp/tiqr/metadata')
->andReturn($serviceProvider);

// Mock second factor
$secondFactor = Mockery::mock(SecondFactor::class);
$secondFactor->secondFactorId = 'mocked-second-factor-id';
$secondFactor->displayLocale = 'nl_NL';
$secondFactor->shouldReceive('getLoaLevel')
->andReturn(2);

// Mock second factor service
$this->secondFactorService->shouldReceive('findByUuid')
->with('mocked-second-factor-id')
->andReturn($secondFactor);

// This should be done in the SecondFactorController on success
$this->responseContext->saveSelectedSecondFactor($secondFactor);
$this->responseContext->markSecondFactorVerified();

$request = Mockery::mock(Request::class);

$this->validator->shouldReceive('validate')->andThrow(new RuntimeException());
// Handle respond
self::expectException(RuntimeException::class);
$this->gatewayRespondService->respond($this->responseContext, $request);
}

/**
* @test
*/
Expand Down Expand Up @@ -237,9 +297,10 @@ public function it_should_throw_an_exception_when_the_second_factor_method_is_un
->with('mocked-second-factor-id')
->andReturn(null);

$request = Mockery::mock(Request::class);

// Handle respond
$this->gatewayRespondService->respond($this->responseContext);
$this->gatewayRespondService->respond($this->responseContext, $request);
}


Expand Down Expand Up @@ -284,10 +345,11 @@ public function it_should_throw_an_exception_when_the_second_factor_is_not_verif

// This should be done in the SecondFactorController on success
$this->responseContext->saveSelectedSecondFactor($secondFactor);
//$this->responseContext->markSecondFactorVerified();

$request = Mockery::mock(Request::class);

// Handle respond
$this->gatewayRespondService->respond($this->responseContext);
$this->gatewayRespondService->respond($this->responseContext, $request);
}

/**
Expand Down Expand Up @@ -322,13 +384,16 @@ private function initGatewayLoginService(array $idpConfiguration, array $loaLeve
$this->proxyResponseFactory = new ResponseFactory($this->hostedIdp, $this->stateHandler, $assertionSigningService, $now);
$loaAliasLookup = new LoaAliasLookupService($loaAliases);

$this->validator = Mockery::mock(ResponseValidator::class);

$this->gatewayRespondService = new RespondService(
$samlLogger,
$this->loaResolutionService,
$loaAliasLookup,
$this->proxyResponseFactory,
$this->secondFactorService,
$secondFactorTypeService
$secondFactorTypeService,
$this->validator
);
}

Expand Down
Loading

0 comments on commit 25c8b8e

Please sign in to comment.