Entering sudo password through c - c

I asked this question before but no-one gave a straight answer. I wanted to know how I can enter the sudo password through c code. I'm trying to write a script to be able to execute sudo bash and enter the password required. Also I know the risks of hardcoding passwords but I don't mind in this instance.

No. Doing it that way is an antipattern.
There are several alternatives to choose from, depending on the situation:
Use gksudo (if DISPLAY environment variable is set) for a graphical prompt.
Install the scripts to be executed in /usr/share/yourapp/scripts/ or /usr/lib/yourapp/scripts/, and the proper sudo configuration that allows running them with sudo without supplying a password in /etc/sudoers.d/yourapp (or /etc/sudoers in systems without /etc/sudoers.d/)
At the beginning of your program, check if geteuid() == 0. If not, re-execute self using gksudo/sudo, to obtain root privileges.
For normal operations, your program should use only the privileges of the real user who executed the program. To be able to raise the privileges later, the root privileges are "saved". So, initially, your program will drop the privileges using e.g.
uid_t uid = getuid();
gid_t gid = getgid();
if (setresgid(gid, gid, 0) == -1 ||
setresuid(uid, uid, 0) == -1) {
/* Failed: no root privileges! */
}
To re-elevate privileges, you use
if (setresgid(gid, 0, 0) == -1 ||
setresuid(uid, 0, 0) == -1) {
/* Failed: no root privileges! */
}
which changes only the effective identity to root (as setuid binaries do), or
if (setresgid(0, 0, 0) == -1 ||
setresuid(0, 0, 0) == -1) {
/* Failed: no root privileges! */
}
which changes both real and effective identity to root.
Often, the privileges are elevated for only forking a privileged child slave, after which the main program drops the privileges completely using
if (setresgid(gid, gid, gid) == -1 ||
setresuid(uid, uid, uid) == -1) {
/* Failed. */
}
keeping just a socket pair or pipes between the parent and the child; the child can then fork and execute new processes. (If an Unix domain socket is used, the parent can even send new descriptors to be used for the new processes' standard streams via ancillary messages.)
Use filesystem capabilities to give your program the capabilities it needs, without elevating all its privileges.
For example, sudo setcap CAP_NET_BIND_SERVICE=pe /usr/bin/yourapp gives /usr/bin/yourapp the CAP_NET_BIND_SERVICE capability (permitted and effective; not inherited), which allows your program to bind to any unused TCP/IP and UDP/IP ports, including 1-1024. See man 7 capabilities for detailed descriptions of the capabilities.
Use a trusted helper binary (program) to act as sudo for you. If you install this at e.g. /usr/lib/yourapp/execute, you can add the sudo configuration necessary to allow executing it without supplying a password. Alternatively, you can make it setuid root, or give it the necessary capabilities via filesystem capabilities.
To avoid other programs from exploiting this helper, you must ensure it is only executed by your program. One way to ensure that is to have your program create an Unix domain socket pair, leaving one end open in your program, and the other end for the helper in e.g. descriptor 3. Before doing anything, the helper checks that there is nothing to receive yet (to avoid "pipe stuffing" attacks), and writes a single byte to the parent. The parent responds with a single byte, but with its credentials in an ancillary message. The credentials contain the process ID of the parent. (Do not simply use getppid(), because that allows certain attacks; this socket approach verifies the parent is still alive when we do the check.) Finally, use readlink() to read the /proc/PID/exe pseudo-symlink, where PID is the parent process ID from the credentials ancillary message. At this point, the helper should send a byte, and receive a byte with the credentials again as an ancillary message, to ensure the parent process is still the same.
The verification process is complex, but necessary, to avoid making it easy to exploit root privileges by misusing the helper. For another approach to do exactly this, look into Apache suEXEC, the helper used by Apache to execute CGI programs with specific user privileges.
Let's say you are totally uninterested in doing things in a sensible way, and insist on using passwords. Fine; all I ask is that you don't publish such code, or at least warn your users that it is completely unsafe.
This is not just a crude hack: it is a suicidal one, similar to putting the password to your web site in your e-mail signature, because you only mail to friends who should have admin access to your site in the first place. So, footgun, with a hair trigger, no safety, and armed with buckshot coated in tetrodotoxin. With a nice label with big, child-readable letters saying "Please play with me! I'm safe!", stored in the kids bedroom.
The simplest thing to do is to execute sudo with the -S flag, which causes it to read the password from the standard input. For example, example.c:
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
int main(void)
{
FILE *cmd;
int status;
cmd = popen("/usr/bin/sudo -S id -un 2>/dev/null", "w");
if (!cmd) {
fprintf(stderr, "Cannot run sudo: %s.\n", strerror(errno));
return EXIT_FAILURE;
}
fprintf(cmd, "Password\n");
fflush(cmd);
status = pclose(cmd);
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) == EXIT_SUCCESS)
fprintf(stderr, "No errors.\n");
else
fprintf(stderr, "Command failed with exit status %d.\n", WEXITSTATUS(status));
} else
if (WIFSIGNALED(status))
fprintf(stderr, "Command killed by signal %d.\n", WTERMSIG(status));
else
fprintf(stderr, "Command failed.\n");
return EXIT_SUCCESS;
}
The command pipe is opened in write mode, so that we can write the password to it. The 2>/dev/null redirection hides the password prompt.
If the password is correct, the above will output what id -un outputs when run as root (i.e.: root) to standard output, and No errors. to standard error.
If the password is incorrect, sudo will retry a couple of times (so nothing will happen for a few seconds), then the program will report Command failed with exit status 1. to standard error, because that's what sudo does when the password is incorrect.

Related

Why is unprivileged recursive unshare(CLONE_NEWUSER) not permitted?

I'm on Ubuntu 17.04.
Single unprivilleged unshare of mount namespace works. You can try using unshare(1) command:
$ unshare -m -U /bin/sh
#
However unshare within unshare is not permitted:
$ unshare -m -U /bin/sh
# unshare -m -U /bin/sh
unshare: Operation not permitted
#
Here is a C program that will basically do the same:
#define _GNU_SOURCE
#include <stdio.h>
#include <sched.h>
#include <sys/mount.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{
if(unshare(CLONE_NEWUSER|CLONE_NEWNS) == -1) {
perror("unshare");
return -1;
}
if(unshare(CLONE_NEWUSER|CLONE_NEWNS) == -1) {
perror("unshare2");
return -1;
}
return 0;
}
Why it's not permitted? Where I can find documentation about this? I failed to find this information in unshare or clone man page and in kernel unshare documentation.
Is there a system setting that would allow this?
What I want to achieve:
First unshare: I want to mask few binaries on system with my own versions.
Second unshare: unprivilleged chroot.
I'm somewhat guessing here, but I think that the reason is the UID mapping. In order to perform it, certain conditions must be met (from the user_namespaces man page):
In order for a process to write to the /proc/[pid]/uid_map (/proc/[pid]/gid_map) file, all of the following require‐
ments must be met:
1. The writing process must have the CAP_SETUID (CAP_SETGID) capability in the user namespace of the process pid.
2. The writing process must either be in the user namespace of the process pid or be in the parent user namespace of
the process pid.
3. The mapped user IDs (group IDs) must in turn have a mapping in the parent user namespace.
I believe what happens is that the first time you run, the mapping matches that of the parent UID. The second time, however, it does not, and this fails the system call.
From the unshare(2) manual page:
EPERM CLONE_NEWUSER was specified in flags, but either the effective user ID or the effective group ID of the caller
does not have a mapping in the parent namespace (see user_namespaces(7)).

Creating a daemon in Linux

In Linux I want to add a daemon that cannot be stopped and which monitors filesystem changes.
If any changes are detected, it should write the path to the console where it was started plus a newline.
I already have the filesystem changing code almost ready but I cannot figure out how to create a daemon.
My code is from here: http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
What to do after the fork?
int main (int argc, char **argv) {
pid_t pID = fork();
if (pID == 0) { // child
// Code only executed by child process
sIdentifier = "Child Process: ";
}
else if (pID < 0) {
cerr << "Failed to fork" << endl;
exit(1);
// Throw exception
}
else // parent
{
// Code only executed by parent process
sIdentifier = "Parent Process:";
}
return 0;
}
In Linux i want to add a daemon that cannot be stopped and which monitors filesystem changes. If any changes would be detected it should write the path to the console where it was started + a newline.
Daemons work in the background and (usually...) don't belong to a TTY that's why you can't use stdout/stderr in the way you probably want.
Usually a syslog daemon (syslogd) is used for logging messages to files (debug, error,...).
Besides that, there are a few required steps to daemonize a process.
If I remember correctly these steps are:
fork off the parent process & let it terminate if forking was successful. -> Because the parent process has terminated, the child process now runs in the background.
setsid - Create a new session. The calling process becomes the leader of the new session and the process group leader of the new process group. The process is now detached from its controlling terminal (CTTY).
Catch signals - Ignore and/or handle signals.
fork again & let the parent process terminate to ensure that you get rid of the session leading process. (Only session leaders may get a TTY again.)
chdir - Change the working directory of the daemon.
umask - Change the file mode mask according to the needs of the daemon.
close - Close all open file descriptors that may be inherited from the parent process.
To give you a starting point: Look at this skeleton code that shows the basic steps. This code can now also be forked on GitHub: Basic skeleton of a linux daemon
/*
* daemonize.c
* This example daemonizes a process, writes a few log messages,
* sleeps 20 seconds and terminates afterwards.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>
static void skeleton_daemon()
{
pid_t pid;
/* Fork off the parent process */
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* On success: The child process becomes session leader */
if (setsid() < 0)
exit(EXIT_FAILURE);
/* Catch, ignore and handle signals */
//TODO: Implement a working signal handler */
signal(SIGCHLD, SIG_IGN);
signal(SIGHUP, SIG_IGN);
/* Fork off for the second time*/
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* Set new file permissions */
umask(0);
/* Change the working directory to the root directory */
/* or another appropriated directory */
chdir("/");
/* Close all open file descriptors */
int x;
for (x = sysconf(_SC_OPEN_MAX); x>=0; x--)
{
close (x);
}
/* Open the log file */
openlog ("firstdaemon", LOG_PID, LOG_DAEMON);
}
int main()
{
skeleton_daemon();
while (1)
{
//TODO: Insert daemon code here.
syslog (LOG_NOTICE, "First daemon started.");
sleep (20);
break;
}
syslog (LOG_NOTICE, "First daemon terminated.");
closelog();
return EXIT_SUCCESS;
}
Compile the code: gcc -o firstdaemon daemonize.c
Start the daemon: ./firstdaemon
Check if everything is working properly: ps -xj | grep firstdaemon
The output should be similar to this one:
+------+------+------+------+-----+-------+------+------+------+-----+
| PPID | PID | PGID | SID | TTY | TPGID | STAT | UID | TIME | CMD |
+------+------+------+------+-----+-------+------+------+------+-----+
| 1 | 3387 | 3386 | 3386 | ? | -1 | S | 1000 | 0:00 | ./ |
+------+------+------+------+-----+-------+------+------+------+-----+
What you should see here is:
The daemon has no controlling terminal (TTY = ?)
The parent process ID (PPID) is 1 (The init process)
The PID != SID which means that our process is NOT the session leader
(because of the second fork())
Because PID != SID our process can't take control of a TTY again
Reading the syslog:
Locate your syslog file. Mine is here: /var/log/syslog
Do a: grep firstdaemon /var/log/syslog
The output should be similar to this one:
firstdaemon[3387]: First daemon started.
firstdaemon[3387]: First daemon terminated.
A note:
In reality you would also want to implement a signal handler and set up the logging properly (Files, log levels...).
Further reading:
Linux-UNIX-Programmierung - German
Unix Daemon Server Programming
man 7 daemon describes how to create daemon in great detail. My answer is just excerpt from this manual.
There are at least two types of daemons:
traditional SysV daemons (old-style),
systemd daemons (new-style).
SysV Daemons
If you are interested in traditional SysV daemon, you should implement the following steps:
Close all open file descriptors except standard input, output, and error (i.e. the first three file descriptors 0, 1, 2). This ensures that no accidentally passed file descriptor stays around in the daemon process. On Linux, this is best implemented by iterating through /proc/self/fd, with a fallback of iterating from file descriptor 3 to the value returned by getrlimit() for RLIMIT_NOFILE.
Reset all signal handlers to their default. This is best done by iterating through the available signals up to the limit of _NSIG and resetting them to SIG_DFL.
Reset the signal mask using sigprocmask().
Sanitize the environment block, removing or resetting environment variables that might negatively impact daemon runtime.
Call fork(), to create a background process.
In the child, call setsid() to detach from any terminal and create an independent session.
In the child, call fork() again, to ensure that the daemon can never re-acquire a terminal again.
Call exit() in the first child, so that only the second child (the actual daemon process) stays around. This ensures that the daemon process is re-parented to init/PID 1, as all daemons should be.
In the daemon process, connect /dev/null to standard input, output, and error.
In the daemon process, reset the umask to 0, so that the file modes passed to open(), mkdir() and suchlike directly control the access mode of the created files and directories.
In the daemon process, change the current directory to the root directory (/), in order to avoid that the daemon involuntarily blocks mount points from being unmounted.
In the daemon process, write the daemon PID (as returned by getpid()) to a PID file, for example /run/foobar.pid (for a hypothetical daemon "foobar") to ensure that the daemon cannot be started more than once. This must be implemented in race-free fashion so that the PID file is only updated when it is verified at the same time that the PID previously stored in the PID file no longer exists or belongs to a foreign process.
In the daemon process, drop privileges, if possible and applicable.
From the daemon process, notify the original process started that initialization is complete. This can be implemented via an unnamed pipe or similar communication channel that is created before the first fork() and hence available in both the original and the daemon process.
Call exit() in the original process. The process that invoked the daemon must be able to rely on that this exit() happens after initialization is complete and all external communication channels are established and accessible.
Note this warning:
The BSD daemon() function should not be used, as it implements only a subset of these steps.
A daemon that needs to provide compatibility with SysV systems should implement the scheme pointed out above. However, it is recommended to make this behavior optional and configurable via a command line argument to ease debugging as well as to simplify integration into systems using systemd.
Note that daemon() is not POSIX compliant.
New-Style Daemons
For new-style daemons the following steps are recommended:
If SIGTERM is received, shut down the daemon and exit cleanly.
If SIGHUP is received, reload the configuration files, if this applies.
Provide a correct exit code from the main daemon process, as this is used by the init system to detect service errors and problems. It is recommended to follow the exit code scheme as defined in the LSB recommendations for SysV init scripts.
If possible and applicable, expose the daemon's control interface via the D-Bus IPC system and grab a bus name as last step of initialization.
For integration in systemd, provide a .service unit file that carries information about starting, stopping and otherwise maintaining the daemon. See systemd.service(5) for details.
As much as possible, rely on the init system's functionality to limit the access of the daemon to files, services and other resources, i.e. in the case of systemd, rely on systemd's resource limit control instead of implementing your own, rely on systemd's privilege dropping code instead of implementing it in the daemon, and similar. See systemd.exec(5) for the available controls.
If D-Bus is used, make your daemon bus-activatable by supplying a D-Bus service activation configuration file. This has multiple advantages: your daemon may be started lazily on-demand; it may be started in parallel to other daemons requiring it — which maximizes parallelization and boot-up speed; your daemon can be restarted on failure without losing any bus requests, as the bus queues requests for activatable services. See below for details.
If your daemon provides services to other local processes or remote clients via a socket, it should be made socket-activatable following the scheme pointed out below. Like D-Bus activation, this enables on-demand starting of services as well as it allows improved parallelization of service start-up. Also, for state-less protocols (such as syslog, DNS), a daemon implementing socket-based activation can be restarted without losing a single request. See below for details.
If applicable, a daemon should notify the init system about startup completion or status updates via the sd_notify(3) interface.
Instead of using the syslog() call to log directly to the system syslog service, a new-style daemon may choose to simply log to standard error via fprintf(), which is then forwarded to syslog by the init system. If log levels are necessary, these can be encoded by prefixing individual log lines with strings like "<4>" (for log level 4 "WARNING" in the syslog priority scheme), following a similar style as the Linux kernel's printk() level system. For details, see sd-daemon(3) and systemd.exec(5).
To learn more read whole man 7 daemon.
You cannot create a process in linux that cannot be killed. The root user (uid=0) can send a signal to a process, and there are two signals which cannot be caught, SIGKILL=9, SIGSTOP=19. And other signals (when uncaught) can also result in process termination.
You may want a more general daemonize function, where you can specify a name for your program/daemon, and a path to run your program (perhaps "/" or "/tmp"). You may also want to provide file(s) for stderr and stdout (and possibly a control path using stdin).
Here are the necessary includes:
#include <stdio.h> //printf(3)
#include <stdlib.h> //exit(3)
#include <unistd.h> //fork(3), chdir(3), sysconf(3)
#include <signal.h> //signal(3)
#include <sys/stat.h> //umask(3)
#include <syslog.h> //syslog(3), openlog(3), closelog(3)
And here is a more general function,
int
daemonize(char* name, char* path, char* outfile, char* errfile, char* infile )
{
if(!path) { path="/"; }
if(!name) { name="medaemon"; }
if(!infile) { infile="/dev/null"; }
if(!outfile) { outfile="/dev/null"; }
if(!errfile) { errfile="/dev/null"; }
//printf("%s %s %s %s\n",name,path,outfile,infile);
pid_t child;
//fork, detach from process group leader
if( (child=fork())<0 ) { //failed fork
fprintf(stderr,"error: failed fork\n");
exit(EXIT_FAILURE);
}
if (child>0) { //parent
exit(EXIT_SUCCESS);
}
if( setsid()<0 ) { //failed to become session leader
fprintf(stderr,"error: failed setsid\n");
exit(EXIT_FAILURE);
}
//catch/ignore signals
signal(SIGCHLD,SIG_IGN);
signal(SIGHUP,SIG_IGN);
//fork second time
if ( (child=fork())<0) { //failed fork
fprintf(stderr,"error: failed fork\n");
exit(EXIT_FAILURE);
}
if( child>0 ) { //parent
exit(EXIT_SUCCESS);
}
//new file permissions
umask(0);
//change to path directory
chdir(path);
//Close all open file descriptors
int fd;
for( fd=sysconf(_SC_OPEN_MAX); fd>0; --fd )
{
close(fd);
}
//reopen stdin, stdout, stderr
stdin=fopen(infile,"r"); //fd=0
stdout=fopen(outfile,"w+"); //fd=1
stderr=fopen(errfile,"w+"); //fd=2
//open syslog
openlog(name,LOG_PID,LOG_DAEMON);
return(0);
}
Here is a sample program, which becomes a daemon, hangs around, and then leaves.
int
main()
{
int res;
int ttl=120;
int delay=5;
if( (res=daemonize("mydaemon","/tmp",NULL,NULL,NULL)) != 0 ) {
fprintf(stderr,"error: daemonize failed\n");
exit(EXIT_FAILURE);
}
while( ttl>0 ) {
//daemon code here
syslog(LOG_NOTICE,"daemon ttl %d",ttl);
sleep(delay);
ttl-=delay;
}
syslog(LOG_NOTICE,"daemon ttl expired");
closelog();
return(EXIT_SUCCESS);
}
Note that SIG_IGN indicates to catch and ignore the signal. You could build a signal handler that can log signal receipt, and set flags (such as a flag to indicate graceful shutdown).
Try using the daemon function:
#include <unistd.h>
int daemon(int nochdir, int noclose);
From the man page:
The daemon() function is for programs wishing to detach themselves
from the controlling terminal and run in the background as system
daemons.
If nochdir is zero, daemon() changes the calling process's current
working directory to the root directory ("/"); otherwise, the current
working directory is left unchanged.
If noclose is zero, daemon() redirects standard input, standard
output and standard error to /dev/null; otherwise, no changes are
made to these file descriptors.
I can stop at the first requirement "A daemon which cannot be stopped ..."
Not possible my friend; however, you can achieve the same with a much better tool, a kernel module.
http://www.infoq.com/articles/inotify-linux-file-system-event-monitoring
All daemons can be stopped. Some are more easily stopped than others. Even a daemon pair with the partner in hold down, respawning the partner if lost, can be stopped. You just have to work a little harder at it.
If your app is one of:
{
".sh": "bash",
".py": "python",
".rb": "ruby",
".coffee" : "coffee",
".php": "php",
".pl" : "perl",
".js" : "node"
}
and you don't mind a NodeJS dependency then install NodeJS and then:
npm install -g pm2
pm2 start yourapp.yourext --name "fred" # where .yourext is one of the above
pm2 start yourapp.yourext -i 0 --name "fred" # run your app on all cores
pm2 list
To keep all apps running on reboot (and daemonise pm2):
pm2 startup
pm2 save
Now you can:
service pm2 stop|restart|start|status
(also easily allows you to watch for code changes in your app directory and auto restart the app process when a code change happens)
Daemon Template
I wrote a daemon template following the new-style daemon: link
You can find the entire template code on GitHub: here
Main.cpp
// This function will be called when the daemon receive a SIGHUP signal.
void reload() {
LOG_INFO("Reload function called.");
}
int main(int argc, char **argv) {
// The Daemon class is a singleton to avoid be instantiate more than once
Daemon& daemon = Daemon::instance();
// Set the reload function to be called in case of receiving a SIGHUP signal
daemon.setReloadFunction(reload);
// Daemon main loop
int count = 0;
while(daemon.IsRunning()) {
LOG_DEBUG("Count: ", count++);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
LOG_INFO("The daemon process ended gracefully.");
}
Daemon.hpp
class Daemon {
public:
static Daemon& instance() {
static Daemon instance;
return instance;
}
void setReloadFunction(std::function<void()> func);
bool IsRunning();
private:
std::function<void()> m_reloadFunc;
bool m_isRunning;
bool m_reload;
Daemon();
Daemon(Daemon const&) = delete;
void operator=(Daemon const&) = delete;
void Reload();
static void signalHandler(int signal);
};
Daemon.cpp
Daemon::Daemon() {
m_isRunning = true;
m_reload = false;
signal(SIGINT, Daemon::signalHandler);
signal(SIGTERM, Daemon::signalHandler);
signal(SIGHUP, Daemon::signalHandler);
}
void Daemon::setReloadFunction(std::function<void()> func) {
m_reloadFunc = func;
}
bool Daemon::IsRunning() {
if (m_reload) {
m_reload = false;
m_reloadFunc();
}
return m_isRunning;
}
void Daemon::signalHandler(int signal) {
LOG_INFO("Interrup signal number [", signal,"] recived.");
switch(signal) {
case SIGINT:
case SIGTERM: {
Daemon::instance().m_isRunning = false;
break;
}
case SIGHUP: {
Daemon::instance().m_reload = true;
break;
}
}
}
daemon-template.service
[Unit]
Description=Simple daemon template
After=network.taget
[Service]
Type=simple
ExecStart=/usr/bin/daemon-template --conf_file /etc/daemon-template/daemon-tenplate.conf
ExecReload=/bin/kill -HUP $MAINPID
User=root
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=daemon-template
[Install]
WantedBy=multi-user.target
By calling fork() you've created a child process. If the fork is successful (fork returned a non-zero PID) execution will continue from this point from within the child process. In this case we want to gracefully exit the parent process and then continue our work in the child process.
Maybe this will help:
http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html
A daemon is just a process in the background. If you want to start your program when the OS boots, on linux, you add your start command to /etc/rc.d/rc.local (run after all other scripts) or /etc/startup.sh
On windows, you make a service, register the service, and then set it to start automatically at boot in administration -> services panel.

correct way to run setuid programs in C

I have a process with permissions 4750. Two users exist in my Linux system. The root user and the appz user. The process inherits the permissions of a process manager that runs as "appz" user.
I have two basic routines:
void do_root (void)
{
int status;
status = seteuid (euid);
if (status < 0) {
exit (status);
}
}
/* undo root permissions */
void undo_root (void)
{
int status;
status = seteuid (ruid);
if (status < 0) {
exit (status);
}
status = setuid(ruid);
if (status < 0) {
exit (status);
}
}
My flow is the following:
int main() {
undo_root();
do some stuff;
do_root();
bind( port 80); //needs root perm
undo_root();
while(1) {
accept commads()
if ( commands needs root user access)
{
do_root();
execute();
undo_root();
}
}
As you can see I want to execute some commands as root. I am trying to drop permissions temporarily and if the tasks needs root access I wrap the command between a do_root and undo_root call.
However it seems that my program is not working.
What is the canonical way to do it?
The old-school way is to in both do_root and undo_root to use setreuid() to swap ruid and euid:
setreuid(geteuid(), getuid());
This is perfectly acceptable if the program is small enough to do a complete security audit.
The new-school way is far more complex and involves fork()ing off a child that accepts directives for what to do as root and then doing setuid(getuid()) to drop root permanently in the parent.. The child is responsible for validating all directives it receives. For a large enough program, this drops the amount of code that must be security audited, and allows the user to manage the process with job control or kill it, etc.
There is a paper 'Setuid Demystified' by Hao Chen, David Wagner, and Drew Dean. It was presented at USENIX 2002. It describes how setuid() and transitions work in great detail (correct as of 2002). It is well worth reading (several times - I must be a year or two overdue on a re-read of it).
Fundamentally, as Petesh noted in a comment, when a process with EUID 0 does setuid(nuid) with nuid != 0, there is no way back to root (EUID 0) privileges. And, indeed, it is vital that it is so. Otherwise, when you login, the root process that logs you in could not limit you to your own privileges - you'd be able to get back to root. Saved UID complicates things, but I don't believe it affects the one-way trap of EUID 0 doing setuid().
The setuid man page says the following:
... a set-user-ID-root program wishing to temporarily drop root
privileges, assume the identity of a non-root user, and then regain
root privileges afterwards cannot use setuid()
Meaning that you cannot use setuid(). You have to use seteuid() and, possibly, setreuid(). See Setuid Program Example for more details.

Check if user is root in C?

How can I verify if the user is root?
Usually it's a mistake to test if the user is root. POSIX does not even require a root user, but leaves it to the implementation to determine how permissions work. Code such as:
if (i_am_root) do_privileged_op(); else print_error();
will really annoy users with advanced privilege models where root is not necessary to perform the necessary privileged operations. I remember back in the early days of cd burning on Linux, I had to hack all over the cdrecord source to remove all the useless checks to see if it was running as root, when it worked just fine with permission to read /dev/sga.
Instead, you should always attempt the privileged operation you need to perform, and check for EPERM or similar if it fails to notify the user that they have insufficient privileges (and perhaps should retry running as root).
The one case where it's useful to check for root is checking if your program was invoked "suid-root". A reasonable test would be:
uid_t uid=getuid(), euid=geteuid();
if (uid<0 || uid!=euid) {
/* We might have elevated privileges beyond that of the user who invoked
* the program, due to suid bit. Be very careful about trusting any data! */
} else {
/* Anything goes. */
}
Note that I allowed for the possibility (far-fetched, but best to be paranoid) that either of the calls to get uid/euid could fail, and that in the failure case we should assume we're suid and a malicious user has somehow caused the syscalls to fail in an attempt to hide that we're suid.
getuid or geteuid, depending on what you really mean. In either case, 0 means root.
#include <stdio.h>
#include <unistd.h>
if (geteuid() != 0) {
fprintf(stderr, "App needs root\n");
exit(1);
}
The point made by R is valid. You should consider trial and error, or another approach that does not explicitly require root.
better to use getuid or geteuid but it is in zconf.h header file and you must enter that like bellow :
#include <zconf.h>
#include <stdio.h>
int main()
{
int a;
a=getuid();
//or you can use a=geteuid();
//euid is effective user id and uid is user id
// both euid and uid are zero when you are root user
if (a==0){
printf("you are root user");
//so you can do what`enter code here`ever `enter code here` you want as root user
}
else
printf("please run the script as root user !");
return 0;
}

Start a process in the background in Linux with C

I am trying to do something a little weird here. I need to start a process, logcat, from a deamon that will run in the background and print to the terminal without taking control of stdin. It is for logging so ideally logcat will print log messages while still allowing the user to input standard commands and initialize programs from the shell. Here is the code for the daemon I have so far. The program, logcat, starts and shows log messages but I cannot enter any commands into stdin as it appears that the program has taken control of stdin.
int main ( int argc, char** argv, char** env )
{
int fd;
if ((fd = open("/dev/console", O_RDWR)) < 0) {
fd = open("/dev/null", O_RDWR);
}
printf("THIS IS A TEST\n");
dup2(1, fd);
dup2(2, fd);
pid_t childpid = fork();
if(childpid == -1) {
perror("Failed to fork, logcat not starting");
return 1;
}
if(childpid == 0) {
//this is the child, exec logcat
setsid();
int execReturn = execl("/system/bin/logcat", "logcat", (char *) 0);
} else {
//this is the parent do nothing
close(fd);
return 0;
}
close(fd);
return 0;
}
Thanks
The 'logcat' command seems to be for Android development - that might explain the odd location of the command.
The key operation that you must fix is to ensure that you close your current standard input (the terminal) and open /dev/null/ for the input device:
close(0);
if ((fd = open("/dev/null", O_RDONLY)) != 0)
...error - failed to open /dev/null!
This means that your daemonized child process will not read anything from the terminal.
What I think you want to do is:
Run your launcher program from a command line, which will have standard input, standard output and standard error connected to 'the terminal'.
Inside your program, you want to replace the standard input so it comes from /dev/null.
You want to leave standard output alone - you want logcat to write to the current standard output.
You probably want to leave standard error alone too.
At some point in the proceedings, you do your daemonization properly (borrowing the link from #bstpierre's answer), making sure that the terminal you are connected to is not your controlling terminal, so that interrupts and hangups sent to the terminal don't affect your daemon. The plumbing is simpler than what you have set up - you should deal with standard input and leave standard output and standard error unchanged (instead of changing the outputs and leaving the input unchanged).
Now, you might want the output to go to /dev/console; if so, then it is reasonable to revise the code to open /dev/console. However, it is not reasonable to fall back on /dev/null if you can't open /dev/console; your program should report an error and fail (because there is no point in having logcat writing to /dev/null!). Make sure you open the console with the O_NOCTTY flag so it does not become the controlling terminal for the daemon.
The final comment I'd make is:
Are you sure you want random text appearing over your terminal or console when it is in use for other things?
I don't much like it when that happens.
See also: SO 958249
How to Daemonize in Linux [dead link]
How to Daemonize in Linux [wayback machine archive of the above]
gist on github -- code taken from link above
Executive summary:
One of the things I keep running across is Linux daemons that don’t properly daemonize themselves. To properly daemonize, the following steps must be followed.
The fork() call is used to create a separate process.
The setsid() call is used to detach the process from the parent (normally a shell).
The file mask should be reset.
The current directory should be changed to something benign.
The standard files (stdin,stdout and stderr) need to be reopened.
Failure to do any of these steps will lead to a daemon process that can misbehave. The typical symptoms are as follows.
Starting the daemon and then logging out will cause the terminal to hang. This is particularly nasty with ssh.
The directory from which the daemon was launched remains locked.
Spurious output appears in the shell from which the daemon was started.
There is special purposed function for this in glibc:
#include <unistd.h>
...
/* We are in the parent, yet */
daemon(0,0);
/* Now we are in the child */
...
More details here http://linux.die.net/man/3/daemon

Resources