-
Notifications
You must be signed in to change notification settings - Fork 2
/
jfauthd.cc
506 lines (436 loc) · 12.3 KB
/
jfauthd.cc
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#include "jfauthd.h"
#include "jfauth.h"
#include "wvstreamsdaemon.h"
#include "wvtcp.h"
#include "wvunixsocket.h"
#include "wvstreamclone.h"
#include "wvfileutils.h"
#include "wvsslstream.h"
#include "wvx509mgr.h"
#include "wvstrutils.h"
#include "wvpipe.h"
#include "wvscatterhash.h"
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#define UNIX_TIMEOUT_MS 10000
#define TCP_TIMEOUT_MS 120000
class AuthBase;
static AuthBase *globalauth;
static WvX509Mgr *x509;
struct UserPass { WvString user, pass; time_t when, lastused; };
DeclareWvScatterDict(UserPass, WvString, user);
static UserPassDict authcache;
// config options
static WvString
forwardhost,
appname = "jfauthd";
static bool
enable_tcp = false,
enable_ssl = false,
enable_unix = false,
do_smbpasswd = false;
static int
cache_expire_secs = -1,
cache_accel_secs = 60,
cache_max_size = 100;
static int lru_cmp(const UserPass *a, const UserPass *b)
{
return a->lastused - b->lastused;
}
static void authcache_add(WvStringParm user, WvStringParm pass)
{
// FIXME: cache the password's hash instead? If so, use a specific
// hash designed for passwords, not just md5/sha1 (which are too fast).
// For more, see:
// http://www.usenix.org/events/usenix99/provos/provos_html/index.html
//
// Hashing isn't so important if the cache is only in RAM, but it
// becomes critical if we'll be persisting to disk.
time_t now = time(NULL);
UserPass *up = authcache[user];
if (up && up->pass == pass)
up->when = up->lastused = now;
else
{
up = new UserPass;
up->user = user;
up->pass = pass;
up->when = up->lastused = now;
authcache.add(up, true);
}
// If the cache is too full, expire entries until it isn't.
int cnt = authcache.count();
if (cnt > cache_max_size)
{
WvList<UserPass> deathq;
UserPassDict::Sorter i(authcache, lru_cmp);
for (i.rewind(); i.next() && cnt > cache_max_size; cnt--)
deathq.append(i.ptr(), false);
while (!deathq.isempty())
{
authcache.remove(deathq.first());
deathq.unlink_first();
}
}
}
// expire an entry if it has the given password, because we're now sure that
// that password is wrong. Perhaps the user has changed his password.
static void authcache_del(WvStringParm user, WvStringParm pass)
{
UserPass *oldup = authcache[user];
if (oldup && oldup->pass == pass)
authcache.remove(oldup);
}
static bool authcache_check(WvStringParm user, WvStringParm pass,
int expire_secs)
{
UserPass *up = authcache[user];
time_t now = time(NULL);
if (up && up->pass == pass
&& (expire_secs < 0 || now - up->when < expire_secs))
{
up->lastused = now;
return true;
}
else
return false;
}
class AuthBase
{
public:
virtual WvError check(WvStringParm rhost,
WvStringParm user, WvStringParm pass) = 0;
virtual ~AuthBase() {}
};
class PamAuth : public AuthBase
{
public:
virtual WvError check(WvStringParm rhost,
WvStringParm user, WvStringParm pass)
{
WvError e = jfauth_pam(appname, rhost, user, pass);
// If PAM has rejected it, we assume the password is *definitely*
// wrong. This is arguable; for example, if the LDAP server fails,
// PAM will reject it, but we might want to cache it anyway. But I
// guess that should be PAM's job to consider, not ours.
//
// Maybe we need to consider the PAM return code more carefully?
if (e.isok())
authcache_add(user, pass);
else
authcache_del(user, pass);
return e;
}
};
class ForwardAuth : public AuthBase
{
WvString hostport;
WvStream *s;
WvLog log;
bool _ok;
bool connection_ok() const
{ return _ok && s && s->isok(); }
void unconnect()
{
if (s)
{
WvIStreamList::globallist.unlink(s);
WVRELEASE(s);
s = NULL;
_ok = false;
}
}
void reconnect()
{
log(WvLog::Info, "Connecting.\n");
unconnect();
WvStream *_s;
if (!!hostport && strchr(hostport, ':'))
_s = new WvTCPConn(hostport);
else
_s = new WvTCPConn(hostport, 5479);
s = new WvSSLStream(_s);
s->runonce(0);
s->runonce(0);
s->alarm(5000);
s->setcallback(_callback, this);
WvIStreamList::globallist.append(s, false, (char *)"forwardauth");
}
void callback()
{
if (s->alarm_was_ticking)
{
log(WvLog::Debug, "Sending keepalive.\n");
s->write("\0", 1); // empty keepalive message; no response expected
s->alarm(TCP_TIMEOUT_MS/2);
}
char buf[1024];
size_t len = s->read(buf, sizeof(buf));
if (len)
{
log(WvLog::Warning, "Received unexpected %s bytes\n", len);
unconnect(); // for safety
}
#if 0
// this isn't such a good idea; it'll cause a flood of reconnects
// if the server ever has trouble reconnecting. Instead, if we get
// disconnected, *stay* disconnected until the next time someone
// *really* needs an auth request to go through.
if (!s->isok())
reconnect();
#endif
// if we lived through the above, the connection is valid
_ok = s->isok();
}
static void _callback(WvStream &, void *userdata)
{
ForwardAuth *auth = (ForwardAuth *)userdata;
assert(auth->s); // it should be auth->s *calling* us, so I hope so!
auth->callback();
}
public:
ForwardAuth(WvStringParm _hostport)
: hostport(_hostport), log("AuthForward", WvLog::Debug1)
{
s = NULL;
_ok = false;
reconnect();
}
~ForwardAuth()
{
unconnect();
}
// Okay, this gets a little complicated with caching. Notes:
// - our caller has already checked the cache for cache_accel_secs, so
// that has nothing to do with this logic.
// - if we're disconnected, use the cache up to cache_expire_secs.
// - if we're *not* disconnected, never read the cache, just write to it.
virtual WvError check(WvStringParm rhost,
WvStringParm user, WvStringParm pass)
{
if (!connection_ok())
{
if (!s->isok())
reconnect();
if (authcache_check(user, pass, cache_expire_secs))
return WvError(); // pass
// otherwise fall through and give them another chance
}
WvError e;
s->print("1\r\n%s\r\n%s\r\n", user, pass);
s->write("\0", 1);
WvString r1 = trim_string(s->getline(5000));
WvString r2 = trim_string(s->getline(500));
if (s->geterr())
e.set_both(s->geterr(), s->errstr());
else if (!s->isok())
e.set("Remote auth server disconnected");
else if (!r1 || !r2)
{
e.set("Remote server failed to respond");
s->seterr_both(e.get(), e.str());
}
else if (r1.num())
{
// explicit rejection by server: make sure the cache doesn't think
// this password is okay later.
authcache_del(user, pass);
e.set_both(r1.num(), r2);
}
else if (r1 != "0")
e.set("Remote auth server: syntax error in response");
// otherwise: succeeded
if (e.isok())
authcache_add(user, pass);
return e;
}
};
static void auth_succeeded(WvStringParm user, WvStringParm pass,
bool was_cached)
{
if (!was_cached && do_smbpasswd && !!user && !!pass)
{
const char *argv[] = { "smbpasswd", "-a", "-s", user, NULL };
WvPipe p("smbpasswd", argv, true, false, false);
p.print("%s\n%s\n", pass, pass);
p.nowrite();
p.finish(false);
int ret = p.exit_status();
if (ret)
{
WvLog("smbpasswd", WvLog::Warning)
.print("smbpasswd returned error code %s\n", ret);
}
}
}
class AuthStream : public WvStreamClone
{
WvDynBuf buf;
WvLog log;
bool multiple_requests;
public:
AuthStream(IWvStream *s, bool _multiple_requests)
: WvStreamClone(s), log(*src(), WvLog::Info)
{
multiple_requests = _multiple_requests;
if (!multiple_requests)
alarm(UNIX_TIMEOUT_MS);
else
alarm(TCP_TIMEOUT_MS);
}
virtual void execute()
{
if (alarm_was_ticking)
{
log("No recent requests: disconnecting.\n");
close();
}
else
{
size_t len = read(buf, 1024);
if (len && multiple_requests)
alarm(TCP_TIMEOUT_MS); // not idle, anyway
int ofs = buf.strchr(0);
if (ofs)
{
WvStringList l;
WvString instr = trim_string(buf.getstr(ofs).edit());
if (!instr)
return;
l.split(instr, "\r\n");
int ver = l.popstr().num();
if (ver != 1)
{
WvError e;
e.set("Invalid version (expected 1)");
print("%s\r\n%s\r\n", e.get(), e.str());
seterr_both(e.get(), e.str());
return;
}
WvString user = l.popstr();
WvString pass = l.popstr();
log(WvLog::Debug1, "auth request for user '%s'\n", user);
assert(globalauth);
WvError e;
bool cache_result
= authcache_check(user, pass, cache_accel_secs);
if (!cache_result)
e = globalauth->check(*src(), user, pass);
if (e.isok())
{
log(WvLog::Info,
"PASS: auth succeeded for user '%s'\n", user);
auth_succeeded(user, pass, cache_result);
}
else
log(WvLog::Notice,
"FAIL: auth user '%s': '%s'\n", user, e.str());
print("%s\r\n%s\r\n", e.get(), e.str());
if (!multiple_requests)
close();
}
else if (buf.used() > 1024)
{
log(WvLog::Warning, "too much data received: attacker?\n");
close();
}
}
}
};
static void tcp_incoming(WvStream &, void *userdata)
{
WvTCPListener *l = (WvTCPListener *)userdata;
WvIStreamList::globallist.append(new AuthStream(l->accept(), true),
true, (char *)"tcp_incoming");
}
static void ssl_incoming(WvStream &, void *userdata)
{
WvTCPListener *l = (WvTCPListener *)userdata;
WvSSLStream *ssl = new WvSSLStream(l->accept(), x509, 0, true);
WvIStreamList::globallist.append(new AuthStream(ssl, true),
true, (char *)"ssl_incoming");
}
static void unix_incoming(WvStream &, void *userdata)
{
WvUnixListener *l = (WvUnixListener *)userdata;
WvIStreamList::globallist.append(new AuthStream(l->accept(), false),
true, (char *)"unix_incoming");
}
static void startup(WvStreamsDaemon &daemon, void *)
{
if (!enable_tcp && !enable_ssl && !enable_unix)
{
daemon.log(WvLog::Critical, "Must specify one of -u, -t, -s\n");
return;
}
if (do_smbpasswd && getuid() != 0)
daemon.log(WvLog::Warning,
"smbpasswd updates enabled, but jfauthd not running as root\n");
if (globalauth)
delete globalauth;
if (forwardhost)
globalauth = new ForwardAuth(forwardhost);
else
globalauth = new PamAuth();
if (enable_tcp)
{
WvTCPListener *tcp = new WvTCPListener(5478);
tcp->setcallback(tcp_incoming, tcp);
daemon.add_die_stream(tcp, true, (char *)"tcplistener");
}
if (enable_ssl)
{
daemon.log(WvLog::Debug, "Generating SSL certificate.\n");
if (x509)
WVRELEASE(x509);
x509 = new WvX509Mgr("jfauthd", 2048);
WvTCPListener *ssl = new WvTCPListener(5479);
ssl->setcallback(ssl_incoming, ssl);
daemon.add_die_stream(ssl, true, (char *)"ssllistener");
}
if (enable_unix)
{
mkdirp("/var/run/jfauthd", 0755);
WvUnixListener *unixl = new WvUnixListener(JF_UNIX_SOCKFILE, 0666);
chmod(JF_UNIX_SOCKFILE, 0666);
unixl->setcallback(unix_incoming, unixl);
daemon.add_die_stream(unixl, true, (char *)"unixlistener");
}
}
int main(int argc, char **argv)
{
WvStreamsDaemon daemon("jfauthd", jfversion, startup);
daemon.args.add_option
('f', "forward", "Forward all requests to a remote jfauthd",
"HOST:PORT", forwardhost);
daemon.args.add_option
('n', "name", "Change the PAM appname (default is 'jfauthd')",
"APPNAME", appname);
daemon.args.add_set_bool_option
(0, "smbpasswd", "Auto-update smbpasswd on successful auth",
do_smbpasswd);
daemon.args.add_option
(0, "cache-time",
"Time to cache successful authentications for use when "
"forwarding server is broken (0=disable, -1=forever), "
"default is -1",
"SECONDS", cache_expire_secs);
daemon.args.add_option
(0, "accel-time",
"Time to cache successful authentications just to speed things up "
"(0=disable, -1=forever), default is 60",
"SECONDS", cache_accel_secs);
daemon.args.add_option
(0, "cache-size",
"Max number of users in the auth cache (default=100)",
"NUMUSERS", cache_max_size);
daemon.args.add_set_bool_option
('u', "unix", WvString("Listen on unix socket %s",
JF_UNIX_SOCKFILE), enable_unix);
daemon.args.add_set_bool_option
('t', "tcp", "[DANGER INSECURE] Listen on tcp port 5478", enable_tcp);
daemon.args.add_set_bool_option
('s', "ssl", "Listen on tcp-ssl port 5479 (encrypted)", enable_ssl);
return daemon.run(argc, argv);
}