Completed
Pull Request — master (#11)
by Matt
04:56
created

SAMLController::index()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverStripe\SAML\Control;
4
5
use Exception;
6
use OneLogin_Saml2_Auth;
7
use OneLogin_Saml2_Error;
8
use OneLogin_Saml2_Utils;
9
use Psr\Log\LoggerInterface;
10
use SilverStripe\ORM\ValidationResult;
11
use SilverStripe\SAML\Authenticators\SAMLAuthenticator;
12
use SilverStripe\SAML\Authenticators\SAMLLoginForm;
13
use SilverStripe\SAML\Helpers\SAMLHelper;
14
use SilverStripe\Control\Controller;
15
use SilverStripe\Control\Director;
16
use SilverStripe\Control\HTTPResponse;
17
use SilverStripe\Core\Injector\Injector;
18
use SilverStripe\Security\IdentityStore;
19
use SilverStripe\Security\Member;
20
use SilverStripe\Security\Security;
21
use function uniqid;
22
23
/**
24
 * Class SAMLController
25
 *
26
 * This controller handles serving metadata requests for the identity provider (IdP), as well as handling the creation
27
 * of new users and logging them into SilverStripe after being authenticated at the IdP.
28
 */
29
class SAMLController extends Controller
30
{
31
    /**
32
     * @var array
33
     */
34
    private static $allowed_actions = [
35
        'index',
36
        'acs',
37
        'metadata'
38
    ];
39
40
    public function index()
41
    {
42
        return $this->redirect('/');
43
    }
44
45
    /**
46
     * Assertion Consumer Service
47
     *
48
     * The user gets sent back here after authenticating with the IdP, off-site.
49
     * The earlier redirection to the IdP can be found in the SAMLAuthenticator::authenticate.
50
     *
51
     * After this handler completes, we end up with a rudimentary Member record (which will be created on-the-fly
52
     * if not existent), with the user already logged in. Login triggers memberLoggedIn hooks, which allows
53
     * LDAP side of this module to finish off loading Member data.
54
     *
55
     * @throws OneLogin_Saml2_Error
56
     * @throws \Psr\Container\NotFoundExceptionInterface
57
     */
58
    public function acs()
59
    {
60
        /** @var \OneLogin_Saml2_Auth $auth */
61
        $auth = Injector::inst()->get(SAMLHelper::class)->getSAMLAuth();
62
        $caughtException = null;
63
64
        // Force php-saml module to use the current absolute base URL (e.g. https://www.example.com/saml). This avoids
65
        // errors that we otherwise get when having a multi-directory ACS URL like /saml/acs).
66
        // See https://github.com/onelogin/php-saml/issues/249
67
        OneLogin_Saml2_Utils::setBaseURL(Controller::join_links($auth->getSettings()->getSPData()['entityId'], 'saml'));
68
69
        // Attempt to process the SAML response. If there are errors during this, log them and redirect to the generic
70
        // error page. Note: This does not necessarily include all SAML errors (e.g. we still need to confirm if the
71
        // user is authenticated after this block
72
        try {
73
            $auth->processResponse();
74
            $error = $auth->getLastErrorReason();
75
        } catch(Exception $e) {
76
            $caughtException = $e;
77
        }
78
79
        // If there was an issue with the SAML response, if it was missing or if the SAML response indicates that they
80
        // aren't authorised, then log the issue and provide a traceable error back to the user via the LoginForm
81
        if ($caughtException || !empty($error) || !$auth->isAuthenticated()) {
82
            // Log both errors (reported by php-saml and thrown as exception) with a common ID for later tracking
83
            $id = uniqid('SAML-');
84
85
            if ($caughtException instanceof Exception) {
86
                $this->getLogger()->error(sprintf(
87
                    '[%s] [code: %s] %s (%s:%s)',
88
                    $id,
89
                    $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...
90
                    $e->getMessage(),
91
                    $e->getFile(),
92
                    $e->getLine()
93
                ));
94
            }
95
96
            if (!empty($error)) {
97
                $this->getLogger()->error(sprintf('[%s] %s', $id, $error));
98
            }
99
100
            $this->getForm()->sessionMessage(
101
                _t(
102
                    'SilverStripe\\SAML\\Control\\SAMLController.ERR_SAML_ACS_FAILURE',
103
                    'Unfortunately we couldn\'t log you in. If this continues, please contact your I.T. department with the following reference: {ref}',
104
                    ['ref' => $id]
105
                ),
106
                ValidationResult::TYPE_ERROR
107
            );
108
109
            // Redirect the user back to the login form to display the generic error message and reference
110
            $this->getRequest()->getSession()->save($this->getRequest());
111
            return $this->redirect('Security/login');
112
        }
113
114
        // If processing reaches here, then the user is authenticated - the rest of this method is just processing their
115
        // legitimate information and configuring their account.
116
117
        // Check that the NameID is a binary string (which signals that it is a guid
118
        $decodedNameId = base64_decode($auth->getNameId());
119
        if (ctype_print($decodedNameId)) {
120
            $this->getForm()->sessionMessage('NameID from IdP is not a binary GUID.', ValidationResult::TYPE_ERROR);
121
            $this->getRequest()->getSession()->save($this->getRequest());
122
            return $this->getRedirect();
123
        }
124
125
        // transform the NameId to guid
126
        $helper = SAMLHelper::singleton();
127
        $guid = $helper->binToStrGuid($decodedNameId);
128
        if (!$helper->validGuid($guid)) {
129
            $errorMessage = "Not a valid GUID '{$guid}' recieved from server.";
130
            $this->getLogger()->error($errorMessage);
131
            $this->getForm()->sessionMessage($errorMessage, ValidationResult::TYPE_ERROR);
132
            $this->getRequest()->getSession()->save($this->getRequest());
133
            return $this->getRedirect();
134
        }
135
136
        // Write a rudimentary member with basic fields on every login, so that we at least have something
137
        // if LDAP synchronisation fails.
138
        $member = Member::get()->filter('GUID', $guid)->limit(1)->first();
139
        if (!($member && $member->exists())) {
140
            $member = new Member();
141
            $member->GUID = $guid;
142
        }
143
144
        $attributes = $auth->getAttributes();
145
146
        foreach ($member->config()->claims_field_mappings as $claim => $field) {
147
            if (!isset($attributes[$claim][0])) {
148
                $this->getLogger()->warning(
149
                    sprintf(
150
                        'Claim rule \'%s\' configured in LDAPMember.claims_field_mappings, ' .
151
                                'but wasn\'t passed through. Please check IdP claim rules.',
152
                        $claim
153
                    )
154
                );
155
156
                continue;
157
            }
158
159
            $member->$field = $attributes[$claim][0];
160
        }
161
162
        $member->SAMLSessionIndex = $auth->getSessionIndex();
163
164
        // This will trigger LDAP update through LDAPMemberExtension::memberLoggedIn. The LDAP update will also write
165
        // the Member record a second time, but the member must be written before IdentityStore->logIn() is called.
166
        // Both SAML and LDAP identify Members by the GUID field.
167
        $member->write();
168
169
        /** @var IdentityStore $identityStore */
170
        $identityStore = Injector::inst()->get(IdentityStore::class);
171
        $persistent = Security::config()->get('autologin_enabled');
172
        $identityStore->logIn($member, $persistent, $this->getRequest());
173
174
        return $this->getRedirect();
175
    }
176
177
    /**
178
     * Generate this SP's metadata. This is needed for intialising the SP-IdP relationship.
179
     * IdP is instructed to call us back here to establish the relationship. IdP may also be configured
180
     * to hit this endpoint periodically during normal operation, to check the SP availability.
181
     */
182
    public function metadata()
183
    {
184
        try {
185
            /** @var OneLogin_Saml2_Auth $auth */
186
            $auth = Injector::inst()->get(SAMLHelper::class)->getSAMLAuth();
187
            $settings = $auth->getSettings();
188
            $metadata = $settings->getSPMetadata();
189
            $errors = $settings->validateMetadata($metadata);
190
            if (empty($errors)) {
191
                header('Content-Type: text/xml');
192
                echo $metadata;
193
            } else {
194
                throw new \OneLogin_Saml2_Error(
195
                    'Invalid SP metadata: ' . implode(', ', $errors),
196
                    \OneLogin_Saml2_Error::METADATA_SP_INVALID
197
                );
198
            }
199
        } catch (Exception $e) {
200
            $this->getLogger()->error($e->getMessage());
201
            echo $e->getMessage();
202
        }
203
    }
204
205
    /**
206
     * @return HTTPResponse
207
     */
208
    protected function getRedirect()
209
    {
210
        // Absolute redirection URLs may cause spoofing
211
        if ($this->getRequest()->getSession()->get('BackURL')
212
            && Director::is_site_url($this->getRequest()->getSession()->get('BackURL'))) {
213
            return $this->redirect($this->getRequest()->getSession()->get('BackURL'));
214
        }
215
216
        // Spoofing attack, redirect to homepage instead of spoofing url
217
        if ($this->getRequest()->getSession()->get('BackURL')
218
            && !Director::is_site_url($this->getRequest()->getSession()->get('BackURL'))) {
219
            return $this->redirect(Director::absoluteBaseURL());
220
        }
221
222
        // If a default login dest has been set, redirect to that.
223
        if (Security::config()->default_login_dest) {
224
            return $this->redirect(Director::absoluteBaseURL() . Security::config()->default_login_dest);
225
        }
226
227
        // fallback to redirect back to home page
228
        return $this->redirect(Director::absoluteBaseURL());
229
    }
230
231
    /**
232
     * Get a logger
233
     *
234
     * @return LoggerInterface
235
     */
236
    public function getLogger()
237
    {
238
        return Injector::inst()->get(LoggerInterface::class);
239
    }
240
241
    /**
242
     * Gets the login form
243
     *
244
     * @return SAMLLoginForm
245
     */
246
    public function getForm()
247
    {
248
        return Injector::inst()->get(SAMLLoginForm::class, true, [$this, SAMLAuthenticator::class, 'LoginForm']);
249
    }
250
}
251