pwd_grp.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Copyright (C) 2014 Tito Ragusa <farmatito@tiscali.it>
  4. *
  5. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  6. */
  7. /* This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY!!
  9. *
  10. * Rewrite of some parts. Main differences are:
  11. *
  12. * 1) the buffer for getpwuid, getgrgid, getpwnam, getgrnam is dynamically
  13. * allocated.
  14. * If ENABLE_FEATURE_CLEAN_UP is set the buffers are freed at program
  15. * exit using the atexit function to make valgrind happy.
  16. * 2) the passwd/group files:
  17. * a) must contain the expected number of fields (as per count of field
  18. * delimiters ":") or we will complain with a error message.
  19. * b) leading and trailing whitespace in fields is stripped.
  20. * c) some fields are not allowed to be empty (e.g. username, uid/gid),
  21. * and in this case NULL is returned and errno is set to EINVAL.
  22. * This behaviour could be easily changed by modifying PW_DEF, GR_DEF,
  23. * SP_DEF strings (uppercase makes a field mandatory).
  24. * d) the string representing uid/gid must be convertible by strtoXX
  25. * functions, or errno is set to EINVAL.
  26. * e) leading and trailing whitespace in group member names is stripped.
  27. * 3) the internal function for getgrouplist uses dynamically allocated buffer.
  28. * 4) at the moment only the functions really used by busybox code are
  29. * implemented, if you need a particular missing function it should be
  30. * easy to write it by using the internal common code.
  31. */
  32. #include "libbb.h"
  33. struct const_passdb {
  34. const char *filename;
  35. char def[7 + 2*ENABLE_USE_BB_SHADOW];
  36. uint8_t off[7 + 2*ENABLE_USE_BB_SHADOW];
  37. uint8_t numfields;
  38. uint8_t size_of;
  39. };
  40. struct passdb {
  41. const char *filename;
  42. char def[7 + 2*ENABLE_USE_BB_SHADOW];
  43. uint8_t off[7 + 2*ENABLE_USE_BB_SHADOW];
  44. uint8_t numfields;
  45. uint8_t size_of;
  46. FILE *fp;
  47. char *malloced;
  48. };
  49. /* Note: for shadow db, def[] will not contain terminating NUL,
  50. * but convert_to_struct() logic detects def[] end by "less than SP?",
  51. * not by "is it NUL?" condition; and off[0] happens to be zero
  52. * for every db anyway, so there _is_ in fact a terminating NUL there.
  53. */
  54. /* S = string not empty, s = string maybe empty,
  55. * I = uid,gid, l = long maybe empty, m = members,
  56. * r = reserved
  57. */
  58. #define PW_DEF "SsIIsss"
  59. #define GR_DEF "SsIm"
  60. #define SP_DEF "Ssllllllr"
  61. static const struct const_passdb const_pw_db = {
  62. _PATH_PASSWD, PW_DEF,
  63. {
  64. offsetof(struct passwd, pw_name), /* 0 S */
  65. offsetof(struct passwd, pw_passwd), /* 1 s */
  66. offsetof(struct passwd, pw_uid), /* 2 I */
  67. offsetof(struct passwd, pw_gid), /* 3 I */
  68. offsetof(struct passwd, pw_gecos), /* 4 s */
  69. offsetof(struct passwd, pw_dir), /* 5 s */
  70. offsetof(struct passwd, pw_shell) /* 6 s */
  71. },
  72. sizeof(PW_DEF)-1, sizeof(struct passwd)
  73. };
  74. static const struct const_passdb const_gr_db = {
  75. _PATH_GROUP, GR_DEF,
  76. {
  77. offsetof(struct group, gr_name), /* 0 S */
  78. offsetof(struct group, gr_passwd), /* 1 s */
  79. offsetof(struct group, gr_gid), /* 2 I */
  80. offsetof(struct group, gr_mem) /* 3 m (char **) */
  81. },
  82. sizeof(GR_DEF)-1, sizeof(struct group)
  83. };
  84. #if ENABLE_USE_BB_SHADOW
  85. static const struct const_passdb const_sp_db = {
  86. _PATH_SHADOW, SP_DEF,
  87. {
  88. offsetof(struct spwd, sp_namp), /* 0 S Login name */
  89. offsetof(struct spwd, sp_pwdp), /* 1 s Encrypted password */
  90. offsetof(struct spwd, sp_lstchg), /* 2 l */
  91. offsetof(struct spwd, sp_min), /* 3 l */
  92. offsetof(struct spwd, sp_max), /* 4 l */
  93. offsetof(struct spwd, sp_warn), /* 5 l */
  94. offsetof(struct spwd, sp_inact), /* 6 l */
  95. offsetof(struct spwd, sp_expire), /* 7 l */
  96. offsetof(struct spwd, sp_flag) /* 8 r Reserved */
  97. },
  98. sizeof(SP_DEF)-1, sizeof(struct spwd)
  99. };
  100. #endif
  101. /* We avoid having big global data. */
  102. struct statics {
  103. /* We use same buffer (db[0].malloced) for getpwuid and getpwnam.
  104. * Manpage says:
  105. * "The return value may point to a static area, and may be overwritten
  106. * by subsequent calls to getpwent(), getpwnam(), or getpwuid()."
  107. */
  108. struct passdb db[2 + ENABLE_USE_BB_SHADOW];
  109. char *tokenize_end;
  110. unsigned string_size;
  111. };
  112. static struct statics *ptr_to_statics;
  113. #define S (*ptr_to_statics)
  114. #define has_S (ptr_to_statics)
  115. #if ENABLE_FEATURE_CLEAN_UP
  116. static void free_static(void)
  117. {
  118. free(S.db[0].malloced);
  119. free(S.db[1].malloced);
  120. # if ENABLE_USE_BB_SHADOW
  121. free(S.db[2].malloced);
  122. # endif
  123. free(ptr_to_statics);
  124. }
  125. #endif
  126. static struct statics *get_S(void)
  127. {
  128. if (!ptr_to_statics) {
  129. ptr_to_statics = xzalloc(sizeof(S));
  130. memcpy(&S.db[0], &const_pw_db, sizeof(const_pw_db));
  131. memcpy(&S.db[1], &const_gr_db, sizeof(const_gr_db));
  132. #if ENABLE_USE_BB_SHADOW
  133. memcpy(&S.db[2], &const_sp_db, sizeof(const_sp_db));
  134. #endif
  135. #if ENABLE_FEATURE_CLEAN_UP
  136. atexit(free_static);
  137. #endif
  138. }
  139. return ptr_to_statics;
  140. }
  141. /* Internal functions */
  142. /* Divide the passwd/group/shadow record in fields
  143. * by substituting the given delimiter
  144. * e.g. ':' or ',' with '\0'.
  145. * Returns the number of fields found.
  146. * Strips leading and trailing whitespace in fields.
  147. */
  148. static int tokenize(char *buffer, int ch)
  149. {
  150. char *p = buffer;
  151. char *s = p;
  152. int num_fields = 0;
  153. for (;;) {
  154. if (isblank(*s)) {
  155. overlapping_strcpy(s, skip_whitespace(s));
  156. }
  157. if (*p == ch || *p == '\0') {
  158. char *end = p;
  159. while (p != s && isblank(p[-1]))
  160. p--;
  161. if (p != end)
  162. overlapping_strcpy(p, end);
  163. num_fields++;
  164. if (*end == '\0') {
  165. S.tokenize_end = p + 1;
  166. return num_fields;
  167. }
  168. *p = '\0';
  169. s = p + 1;
  170. }
  171. p++;
  172. }
  173. }
  174. /* Returns !NULL on success and matching line broken up in fields by '\0' in buf.
  175. * We require the expected number of fields to be found.
  176. */
  177. static char *parse_common(FILE *fp, struct passdb *db,
  178. const char *key, int field_pos)
  179. {
  180. char *buf;
  181. while ((buf = xmalloc_fgetline(fp)) != NULL) {
  182. int n;
  183. char *field;
  184. /* Skip empty lines, comment lines */
  185. if (buf[0] == '\0' || buf[0] == '#')
  186. goto free_and_next;
  187. if (tokenize(buf, ':') != db->numfields) {
  188. /* number of fields is wrong */
  189. bb_error_msg("%s: bad record", db->filename);
  190. goto free_and_next;
  191. }
  192. if (field_pos == -1) {
  193. /* no key specified: sequential read, return a record */
  194. break;
  195. }
  196. /* Can't use nth_string() here, it does not allow empty strings
  197. * ("\0\0" terminates the list), and a valid passwd entry
  198. * "user::UID:GID..." would be mishandled */
  199. n = field_pos;
  200. field = buf;
  201. while (n) {
  202. n--;
  203. field += strlen(field) + 1;
  204. }
  205. if (strcmp(key, field) == 0) {
  206. /* record found */
  207. break;
  208. }
  209. free_and_next:
  210. free(buf);
  211. }
  212. S.string_size = S.tokenize_end - buf;
  213. /*
  214. * Ugly hack: group db requires additional buffer space
  215. * for members[] array. If there is only one group, we need space
  216. * for 3 pointers: alignment padding, group name, NULL.
  217. * +1 for every additional group.
  218. */
  219. if (buf && db->numfields == sizeof(GR_DEF)-1) { /* if we read group file... */
  220. int cnt = 3;
  221. char *p = buf;
  222. while (p < S.tokenize_end)
  223. if (*p++ == ',')
  224. cnt++;
  225. S.string_size += cnt * sizeof(char*);
  226. //bb_error_msg("+%d words = %u key:%s buf:'%s'", cnt, S.string_size, key, buf);
  227. buf = xrealloc(buf, S.string_size);
  228. }
  229. return buf;
  230. }
  231. static char *parse_file(struct passdb *db,
  232. const char *key, int field_pos)
  233. {
  234. char *buf = NULL;
  235. FILE *fp = fopen_for_read(db->filename);
  236. if (fp) {
  237. buf = parse_common(fp, db, key, field_pos);
  238. fclose(fp);
  239. }
  240. return buf;
  241. }
  242. /* Convert passwd/group/shadow file record in buffer to a struct */
  243. static void *convert_to_struct(struct passdb *db,
  244. char *buffer, void *result)
  245. {
  246. const char *def = db->def;
  247. const uint8_t *off = db->off;
  248. /* For consistency, zero out all fields */
  249. memset(result, 0, db->size_of);
  250. for (;;) {
  251. void *member = (char*)result + (*off++);
  252. if ((*def | 0x20) == 's') { /* s or S */
  253. *(char **)member = (char*)buffer;
  254. if (!buffer[0] && (*def == 'S')) {
  255. errno = EINVAL;
  256. }
  257. }
  258. if (*def == 'I') {
  259. *(int *)member = bb_strtou(buffer, NULL, 10);
  260. }
  261. #if ENABLE_USE_BB_SHADOW
  262. if (*def == 'l') {
  263. long n = -1;
  264. if (buffer[0])
  265. n = bb_strtol(buffer, NULL, 10);
  266. *(long *)member = n;
  267. }
  268. #endif
  269. if (*def == 'm') {
  270. char **members;
  271. int i = tokenize(buffer, ',');
  272. /* Store members[] after buffer's end.
  273. * This is safe ONLY because there is a hack
  274. * in parse_common() which allocates additional space
  275. * at the end of malloced buffer!
  276. */
  277. members = (char **)
  278. ( ((intptr_t)S.tokenize_end + sizeof(members[0]))
  279. & -(intptr_t)sizeof(members[0])
  280. );
  281. ((struct group *)result)->gr_mem = members;
  282. while (--i >= 0) {
  283. if (buffer[0]) {
  284. *members++ = buffer;
  285. // bb_error_msg("member[]='%s'", buffer);
  286. }
  287. buffer += strlen(buffer) + 1;
  288. }
  289. *members = NULL;
  290. }
  291. /* def "r" does nothing */
  292. def++;
  293. if ((unsigned char)*def <= (unsigned char)' ')
  294. break;
  295. buffer += strlen(buffer) + 1;
  296. }
  297. if (errno)
  298. result = NULL;
  299. return result;
  300. }
  301. static int massage_data_for_r_func(struct passdb *db,
  302. char *buffer, size_t buflen,
  303. void **result,
  304. char *buf)
  305. {
  306. void *result_buf = *result;
  307. *result = NULL;
  308. if (buf) {
  309. if (S.string_size > buflen) {
  310. errno = ERANGE;
  311. } else {
  312. memcpy(buffer, buf, S.string_size);
  313. *result = convert_to_struct(db, buffer, result_buf);
  314. }
  315. free(buf);
  316. }
  317. /* "The reentrant functions return zero on success.
  318. * In case of error, an error number is returned."
  319. * NB: not finding the record is also a "success" here:
  320. */
  321. return errno;
  322. }
  323. static void* massage_data_for_non_r_func(struct passdb *db, char *buf)
  324. {
  325. if (!buf)
  326. return NULL;
  327. free(db->malloced);
  328. /* We enlarge buf and move string data up, freeing space
  329. * for struct passwd/group/spwd at the beginning. This way,
  330. * entire result of getXXnam is in a single malloced block.
  331. * This enables easy creation of xmalloc_getpwnam() API.
  332. */
  333. db->malloced = buf = xrealloc(buf, db->size_of + S.string_size);
  334. memmove(buf + db->size_of, buf, S.string_size);
  335. return convert_to_struct(db, buf + db->size_of, buf);
  336. }
  337. /****** getXXnam/id_r */
  338. static int FAST_FUNC getXXnam_r(const char *name, uintptr_t db_and_field_pos,
  339. char *buffer, size_t buflen,
  340. void *result)
  341. {
  342. char *buf;
  343. struct passdb *db = &get_S()->db[db_and_field_pos >> 2];
  344. buf = parse_file(db, name, 0 /*db_and_field_pos & 3*/);
  345. /* "db_and_field_pos & 3" is commented out since so far we don't implement
  346. * getXXXid_r() functions which would use that to pass 2 here */
  347. return massage_data_for_r_func(db, buffer, buflen, result, buf);
  348. }
  349. int FAST_FUNC getpwnam_r(const char *name, struct passwd *struct_buf,
  350. char *buffer, size_t buflen,
  351. struct passwd **result)
  352. {
  353. /* Why the "store buffer address in result" trick?
  354. * This way, getXXnam_r has the same ABI signature as getpwnam_r,
  355. * hopefully compiler can optimize tail call better in this case.
  356. */
  357. *result = struct_buf;
  358. return getXXnam_r(name, (0 << 2) + 0, buffer, buflen, result);
  359. }
  360. #if ENABLE_USE_BB_SHADOW
  361. int FAST_FUNC getspnam_r(const char *name, struct spwd *struct_buf, char *buffer, size_t buflen,
  362. struct spwd **result)
  363. {
  364. *result = struct_buf;
  365. return getXXnam_r(name, (2 << 2) + 0, buffer, buflen, result);
  366. }
  367. #endif
  368. #ifdef UNUSED
  369. /****** getXXent_r */
  370. static int FAST_FUNC getXXent_r(uintptr_t db_idx, char *buffer, size_t buflen,
  371. void *result)
  372. {
  373. char *buf;
  374. struct passdb *db = &get_S()->db[db_idx];
  375. if (!db->fp) {
  376. db->fp = fopen_for_read(db->filename);
  377. if (!db->fp) {
  378. return errno;
  379. }
  380. close_on_exec_on(fileno(db->fp));
  381. }
  382. buf = parse_common(db->fp, db, /*no search key:*/ NULL, -1);
  383. if (!buf && !errno)
  384. errno = ENOENT;
  385. return massage_data_for_r_func(db, buffer, buflen, result, buf);
  386. }
  387. int FAST_FUNC getpwent_r(struct passwd *struct_buf, char *buffer, size_t buflen,
  388. struct passwd **result)
  389. {
  390. *result = struct_buf;
  391. return getXXent_r(0, buffer, buflen, result);
  392. }
  393. #endif
  394. /****** getXXent */
  395. static void* FAST_FUNC getXXent(uintptr_t db_idx)
  396. {
  397. char *buf;
  398. struct passdb *db = &get_S()->db[db_idx];
  399. if (!db->fp) {
  400. db->fp = fopen_for_read(db->filename);
  401. if (!db->fp) {
  402. return NULL;
  403. }
  404. close_on_exec_on(fileno(db->fp));
  405. }
  406. buf = parse_common(db->fp, db, /*no search key:*/ NULL, -1);
  407. return massage_data_for_non_r_func(db, buf);
  408. }
  409. struct passwd* FAST_FUNC getpwent(void)
  410. {
  411. return getXXent(0);
  412. }
  413. /****** getXXnam/id */
  414. static void* FAST_FUNC getXXnam(const char *name, unsigned db_and_field_pos)
  415. {
  416. char *buf;
  417. struct passdb *db = &get_S()->db[db_and_field_pos >> 2];
  418. buf = parse_file(db, name, db_and_field_pos & 3);
  419. return massage_data_for_non_r_func(db, buf);
  420. }
  421. struct passwd* FAST_FUNC getpwnam(const char *name)
  422. {
  423. return getXXnam(name, (0 << 2) + 0);
  424. }
  425. struct group* FAST_FUNC getgrnam(const char *name)
  426. {
  427. return getXXnam(name, (1 << 2) + 0);
  428. }
  429. struct passwd* FAST_FUNC getpwuid(uid_t id)
  430. {
  431. return getXXnam(utoa(id), (0 << 2) + 2);
  432. }
  433. struct group* FAST_FUNC getgrgid(gid_t id)
  434. {
  435. return getXXnam(utoa(id), (1 << 2) + 2);
  436. }
  437. /****** end/setXXend */
  438. void FAST_FUNC endpwent(void)
  439. {
  440. if (has_S && S.db[0].fp) {
  441. fclose(S.db[0].fp);
  442. S.db[0].fp = NULL;
  443. }
  444. }
  445. void FAST_FUNC setpwent(void)
  446. {
  447. if (has_S && S.db[0].fp) {
  448. rewind(S.db[0].fp);
  449. }
  450. }
  451. void FAST_FUNC endgrent(void)
  452. {
  453. if (has_S && S.db[1].fp) {
  454. fclose(S.db[1].fp);
  455. S.db[1].fp = NULL;
  456. }
  457. }
  458. /****** initgroups and getgrouplist */
  459. static gid_t* FAST_FUNC getgrouplist_internal(int *ngroups_ptr,
  460. const char *user, gid_t gid)
  461. {
  462. FILE *fp;
  463. gid_t *group_list;
  464. int ngroups;
  465. /* We alloc space for 8 gids at a time. */
  466. group_list = xzalloc(8 * sizeof(group_list[0]));
  467. group_list[0] = gid;
  468. ngroups = 1;
  469. fp = fopen_for_read(_PATH_GROUP);
  470. if (fp) {
  471. struct passdb *db = &get_S()->db[1];
  472. char *buf;
  473. while ((buf = parse_common(fp, db, NULL, -1)) != NULL) {
  474. char **m;
  475. struct group group;
  476. if (!convert_to_struct(db, buf, &group))
  477. goto next;
  478. if (group.gr_gid == gid)
  479. goto next;
  480. for (m = group.gr_mem; *m; m++) {
  481. if (strcmp(*m, user) != 0)
  482. continue;
  483. group_list = xrealloc_vector(group_list, /*8=2^3:*/ 3, ngroups);
  484. group_list[ngroups++] = group.gr_gid;
  485. goto next;
  486. }
  487. next:
  488. free(buf);
  489. }
  490. fclose(fp);
  491. }
  492. *ngroups_ptr = ngroups;
  493. return group_list;
  494. }
  495. int FAST_FUNC initgroups(const char *user, gid_t gid)
  496. {
  497. int ngroups;
  498. gid_t *group_list = getgrouplist_internal(&ngroups, user, gid);
  499. ngroups = setgroups(ngroups, group_list);
  500. free(group_list);
  501. return ngroups;
  502. }
  503. int FAST_FUNC getgrouplist(const char *user, gid_t gid, gid_t *groups, int *ngroups)
  504. {
  505. int ngroups_old = *ngroups;
  506. gid_t *group_list = getgrouplist_internal(ngroups, user, gid);
  507. if (*ngroups <= ngroups_old) {
  508. ngroups_old = *ngroups;
  509. memcpy(groups, group_list, ngroups_old * sizeof(groups[0]));
  510. } else {
  511. ngroups_old = -1;
  512. }
  513. free(group_list);
  514. return ngroups_old;
  515. }