Passed
Pull Request — master (#13)
by Simon
02:17
created

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