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