fix getpwnam() thread safe issue

Signed-off-by: Donghwa Jeong <dh48.jeong@samsung.com>
This commit is contained in:
Donghwa Jeong 2018-06-12 17:09:13 +09:00
parent c6d0d3cb30
commit 2dce415b62
No known key found for this signature in database
GPG Key ID: 0BE2750EE612F372
2 changed files with 51 additions and 11 deletions

View File

@ -1520,14 +1520,32 @@ static void cg_escape(void)
/* Get uid and gid for @user. */ /* Get uid and gid for @user. */
static bool get_uid_gid(const char *user, uid_t *uid, gid_t *gid) static bool get_uid_gid(const char *user, uid_t *uid, gid_t *gid)
{ {
struct passwd *pwent; strcut passwd pwent;
struct passwd *pwentp = NULL;
char *buf;
size_t bufsize;
int ret;
pwent = getpwnam(user); bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (!pwent) if (bufsize == -1)
bufsize = 1024;
buf = malloc(bufsize);
if (!buf)
return false; return false;
*uid = pwent->pw_uid; ret = getpwnam_r(user, &pwent, buf, bufsize, &pwentp);
*gid = pwent->pw_gid; if (!pwentp) {
if (ret == 0)
mysyslog(LOG_ERR, "Could not find matched password record.\n", NULL);
free(buf);
return false;
}
*uid = pwent.pw_uid;
*gid = pwent.pw_gid;
free(buf);
return true; return true;
} }

View File

@ -82,29 +82,51 @@ static void usage(char *cmd)
static bool lookup_user(const char *optarg, uid_t *uid) static bool lookup_user(const char *optarg, uid_t *uid)
{ {
char name[TOOL_MAXPATHLEN]; char name[TOOL_MAXPATHLEN];
struct passwd *pwent = NULL; struct passwd pwent;
struct passwd *pwentp = NULL;
char *buf;
size_t bufsize;
int ret;
if (!optarg || (optarg[0] == '\0')) if (!optarg || (optarg[0] == '\0'))
return false; return false;
bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (bufsize == -1)
bufsize = 1024;
buf = malloc(bufsize);
if (!buf)
return false;
if (sscanf(optarg, "%u", uid) < 1) { if (sscanf(optarg, "%u", uid) < 1) {
/* not a uid -- perhaps a username */ /* not a uid -- perhaps a username */
if (sscanf(optarg, "%s", name) < 1) if (sscanf(optarg, "%s", name) < 1)
return false; return false;
pwent = getpwnam(name); ret = getpwnam_r(name, &pwent, buf, bufsize, &pwentp);
if (!pwent) { if (!pwentp) {
if (ret == 0)
fprintf(stderr, "could not find matched password record\n");
fprintf(stderr, "invalid username %s\n", name); fprintf(stderr, "invalid username %s\n", name);
free(buf);
return false; return false;
} }
*uid = pwent->pw_uid; *uid = pwent.pw_uid;
} else { } else {
pwent = getpwuid(*uid); ret = getpwuid_r(*uid, &pwent, buf, bufsize, &pwentp);
if (!pwent) { if (!pwentp) {
if (ret == 0)
fprintf(stderr, "could not find matched password record\n");
fprintf(stderr, "invalid uid %u\n", *uid); fprintf(stderr, "invalid uid %u\n", *uid);
free(buf);
return false; return false;
} }
} }
free(buf);
return true; return true;
} }