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

YubikeyMemberAuthenticator::authenticateYubikey()   B

Complexity

Conditions 6
Paths 18

Size

Total Lines 39
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 24
nc 18
nop 2
dl 0
loc 39
rs 8.439
c 0
b 0
f 0
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->MFAEnabled && empty($data['yubiauth'])) {
121
                return $this->authenticateNoYubikey($member);
122
            }
123
124
            // If we know the member, and it's YubiAuth enabled, continue.
125
            return $this->checkYubikey($data, $member);
126
        }
127
128
        return $validationResult;
129
    }
130
131
    /**
132
     * Handle login if the user did not enter a Yubikey string.
133
     * Will break out and return NULL if the member should use their Yubikey
134
     *
135
     * @param  Member $member
136
     * @return ValidationResult|Member
137
     * @throws ValidationException
138
     */
139
    private function authenticateNoYubikey($member)
140
    {
141
        ++$member->NoYubikeyCount;
142
        $member->write();
143
        $yubiAuthNoYubi = $this->provider->checkNoYubiAttempts($member);
144
        if ($yubiAuthNoYubi instanceof ValidationResult) {
145
            return $yubiAuthNoYubi;
146
        }
147
148
        return $member;
149
    }
150
151
    /**
152
     * @param $data
153
     * @param $member
154
     * @return ValidationResult|Member
155
     * @throws ValidationException
156
     * @throws PasswordEncryptor_NotFoundException
157
     */
158
    protected function checkYubikey($data, $member)
159
    {
160
        /** @var Validate $service */
161
        $this->yubiService = Injector::inst()->createWithArgs(
162
            Validate::class,
163
            [
164
                Environment::getEnv('YUBIAUTH_APIKEY'),
165
                Environment::getEnv('YUBIAUTH_CLIENTID'),
166
            ]
167
        );
168
169
        return $this->authenticateYubikey($data, $member);
170
    }
171
172
    /**
173
     * Validate a member plus it's yubikey login. It compares the fingerprintt and after that,
174
     * tries to validate the Yubikey string
175
     *
176
     * @param  array $data
177
     * @param  Member $member
178
     * @return ValidationResult|Member
179
     * @throws ValidationException
180
     * @throws PasswordEncryptor_NotFoundException
181
     */
182
    private function authenticateYubikey($data, $member)
183
    {
184
        if ($url = Config::inst()->get(self::class, 'AuthURL')) {
185
            $this->yubiService->setHost($url);
186
        }
187
        $yubiCode = QwertyConvertor::convertString($data['yubiauth']);
188
        $yubiFingerprint = substr($yubiCode, 0, -32);
189
        $validationResult = ValidationResult::create();
190
191
        if ($member->Yubikey) {
192
            $validationResult = $this->provider->validateToken($member, $yubiFingerprint);
193
            if (!$validationResult->isValid()) {
194
                $member->registerFailedLogin();
195
196
                return $validationResult;
197
            }
198
        }
199
        try {
200
            /** @var Response $result */
201
            $result = $this->yubiService->check($yubiCode);
202
            $this->updateMember($member, $yubiFingerprint);
203
        } catch (Exception $e) {
204
            $validationResult->addError($e->getMessage());
205
206
            $member->registerFailedLogin();
207
208
            return $validationResult;
209
        }
210
        if ($result->success() === true) {
211
            $this->updateMember($member, $yubiFingerprint);
212
213
            return $member;
214
        }
215
216
        $validationResult = ValidationResult::create();
217
        $validationResult->addError(_t('YubikeyAuthenticator.ERROR', 'Yubikey authentication error'));
218
        $member->registerFailedLogin();
219
220
        return $validationResult;
221
    }
222
223
    /**
224
     * Update the member to forcefully enable YubiAuth
225
     * Also, register the Yubikey to the member.
226
     * Documentation:
227
     * https://developers.yubico.com/yubikey-val/Getting_Started_Writing_Clients.html
228
     *
229
     * @param Member $member
230
     * @param string $yubiString The Identifier String of the Yubikey
231
     * @throws ValidationException
232
     */
233
    private function updateMember($member, $yubiString)
234
    {
235
        $member->registerSuccessfulLogin();
236
        $member->NoYubikeyCount = 0;
237
238
        if (!$member->MFAEnabled) {
239
            $member->MFAEnabled = true;
240
        }
241
        if (!$member->Yubikey) {
242
            $member->Yubikey = $yubiString;
243
        }
244
        $member->write();
245
    }
246
247
    /**
248
     * @param string $link
249
     * @return \SilverStripe\Security\MemberAuthenticator\LoginHandler|static
250
     */
251
    public function getLoginHandler($link)
252
    {
253
        return YubikeyLoginHandler::create($link, $this);
254
    }
255
}
256