Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a linux user using C/C++?

Tags:

c++

c

linux

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 example, I will need to override the PATH, what else should I worry about?

like image 407
Weboide Avatar asked Aug 10 '10 22:08

Weboide


3 Answers

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.

like image 59
MarkR Avatar answered Nov 11 '22 09:11

MarkR


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.

like image 43
Ken Bloom Avatar answered Nov 11 '22 07:11

Ken Bloom


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;
}
like image 39
Gabriel Buades Avatar answered Nov 11 '22 07:11

Gabriel Buades