xref: /plugin/twofactor/action/login.php (revision 6c996db8dff158c7317a04e1185060c59b19ad7d)
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    /** @var Manager */
16    protected $manager;
17
18    /**
19     * Constructor
20     */
21    public function __construct()
22    {
23        $this->manager = Manager::getInstance();
24    }
25
26    /**
27     * Registers the event handlers.
28     */
29    public function register(Doku_Event_Handler $controller)
30    {
31        if (!(Manager::getInstance())->isReady()) return;
32
33        // check 2fa requirements and either move to profile or login handling
34        $controller->register_hook(
35            'ACTION_ACT_PREPROCESS',
36            'BEFORE',
37            $this,
38            'handleActionPreProcess',
39            null,
40            -999999
41        );
42
43        // display login form
44        $controller->register_hook(
45            'TPL_ACT_UNKNOWN',
46            'BEFORE',
47            $this,
48            'handleLoginDisplay'
49        );
50
51        // FIXME disable user in all non-main screens (media, detail, ajax, ...)
52    }
53
54    /**
55     * Decide if any 2fa handling needs to be done for the current user
56     *
57     * @param Doku_Event $event
58     */
59    public function handleActionPreProcess(Doku_Event $event)
60    {
61        if (!$this->manager->getUser()) 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                $INPUT->bool('sticky')
71            )) {
72                $event->data = 'show';
73                return;
74            } else {
75                // show form
76                $event->preventDefault();
77                return;
78            }
79        }
80
81        // authed already, continue
82        if ($this->isAuthed()) {
83            return;
84        }
85
86        if (count($this->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 ($this->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        $event->preventDefault();
112        $event->stopPropagation();
113
114        global $INPUT;
115        $providerID = $INPUT->str('2fa_provider');
116        $providers = $this->manager->getUserProviders();
117        if (isset($providers[$providerID])) {
118            $provider = $providers[$providerID];
119        } else {
120            $provider = $this->manager->getUserDefaultProvider();
121        }
122        // remove current provider from list
123        unset($providers[$provider->getProviderID()]);
124
125        $form = new dokuwiki\Form\Form(['method' => 'POST']);
126        $form->setHiddenField('do', 'twofactor_login');
127        $form->setHiddenField('2fa_provider', $provider->getProviderID());
128        $form->addFieldsetOpen($provider->getLabel());
129        try {
130            $code = $provider->generateCode();
131            $info = $provider->transmitMessage($code);
132            $form->addHTML('<p>' . hsc($info) . '</p>');
133            $form->addTextInput('2fa_code', 'Your Code')->val('');
134            $form->addCheckbox('sticky', 'Remember this browser'); // reuse same name as login
135            $form->addButton('2fa', 'Submit')->attr('type', 'submit');
136        } catch (\Exception $e) {
137            msg(hsc($e->getMessage()), -1); // FIXME better handling
138        }
139        $form->addFieldsetClose();
140
141        if (count($providers)) {
142            $form->addFieldsetOpen('Alternative methods');
143            foreach ($providers as $prov) {
144                $link = $prov->getProviderID(); // FIXME build correct links
145
146                $form->addHTML($link);
147            }
148            $form->addFieldsetClose();
149        }
150
151        echo $form->toHTML();
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 = $this->manager->getUserProvider($providerID);
167            if ($this->cookieHash($provider) !== $hash) return false;
168            return true;
169        } catch (\Exception $e) {
170            return false;
171        }
172    }
173
174    /**
175     * Verify a given code
176     *
177     * @return bool
178     * @throws Exception
179     */
180    protected function verify($code, $providerID, $sticky)
181    {
182        global $conf;
183
184        if (!$code) return false;
185        if (!$providerID) return false;
186        $provider = $this->manager->getUserProvider($providerID);
187        $ok = $provider->checkCode($code);
188        if (!$ok) {
189            msg('code was wrong', -1);
190            return false;
191        }
192
193        // store cookie
194        $hash = $this->cookieHash($provider);
195        $data = base64_encode(serialize([$providerID, $hash, time()]));
196        $cookieDir = empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'];
197        $time = $sticky ? (time() + 60 * 60 * 24 * 365) : 0; //one year
198        setcookie(self::TWOFACTOR_COOKIE, $data, $time, $cookieDir, '', ($conf['securecookie'] && is_ssl()), true);
199
200        return true;
201    }
202
203    /**
204     * Create a hash that validates the cookie
205     *
206     * @param Provider $provider
207     * @return string
208     */
209    protected function cookieHash($provider)
210    {
211        return sha1(join("\n", [
212            $provider->getProviderID(),
213            $this->manager->getUser(),
214            $provider->getSecret(),
215            auth_browseruid(),
216            auth_cookiesalt(false, true),
217        ]));
218    }
219}
220