Passed
Pull Request — master (#13)
by Simon
01:53
created

YubikeyMemberAuthenticator::validateToken()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 28
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 12
nc 8
nop 3
1
<?php
2
3
namespace Firesphere\YubiAuth\Authenticators;
4
5
use Exception;
6
use Firesphere\BootstrapMFA\Authenticators\BootstrapMFAAuthenticator;
7
use Firesphere\BootstrapMFA\Handlers\BootstrapMFALoginHandler;
0 ignored issues
show
Bug introduced by
The type Firesphere\BootstrapMFA\...ootstrapMFALoginHandler was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Firesphere\YubiAuth\Handlers\YubikeyLoginHandler;
9
use Firesphere\YubiAuth\Helpers\QwertyConvertor;
10
use Firesphere\YubiAuth\Providers\YubikeyAuthProvider;
11
use SilverStripe\Control\HTTPRequest;
12
use SilverStripe\Core\Config\Config;
13
use SilverStripe\Core\Environment;
14
use SilverStripe\Core\Injector\Injector;
15
use SilverStripe\ORM\ValidationException;
16
use SilverStripe\ORM\ValidationResult;
17
use SilverStripe\Security\Authenticator;
18
use SilverStripe\Security\Member;
19
use SilverStripe\Security\PasswordEncryptor_NotFoundException;
20
use Yubikey\Response;
21
use Yubikey\Validate;
22
23
/**
24
 * Class YubikeyAuthenticator
25
 *
26
 * Enable Yubikey Authentication for SilverStripe CMS and member-protected pages.
27
 */
28
class YubikeyMemberAuthenticator extends BootstrapMFAAuthenticator
29
{
30
31
    /**
32
     * @var Validate
33
     */
34
    protected $yubiService;
35
36
    /**
37
     * @var YubikeyAuthProvider
38
     */
39
    protected $provider;
40
41
    /**
42
     * @var string
43
     */
44
    private $authenticatorName = 'yubiauth';
0 ignored issues
show
introduced by
The private property $authenticatorName is not used, and could be removed.
Loading history...
45
46
    /**
47
     * Set the provider to a YubikeyAuthProvider instance
48
     *
49
     * YubikeyMemberAuthenticator constructor.
50
     */
51
    public function __construct()
52
    {
53
        if (!$this->provider) {
54
            $this->provider = Injector::inst()->get(YubikeyAuthProvider::class);
55
        }
56
    }
57
58
    /**
59
     * Name of this authenticator
60
     *
61
     * @return string
62
     */
63
    public static function get_name()
64
    {
65
        return _t('YubikeyAuthenticator.TITLE', 'Yubikey 2 factor login');
66
    }
67
68
    /**
69
     * @return YubikeyAuthProvider
70
     */
71
    public function getProvider()
72
    {
73
        return $this->provider;
74
    }
75
76
    /**
77
     * @param YubikeyAuthProvider $provider
78
     * @return $this
79
     */
80
    public function setProvider($provider)
81
    {
82
        $this->provider = $provider;
83
84
        return $this;
85
    }
86
87
    public function supportedServices()
88
    {
89
        // Bitwise-OR of all the supported services in this Authenticator, to make a bitmask
90
        return Authenticator::LOGIN | Authenticator::LOGOUT | Authenticator::CHANGE_PASSWORD
91
            | Authenticator::RESET_PASSWORD | Authenticator::CHECK_PASSWORD;
92
    }
93
94
    /**
95
     * @inheritdoc
96
     *
97
     * @param array $data
98
     * @param HTTPRequest $request
99
     * @param ValidationResult $validationResult
100
     *
101
     * @return ValidationResult|Member
102
     * @throws ValidationException
103
     * @throws PasswordEncryptor_NotFoundException
104
     */
105
    public function validateToken($data, $request, &$validationResult = null)
106
    {
107
        if (!$validationResult instanceof ValidationResult) {
108
            $validationResult = ValidationResult::create();
109
        }
110
111
        $memberID = $request->getSession()->get(BootstrapMFALoginHandler::SESSION_KEY . '.MemberID');
112
        // First, let's see if we know the member
113
        /** @var Member|null $member */
114
        $member = Member::get()->filter(['ID' => $memberID])->first();
115
116
        // Continue if we have a valid member
117
        if ($member && $member instanceof Member) {
118
119
            // We do not have to check the YubiAuth for now.
120
            if (!$member->YubiAuthEnabled && empty($data['yubiauth'])) {
121
                return $this->authenticateNoYubikey($member);
122
            }
123
124
            // If we know the member, and it's YubiAuth enabled, continue.
125
            if (!empty($data['yubiauth'])) {
126
                return $this->checkYubikey($data, $member);
127
            }
128
            $member->registerFailedLogin();
129
            $validationResult->addError('Yubikey Authentication error');
130
        }
131
132
        return $validationResult;
133
    }
134
135
    /**
136
     * Handle login if the user did not enter a Yubikey string.
137
     * Will break out and return NULL if the member should use their Yubikey
138
     *
139
     * @param  Member $member
140
     * @return ValidationResult|Member
141
     * @throws ValidationException
142
     */
143
    private function authenticateNoYubikey($member)
144
    {
145
        ++$member->NoYubikeyCount;
146
        $member->write();
147
        $yubiAuthNoYubi = $this->provider->checkNoYubiAttempts($member);
148
        if ($yubiAuthNoYubi instanceof ValidationResult) {
149
            return $yubiAuthNoYubi;
150
        }
151
152
        return $member;
153
    }
154
155
    /**
156
     * @param $data
157
     * @param $member
158
     * @return ValidationResult|Member
159
     * @throws ValidationException
160
     * @throws PasswordEncryptor_NotFoundException
161
     */
162
    protected function checkYubikey($data, $member)
163
    {
164
        /** @var Validate $service */
165
        $this->yubiService = Injector::inst()->createWithArgs(
166
            Validate::class,
167
            [
168
                Environment::getEnv('YUBIAUTH_APIKEY'),
169
                Environment::getEnv('YUBIAUTH_CLIENTID'),
170
            ]
171
        );
172
173
        return $this->authenticateYubikey($data, $member);
174
    }
175
176
    /**
177
     * Validate a member plus it's yubikey login. It compares the fingerprintt and after that,
178
     * tries to validate the Yubikey string
179
     *
180
     * @param  array $data
181
     * @param  Member $member
182
     * @return ValidationResult|Member
183
     * @throws ValidationException
184
     * @throws PasswordEncryptor_NotFoundException
185
     */
186
    private function authenticateYubikey($data, $member)
187
    {
188
        if ($url = Config::inst()->get(self::class, 'AuthURL')) {
189
            $this->yubiService->setHost($url);
190
        }
191
        $yubiCode = QwertyConvertor::convertString($data['yubiauth']);
192
        $yubiFingerprint = substr($yubiCode, 0, -32);
193
        $validationResult = ValidationResult::create();
194
195
        if ($member->Yubikey) {
196
            $validationResult = $this->provider->validateToken($member, $yubiFingerprint);
197
            if (!$validationResult->isValid()) {
198
                $member->registerFailedLogin();
199
200
                return $validationResult;
201
            }
202
        }
203
        try {
204
            /** @var Response $result */
205
            $result = $this->yubiService->check($yubiCode);
206
            $this->updateMember($member, $yubiFingerprint);
207
        } catch (Exception $e) {
208
            $validationResult->addError($e->getMessage());
209
210
            $member->registerFailedLogin();
211
212
            return $validationResult;
213
        }
214
        if ($result->success() === true) {
215
            $this->updateMember($member, $yubiFingerprint);
216
217
            return $member;
218
        }
219
220
        $validationResult = ValidationResult::create();
221
        $validationResult->addError(_t('YubikeyAuthenticator.ERROR', 'Yubikey authentication error'));
222
        $member->registerFailedLogin();
223
224
        return $validationResult;
225
    }
226
227
    /**
228
     * Update the member to forcefully enable YubiAuth
229
     * Also, register the Yubikey to the member.
230
     * Documentation:
231
     * https://developers.yubico.com/yubikey-val/Getting_Started_Writing_Clients.html
232
     *
233
     * @param Member $member
234
     * @param string $yubiString The Identifier String of the Yubikey
235
     * @throws ValidationException
236
     */
237
    private function updateMember($member, $yubiString)
238
    {
239
        $member->registerSuccessfulLogin();
240
        $member->NoYubikeyCount = 0;
241
242
        if (!$member->MFAEnabled) {
243
            $member->MFAEnabled = true;
244
        }
245
        if (!$member->Yubikey) {
246
            $member->Yubikey = $yubiString;
247
        }
248
        $member->write();
249
    }
250
251
    /**
252
     * @param string $link
253
     * @return \SilverStripe\Security\MemberAuthenticator\LoginHandler|static
254
     */
255
    public function getLoginHandler($link)
256
    {
257
        return YubikeyLoginHandler::create($link, $this);
258
    }
259
}
260