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

YubikeyMemberAuthenticator::validateYubikey()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 37
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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