1<?php
2
3use dokuwiki\plugin\twofactor\Manager;
4use dokuwiki\plugin\twofactor\OtpField;
5use dokuwiki\plugin\twofactor\Provider;
6
7/**
8 * DokuWiki Plugin twofactor (Action Component)
9 *
10 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
11 */
12class action_plugin_twofactor_login extends DokuWiki_Action_Plugin
13{
14    const TWOFACTOR_COOKIE = '2FA' . DOKU_COOKIE;
15
16    /**
17     * Registers the event handlers.
18     */
19    public function register(Doku_Event_Handler $controller)
20    {
21        // check 2fa requirements and either move to profile or login handling
22        $controller->register_hook(
23            'ACTION_ACT_PREPROCESS',
24            'BEFORE',
25            $this,
26            'handleActionPreProcess',
27            null,
28            Manager::EVENT_PRIORITY
29        );
30
31        // display login form
32        $controller->register_hook(
33            'TPL_ACT_UNKNOWN',
34            'BEFORE',
35            $this,
36            'handleLoginDisplay'
37        );
38
39        // disable user in all non-main screens (media, detail, ajax, ...)
40        $controller->register_hook(
41            'DOKUWIKI_INIT_DONE',
42            'BEFORE',
43            $this,
44            'handleInitDone'
45        );
46    }
47
48    /**
49     * Decide if any 2fa handling needs to be done for the current user
50     *
51     * @param Doku_Event $event
52     */
53    public function handleActionPreProcess(Doku_Event $event)
54    {
55        if ($event->data === 'resendpwd') {
56            // this is completely handled in resendpwd.php
57            return;
58        }
59
60        $manager = Manager::getInstance();
61        if (!$manager->isReady()) return;
62
63        global $INPUT;
64
65        // already in a 2fa login?
66        if ($event->data === 'twofactor_login') {
67            if ($this->verify(
68                $INPUT->str('2fa_code'),
69                $INPUT->str('2fa_provider'),
70                $this->isSticky()
71            )) {
72                $event->data = 'show';
73                return;
74            } else {
75                // show form
76                $event->preventDefault();
77                return;
78            }
79        }
80
81        // clear cookie on logout
82        if ($event->data === 'logout') {
83            $this->deAuth();
84            return;
85        }
86
87        // authed already, continue
88        if ($this->isAuthed()) {
89            return;
90        }
91
92        if (count($manager->getUserProviders())) {
93            // user has already 2fa set up - they need to authenticate before anything else
94            $event->data = 'twofactor_login';
95            $event->preventDefault();
96            $event->stopPropagation();
97            return;
98        }
99
100        if ($manager->isRequired()) {
101            // 2fa is required - they need to set it up now
102            // this will be handled by action/profile.php
103            $event->data = 'twofactor_profile';
104        }
105
106        // all good. proceed
107    }
108
109    /**
110     * Show a 2fa login screen
111     *
112     * @param Doku_Event $event
113     */
114    public function handleLoginDisplay(Doku_Event $event)
115    {
116        if ($event->data !== 'twofactor_login') return;
117        $manager = Manager::getInstance();
118        if (!$manager->isReady()) return;
119
120        $event->preventDefault();
121        $event->stopPropagation();
122
123        global $INPUT;
124        $providerID = $INPUT->str('2fa_provider');
125
126        echo '<div class="plugin_twofactor_login">';
127        echo inlineSVG(__DIR__ . '/../admin.svg');
128        echo $this->locale_xhtml('login');
129        echo $manager->getCodeForm($providerID)->toHTML();
130        echo '</div>';
131    }
132
133    /**
134     * Remove user info from non-main entry points while we wait for 2fa
135     *
136     * @param Doku_Event $event
137     */
138    public function handleInitDone(Doku_Event $event)
139    {
140        global $INPUT;
141
142        if (!(Manager::getInstance())->isReady()) return;
143        if (basename($INPUT->server->str('SCRIPT_NAME')) == DOKU_SCRIPT) return;
144        if ($this->isAuthed()) return;
145
146        if ($this->getConf('optinout') !== 'mandatory' && empty(Manager::getInstance()->getUserProviders())) return;
147
148        // temporarily remove user info from environment
149        $INPUT->server->remove('REMOTE_USER');
150        unset($_SESSION[DOKU_COOKIE]['auth']);
151        unset($GLOBALS['USERINFO']);
152    }
153
154    /**
155     * Has the user already authenticated with the second factor?
156     * @return bool
157     */
158    protected function isAuthed()
159    {
160        if (!isset($_COOKIE[self::TWOFACTOR_COOKIE])) return false;
161        $data = unserialize(base64_decode($_COOKIE[self::TWOFACTOR_COOKIE]));
162        if (!is_array($data)) return false;
163        list($providerID, $hash,) = $data;
164
165        try {
166            $provider = (Manager::getInstance())->getUserProvider($providerID);
167            if ($this->cookieHash($provider) !== $hash) return false;
168            return true;
169        } catch (Exception $ignored) {
170            return false;
171        }
172    }
173
174    /**
175     * Get sticky value from standard cookie
176     *
177     * @return bool
178     */
179    protected function isSticky()
180    {
181        if (!isset($_COOKIE[DOKU_COOKIE])) {
182            return false;
183        }
184        list(, $sticky,) = explode('|', $_COOKIE[DOKU_COOKIE], 3);
185        return (bool)$sticky;
186    }
187
188    /**
189     * Deletes the cookie
190     *
191     * @return void
192     */
193    protected function deAuth()
194    {
195        global $conf;
196
197        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
198        $time = time() - 60 * 60 * 24 * 365; // one year in the past
199        setcookie(self::TWOFACTOR_COOKIE, null, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
200    }
201
202    /**
203     * Verify a given code
204     *
205     * @return bool
206     * @throws Exception
207     */
208    protected function verify($code, $providerID, $sticky)
209    {
210        global $conf;
211
212        $manager = Manager::getInstance();
213        if (!$manager->verifyCode($code, $providerID)) return false;
214
215        $provider = (Manager::getInstance())->getUserProvider($providerID);
216
217        // store cookie
218        $hash = $this->cookieHash($provider);
219        $data = base64_encode(serialize([$providerID, $hash, time()]));
220        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
221        $time = $sticky ? (time() + 60 * 60 * 24 * 30 * 3) : 0; //three months on sticky login
222        setcookie(self::TWOFACTOR_COOKIE, $data, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
223
224        return true;
225    }
226
227    /**
228     * Create a hash that validates the cookie
229     *
230     * @param Provider $provider
231     * @return string
232     */
233    protected function cookieHash($provider)
234    {
235        return sha1(join("\n", [
236            $provider->getProviderID(),
237            (Manager::getInstance())->getUser(),
238            $provider->getSecret(),
239            $this->getConf("useinternaluid") ? auth_browseruid() : $_SERVER['HTTP_USER_AGENT'],
240            auth_cookiesalt(false, true),
241        ]));
242    }
243}
244