Debian Codegraph @

hfaxd/User.c++

raw
1 /* $Id$ */
2 /*
3 * Copyright (c) 1995-1996 Sam Leffler
4 * Copyright (c) 1995-1996 Silicon Graphics, Inc.
5 * HylaFAX is a trademark of Silicon Graphics
6 *
7 * Permission to use, copy, modify, distribute, and sell this software and
8 * its documentation for any purpose is hereby granted without fee, provided
9 * that (i) the above copyright notices and this permission notice appear in
10 * all copies of the software and related documentation, and (ii) the names of
11 * Sam Leffler and Silicon Graphics may not be used in any advertising or
12 * publicity relating to the software without the specific, prior written
13 * permission of Sam Leffler and Silicon Graphics.
14 *
15 * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
16 * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
17 * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
18 *
19 * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
20 * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
21 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
22 * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
23 * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
24 * OF THIS SOFTWARE.
25 */
26 #include "HylaFAXServer.h"
27 #include "Sys.h"
28 #include "RE.h"
29 #include "config.h"
30
31 #include <ctype.h>
32 #include <pwd.h>
33 #if HAS_CRYPT_H
34 #include <crypt.h>
35 #endif
36 #include <math.h>
37
38 #ifndef CHAR_BIT
39 #ifdef NBBY
40 #define CHAR_BIT NBBY
41 #else
42 #define CHAR_BIT 8
43 #endif
44 #endif /* CHAR_BIT */
45
46
47 /*
48 * User Access Control Support.
49 */
50 gid_t HylaFAXServer::faxuid = 0; // reserved fax uid
51
52 bool
53 HylaFAXServer::checkUser(const char* name)
54 {
55 bool check = false;
56 FILE* db = fopen(fixPathname(userAccessFile), "r");
57 if (db != NULL) {
58 check = checkuserHosts(db, name);
59 fclose(db);
60 } else
61 logError("Unable to open the user access file %s: %s",
62 (const char*) userAccessFile, strerror(errno));
63
64 if (! check)
65 check = checkuserPAM(name);
66
67 /*
68 * This causes the user to be prompted for a password
69 * and then denied access. We do this to guard against
70 * folks that probe the server looking for valid accounts.
71 */
72 return (true);
73 }
74
75 bool
76 HylaFAXServer::checkPasswd (const char* pass)
77 {
78 if (pass[0] == '\0')
79 return false;
80
81 if (checkpasswdHosts(pass))
82 return true;
83
84 if (checkpasswdPAM(pass))
85 return true;
86
87 return false;
88 }
89
90
91 static bool
92 nextRecord(FILE* db, char line[], u_int size)
93 {
94 while (fgets(line, size-1, db)) {
95 char* cp = strchr(line, '#');
96 if (cp) { // trim trailing white space */
97 for (cp = strchr(line, '\0'); cp > line; cp--)
98 if (!isspace(cp[-1]))
99 break;
100 *cp = '\0';
101 }
102 if ((cp = strchr(line, '\n')))
103 *cp = '\0';
104 if (line[0] != '\0')
105 return (true);
106 }
107 return (false);
108 }
109
110 /*
111 * Check the user name and host name/address against
112 * the list of users and hosts that are permitted to
113 * user the server and setup password handling.
114 */
115 bool
116 HylaFAXServer::checkuserHosts(FILE* db, const char* name)
117 {
118 struct stat sb;
119 if (Sys::fstat(fileno(db), sb) < 0)
120 return (false);
121 if (sb.st_mode&077) { // file must not be publicly readable
122 logError("Access control file not mode 600; access denied.");
123 return (false);
124 }
125 uid = FAXUID_ANON; // anonymous user
126 adminwd = "*"; // disallow privileged access
127
128 fxStr dotform = fxStr::format("%s@%s", name, (const char*) remoteaddr);
129 fxStr hostform = fxStr::format("%s@%s", name, (const char*) remotehost);
130
131 rewind(db);
132 char line[1024];
133 while (nextRecord(db, line, sizeof (line))) {
134 /*
135 * Records are of the form:
136 *
137 * [!]regex[:uid[:passwd[:adminwd]]]
138 *
139 * where regex is a regular expression that must
140 * match a string of the form "user@host" or "user@addr"
141 * (where addr is the dot-notation form of the client
142 * host). If subsequent fields are present then the
143 * first is treated as the numeric ID for the user,
144 * followed by the encrypted password that the client
145 * must supply. The next field is the password that
146 * must be presented to gain administrative privileges.
147 *
148 * If the regex is a single word (no @ sign), we take it
149 * as a host only short form for (^.*@<input>$)
150 *
151 * If the first character of the <regex> is a ``!''
152 * then the line specifies user(s) to disallow; a match
153 * causes the user to be rejected w/o a password prompt.
154 * This facility is mainly for backwards compatibility.
155 */
156 char* cp;
157 bool userandhost = false;
158 for (cp = line; *cp && *cp != ':'; cp++)
159 if (*cp == '\\' && *(cp+1)) // skip check of next char unless it's end of string
160 cp++;
161 else if (*cp == '@')
162 userandhost = true;
163
164 const char* base = &line[line[0] == '!'];
165 fxStr pattern(base, cp-base);
166 if (! userandhost) {
167 pattern.insert("^.*@");
168 pattern.append("$");
169 }
170 RE pat(pattern);
171 if (line[0] == '!') { // disallow access on match
172 if (pat.Find(dotform) || pat.Find(hostform))
173 return (false);
174 } else { // allow access on match
175 if (pat.Find(dotform) || pat.Find(hostform)) {
176 passwd = ""; // no password required
177 if (*cp == ':') { // :uid[:passwd[:adminwd]]
178 if (isdigit(*++cp)) {
179 uid = atoi(cp);
180 for (; *cp && *cp != ':'; cp++)
181 ;
182 }
183 if (*cp == ':') { // :passwd[:adminwd]
184 for (base = ++cp; *cp && *cp != ':'; cp++)
185 ;
186 if (*cp == ':') {
187 passwd = fxStr(base, cp-base);
188 adminwd = cp+1;
189 } else
190 passwd = base;
191 } else
192 passwd = ""; // no password required
193 }
194 return (true);
195 }
196 }
197 }
198 passwd = "*";
199 return (false);
200 }
201
202 bool
203 HylaFAXServer::checkpasswdHosts (const char* pass)
204 {
205 if (strcmp(crypt(pass,passwd),passwd) == 0)
206 return true;
207
208 return false;
209 }
210
211 fxDECLARE_PtrKeyDictionary(IDCache, u_int, fxStr)
212 fxIMPLEMENT_PtrKeyObjValueDictionary(IDCache, u_int, fxStr)
213
214 /*
215 * Read the host access file and fill the ID cache
216 * with entries that map fax UID to name. We pick
217 * names by stripping any host part from matching
218 * regex's and by mapping ``.*'' user matches to a
219 * generic ``anyone'' name.
220 *
221 * XXX Maybe should convert RE entries to numeric
222 * equivalent of ID to avoid funky names???
223 */
224 void
225 HylaFAXServer::fillIDCache(void)
226 {
227 idcache = new IDCache;
228 FILE* db = fopen(fixPathname(userAccessFile), "r");
229 if (db != NULL) {
230 char line[1024];
231 while (nextRecord(db, line, sizeof (line))) {
232 if (line[0] == '!') // ignore ! entries
233 continue;
234 char* cp;
235 for (cp = line; *cp && *cp != ':'; cp++)
236 ;
237 fxStr name(line, cp-line);
238 name.resize(name.next(0, '@')); // strip @host part
239 if (name == ".*") // map .* -> ``anyone''
240 name = "anyone";
241 if (*cp == ':')
242 cp++;
243 u_int id; // fax UID
244 if (isdigit(*cp))
245 id = atoi(cp);
246 else
247 id = FAXUID_ANON;
248 (*idcache)[id] = name;
249 }
250 fclose(db);
251 }
252 }
253
254 /*
255 * Map fax UID to user name.
256 */
257 const char*
258 HylaFAXServer::userName(u_int id)
259 {
260 if (id == uid) // user currently logged in
261 return (const char*) the_user;
262 if (id == FAXUID_ANON) // anonymous user
263 return "fax";
264 if (idcache == NULL) // load cache from file
265 fillIDCache();
266 const fxStr* hit = idcache->find(id); // check cache
267 if (!hit) { // create entry w/ numeric value
268 (*idcache)[id] = fxStr((int) id, "%u");
269 hit = idcache->find(id); // new entry
270 }
271 return (*hit);
272 }
273
274 /*
275 * Map user name to fax UID.
276 */
277 bool
278 HylaFAXServer::userID(const char* name, u_int& id)
279 {
280 if (name == the_user)
281 id = uid;
282 else if (strcmp(name, "fax") == 0)
283 id = FAXUID_ANON;
284 else {
285 if (idcache == NULL)
286 fillIDCache();
287 for (IDCacheIter iter(*idcache); iter.notDone(); iter++)
288 if (iter.value() == name) {
289 id = iter.key();
290 return (true);
291 }
292 return (false);
293 }
294 return (true);
295 }
296
297 static bool
298 isAllLower(const char* cp)
299 {
300 while (*cp) {
301 if (!islower(*cp))
302 return (false);
303 cp++;
304 }
305 return (true);
306 }
307
308 static void
309 to64(char* cp, long v, int len)
310 {
311 while (--len >= 0) {
312 *cp++ = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[v&0x3f];
313 v >>= 6;
314 }
315 }
316
317 bool
318 HylaFAXServer::cvtPasswd(const char* type, const char* pass, fxStr& result)
319 {
320 if (*pass == '\0') { // null password *IS* permitted
321 result = "";
322 return (true);
323 }
324 if (strlen(pass) <= 5) {
325 reply(500, "%s password is too short; use 5-8 characters.", type);
326 return (false);
327 }
328 if (isAllLower(pass)) {
329 reply(500, "%s password is all lower-case; use something more.", type);
330 return (false);
331 }
332 srandom((int) Sys::now());
333 char salt[9];
334 /*
335 * Contemporary systems use an extended salt that
336 * is distinguished by a leading character (``_'').
337 * Older systems use a 2-character salt that results
338 * in encrypted strings that are easier to crack.
339 */
340 #ifdef _PASSWORD_EFMT1
341 salt[0] = _PASSWORD_EFMT1;
342 to64(&salt[1], (long)(29 * 25), 4);
343 to64(&salt[5], random(), 4);
344 #else
345 to64(&salt[0], random(), 2);
346 #endif
347 result = crypt(pass, salt);
348 return (true);
349 }
350
351 #define NBPL (sizeof (u_long) * CHAR_BIT) // bits/u_long
352 #define SetBit(b) (allocated[(b)/NBPL] |= ((u_long) 1)<<((b)%NBPL))
353 #define ClrBit(b) (allocated[(b)/NBPL] &= ~(((u_long) 1)<<((b)%NBPL)))
354 #ifndef howmany
355 #define howmany(x, y) (((x)+((y)-1))/(y))
356 #endif
357 #define N(a) (sizeof (a) / sizeof (a[0]))
358
359 bool
360 HylaFAXServer::findUser(FILE* db, const char* user, u_int& newuid)
361 {
362 rewind(db);
363 char line[1024];
364 u_long allocated[howmany(FAXUID_MAX+1,NBPL)];
365 memset(allocated, 0, sizeof (allocated));
366 if (faxuid < FAXUID_MAX)
367 SetBit(faxuid); // reserved uid
368 else
369 logError("Internal error, \"fax\" UID (%u) too large.", faxuid);
370 SetBit(0); // 0 uid is reserved
371 SetBit(FAXUID_ANON); // anonymous uid is reserved
372 while (nextRecord(db, line, sizeof (line))) {
373 if (line[0] == '!')
374 continue;
375 char* cp;
376 for (cp = line; *cp && *cp != ':'; cp++)
377 ;
378 if (strncmp(user, line, cp-line) == 0)
379 return (true);
380 if (*cp == ':' && isdigit(cp[1])) { // mark uid as in-use
381 u_int uid = (u_int) atoi(cp+1);
382 if (uid < FAXUID_MAX)
383 SetBit(uid);
384 else
385 logError("Error in %s: UID (%u) too large.", (const char*)userAccessFile, uid);
386 }
387 }
388 // find unallocated uid
389 for (u_int l = 0; l < N(allocated); l++)
390 if (allocated[l] != (u_long) -1) {
391 u_int b = 0;
392 for (u_long mask = 1; allocated[l] & mask; mask <<= 1)
393 b++;
394 newuid = (u_int) (l*NBPL + b);
395 return (false);
396 }
397 newuid = (u_int) -1; // no more space
398 return (false);
399 }
400
401 bool
402 HylaFAXServer::addUser(FILE* db, const char* user, u_int uid, const char* upass, const char* apass)
403 {
404 const char* templ = "/" FAX_TMPDIR "/uaddXXXXXX";
405 char* buff = strcpy(new char[strlen(templ) + 1], templ);
406 int fd = Sys::mkstemp(buff);
407 fxStr tfile = buff;
408 delete [] buff;
409 if (fd < 0) {
410 reply(550, "Error creating temp file %s: %s.",
411 (const char*) tfile, strerror(errno));
412 return (false);
413 }
414 rewind(db);
415 char buf[8*1024];
416 int cc;
417 while ((cc = Sys::read(fileno(db), buf, sizeof (buf))) > 0)
418 if (Sys::write(fd, buf, cc) != cc) {
419 perror_reply(550, "Write error", errno);
420 Sys::close(fd);
421 (void) Sys::unlink(tfile);
422 return (false);
423 }
424 fxStr line;
425 if (*apass != '\0')
426 line = fxStr::format("^%s@:%u:%s:%s\n", user, uid, upass, apass);
427 else if (*upass != '\0')
428 line = fxStr::format("^%s@:%u:%s\n", user, uid, upass);
429 else
430 line = fxStr::format("^%s@:%u\n", user, uid);
431 if (Sys::write(fd, line, line.length()) != (ssize_t)line.length()) {
432 perror_reply(550, "Write error", errno);
433 Sys::close(fd);
434 (void) Sys::unlink(tfile);
435 return (false);
436 }
437 Sys::close(fd);
438 if (Sys::rename(tfile, fixPathname(userAccessFile)) < 0) {
439 perror_reply(550, "Rename of temp file failed", errno);
440 (void) Sys::unlink(tfile);
441 return (false);
442 }
443 return (true);
444 }
445
446 /*
447 * Add a new user to the access control file.
448 */
449 void
450 HylaFAXServer::addUserCmd(const char* user, const char* up, const char* ap)
451 {
452 logcmd(T_ADDUSER, "%s XXXX YYYY", user);
453 fxStr upass, apass;
454 if (!cvtPasswd("User", up, upass) || !cvtPasswd("Admin", ap, apass))
455 return;
456 FILE* db = fopen(fixPathname(userAccessFile), "r");
457 if (db != NULL) {
458 u_int newuid;
459 if (findUser(db, user, newuid))
460 reply(500, "User %s is already present.", user);
461 else if (newuid == (u_int) -1)
462 reply(500, "Unable to add user %s; out of user IDs.", user);
463 else if (addUser(db, user, newuid, upass, apass))
464 reply(200, "User %s added with uid %u.", user, newuid);
465 fclose(db);
466 } else
467 reply(500, "Cannot open user access file %s: %s.",
468 (const char*) userAccessFile, strerror(errno));
469 }
470
471 bool
472 HylaFAXServer::deleteUser(FILE* db, const char* user)
473 {
474 const char* templ = "/" FAX_TMPDIR "/udelXXXXXX";
475 char* buff = strcpy(new char[strlen(templ) + 1], templ);
476 int fd = Sys::mkstemp(buff);
477 fxStr tfile = buff;
478 delete [] buff;
479 FILE* ftmp;
480 if (fd < 0 || (ftmp = fdopen(fd, "w")) == NULL) {
481 reply(550, "Error creating temp file %s: %s.",
482 (const char*)tfile, strerror(errno));
483 return (false);
484 }
485 /*
486 * Scan the existing file for the specified user
487 * and copy other entries to the temporary file.
488 * Once the entry for the user is found, stop
489 * scanning line-by-line and just block-copy the
490 * remaining part of the file.
491 */
492 bool found = false;
493 rewind(db);
494 char line[8*1024];
495 while (fgets(line, sizeof (line)-1, db)) {
496 if (line[0] != '!') {
497 const char* cp;
498 for (cp = line; *cp && *cp != '\n' && *cp != ':'; cp++)
499 ;
500 if (strncmp(user, line, cp-line) == 0) {
501 found = true;
502 break;
503 }
504 }
505 fputs(line, ftmp);
506 }
507 int cc;
508 while ((cc = fread(line, 1, sizeof (line), db)) > 0)
509 fwrite(line, cc, 1, ftmp);
510 bool ioError = (fclose(ftmp) != 0);
511 if (found) {
512 if (ioError)
513 perror_reply(550, "I/O error", errno);
514 else if (Sys::rename(tfile, fixPathname(userAccessFile)) < 0)
515 perror_reply(550, "Rename of temp file failed", errno);
516 else {
517 return (true);
518 }
519 } else
520 reply(500, "User %s not found in access file.", user);
521 (void) Sys::unlink(tfile);
522 return (false);
523 }
524
525 /*
526 * Remove a user from the access control file.
527 */
528 void
529 HylaFAXServer::delUserCmd(const char* user)
530 {
531 logcmd(T_DELUSER, "%s", user);
532 FILE* db = fopen(fixPathname(userAccessFile), "r");
533 if (db != NULL) {
534 if (deleteUser(db, user))
535 reply(200, "User %s deleted.", user);
536 fclose(db);
537 } else
538 reply(500, "Cannot open user access file %s: %s.",
539 (const char*) userAccessFile, strerror(errno));
540 }