-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAuth2FactorPPP.module
424 lines (353 loc) · 15 KB
/
Auth2FactorPPP.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
<?php
/**
* An implementation of Steve Gibson's Perfect Paper Passwords (PPP) system.
*
* PPP is a one-time-pad cryptographic system that allows easy provision of 2-factor
* authentication for software applications at a very low-cost. Read more about PPP
* at http://www.grc.com/ppp/design.htm
*
* TODO Require new users to have valid email address if DELIVERY_VIA_EMAIL and (USE_ALWAYS or USE_USER and ppp_login_enable is set for that user)
*
**/
class Auth2FactorPPP extends WireData implements Module, ConfigurableModule
{
const USE_NEVER = 0;
const USE_USER = 1;
const USE_ALWAYS = 2;
const DELIVERY_VIA_EMAIL = 0;
const DELIVERY_VIA_PASSCARD = 1;
public static function getModuleInfo()
{
return [
'title' => __('PPP 2-Factor Authentication'),
'summary' => __("Adds 2-factor authentication to ProcessWire via Steve Gibson's PPP one-time-pad system."),
'version' => '2.0.1',
'author' => 'Netcarver',
'singular' => true,
'permanent' => false,
'autoload' => "template=admin",
'requires' => 'ProcessWire>=3.0.0, PHP>=5.4.0, CryptoPPP',
'installs' => 'CryptoPPP',
'href' => 'http://www.grc.com/ppp/design.htm',
'icon' => 'id-card-o',
];
}
public static function getModuleConfigInputfields(array $data)
{
$fields = new InputfieldWrapper();
$m = wire('modules');
$f = $m->get('InputfieldRadios');
$f->attr('name', 'ppp_global_control');
$f->label = __('Use PPP tokens during login?');
$f->addOption(self::USE_NEVER, __('Never'));
$f->addOption(self::USE_USER, __('Only if a user turns them on for their account'));
$f->addOption(self::USE_ALWAYS, __('Always'));
$f->value = (isset($data['ppp_global_control']) ? (int) $data['ppp_global_control'] : self::USE_NEVER);
$fields->add($f);
$f = $m->get('InputfieldRadios');
$f->attr('name', 'ppp_delivery_medium');
$f->label = __('How should tokens be delivered?');
$f->addOption(self::DELIVERY_VIA_EMAIL, __('By email (if present in user account)'));
$f->addOption(self::DELIVERY_VIA_PASSCARD, __('By passcard'));
$f->attr('value', (isset($data['ppp_delivery_medium']) ? (int) $data['ppp_delivery_medium'] : self::DELIVERY_VIA_EMAIL));
$fields->add($f);
$f = $m->get('InputfieldText');
$f->name = 'ppp_charset';
$f->label = __("The characters that can be in a PPP code");
$f->set( "collapsed", Inputfield::collapsedHidden);
if (isset($data['ppp_charset'])) {
$f->value = $data['ppp_charset'];
} else {
$f->value = CryptoPPP::DEFAULT_CHARSET;
}
$fields->add($f);
$f = $m->get('InputfieldText');
$f->name = 'ppp_label';
$f->label = __("Label to output on passcards");
$f->set( "collapsed", Inputfield::collapsedYes);
if (isset($data['ppp_label'])) {
$f->value = $data['ppp_label'];
} else {
$f->value = fuel()->config->httpHost;
}
$fields->add($f);
return $fields;
}
public function __construct()
{
/**
* List of per-user fields to be created and installed by this module.
**/
$this->new_fields = [
'ppp_login_enable' => [
'type' => 'FieldtypeCheckbox',
'label' => __("Enable 2-factor PPP login?"),
'set' => ['columnWidth' => 30, 'tags' => '-PPP'],
'add_to_templates' => ['user'],
],
'ppp_login_vector' => [
'type' => 'FieldtypeText',
'label' => __("PPP initialisation vector"),
'set' => ['columnWidth' => 50, 'tags' => '-PPP'],
'add_to_templates' => ['user'],
],
'ppp_login_nextseq' => [
'type' => 'FieldtypeInteger',
'label' => __("PPP Sequence #"),
'set' => ['columnWidth' => 20, 'tags' => '-PPP'],
'add_to_templates' => ['user'],
],
'ppp_login_lastsent' => [
'type' => 'FieldtypeText',
'label' => __("Time the last PPP token reminder was sent"),
'set' => ['collapsed' => Inputfield::collapsedHidden, 'tag' => '-PPP'],
'add_to_templates' => ['user'],
],
];
}
public function init()
{
if (self::USE_NEVER != $this->ppp_global_control) {
$this->session->addHookAfter('login', $this, 'loginHook', ['priority' => 10]); // Check login token: this hook needs to be executed early
$this->addHookAfter('ProcessLogin::buildLoginForm', $this, 'buildLoginFormHook'); // Add token field to login form
}
$this->addHookBefore('Inputfield::render', $this, 'makeFieldsReadonlyHook'); // Init vector should be read-only - allows backup but no fiddling
wire('pages')->addHookBefore('save', $this, 'newUserFieldsHook'); // Add Init vector and count to new user pages
$this->addHookBefore('ProcessProfile::execute', $this, 'extendProfileFieldsHook'); // Show PPP fields in user profiles
$this->addHookAfter('Inputfield::render', $this, 'renderPasscardLink'); // Adds link to GRC's passcard generation page to the user's page
}
/**
* Make sure some of the additional per-user fields appear in the user profile
* so users get the chance of backing up their PPP init vector if they need to or
* switching PPP on & off if the global setting allows it.
**/
protected function extendProfileFieldsHook($event)
{
$fields = $event->object->get('profileFields');
$fields[] = "ppp_login_vector";
$fields[] = "ppp_login_nextseq";
if (self::USE_USER == $this->ppp_global_control || NULL == $this->ppp_global_control) {
$fields[] = "ppp_login_enable";
}
$event->object->set('profileFields', $fields);
}
/**
* Sets up default values in the per-user PPP fields of new users.
**/
protected function newUserFieldsHook($event)
{
$arguments = $event->arguments;
$page = $arguments[0];
if (!$page instanceof User) {
return;
}
if ($page->get('ppp_login_vector') || 'guest' === $page->get('name')) {
return;
}
$this->addNewFieldsToUser($page);
}
/**
* Make some of the per-user fields read-only in the profile / user page.
**/
protected function makeFieldsReadonlyHook($event)
{
if (in_array($event->object->name, ['ppp_login_vector', 'ppp_login_nextseq'])) {
$event->object->attr('readonly', 'readonly'); // Don't allow GUI to change the user's initialization vector but do allow them to copy it out for backup if needed.
}
}
/**
* Add link to grc.com's passcard layout and print page.
**/
protected function renderPasscardLink($event)
{
if ('ppp_login_vector' === $event->object->name && $event->object->value) {
$label = urlencode($this->ppp_label);
$nexts = $event->object->parent->ppp_login_nextseq->value;
$pos = CryptoPPP::numberToIndex($nexts);
$card = $pos['page'];
$link = "<a class='ui-button ui-corner-all ui-state-control' href='https://www.grc.com/ppp?1={$event->object->value}&2=$card&5=$label' target='_ppp' style='margin-top:10px'><span class='ui-button-text'>" . __("Show/Print Token Cards") . " <i class='fa fa-icon fa-external-link'></i></span></a>";
$event->return .= $link;
}
}
/**
* Adds a "Login Token" field to the PW login form.
**/
public function buildLoginFormHook($event)
{
$f = $this->modules->get('InputfieldText');
$f->set('label', __('Login Token'));
$f->attr('id+name', 'login_token');
$f->attr('class', $event->object->className() . 'Token');
$f->attr('placeholder', __('Enter next token'));
$f->set( "collapsed", Inputfield::collapsedNever);
if (!empty($_POST['login_submit'])) {
$username = $this->sanitizer->username($_POST['login_name']);
$user = $this->users->get("name=".$username);
if ($user->id) {
$next = $user->get('ppp_login_nextseq');
if (isset($next)) {
$loc = CryptoPPP::numberToIndex($next);
$f->attr('placeholder', sprintf(__("Enter token from card %s, cell %s %s"), $loc['page'], $loc['row'], $loc['col']));
}
}
}
$login_form = $event->return;
$login_form->insertBefore($f, $login_form->get('login_submit'));
}
/**
* Extends the processing of a login to add a token check where possible.
**/
protected function loginHook($event)
{
if (!$event->return) {
return; // Username/pass authenitcation failed so no need to check token
}
$name = strtolower($event->arguments[0]);
$user = $this->users->get($name);
if ('guest' === $name || !$user->id || self::USE_NEVER == $this->ppp_global_control) {
return; // No need to check PPP token
}
$next = $user->get('ppp_login_nextseq');
$vect = $user->get('ppp_login_vector');
$ppp = self::USE_ALWAYS == $this->ppp_global_control || $user->get('ppp_login_enable');
if ($ppp && isset($next) && $vect) {
$actual = (string) $_POST['login_token'];
$expected = (string) CryptoPPP::getCode($vect, $next, null, 4);
$ok = 0 === strcmp( $expected, $actual);
if ($ok) {
$user->set('ppp_login_nextseq', $next + 1) // Successful login so move to next token
->set('ppp_login_lastsent', '')
->save();
} else {
$event->return = null; // Token match failed -- prevent login.
$this->session->logout(); // Seem to need to do this to prevent a simple re-press of submit from logging the user in.
$to = $user->email;
// TODO validate user email address properly...
if ((self::DELIVERY_VIA_EMAIL == $this->ppp_delivery_medium) && $to) {
$now = time();
$lastsent = $user->get('ppp_login_lastsent');
$diff = (int)$now - (int)$lastsent;
$timeout = $diff > 60;
if (!$lastsent || $timeout) {
$this->sendTokenByEmail($expected, $next, $now, $user);
}
}
sleep(2);
}
}
}
/**
* Sends a copy of the needed token to the given user's email address.
**/
protected function sendTokenByEmail($token, $seq, $time, $user)
{
$o = CryptoPPP::numberToIndex( $seq);
$subject = $this->ppp_label . __(" token for : ") . $o['page'] . " / " . $o['cell'];
$body[] = sprintf(__("Seq %s."), htmlspecialchars($seq));
$body[] = sprintf(__("Your token is : %s"), $token);
$mail = wireMail();
$mail
->to($user->email)
->from(sprintf(__('Token Generator <%s>'), "blackhole@{$this->config->httpHost}"))
->subject($subject)
->body(join("\n", $body))
;
$sent = $mail->send();
if ($sent) {
$user->set('ppp_login_lastsent', $time);
$user->save();
}
return $sent;
}
/**
* Read the field data. Create the field if it doesn't exist and then
* add it to the fieldgroups of any listed templates.
**/
protected function installField($name, &$fd)
{
$f = $this->fields->get($name);
if (!$f) {
$f = new Field();
$f->type = $this->modules->get($fd['type']);
$f->name = $name;
if (@$fd['label']) $f->label = $fd['label'];
if (count( @$fd['set'])) {
foreach( $fd['set'] as $k => $v) {
$f->set($k, $v);
}
}
$f->save();
if (count(@$fd['add_to_templates'])) {
foreach ($fd['add_to_templates'] as $temp) {
$t = $this->templates->get($temp);
if (!$t->id) {
continue; // no such template.
}
if ($t->fieldgroup->get($name)) {
continue; // field already in template
}
$t->fieldgroup->add($f);
$t->fieldgroup->save();
}
}
}
}
/**
* Adds needed fields and sets up the per-user values needed for each existing user.
**/
public function ___install()
{
foreach ($this->new_fields as $name => $field_data) {
$this->installField( $name, $field_data);
}
foreach ($this->users as $user) {
$this->addNewFieldsToUser($user);
$user->save();
}
}
/**
* Setup the default values for a user's ppp fields.
**/
public function addNewFieldsToUser(&$user)
{
if ($user->name !== 'guest') {
$user->ppp_login_vector = CryptoPPP::genKeys(1); // Create init vector for PPP system
$user->ppp_login_nextseq = 0; // Start at first token
}
$user->ppp_login_enable = false; // Tokens off for user
}
/**
* Removes our setup from the PW system.
**/
public function ___uninstall()
{
$fieldgroups_to_save = [];
// Remove installed fields from fieldgroups...
foreach ($this->new_fields as $name => $fd) {
if (count( @$fd['add_to_templates'])) {
foreach ($fd['add_to_templates'] as $template) {
$t = $this->templates->get($template);
if (!$t->id) {
continue; // no such template
}
if (!$t->fieldgroup->get($name)) {
continue; // no such field in group
}
$t->fieldgroup->remove($name);
$fieldgroups_to_save[$template] = $t->fieldgroup;
}
}
}
// Save changes to the fieldgroups...
if (count($fieldgroups_to_save)) {
foreach ($fieldgroups_to_save as $name => $fg) $fg->save();
}
// Now the fields can be deleted...
foreach ($this->new_fields as $name => $fd) {
$f = $this->fields->get($name);
if ($f->id) {
$this->fields->delete($f);
}
}
}
}