C++ add linux user - c++

Whats the best way to add a user/group in linux using C++ is there a library I can call on? I dont want to start doing things like:
fopen("/etc/passwd", "a");
fprintf(tmp, "%s:x:%d:1:%s:/%s/%s:/bin/ksh\n", username, usernumber, commentfield, userdir, username);
fclose(tmp);
fopen("/etc/shadow", "a");
fprintf(stmp, "%s:*LK*:::::::\n", username);
fclose(stmp);
Thanks!

I've noticed that most major utilities that add and change users do so directly, often in different ways. The functions you can use to modify the passwd and shadow files are exposed in <pwd.h> and in <sys/types.h>, and they're part of glibc.
fgetpwent, getpwnam, getpw, getpwent_r, putpwent, setpwent
We can look into how busybox (via TinyLogin) does it, as an example. In busybox/loginutils/adduser.c, they put a user in the passwd file by building the passwd structure and then call putpwent. For adding the user's password in the shadow file, they simply call fprintf and write the string directly.
For authenticating users the modern way, there's Linux-PAM. But as far as adding users, you can see in pam_unix_passwd.c that they call unix_update_db(), which calls various functions in libpwdb, which you'd have to add as a dependency to your project if you use it.
That being said, I'm guilty of having written a couple utilities to parse the passwd and shadow databases and modify them directly. It worked fine, but this was on an embedded system where I could tightly control everything. I didn't have to worry about things like race conditions with other programs modifying the passwd db.
If you need to add a group, same goes for the group database.

You might try using the libuser library.
One of the applications that are distributed with libuser is luseradd, a program that appears to be a cross-platform useradd utility. At its core, luseradd uses libuser's lu_user_add function to physically create the user.
See the docs/html folder in the source distribution for documentation.

Adding a user is a bit too high-level for there to be a system call for it. As far as I'm aware, there aren't any widely used libraries for this either. Your best bet will probably be to use the system call to invoke the useradd program with appropriate options.

Related

Is there an alternative to the 'system()' command in C++.?

I have read a lot of answers saying that the system() command is bad. First off, why is it so bad? Second off, is there an alternative that doesn't produce such a security hole? I mostly want to know if there is a way to clear screen in C++. In python I have a clear function that checks the os name and runs either system('cls') or system('clear'). Is this a security hole as well? If so, is there a python alternative?
system functions (across many language, including Python and C++) are not inherently "bad" but they present difficulties for correct use.
Security
You need to be absolutely sure that whatever you're executing via system is secure.
If you write system("echo hello " + name) then you need to be absolutely sure that name cannot be controlled by a malicious user. name = "; rm -rf /" would result in echo hello ; rm -rf /, so if that's coming from a user, via something like a web form or a database, then you need to exercise a lot of caution, and I would recommend a more sophisticated solution than system.
A call like system("clear") is secure for your purposes.
Usability
System calls give you several outputs (I'll give an example for calls to a bash shell):
status code (whether the shell indicated an error condition)
contents of STDOUT
contents of STDERR
system returns the status code. For commands like ls, you are interested in receiving STDOUT, and you may also check the status code. This is unwieldy with system.
The Python subprocess module is generally accepted by the community as an easier way to manage these concerns.
How to manage the console
If you're trying to manage the console display, you may be interested in a library like ncurses which has broad OS support.
Adding ncurses as a dependency could be heavy-handed, if clearing the screen is the only thing you need to do. If that's the case, then I see nothing wrong with using system() like you're doing.
First off, why is it so bad?
Because you introduce dependencies to the OS in your code, and make it unportable.
Second off, is there an alternative that doesn't produce such a security hole?
No, the existing alternatives (POSIX compatible) fork() and execxx() or pipe() have the same problems of introducing OS dependencies and security holes.
Is this a security hole as well?
The main secuity hole is introduced with commands constructed from parameters like
void exec_ls(const std::string param) {
std::string cmd;
cmd = "ls -l " + param;
system(cmd.c_str());
If someone manages to inject some additional command via param, e.g.
std::string param = "dir ; rm -rf /*";
// ^^^^^^^^^^^
exec_ls(param);
they can call all kinds of malicious commands.
Another security hole comes from the point, that someone might replace cls or clear commands on your system with some malicious code.
The only way to get over this, is to secure your system in a way, that such isn't possible.
If so, is there a python alternative?
Using a different programming language as an intermediate caller doesn't fix the problem I mentioned above.

C++, linux: how to limit function access to file system?

Our app is ran from SU or normal user. We have a library we have connected to our project. In that library there is a function we want to call. We have a folder called notRestricted in the directory where we run application from. We have created a new thread. We want to limit access of the thread to file system. What we want to do is simple - call that function but limit its access to write only to that folder (we prefer to let it read from anywhere app can read from).
Update:
So I see that there is no way to disable only one thread from all FS but one folder...
I read your propositions dear SO users and posted some kind of analog to this question here so in there thay gave us a link to sandbox with not a bad api, but I do not really know if it would work on anething but GentOS (but any way such script looks quite intresting in case of using Boost.Process command line to run it and than run desired ex-thread (which migrated to seprate application=)).
There isn't really any way you can prevent a single thread, because its in the same process space as you are, except for hacking methods like function hooking to detect any kind of file system access.
Perhaps you might like to rethink how you're implementing your application - having native untrusted code run as su isn't exactly a good idea. Perhaps use another process and communicate via. RPC, or use a interpreted language that you can check against at run time.
In my opinion, the best strategy would be:
Don't run this code in a different thread, but run it in a different process.
When you create this process (after the fork but before any call to execve), use chroot to change the root of the filesystem.
This will give you some good isolation... However doing so will make your code require root... Don't run the child process as root since root can trivially work around this.
Inject a replacement for open(2) that checks the arguments and returns -EACCES as appropriate.
This doesn't sound like the right thing to do. If you think about it, what you are trying to prevent is a problem well known to the computer games industry. The most common approach to deal with this problem is simply encoding or encrypting the data you don't want others to have access to, in such a way that only you know how to read/understand it.

c / c++ disable access to files

Is it possible to disable access of some program to files completely?
Because I don't want it to have any kind of access to files on system, is it possible to compile it so it doesn't have access to file stream or to run it someway it cant access files?
The closest you'd be able to come to that is to run your program in a chroot jail.
In an unmanaged environment, code cannot tell itself not to do something it shouldn't. CAS is part of managed environments only, where the runtime provides an extra level of access control. It's up to the OS to prevent applications from doing things that the user they are running on behalf of cannot do. You should be able to run the application as if you were a different, more limited user; then, you could limit the user's access rights to the resource and the OS will prevent the code from accessing it.
In Linux, you can change the owner of the process to nobody. This is no big security increase, as nobody still can access files etc. but it's better than running as a local user or root:
struct passwd *pw = getpwnam("nobody");
if (!pw)
printf("Error: Unable to look up info about user nobody");
else{
setuid(pw->pw_uid);
setgid(pw->pw_gid);
}
In theory you can direct the linker not to link fopen and so on. You'll probably have to use static linkage.
But, often, when you come to a requirement like this you're approaching the problem from the wrong direction. What is it you are trying to achieve with this hack? Why do you want this?
Under Windows, you can start the process under a restricted token
This requires more than just a basic knowledge of Windows API, but it's possible.

Control Debug Level in C++ Library - Linux

I have a C++ library, which is used in both Linux and Windows.
I want to enable the user to control the debug level (0 - no debug, 1 - only critical errors ... 5 - informative debug information).
The debug log is printed to a text file.
In Windows, I can do it using a registry value (DWORD DebugLevel).
What can be a good replacement which works also for Linux?
(Without 3rd party tools, for example Linux "registry").
Thanks in advance!
Does your library have some sort of initialisation function? Make the level a parameter to that function. Ideally store the passed-in value in a context structure or class if it makes sense for your API (i.e. if you require clients to always operate via a "context") - but if not, a global might be reasonable.
If it's largely for development purposes (ie the "user" you refer to is a developer using your library, not the end user of that code), the quickest/easiest way is to use an environment variable.
If it's to be controlled by the end-user, you probably need to extend your API so that the app developer can set the debug level in code, after reading his configuration files -- you wouldn't normally have a separate config file for just one library used by a program.
You can use the log4cxx framework. This is configurable through a file. I haven't tried it yet, but it should work with Windows too.
You could use a configuration file in /etc/YOURAPP or ~/.YOURAPP or ~/.config/YOURAPP

I want to hide system commands issued from system()

Writing a program in c++ and I want to issue a system command from the system() function but I don't want the user to see the command (because the command includes a pwd) in the executable window. I need to copy a file from the user's directory onto the server without allowing user access to the server or displaying the pwd. Figured having a .exe that does this is the easiest way.
Ex:
system("FILETRANSFER_SW.exe -pw helloWORLD11!# C:/temp.txt F:/tempfolder/")
But the executable window is showing this command, hence defeating the purpose of trying to hide the password.
I tried issuing
system("#echo OFF")
at the beginning of the program but that does not suppress the following commands, they still show up in the executable window.
Any suggestions?
Thanks...
The command line of running processes is considered public information in most operating systems.
Therefore it is a very bad idea to pass passwords on the command line.
There are two common workarounds to this problem, both of which require the support of the executable being called:
instead of passing the username/password on the command line, pass the name of a file containing the username/password
re-set the command line of the running process from within the called executable.
The first solution is easy and universally possible, the second one has a race condition and is harder to implement, because there's no cross-platform way to do it (on some OSes, changing argv will help).
I'm assuming from your command line that you're using Windows. If it doesn't need to be portable I would suggest you use the CreateProcess() API instead of calling system().
The CreateProcess() API can take a command-line and you can set up the STARTUP_INFORMATION parameter to hide the new process window (wShowWindow = SW_HIDE).
The command line will be hidden from the casual user, but as others have pointed out, it's not that hard to retrieve. Since you are creating a new process, I would suggest writing the sensitive data to that process' standard input. That way the process can just read it and proceed normally.
Using CreateProcess() API will hide the sensitive data from a user, but a power user can easily get the command line associated with the process using a free utilty, e.g. Process Explorer
Another solution is to send the password between your programs, encrypted with something like 3DES, or AES.
You could use a pipe to comunicate between both programs, and don't use the command line at all.
But any of this schemes is not really secure they can be circumvent rather easily. If you want more security you should use some kind of challenge-response protocol with the server.