Passed
Pull Request — master (#13)
by Simon
02:08
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 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 YubiAuthProvider
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 YubiAuthProvider instance
43
     *
44
     * YubikeyMemberAuthenticator constructor.
45
     */
46
    public function __construct()
47
    {
48
        if (!$this->provider) {
49
            $this->provider = Injector::inst()->get(YubiAuthProvider::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 YubiAuthProvider
65
     */
66
    public function getProvider()
67
    {
68
        return $this->provider;
69
    }
70
71
    /**
72
     * @param YubiAuthProvider $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 null|Member
97
     */
98
    public function validateYubikey($data, $request, &$validationResult)
99
    {
100
        if (!$validationResult) {
0 ignored issues
show
introduced by
$validationResult is of type SilverStripe\ORM\ValidationResult, thus it always evaluated to true.
Loading history...
101
            $validationResult = ValidationResult::create();
102
        }
103
104
        $memberID = $request->getSession()->get('YubikeyLoginHandler.MemberID');
105
        // First, let's see if we know the member
106
        /** @var Member|null $member */
107
        $member = Member::get()->filter(['ID' => $memberID])->first();
108
109
        // Continue if we have a valid member
110
        if ($member && $member instanceof Member) {
111
112
            // We do not have to check the YubiAuth for now.
113
            if (!$member->YubiAuthEnabled && empty($data['yubiauth'])) {
114
                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...
115
            }
116
117
            // If we know the member, and it's YubiAuth enabled, continue.
118
            if (!empty($data['yubiauth'])) {
119
                /** @var Validate $service */
120
                $this->yubiService = Injector::inst()->createWithArgs(
121
                    Validate::class,
122
                    [
123
                        Environment::getEnv('YUBIAUTH_APIKEY'),
124
                        Environment::getEnv('YUBIAUTH_CLIENTID'),
125
                    ]
126
                );
127
128
                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...
129
            }
130
            $member->registerFailedLogin();
131
            $validationResult->addError('Yubikey Authentication error');
132
        }
133
134
        return null;
135
    }
136
137
    /**
138
     * Handle login if the user did not enter a Yubikey string.
139
     * Will break out and return NULL if the member should use their Yubikey
140
     *
141
     * @param  Member $member
142
     * @return ValidationResult|Member
143
     */
144
    private function authenticateNoYubikey($member)
145
    {
146
        ++$member->NoYubikeyCount;
147
        $member->write();
148
        $yubiAuthNoYubi = $this->provider->checkNoYubiAttempts($member);
149
        if ($yubiAuthNoYubi instanceof ValidationResult) {
150
            return $yubiAuthNoYubi;
151
        }
152
153
        return $member;
154
    }
155
156
    /**
157
     * Validate a member plus it's yubikey login. It compares the fingerprintt and after that,
158
     * tries to validate the Yubikey string
159
     *
160
     * @param  array $data
161
     * @param  Member $member
162
     * @return ValidationResult|Member
163
     */
164
    private function authenticateYubikey($data, $member)
165
    {
166
        if ($url = Config::inst()->get(self::class, 'AuthURL')) {
167
            $this->yubiService->setHost($url);
168
        }
169
        $yubiCode = QwertyConvertor::convertString($data['yubiauth']);
170
        $yubiFingerprint = substr($yubiCode, 0, -32);
171
        $validationResult = ValidationResult::create();
172
173
        if ($member->Yubikey) {
174
            $validationResult = $this->provider->validateYubikey($member, $yubiFingerprint);
175
            if (!$validationResult->isValid()) {
176
                $member->registerFailedLogin();
177
178
                return $validationResult;
179
            }
180
        }
181
        try {
182
            /** @var Response $result */
183
            $result = $this->yubiService->check($yubiCode);
184
            $this->updateMember($member, $yubiFingerprint);
185
        } catch (Exception $e) {
186
            $validationResult->addError($e->getMessage());
187
188
            $member->registerFailedLogin();
189
190
            return $validationResult;
191
        }
192
        if ($result->success() === true) {
193
            $this->updateMember($member, $yubiFingerprint);
194
195
            return $member;
196
        }
197
198
        $validationResult = ValidationResult::create();
199
        $validationResult->addError(_t('YubikeyAuthenticator.ERROR', 'Yubikey authentication error'));
200
        $member->registerFailedLogin();
201
202
        return $validationResult;
203
    }
204
205
    /**
206
     * Update the member to forcefully enable YubiAuth
207
     * Also, register the Yubikey to the member.
208
     * Documentation:
209
     * https://developers.yubico.com/yubikey-val/Getting_Started_Writing_Clients.html
210
     *
211
     * @param Member $member
212
     * @param string $yubiString The Identifier String of the Yubikey
213
     */
214
    private function updateMember($member, $yubiString)
215
    {
216
        $member->registerSuccessfulLogin();
217
        $member->NoYubikeyCount = 0;
218
219
        if (!$member->YubiAuthEnabled) {
220
            $member->YubiAuthEnabled = true;
221
        }
222
        if (!$member->Yubikey) {
223
            $member->Yubikey = $yubiString;
224
        }
225
        $member->write();
226
    }
227
228
229
    /**
230
     * @param string $link
231
     * @return \SilverStripe\Security\MemberAuthenticator\LoginHandler|static
232
     */
233
    public function getLoginHandler($link)
234
    {
235
        return YubikeyLoginHandler::create($link, $this);
236
    }
237
}
238