xref: /plugin/twofactor/action/login.php (revision 848a9be0bf692dd7dee51fee25ed5a3a29453972)
1<?php
2
3/**
4 * Two Factor Action Plugin
5 *
6 * @author Mike Wilmes mwilmes@avc.edu
7 * Big thanks to Daniel Popp and his Google 2FA code (authgoogle2fa) as a
8 * starting reference.
9 *
10 * Overview:
11 * The plugin provides for two opportunities to perform two factor
12 * authentication. The first is on the main login page, via a code provided by
13 * an external authenticator. The second is at a separate prompt after the
14 * initial login. By default, all modules will process from the second login,
15 * but a module can subscribe to accepting a password from the main login when
16 * it makes sense, because the user has access to the code in advance.
17 *
18 * If a user only has configured modules that provide for login at the main
19 * screen, the code will only be accepted at the main login screen for
20 * security purposes.
21 *
22 * Modules will be called to render their configuration forms on the profile
23 * page and to verify a user's submitted code. If any module accepts the
24 * submitted code, then the user is granted access.
25 *
26 * Each module may be used to transmit a message to the user that their
27 * account has been logged into. One module may be used as the default
28 * transmit option. These options are handled by the parent module.
29 */
30
31// Create a definition for a 2FA cookie.
32use dokuwiki\plugin\twofactor\Manager;
33
34class action_plugin_twofactor_login extends DokuWiki_Action_Plugin
35{
36    const TWOFACTOR_COOKIE = '2FA' . DOKU_COOKIE;
37
38    /** @var Manager */
39    protected $manager;
40
41    /**
42     * Constructor
43     */
44    public function __construct()
45    {
46        $this->manager = Manager::getInstance();
47    }
48
49    /**
50     * Registers the event handlers.
51     */
52    public function register(Doku_Event_Handler $controller)
53    {
54        if (!(Manager::getInstance())->isReady()) return;
55
56        // check 2fa requirements and either move to profile or login handling
57        $controller->register_hook(
58            'ACTION_ACT_PREPROCESS',
59            'BEFORE',
60            $this,
61            'handleActionPreProcess',
62            null,
63            -999999
64        );
65
66        // display login form
67        $controller->register_hook(
68            'TPL_ACT_UNKNOWN',
69            'BEFORE',
70            $this,
71            'handleLoginDisplay'
72        );
73
74        // FIXME disable user in all non-main screens (media, detail, ajax, ...)
75
76        /*
77        $controller->register_hook('HTML_LOGINFORM_OUTPUT', 'BEFORE', $this, 'twofactor_login_form');
78
79        // Manage action flow around the twofactor authentication requirements.
80
81        // Handle the twofactor login and profile actions.
82        $controller->register_hook('TPL_ACT_UNKNOWN', 'BEFORE', $this, 'twofactor_handle_unknown_action');
83        $controller->register_hook('TPL_ACTION_GET', 'BEFORE', $this, 'twofactor_get_unknown_action');
84
85        // If the user supplies a token code at login, checks it before logging the user in.
86        $controller->register_hook('AUTH_LOGIN_CHECK', 'BEFORE', $this, 'twofactor_before_auth_check', null,
87            -999999);
88        // Atempts to process the second login if the user hasn't done so already.
89        $controller->register_hook('AUTH_LOGIN_CHECK', 'AFTER', $this, 'twofactor_after_auth_check');
90        $this->log('register: Session: ' . print_r($_SESSION, true), self::LOGGING_DEBUGPLUS);
91        */
92    }
93
94    /**
95     * Decide if any 2fa handling needs to be done for the current user
96     *
97     * @param Doku_Event $event
98     */
99    public function handleActionPreProcess(Doku_Event $event)
100    {
101        if (!$this->manager->getUser()) return;
102
103        global $INPUT;
104
105        // already in a 2fa login?
106        if ($event->data === 'twofactor_login') {
107            if ($this->verify(
108                $INPUT->str('2fa_code'),
109                $INPUT->str('2fa_provider'),
110                $INPUT->bool('sticky')
111            )) {
112                $event->data = 'show';
113                return;
114            } else {
115                // show form
116                $event->preventDefault();
117                return;
118            }
119        }
120
121        // authed already, continue
122        if ($this->isAuthed()) {
123            return;
124        }
125
126        if (count($this->manager->getUserProviders())) {
127            // user has already 2fa set up - they need to authenticate before anything else
128            $event->data = 'twofactor_login';
129            $event->preventDefault();
130            $event->stopPropagation();
131            return;
132        }
133
134        if ($this->manager->isRequired()) {
135            // 2fa is required - they need to set it up now
136            // this will be handled by action/profile.php
137            $event->data = 'twofactor_profile';
138        }
139
140        // all good. proceed
141    }
142
143    /**
144     * Show a 2fa login screen
145     *
146     * @param Doku_Event $event
147     */
148    public function handleLoginDisplay(Doku_Event $event)
149    {
150        if ($event->data !== 'twofactor_login') return;
151        $event->preventDefault();
152        $event->stopPropagation();
153
154        global $INPUT;
155        $providerID = $INPUT->str('2fa_provider');
156        $providers = $this->manager->getUserProviders();
157        if (isset($providers[$providerID])) {
158            $provider = $providers[$providerID];
159            unset($providers[$providerID]);
160        } else {
161            $provider = array_shift($providers);
162        }
163
164        $form = new dokuwiki\Form\Form(['method' => 'POST']);
165        $form->setHiddenField('do', 'twofactor_login');
166        $form->setHiddenField('2fa_provider', $provider->getProviderID());
167        $form->addFieldsetOpen($provider->getLabel());
168        try {
169            $code = $provider->generateCode();
170            $info = $provider->transmitMessage($code);
171            $form->addHTML('<p>' . hsc($info) . '</p>');
172            $form->addTextInput('2fa_code', 'Your Code')->val('');
173            $form->addCheckbox('sticky', 'Remember this browser'); // reuse same name as login
174            $form->addButton('2fa', 'Submit')->attr('type', 'submit');
175        } catch (\Exception $e) {
176            msg(hsc($e->getMessage()), -1); // FIXME better handling
177        }
178        $form->addFieldsetClose();
179
180        if (count($providers)) {
181            $form->addFieldsetOpen('Alternative methods');
182            foreach ($providers as $prov) {
183                $link = $prov->getProviderID(); // FIXME build correct links
184
185                $form->addHTML($link);
186            }
187            $form->addFieldsetClose();
188        }
189
190        echo $form->toHTML();
191    }
192
193    /**
194     * Has the user already authenticated with the second factor?
195     * @return bool
196     */
197    protected function isAuthed()
198    {
199        if (!isset($_COOKIE[self::TWOFACTOR_COOKIE])) return false;
200        $data = unserialize(base64_decode($_COOKIE[self::TWOFACTOR_COOKIE]));
201        if (!is_array($data)) return false;
202        list($providerID, $buid,) = $data;
203        if (auth_browseruid() !== $buid) return false;
204
205        try {
206            // ensure it's a still valid provider
207            $this->manager->getUserProvider($providerID);
208            return true;
209        } catch (\Exception $e) {
210            return false;
211        }
212    }
213
214    /**
215     * Verify a given code
216     *
217     * @return bool
218     * @throws Exception
219     */
220    protected function verify($code, $providerID, $sticky)
221    {
222        global $conf;
223
224        if (!$code) return false;
225        if (!$providerID) return false;
226        $provider = $this->manager->getUserProvider($providerID);
227        $ok = $provider->checkCode($code);
228        if (!$ok) {
229            msg('code was wrong', -1);
230            return false;
231        }
232
233        // store cookie
234        $data = base64_encode(serialize([$providerID, auth_browseruid(), time()]));
235        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
236        $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
237        setcookie(self::TWOFACTOR_COOKIE, $data, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
238
239        return true;
240    }
241
242
243    // region old shit
244
245    /**
246     * Handles the login form rendering.
247     */
248    public function twofactor_login_form(&$event, $param)
249    {
250        $this->log('twofactor_login_form: start', self::LOGGING_DEBUG);
251        $twofa_form = form_makeTextField('otp', '', $this->getLang('twofactor_login'), '', 'block',
252            array('size' => '50', 'autocomplete' => 'off'));
253        $pos = $event->data->findElementByAttribute('name', 'p');
254        $event->data->insertElement($pos + 1, $twofa_form);
255    }
256
257    /**
258     * Action process redirector.  If logging out, processes the logout
259     * function.  If visiting the profile, sets a flag to confirm that the
260     * profile is being viewed in order to enable OTP attribute updates.
261     */
262    public function twofactor_action_process_handler(&$event, $param)
263    {
264        global $USERINFO, $ID, $INFO, $INPUT;
265        $this->log('twofactor_action_process_handler: start ' . $event->data, self::LOGGING_DEBUG);
266        // Handle logout.
267        if ($event->data == 'logout') {
268            $this->_logout();
269            return;
270        }
271        // Handle main login.
272        if ($event->data == 'login') {
273            // To support loglog or any other module that hooks login checking for success,
274            // Confirm that the user is logged in.  If not, then redirect to twofactor_login
275            // and fail the login.
276            if ($USERINFO && !$this->get_clearance()) {
277                // Hijack this event.  We need to resend it after 2FA is done.
278                $event->stopPropagation();
279                // Send loglog an event to show the user logged in but needs OTP code.
280                $log = array('message' => 'logged in, ' . $this->getLang('requires_otp'), 'user' => $user);
281                trigger_event('PLUGIN_LOGLOG_LOG', $log);
282            }
283            return;
284        }
285
286        // Check to see if we are heading to the twofactor login.
287        if ($event->data == 'twofactor_login') {
288            // Check if we already have clearance- just in case.
289            if ($this->get_clearance()) {
290                // Okay, this continues on with normal processing.
291                return;
292            }
293            // We will be handling this action's permissions here.
294            $event->preventDefault();
295            $event->stopPropagation();
296            // If not logged into the main auth plugin then send there.
297            if (!$USERINFO) {
298                $event->result = false;
299                send_redirect(wl($ID, array('do' => 'login'), true, '&'));
300                return;
301            }
302            if (count($this->otpMods) == 0) {
303                $this->log('No available otp modules.', self::LOGGING_DEBUG);
304                // There is no way to handle this login.
305                msg($this->getLang('mustusetoken'), -1);
306                $event->result = false;
307                send_redirect(wl($ID, array('do' => 'logout'), true, '&'));
308                return;
309            }
310            // Otherwise handle the action.
311            $act = $this->_process_otp($event, $param);
312            $event->result = true;
313            if ($act) {
314                send_redirect(wl($ID, array('do' => $act), true, '&'));
315            }
316            return;
317        }
318
319        // Is the user logged into the wiki?
320        if (!$USERINFO) {
321            // If not logged in, then do nothing.
322            return;
323        }
324
325        // See if this user has any OTP methods configured.
326        $available = count($this->tokenMods) + count($this->otpMods) > 0;
327        // Check if this user needs to login with 2FA.
328        // Wiki mandatory is on if user is logged in and config is mandatory
329        $mandatory = $this->getConf("optinout") == 'mandatory' && $INPUT->server->str('REMOTE_USER', '');
330        // User is NOT OPTED OUT if the optin setting is undefined and the wiki config is optout.
331        $not_opted_out = $this->attribute->get("twofactor", "state") == '' && $this->getConf("optinout") == 'optout';
332        // The user must login if wiki mandatory is on or if the user is logged in and user is opt in.
333        $must_login = $mandatory || ($this->attribute->get("twofactor",
334                    "state") == 'in' && $INPUT->server->str('REMOTE_USER', ''));
335        $has_clearance = $this->get_clearance() === true;
336        $this->log('twofactor_action_process_handler: USERINFO: ' . print_r($USERINFO, true), self::LOGGING_DEBUGPLUS);
337
338        // Possible combination skipped- not logged in and 2FA is not requred for user {optout conf or (no selection and optin conf)}.
339
340        // Check to see if updating twofactor is required.
341        // This happens if the wiki is mandatory, the user has not opted out of an opt-out wiki, or if the user has opted in, and if there are no available mods for use.
342        // The user cannot have available mods without setting them up, and cannot unless the wiki is mandatory or the user has opted in.
343        if (($must_login || $not_opted_out) && !$available) {
344            // If the user has not been granted access at this point, do so or they will get booted after setting up 2FA.
345            if (!$has_clearance) {
346                $this->_grant_clearance();
347            }
348            // We need to go to the twofactor profile.
349            // If we were setup properly, we would not be here in the code.
350            $event->preventDefault();
351            $event->stopPropagation();
352            $event->result = false;
353            // Send loglog an event to show the user aborted 2FA.
354            $log = array('message' => 'logged in, ' . $this->getLang('2fa_mandatory'), 'user' => $user);
355            trigger_event('PLUGIN_LOGLOG_LOG', $log);
356            send_redirect(wl($ID, array('do' => 'twofactor_profile'), true, '&'));
357            return;
358        }
359
360        // Now validate login before proceeding.
361        if (!$has_clearance) {
362            if ($must_login) {
363                if (!in_array($event->data, array('login', 'twofactor_login'))) {
364                    // If not logged in then force to the login page.
365                    $event->preventDefault();
366                    $event->stopPropagation();
367                    $event->result = false;
368                    // If there are OTP generators, then use them.
369                    send_redirect(wl($ID, array('do' => 'twofactor_login'), true, '&'));
370                    return;
371                }
372                // Otherwise go to where we are told.
373                return;
374            }
375            // The user is not set with 2FA and is not required to.
376            // Grant clearance and continue.
377            $this->_grant_clearance();
378        }
379        // Otherwise everything is good!
380        return;
381    }
382
383    public function twofactor_handle_unknown_action(Doku_Event $event, $param)
384    {
385        if ($event->data == 'twofactor_login') {
386            $event->preventDefault();
387            $event->stopPropagation();
388            $event->result = $this->twofactor_otp_login($event, $param);
389            return;
390        }
391    }
392
393    public function twofactor_get_unknown_action(&$event, $param)
394    {
395        $this->log('start: twofactor_before_auth_check', self::LOGGING_DEBUG);
396        switch ($event->data['type']) {
397            case 'twofactor_profile':
398                $event->data['params'] = array('do' => 'twofactor_profile');
399                // Inject text into $lang.
400                global $lang;
401                $lang['btn_twofactor_profile'] = $this->getLang('btn_twofactor_profile');
402                $event->preventDefault();
403                $event->stopPropagation();
404                $event->result = false;
405                break;
406        }
407    }
408
409    /**
410     * Logout this session from two factor authentication.  Purge any existing
411     * OTP from the user's attributes.
412     */
413    private function _logout()
414    {
415        global $conf, $INPUT;
416        $this->log('_logout: start', self::LOGGING_DEBUG);
417        $this->log(print_r(array($_SESSION, $_COOKIE), true), self::LOGGING_DEBUGPLUS);
418        // No need to do this as long as no Cookie or session for login is present!
419        if (empty($_SESSION[DOKU_COOKIE]['twofactor_clearance']) && empty($_COOKIE[TWOFACTOR_COOKIE])) {
420            $this->log('_logout: quitting, no cookies', self::LOGGING_DEBUG);
421            return;
422        }
423        // Audit log.
424        $this->log("2FA Logout: " . $INPUT->server->str('REMOTE_USER', $_REQUEST['r']), self::LOGGING_AUDIT);
425        if ($this->attribute) {
426            // Purge outstanding OTPs.
427            $this->attribute->del("twofactor", "otp");
428            // Purge cookie and session ID relation.
429            $key = $_COOKIE[TWOFACTOR_COOKIE];
430            if (!empty($key) && substr($key, 0, 3) != 'id.') {
431                $id = $this->attribute->del("twofactor", $key);
432            }
433            // Wipe out 2FA cookie.
434            $this->log('del cookies: ' . TWOFACTOR_COOKIE . ' ' . print_r(headers_sent(), true),
435                self::LOGGING_DEBUGPLUS);
436            $cookie = '';
437            $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
438            $time = time() - 600000; //many seconds ago
439            setcookie(TWOFACTOR_COOKIE, $cookie, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
440            unset($_COOKIE[TWOFACTOR_COOKIE]);
441            // Just in case, unset the setTime flag so attributes will be saved again.
442            $this->setTime = false;
443        }
444        // Before we get here, the session is closed. Reopen it to logout the user.
445        if (!headers_sent()) {
446            $session = session_status() != PHP_SESSION_NONE;
447            if (!$session) {
448                session_start();
449            }
450            $_SESSION[DOKU_COOKIE]['twofactor_clearance'] = false;
451            unset($_SESSION[DOKU_COOKIE]['twofactor_clearance']);
452            if (!$session) {
453                session_write_close();
454            }
455        } else {
456            msg("Error! You have not been logged off!!!", -1);
457        }
458    }
459
460    /**
461     * See if the current session has passed two factor authentication.
462     * @return bool - true if the session as successfully passed two factor
463     *      authentication.
464     */
465    public function get_clearance($user = null)
466    {
467        global $INPUT;
468        $this->log("get_clearance: start", self::LOGGING_DEBUG);
469        $this->log("User:" . $INPUT->server->str('REMOTE_USER', null), self::LOGGING_DEBUGPLUS);
470        # Get and correct the refresh expiry.
471        # At least 5 min, at most 1440 min (1 day).
472        $refreshexpiry = min(max($this->getConf('refreshexpiry'), 5), 1400) * 60;
473        # First check if we have a key.  No key === no login.
474        $key = $_COOKIE[TWOFACTOR_COOKIE];
475        if (empty($key)) {
476            $this->log("get_clearance: No cookie.", self::LOGGING_DEBUGPLUS);
477            return false;
478        }
479        # If the key is not valid, logout.
480        if (substr($key, 0, 3) != 'id.') {
481            $this->log("get_clearance: BAD cookie.", self::LOGGING_DEBUGPLUS);
482            // Purge the login data just in case.
483            $this->_logout();
484            return false;
485        }
486        # Load the expiry value from session.
487        $expiry = $_SESSION[DOKU_COOKIE]['twofactor_clearance'];
488        # Check if this time is valid.
489        $clearance = (!empty($expiry) && $expiry + $refreshexpiry > time());
490        if (!$clearance) {
491            # First use this time to purge the old IDs from attribute.
492            foreach (array_filter($this->attribute->enumerateAttributes("twofactor", $user), function ($key) {
493                substr($key, 0, 3) == 'id.';
494            }) as $attr) {
495                if ($this->attribute->get("twofactor", $attr, $user) + $refreshexpiry < time()) {
496                    $this->attribute->del("twofactor", $attr, $user);
497                }
498            }
499            # Check if this key still exists.
500            $clearance = $this->attribute->exists("twofactor", $key, $user);
501            if ($clearance) {
502                $this->log("get_clearance: 2FA revived by cookie. Expiry: " . print_r($expiry,
503                        true) . " Session: " . print_r($_SESSION, true), self::LOGGING_DEBUGPLUS);
504            }
505        }
506        if ($clearance && !$this->setTime) {
507            $session = session_status() != PHP_SESSION_NONE;
508            if (!$session) {
509                session_start();
510            }
511            $_SESSION[DOKU_COOKIE]['twofactor_clearance'] = time();
512            if (!$session) {
513                session_write_close();
514            }
515            $this->attribute->set("twofactor", $key, $_SESSION[DOKU_COOKIE]['twofactor_clearance'], $user);
516            // Set this flag to stop future updates.
517            $this->setTime = true;
518            $this->log("get_clearance: Session reset. Session: " . print_r($_SESSION, true), self::LOGGING_DEBUGPLUS);
519        } elseif (!$clearance) {
520            // Otherwise logout.
521            $this->_logout();
522        }
523        return $clearance;
524    }
525
526    /**
527     * Flags this session as having passed two factor authentication.
528     * @return bool - returns true on successfully granting two factor clearance.
529     */
530    private function _grant_clearance($user = null)
531    {
532        global $conf, $INPUT;
533        $this->log("_grant_clearance: start", self::LOGGING_DEBUG);
534        $this->log('2FA Login: ' . $INPUT->server->str("REMOTE_USER", $user), self::LOGGING_AUDIT);
535        if ($INPUT->server->str("REMOTE_USER", $user) == 1) {
536            $this->log("_grant_clearance: start", self::LOGGING_DEBUGPLUS);
537        }
538        // Purge the otp code as a security measure.
539        $this->attribute->del("twofactor", "otp", $user);
540        if (!headers_sent()) {
541            $session = session_status() != PHP_SESSION_NONE;
542            if (!$session) {
543                session_start();
544            }
545            $_SESSION[DOKU_COOKIE]['twofactor_clearance'] = time();
546            // Set the notify flag if set or required by wiki.
547            $this->log('_grant_clearance: conf:' . $this->getConf('loginnotice') . ' user:' . ($this->attribute->get("twofactor",
548                    "loginnotice", $user) === true ? 'true' : 'false'), self::LOGGING_DEBUG);
549            $send_wanted = $this->getConf('loginnotice') == 'always' || ($this->getConf('loginnotice') == 'user' && $this->attribute->get("twofactor",
550                        "loginnotice", $user) == true);
551            if ($send_wanted) {
552                $_SESSION[DOKU_COOKIE]['twofactor_notify'] = true;
553            }
554            if (!$session) {
555                session_write_close();
556            }
557        } else {
558            msg("Error! You have not been logged in!!!", -1);
559        }
560        // Creating a cookie in case the session purges.
561        $key = 'id.' . session_id();
562        // Storing a timeout value.
563        $this->attribute->set("twofactor", $key, $_SESSION[DOKU_COOKIE]['twofactor_clearance'], $user);
564        // Set the 2FA cookie.
565        $this->log('_grant_clearance: new cookies: ' . TWOFACTOR_COOKIE . ' ' . print_r(headers_sent(), true),
566            self::LOGGING_DEBUGPLUS);
567        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
568        $time = time() + 60 * 60 * 24 * 365; //one year
569        setcookie(TWOFACTOR_COOKIE, $key, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
570        $_COOKIE[TWOFACTOR_COOKIE] = $key;
571        return !empty($_SESSION[DOKU_COOKIE]['twofactor_clearance']);
572    }
573
574    /**
575     * Sends emails notifying user of successfult 2FA login.
576     * @return mixed - returns true on successfully sending notification to all
577     *     modules, false if no notifications were sent, or a number indicating
578     *     the number of modules that suceeded.
579     */
580    private function _send_login_notification()
581    {
582        $this->log("_send_login_notification: start", self::LOGGING_DEBUG);
583        // Send login notification.
584        $module = $this->attribute->exists("twofactor", "defaultmod") ? $this->attribute->get("twofactor",
585            "defaultmod") : null;
586        $subject = $this->getConf('loginsubject');
587        $time = date(DATE_RFC2822);
588        $message = str_replace('$time', $time, $this->getConf('logincontent'));
589        $result = $this->_send_message($subject, $message, $module);
590        return $result;
591    }
592
593    /**
594     * Handles the authentication check. Screens Google Authenticator OTP, if available.
595     * NOTE: NOT LOGGED IN YET. Attribute requires user name.
596     */
597    function twofactor_before_auth_check(&$event, $param)
598    {
599        global $ACT, $INPUT;
600        $this->log("twofactor_before_auth_check: start $ACT", self::LOGGING_DEBUG);
601        $this->log("twofactor_before_auth_check: Cookie: " . print_r($_COOKIE, true), self::LOGGING_DEBUGPLUS);
602        // Only operate if this is a login.
603        if ($ACT !== 'login') {
604            return;
605        }
606        // If there is no supplied username, then there is nothing to check at this time.
607        if (!$event->data['user']) {
608            return;
609        }
610        $user = $INPUT->server->str('REMOTE_USER', $event->data['user']);
611        // Set helper variables here.
612        $this->_setHelperVariables($user);
613        // If the user still has clearance, then we can skip this.
614        if ($this->get_clearance($user)) {
615            return;
616        }
617        // Allow the user to try to use login tokens, even if the account cannot use them.
618        $otp = $INPUT->str('otp', '');
619        if ($otp !== '') {
620            // Check for any modules that support OTP at login and are ready for use.
621            foreach ($this->tokenMods as $mod) {
622                $result = $mod->processLogin($otp, $user);
623                if ($result) {
624                    // The OTP code was valid.
625                    $this->_grant_clearance($user);
626                    // Send loglog an event to show the user logged in using a token.
627                    $log = array('message' => 'logged in ' . $this->getLang('token_ok'), 'user' => $user);
628                    trigger_event('PLUGIN_LOGLOG_LOG', $log);
629                    return;
630                }
631            }
632            global $lang;
633            msg($lang['badlogin'], -1);
634            $event->preventDefault();
635            $event->result = false;
636            // Send loglog an event to show the failure
637            if (count($this->tokenMods) == 0) {
638                $log = array('message' => 'failed ' . $this->getLang('no_tokens'), 'user' => $user);
639            } else {
640                $log = array('message' => 'failed ' . $this->getLang('token_mismatch'), 'user' => $user);
641            }
642            trigger_event('PLUGIN_LOGLOG_LOG', $log);
643            return;
644        }
645        // No GA OTP was supplied.
646        // If the user has no modules available, then grant access.
647        // The action preprocessing will send the user to the profile if needed.
648        $available = count($this->tokenMods) + count($this->otpMods) > 0;
649        $this->log('twofactor_before_auth_check: Tokens:' . count($this->tokenMods) . ' Codes:' . count($this->otpMods) . " Available:" . (int)$available,
650            self::LOGGING_DEBUGPLUS);
651        if (!$available) {
652            // The user could not authenticate if they wanted to.
653            // Set this so they don't get auth prompted while setting up 2FA.
654            $this->_grant_clearance($user);
655            return;
656        }
657        // At this point, the user has a working module.
658        // If the only working module is for a token, then fail.
659        if (count($this->otpMods) == 0) {
660            msg($this->getLang('mustusetoken'), -1);
661            $event->preventDefault();
662            return;
663        }
664        // The user is logged in to auth, but not into twofactor.
665        // The redirection handler will send the user to the twofactor login.
666        return;
667    }
668
669    /**
670     * @param $event
671     * @param $param
672     */
673    function twofactor_after_auth_check(&$event, $param)
674    {
675        global $ACT;
676        global $INPUT;
677        $this->log("twofactor_after_auth_check: start", self::LOGGING_DEBUG);
678        // Check if the action was login.
679        if ($ACT == 'login') {
680            // If there *was* no one logged in, then purge 2FA tokens.
681            if ($INPUT->server->str('REMOTE_USER', '') == '') {
682                $this->_logout();
683                // If someone *just* logged in, then fire off a log.
684                if ($event->data['user']) {
685                    // Send loglog an event to show the user logged in but needs OTP code.
686                    $log = array(
687                        'message' => 'logged in, ' . $this->getLang('requires_otp'),
688                        'user' => $event->data['user'],
689                    );
690                    trigger_event('PLUGIN_LOGLOG_LOG', $log);
691                }
692                return;
693            }
694        }
695        // Update helper variables here since we are logged in.
696        $this->_setHelperVariables();
697        // If set, then send login notification and clear flag.
698        if ($_SESSION[DOKU_COOKIE]['twofactor_notify'] == true) {
699            // Set the clear flag if no messages can be sent or if the result is not false.
700            $clear = count($this_ > otpMods) > 0 || $this->_send_login_notification() !== false;
701            if ($clear) {
702                unset($_SESSION[DOKU_COOKIE]['twofactor_notify']);
703            }
704        }
705        return;
706    }
707
708    /* Returns action to take. */
709    private function _process_otp(&$event, $param)
710    {
711        global $ACT, $ID, $INPUT;
712        $this->log("_process_otp: start", self::LOGGING_DEBUG);
713        // Get the logged in user.
714        $user = $INPUT->server->str('REMOTE_USER');
715        // See if the user is quitting OTP.  We don't call it logoff because we don't want the user to think they are logged in!
716        // This has to be checked before the template is started.
717        if ($INPUT->has('otpquit')) {
718            // Send loglog an event to show the user aborted 2FA.
719            $log = array('message' => 'logged off, ' . $this->getLang('quit_otp'), 'user' => $user);
720            trigger_event('PLUGIN_LOGLOG_LOG', $log);
721            // Redirect to logout.
722            return 'logout';
723        }
724        // Check if the user asked to generate and resend the OTP.
725        if ($INPUT->has('resend')) {
726            if ($INPUT->has('useall')) {
727                $defaultMod = null;
728            } else {
729                $defaultMod = $this->attribute->exists("twofactor", "defaultmod") ? $this->attribute->get("twofactor",
730                    "defaultmod") : null;
731            }
732            // At this point, try to send the OTP.
733            $mod = array_key_exists($defaultMod, $this->otpMods) ? $this->otpMods[$defaultMod] : null;
734            $this->_send_otp($mod);
735            return;
736        }
737        // If a OTP has been submitted by the user, then verify the OTP.
738        // If verified, then grant clearance and continue normally.
739        $otp = $INPUT->str('otpcode');
740        if ($otp) {
741            foreach ($this->otpMods as $mod) {
742                $result = $mod->processLogin($otp);
743                if ($result) {
744                    // The OTP code was valid.
745                    $this->_grant_clearance();
746                    // Send loglog an event to show the user passed 2FA.
747                    $log = array('message' => 'logged in ' . $this->getLang('otp_ok'), 'user' => $user);
748                    trigger_event('PLUGIN_LOGLOG_LOG', $log);
749                    /*
750                    // This bypasses sending any further events to other modules for the login we stole earlier.
751                    return 'show';
752                    */
753                    // This will trigger the login events again.  However, this is to ensure
754                    // that other modules work correctly because we hijacked this event earlier.
755                    return 'login';
756                }
757            }
758            // Send loglog an event to show the user entered the wrong OTP code.
759            $log = array('message' => 'failed OTP login, ' . $this->getLang('otp_mismatch'), 'user' => $user);
760            trigger_event('PLUGIN_LOGLOG_LOG', $log);
761            msg($this->getLang('twofactor_invalidotp'), -1);
762        }
763        return;
764    }
765
766    /**
767     * Process any updates to two factor settings.
768     */
769    private function _process_changes(&$event, $param)
770    {
771        // If the plugin is disabled, then exit.
772        $this->log("_process_changes: start", self::LOGGING_DEBUG);
773        $changed = false;
774        global $INPUT, $USERINFO, $conf, $auth, $lang, $ACT;
775        if (!$INPUT->has('save')) {
776            return;
777        }
778        // In needed, verify password.
779        if ($conf['profileconfirm']) {
780            if (!$auth->checkPass($INPUT->server->str('REMOTE_USER'), $INPUT->post->str('oldpass'))) {
781                msg($lang['badpassconfirm'], -1);
782                return;
783            }
784        }
785        // Process opt in/out.
786        if ($this->getConf("optinout") != 'mandatory') {
787            $oldoptinout = $this->attribute->get("twofactor", "state");
788            $optinout = $INPUT->bool('optinout', false) ? 'in' : 'out';
789            if ($oldoptinout != $optinout) {
790                $this->attribute->set("twofactor", "state", $optinout);
791                $changed = true;
792            }
793        }
794        // Process notifications.
795        if ($this->getConf("loginnotice") == 'user') {
796            $oldloginnotice = $this->attribute->get("twofactor", "loginnotice");
797            $loginnotice = $INPUT->bool('loginnotice', false);
798            if ($oldloginnotice != $loginnotice) {
799                $this->attribute->set("twofactor", "loginnotice", $loginnotice);
800                $changed = true;
801            }
802        }
803        // Process default module.
804        $defaultmodule = $INPUT->str('default_module', '');
805        if ($defaultmodule) {
806            if ($defaultmodule === $this->getLang('useallotp')) {
807                // Set to use ALL OTP channels.
808                $this->attribute->set("twofactor", "defaultmod", null);
809                $changed = true;
810            } else {
811                $useableMods = array();
812                foreach ($this->modules as $name => $mod) {
813                    if (!$mod->canAuthLogin() && $mod->canUse()) {
814                        $useableMods[$mod->getLang("name")] = $mod;
815                    }
816                }
817                if (array_key_exists($defaultmodule, $useableMods)) {
818                    $this->attribute->set("twofactor", "defaultmod", $defaultmodule);
819                    $changed = true;
820                }
821            }
822        }
823        // Update module settings.
824        $sendotp = null;
825        foreach ($this->modules as $name => $mod) {
826            $this->log('_process_changes: processing ' . get_class($mod) . '::processProfileForm()',
827                self::LOGGING_DEBUG);
828            $result = $mod->processProfileForm();
829            $this->log('_process_changes: processing ' . get_class($mod) . '::processProfileForm() == ' . $result,
830                self::LOGGING_DEBUGPLUS);
831            // false:change failed  'failed':OTP failed  null: no change made
832            $changed |= $result !== false && $result !== 'failed' && $result !== null;
833            switch ((string)$result) {
834                case 'verified':
835                    // Remove used OTP.
836                    $this->attribute->del("twofactor", "otp");
837                    msg($mod->getLang('passedsetup'), 1);
838                    // Reset helper variables.
839                    $this->_setHelperVariables();
840                    $this->log("2FA Added: " . $INPUT->server->str('REMOTE_USER', '') . ' ' . get_class($mod),
841                        self::LOGGING_AUDIT);
842                    break;
843                case 'failed':
844                    msg($mod->getLang('failedsetup'), -1);
845                    break;
846                case 'otp':
847                    if (!$sendotp) {
848                        $sendotp = $mod;
849                    }
850                    break;
851                case 'deleted':
852                    $this->log("2FA Removed: " . $INPUT->server->str('REMOTE_USER', '') . ' ' . get_class($mod),
853                        self::LOGGING_AUDIT);
854                    // Reset helper variables.
855                    $this->_setHelperVariables();
856                    break;
857            }
858        }
859        // Send OTP if requested.
860        if (is_object($sendotp)) {
861            // Force the message since it will fail the canUse function.
862            if ($this->_send_otp($sendotp, true)) {
863                msg($sendotp->getLang('needsetup'), 1);
864            } else {
865                msg("Could not send message using " . get_class($sendotp), -1);
866            }
867        }
868        // Update change status if changed.
869        if ($changed) {
870            // If there were any changes, update the available tokens accordingly.
871            $this->_setHelperVariables();
872            msg($this->getLang('updated'), 1);
873        }
874        return true;
875    }
876
877    /**
878     * Handles the email and text OTP options.
879     * NOTE: The user will be technically logged in at this point.  This module will rewrite the
880     * page with the prompt for the OTP until validated or the user logs out.
881     */
882    function twofactor_otp_login(&$event, $param)
883    {
884        $this->log("twofactor_otp_login: start", self::LOGGING_DEBUG);
885        // Skip this if not logged in or already two factor authenticated.
886        // Ensure the OTP exists and is still valid. If we need to, send a OTP.
887        $otpQuery = $this->get_otp_code();
888        if ($otpQuery == false) {
889            $useableMods = array();
890            foreach ($this->modules as $name => $mod) {
891                if (!$mod->canAuthLogin() && $mod->canUse()) {
892                    $useableMods[$mod->getLang("name")] = $mod;
893                }
894            }
895            $defaultMod = $this->attribute->exists("twofactor", "defaultmod") ? $this->attribute->get("twofactor",
896                "defaultmod") : null;
897            $mod = array_key_exists($defaultMod, $useableMods) ? $useableMods[$defaultMod] : null;
898            $this->_send_otp($mod);
899        }
900        // Generate the form to login.
901        // If we are here, then only provide options to accept the OTP or to logout.
902        global $lang;
903        $form = new Doku_Form(array('id' => 'otp_setup'));
904        $form->startFieldset($this->getLang('twofactor_otplogin'));
905        $form->addElement(form_makeTextField('otpcode', '', $this->getLang('twofactor_otplogin'), '', 'block',
906            array('size' => '50', 'autocomplete' => 'off')));
907        $form->addElement(form_makeButton('submit', '', $this->getLang('btn_login')));
908        $form->addElement(form_makeTag('br'));
909        $form->addElement(form_makeCheckboxField('useall', '1', $this->getLang('twofactor_useallmods'), '', 'block'));
910        $form->addElement(form_makeTag('br'));
911        $form->addElement(form_makeButton('submit', '', $this->getLang('btn_resend'), array('name' => 'resend')));
912        $form->addElement(form_makeButton('submit', '', $this->getLang('btn_quit'), array('name' => 'otpquit')));
913        $form->endFieldset();
914        echo '<div class="centeralign">' . NL . $form->getForm() . '</div>' . NL;
915    }
916
917    /**
918     * Sends a message using configured modules.
919     * If $module is set to a specific instance, that instance will be used to
920     * send the message. If not supplied or null, then all configured modules
921     * will be used to send the message. $module can also be an array of
922     * selected modules.
923     * If $force is true, then will try to send the message even if the module
924     * has not been validated.
925     * @return array(array, mixed) - The first item in the array is an array
926     *     of all modules that the message was successfully sent by.  The
927     *     second item is true if successfull to all attempted tramsmission
928     *     modules, false if all failed, and a number of how many successes
929     *     if only some modules failed.
930     */
931    private function _send_message($subject, $message, $module = null, $force = false)
932    {
933        global $INPUT;
934        $this->log("_send_message: start", self::LOGGING_DEBUG);
935        if ($module === null) {
936            $module = $this->otpMods;
937        }
938        if (!is_array($module)) {
939            $module = array($module);
940        }
941        if (count($module) >= 1) {
942            $modulekeys = array_keys($module);
943            $modulekey = $modulekeys[0];
944            $modname = get_class($module[$modulekey]);
945        } else {
946            $modname = null;
947        }
948        // Attempt to deliver messages.
949        $user = $INPUT->server->str('REMOTE_USER', '*unknown*');
950        $success = 0;
951        $modname = array();
952        foreach ($module as $mod) {
953            if ($mod->canTransmitMessage()) {
954                $worked = $mod->transmitMessage($subject, $message, $force);
955                if ($worked) {
956                    $success += 1;
957                    $modname[] = get_class($mod);
958                }
959                $this->log("Message " . ($worked ? '' : 'not ') . "sent to $user via " . get_class($mod),
960                    self::LOGGING_AUDITPLUS);
961            }
962        }
963        return array($modname, $success == 0 ? false : ($success == count($module) ? true : $success));
964    }
965
966    /**
967     * Transmits a One-Time Password (OTP) using configured modules.
968     * If $module is set to a specific instance, that instance will be used to
969     * send the OTP. If not supplied or null, then all configured modules will
970     * be used to send the OTP. $module can also be an array of selected
971     * modules.
972     * If $force is true, then will try to send the message even if the module
973     * has not been validated.
974     * @return mixed - true if successfull to all attempted tramsmission
975     *     modules, false if all failed, and a number of how many successes
976     *     if only some modules failed.
977     */
978    private function _send_otp($module = null, $force = false)
979    {
980        $this->log("_send_otp: start", self::LOGGING_DEBUG);
981        // Generate the OTP code.
982        $characters = '0123456789';
983        $otp = '';
984        for ($index = 0; $index < $this->getConf('otplength'); ++$index) {
985            $otp .= $characters[rand(0, strlen($characters) - 1)];
986        }
987        // Create the subject.
988        $subject = $this->getConf('otpsubject');
989        // Create the message.
990        $message = str_replace('$otp', $otp, $this->getConf('otpcontent'));
991        // Attempt to deliver the message.
992        list($modname, $result) = $this->_send_message($subject, $message, $module, $force);
993        // If partially successful, store the OTP code and the timestamp the OTP expires at.
994        if ($result) {
995            $otpData = array($otp, time() + $this->getConf('sentexpiry') * 60, $modname);
996            if (!$this->attribute->set("twofactor", "otp", $otpData)) {
997                msg("Unable to record OTP for later use.", -1);
998            }
999        }
1000        return $result;
1001    }
1002
1003    /**
1004     * Returns the OTP code sent to the user, if it has not expired.
1005     * @return mixed - false if there is no unexpired OTP, otherwise
1006     *     array of the OTP and the modules that successfully sent it.
1007     */
1008    public function get_otp_code()
1009    {
1010        $this->log("get_otp_code: start", self::LOGGING_DEBUG);
1011        $otpQuery = $this->attribute->get("twofactor", "otp", $success);
1012        if (!$success) {
1013            return false;
1014        }
1015        list($otp, $expiry, $modname) = $otpQuery;
1016        if (time() > $expiry) {
1017            $this->attribute->del("twofactor", "otp");
1018            return false;
1019        }
1020        return array($otp, $modname);
1021    }
1022
1023    private function _setHelperVariables($user = null)
1024    {
1025        $this->log("_setHelperVariables: start", self::LOGGING_DEBUGPLUS);
1026        $tokenMods = array();
1027        $otpMods = array();
1028        $state = $this->attribute->get("twofactor", "state");
1029        $optinout = $this->getConf("optinout");
1030        $enabled = $optinout == 'mandatory' || ($state == '' ? $optinout == 'optin' : $state == 'in');
1031        $this->log("_setHelperVariables: " . print_r(array($optinout, $state, $enabled), true), self::LOGGING_DEBUG);
1032        // Skip if not enabled for user
1033        if ($enabled) {
1034            // List all working token modules (GA, RSA, etc.).
1035            foreach ($this->modules as $name => $mod) {
1036                if ($mod->canAuthLogin() && $mod->canUse($user)) {
1037                    $this->log('Can use ' . get_class($mod) . ' for tokens', self::LOGGING_DEBUG);
1038                    $tokenMods[$mod->getLang("name")] = $mod;
1039                } else {
1040                    $this->log('Can NOT use ' . get_class($mod) . ' for tokens', self::LOGGING_DEBUG);
1041                }
1042            }
1043            // List all working OTP modules (SMS, Twilio, etc.).
1044            foreach ($this->modules as $name => $mod) {
1045                if (!$mod->canAuthLogin() && $mod->canUse($user)) {
1046                    $this->log('Can use ' . get_class($mod) . ' for otp', self::LOGGING_DEBUG);
1047                    $otpMods[$mod->getLang("name")] = $mod;
1048                } else {
1049                    $this->log('Can NOT use ' . get_class($mod) . ' for otp', self::LOGGING_DEBUG);
1050                }
1051            }
1052        }
1053        $this->tokenMods = $tokenMods;
1054        $this->otpMods = $otpMods;
1055    }
1056
1057    const LOGGING_AUDIT = 1;     // Audit records 2FA login and logout activity.
1058    const LOGGING_AUDITPLUS = 2; // Audit+ also records sending of notifications.
1059    const LOGGING_DEBUG = 3;     // Debug provides detailed workflow data.
1060    const LOGGING_DEBUGPLUS = 4; // Debug+ also includes variables passed to and from functions.
1061
1062    public function log($message, $level = 1)
1063    {
1064        // If the log level requested is below audit or greater than what is permitted in the configuration, then exit.
1065        if ($level < self::LOGGING_AUDIT || $level > $this->getConf('logging_level')) {
1066            return;
1067        }
1068        global $conf;
1069        // Always purge line containing "[pass]".
1070        $message = implode("\n", array_filter(explode("\n", $message), function ($x) {
1071            return !strstr($x, '[pass]');
1072        }));
1073        // If DEBUGPLUS, then append the trace log.
1074        if ($level == self::LOGGING_DEBUGPLUS) {
1075            $e = new Exception();
1076            $message .= "\n" . print_r(str_replace(DOKU_REL, '', $e->getTraceAsString()), true);
1077        }
1078        $logfile = $this->getConf('logging_path');
1079        $logfile = substr($logfile, 0, 1) == '/' ? $logfile : DOKU_INC . $conf['savedir'] . '/' . $logfile;
1080        io_lock($logfile);
1081        #open for append logfile
1082        $handle = @fopen($logfile, 'at');
1083        if ($handle) {
1084            $date = date(DATE_RFC2822);
1085            $IP = $_SERVER["REMOTE_ADDR"];
1086            $id = session_id();
1087            fwrite($handle, "$date,$id,$IP,$level,\"$message\"\n");
1088            fclose($handle);
1089        }
1090        #write "date level message"
1091        io_unlock($logfile);
1092    }
1093
1094    // endregion
1095}
1096