Passed
Pull Request — master (#16)
by Matt
02:26
created

SAMLController::checkForReplayAttack()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 28
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 17
nc 2
nop 2
dl 0
loc 28
rs 9.7
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\SAML\Control;
4
5
use Exception;
6
use function gmmktime;
7
use OneLogin\Saml2\Auth;
8
use OneLogin\Saml2\Constants;
9
use OneLogin\Saml2\Utils;
10
use OneLogin\Saml2\Error;
11
use Psr\Log\LoggerInterface;
12
use SilverStripe\Core\Config\Config;
13
use SilverStripe\ORM\ValidationResult;
14
use SilverStripe\SAML\Authenticators\SAMLAuthenticator;
15
use SilverStripe\SAML\Authenticators\SAMLLoginForm;
16
use SilverStripe\SAML\Helpers\SAMLHelper;
17
use SilverStripe\Control\Controller;
18
use SilverStripe\Control\Director;
19
use SilverStripe\Control\HTTPResponse;
20
use SilverStripe\Core\Injector\Injector;
21
use SilverStripe\SAML\Model\SAMLResponse;
22
use SilverStripe\SAML\Services\SAMLConfiguration;
23
use SilverStripe\Security\IdentityStore;
24
use SilverStripe\Security\Member;
25
use SilverStripe\Security\Security;
26
use function uniqid;
27
28
/**
29
 * Class SAMLController
30
 *
31
 * This controller handles serving metadata requests for the identity provider (IdP), as well as handling the creation
32
 * of new users and logging them into SilverStripe after being authenticated at the IdP.
33
 */
34
class SAMLController extends Controller
35
{
36
    /**
37
     * @var array
38
     */
39
    private static $allowed_actions = [
40
        'index',
41
        'acs',
42
        'metadata'
43
    ];
44
45
    public function index()
46
    {
47
        return $this->redirect('/');
48
    }
49
50
    /**
51
     * Assertion Consumer Service
52
     *
53
     * The user gets sent back here after authenticating with the IdP, off-site.
54
     * The earlier redirection to the IdP can be found in the SAMLAuthenticator::authenticate.
55
     *
56
     * After this handler completes, we end up with a rudimentary Member record (which will be created on-the-fly
57
     * if not existent), with the user already logged in. Login triggers memberLoggedIn hooks, which allows
58
     * LDAP side of this module to finish off loading Member data.
59
     *
60
     * @throws Error
61
     * @throws \Psr\Container\NotFoundExceptionInterface
62
     */
63
    public function acs()
64
    {
65
        /** @var Auth $auth */
66
        $auth = Injector::inst()->get(SAMLHelper::class)->getSAMLAuth();
67
        $caughtException = null;
68
69
        // Log both errors (reported by php-saml and thrown as exception) with a common ID for later tracking
70
        $uniqueErrorId = uniqid('SAML-');
71
72
        // Force php-saml module to use the current absolute base URL (e.g. https://www.example.com/saml). This avoids
73
        // errors that we otherwise get when having a multi-directory ACS URL like /saml/acs).
74
        // See https://github.com/onelogin/php-saml/issues/249
75
        Utils::setBaseURL(Controller::join_links($auth->getSettings()->getSPData()['entityId'], 'saml'));
76
77
        // Attempt to process the SAML response. If there are errors during this, log them and redirect to the generic
78
        // error page. Note: This does not necessarily include all SAML errors (e.g. we still need to confirm if the
79
        // user is authenticated after this block
80
        try {
81
            $auth->processResponse();
82
            $error = $auth->getLastErrorReason();
83
        } catch (Exception $e) {
84
            $caughtException = $e;
85
        }
86
87
        // If there was an issue with the SAML response, if it was missing or if the SAML response indicates that they
88
        // aren't authorised, then log the issue and provide a traceable error back to the user via the login form
89
        if (
90
            $caughtException ||
91
            !empty($error) ||
92
            !$auth->isAuthenticated() ||
93
            $this->checkForReplayAttack($auth, $uniqueErrorId)
94
        ) {
95
            if ($caughtException instanceof Exception) {
96
                $this->getLogger()->error(sprintf(
97
                    '[%s] [code: %s] %s (%s:%s)',
98
                    $uniqueErrorId,
99
                    $e->getCode(),
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $e does not seem to be defined for all execution paths leading up to this point.
Loading history...
100
                    $e->getMessage(),
101
                    $e->getFile(),
102
                    $e->getLine()
103
                ));
104
            }
105
106
            if (!empty($error)) {
107
                $this->getLogger()->error(sprintf('[%s] %s', $uniqueErrorId, $error));
108
            }
109
110
            $this->getForm()->sessionMessage(
111
                _t(
112
                    'SilverStripe\\SAML\\Control\\SAMLController.ERR_SAML_ACS_FAILURE',
113
                    'Unfortunately we couldn\'t log you in. If this continues, please contact your I.T. department'
114
                    . ' with the following reference: {ref}',
115
                    ['ref' => $uniqueErrorId]
116
                ),
117
                ValidationResult::TYPE_ERROR
118
            );
119
120
            // Redirect the user back to the login form to display the generic error message and reference
121
            $this->getRequest()->getSession()->save($this->getRequest());
122
            return $this->redirect('Security/login');
123
        }
124
125
        /**
126
         * If processing reaches here, then the user is authenticated - the rest of this method is just processing their
127
         * legitimate information and configuring their account.
128
         */
129
130
        // If we expect the NameID to be a binary version of the GUID (ADFS), check that it actually is
131
        // If we are configured not to expect a binary NameID, then we assume it is a direct GUID (Azure AD)
132
        if (Config::inst()->get(SAMLConfiguration::class, 'expect_binary_nameid')) {
133
            $decodedNameId = base64_decode($auth->getNameId());
134
            if (ctype_print($decodedNameId)) {
135
                $this->getForm()->sessionMessage('NameID from IdP is not a binary GUID.', ValidationResult::TYPE_ERROR);
136
                $this->getRequest()->getSession()->save($this->getRequest());
137
                return $this->getRedirect();
138
            }
139
140
            // transform the NameId to guid
141
            $helper = SAMLHelper::singleton();
142
            $guid = $helper->binToStrGuid($decodedNameId);
143
            if (!$helper->validGuid($guid)) {
144
                $errorMessage = "Not a valid GUID '{$guid}' recieved from server.";
145
                $this->getLogger()->error($errorMessage);
146
                $this->getForm()->sessionMessage($errorMessage, ValidationResult::TYPE_ERROR);
147
                $this->getRequest()->getSession()->save($this->getRequest());
148
                return $this->getRedirect();
149
            }
150
        } else {
151
            $guid = $auth->getNameId();
152
        }
153
154
        $attributes = $auth->getAttributes();
155
156
        $fieldToClaimMap = array_flip(Member::config()->claims_field_mappings);
157
158
        // Write a rudimentary member with basic fields on every login, so that we at least have something
159
        // if there is no further sync (e.g. via LDAP)
160
        $member = Member::get()->filter('GUID', $guid)->limit(1)->first();
161
        if (!($member && $member->exists()) && Config::inst()->get(SAMLConfiguration::class, 'allow_insecure_email_linking') && isset($fieldToClaimMap['Email'])) {
162
            // If there is no member found via GUID and we allow linking via email, search by email
163
            $member = Member::get()->filter('Email', $attributes[$fieldToClaimMap['Email']])->limit(1)->first();
164
165
            if (!($member && $member->exists())) {
166
                $member = new Member();
167
            }
168
169
            $member->GUID = $guid;
170
        } else if(!($member && $member->exists())) {
171
            // If the member doesn't exist and we don't allow linking via email, then create a new member
172
            $member = new Member();
173
            $member->GUID = $guid;
174
        }
175
176
        foreach ($member->config()->claims_field_mappings as $claim => $field) {
177
            if (!isset($attributes[$claim][0])) {
178
                $this->getLogger()->warning(
179
                    sprintf(
180
                        'Claim rule \'%s\' configured in SAMLMemberExtension.claims_field_mappings, ' .
181
                                'but wasn\'t passed through. Please check IdP claim rules.',
182
                        $claim
183
                    )
184
                );
185
186
                continue;
187
            }
188
189
            $member->$field = $attributes[$claim][0];
190
        }
191
192
        $member->SAMLSessionIndex = $auth->getSessionIndex();
193
194
        // This will trigger LDAP update through LDAPMemberExtension::memberLoggedIn, if the LDAP module is installed.
195
        // The LDAP update will also write the Member record a second time, but the member *must* be written before
196
        // IdentityStore->logIn() is called, otherwise the identity store throws an exception.
197
        // Both SAML and LDAP identify Members by the same GUID field.
198
        $member->write();
199
200
        /** @var IdentityStore $identityStore */
201
        $identityStore = Injector::inst()->get(IdentityStore::class);
202
        $identityStore->logIn($member, false, $this->getRequest());
203
204
        return $this->getRedirect();
205
    }
206
207
    /**
208
     * Generate this SP's metadata. This is needed for intialising the SP-IdP relationship.
209
     * IdP is instructed to call us back here to establish the relationship. IdP may also be configured
210
     * to hit this endpoint periodically during normal operation, to check the SP availability.
211
     */
212
    public function metadata()
213
    {
214
        try {
215
            /** @var Auth $auth */
216
            $auth = Injector::inst()->get(SAMLHelper::class)->getSAMLAuth();
217
            $settings = $auth->getSettings();
218
            $metadata = $settings->getSPMetadata();
219
            $errors = $settings->validateMetadata($metadata);
220
            if (empty($errors)) {
221
                header('Content-Type: text/xml');
222
                echo $metadata;
223
            } else {
224
                throw new Error(
225
                    'Invalid SP metadata: ' . implode(', ', $errors),
226
                    Error::METADATA_SP_INVALID
227
                );
228
            }
229
        } catch (Exception $e) {
230
            $this->getLogger()->error($e->getMessage());
231
            echo $e->getMessage();
232
        }
233
    }
234
235
    /**
236
     * @return HTTPResponse
237
     */
238
    protected function getRedirect()
239
    {
240
        // Absolute redirection URLs may cause spoofing
241
        if ($this->getRequest()->getSession()->get('BackURL')
242
            && Director::is_site_url($this->getRequest()->getSession()->get('BackURL'))) {
243
            return $this->redirect($this->getRequest()->getSession()->get('BackURL'));
244
        }
245
246
        // Spoofing attack, redirect to homepage instead of spoofing url
247
        if ($this->getRequest()->getSession()->get('BackURL')
248
            && !Director::is_site_url($this->getRequest()->getSession()->get('BackURL'))) {
249
            return $this->redirect(Director::absoluteBaseURL());
250
        }
251
252
        // If a default login dest has been set, redirect to that.
253
        if (Security::config()->default_login_dest) {
254
            return $this->redirect(Director::absoluteBaseURL() . Security::config()->default_login_dest);
255
        }
256
257
        // fallback to redirect back to home page
258
        return $this->redirect(Director::absoluteBaseURL());
259
    }
260
261
    /**
262
     * If processing reaches here, then the user is authenticated but potentially not valid. We first need to confirm
263
     * that they are not an attacker performing a SAML replay attack (capturing the raw traffic from a compromised
264
     * device and then re-submitting the same SAML response).
265
     *
266
     * To combat this, we store SAML response IDs for the amount of time they're valid for (plus a configurable offset
267
     * to account for potential time skew), and if the ID has been seen before we log an error message and return true
268
     * (which indicates that this specific request is a replay attack).
269
     *
270
     * If no replay attack is detected, then the SAML response is logged so that future requests can be blocked.
271
     *
272
     * @param Auth $auth The Auth object that includes the processed response
273
     * @param string $uniqueErrorId The error code to use when logging error messages for this given error
274
     * @return bool true if this response is a replay attack, false if it's the first time we've seen the ID
275
     */
276
    protected function checkForReplayAttack(Auth $auth, $uniqueErrorId = '')
277
    {
278
        $responseId = $auth->getLastMessageId();
279
        $expiry = $auth->getLastAssertionNotOnOrAfter(); // Note: Expiry will always be stored and returned in UTC
280
281
        // Search for any SAMLResponse objects where the response ID is the same and the expiry is within the range
282
        $count = SAMLResponse::get()->filter(['ResponseID' => $responseId])->count();
283
284
        if ($count > 0) {
285
            // Response found, therefore this is a replay attack - log the error and return false so the user is denied
286
            $this->getLogger()->error(sprintf(
287
                '[%s] SAML replay attack detected! Response ID "%s", expires "%s", client IP "%s"',
288
                $uniqueErrorId,
289
                $responseId,
290
                $expiry,
291
                $this->getRequest()->getIP()
292
            ));
293
294
            return true;
295
        } else {
296
            // No attack detected, log the SAML response
297
            $response = new SAMLResponse([
298
                'ResponseID' => $responseId,
299
                'Expiry' => $expiry
300
            ]);
301
302
            $response->write();
303
            return false;
304
        }
305
    }
306
307
    /**
308
     * Get a logger
309
     *
310
     * @return LoggerInterface
311
     */
312
    public function getLogger()
313
    {
314
        return Injector::inst()->get(LoggerInterface::class);
315
    }
316
317
    /**
318
     * Gets the login form
319
     *
320
     * @return SAMLLoginForm
321
     */
322
    public function getForm()
323
    {
324
        return Injector::inst()->get(SAMLLoginForm::class, true, [$this, SAMLAuthenticator::class, 'LoginForm']);
325
    }
326
}
327