How to create a linux user using C/C++?
I would like to build a program which takes a username as parameter and creates the user and its home folder (with some hard-coded specifications like folder, and security checks like username cannot be root or an existing user).
My application needs to create users in order to give SSH access.
The program will be executed using sudo. I've read it should be written in C or C++ instead of scripts because scripts could easily be exploited.
- Can you give me some advices or good practices about how to achieve this?
- Should I use some Pam library? Is there any examples?
- What are the possible security flaws?
I know C/C++, and running Ubuntu Lucid.
Edit:
The user will only have sudo access to run that specific command, I do not want it to be able to run a shell or bypass some programs (by changing PATH environment, for example).
As a result, for e开发者_StackOverflow社区xample, I will need to override the PATH, what else should I worry about?
Probably your best bet is to invoke useradd; it will do the right things (given appropriate parameters).
Trying to create one manually by calling the appropriate APIs is possible but not desirable.
There is no API for this. You just write into /etc/passwd
and /etc/group
(and possibly the shadow versions as well) using normal file access system calls.
Actually, there is a C API method to create a Linux user. It is in the pwd.h include file.
Here you have a sample test:
#include <pwd.h>
#include <stdio.h>
#include <string.h>
static void createUser(char *userName, char *homeDir, int uid) {
struct passwd * pwd = getpwent ();
struct passwd pwd2;
pwd = getpwnam(userName);
if (pwd != NULL) {
return;
}
pwd2.pw_dir = homeDir;
pwd2.pw_gecos=userName;
pwd2.pw_name=userName;
pwd2.pw_gid=uid;
pwd2.pw_uid=uid;
pwd2.pw_shell=strdup("/bin/bash");
FILE *f = fopen("/etc/passwd", "a");
if (f != NULL) {
putpwent(&pwd2, f);
fclose(f);
}
free (pwd2.pw_shell);
}
int main (int argc, char **argv) {
createUser("test", "/home/test", 12345");
return 0;
}
精彩评论