Debian: How to access GPIO without root permissions - c++

I’m using a C program to read/write GPIO pins, but there is the problem: I’m using ioperm to give permissions to do write / read operations on ports, but I really need to run this program without root privileges (the error is “Segmentation fault” …)
Is there any way to do this? (not doing setuid…)
//something like that to test
void setIo(unsigned char value)
{
iopl(3);
ioperm(PORT_IO,1,1);
outb(value,PORT_IO);
ioperm(PORT_IO,1,0);
}
Thank you.
Monique

Related

set proxy configuration in c++ code

I have a raspberry running Yocto.
I'm making a code to setup de proxy configuration of the OS connection.
An example of the conde that I'm using is the following
int main(void)
{
system("unset http_proxy");
command = "export http_proxy=\"http://hostname.com\"";
system(command.c_str());
}
The solution on code is not working, however, if I input in a terminal the same command, it works.
What can be the problem?
What can be the problem?
system() creates a sub-process. So changing the http_proxyenvironment variable with a system call doesn't affect the calling process.
You may try to change the environment variable using setenv(), and then fork() and continue in the child process to do whatever you need with the new proxy settings.

ssh remote login to server using system(char * command), and excute commands?

Someone familiar with SSH and System(const char * command) to execute shell command!??
Am trying to remotely login to multiple servers/machines from my C++ code, and i have to execute some commands remotely. To the best of my experience, i decided to use ssh. But, now i want to load and send all my commands through the System(const char * command). pls see my code below..
#include "all my headers"
int main()
{
system("ssh 172.10.10.1");//login to server_one, password=123
system("ssh 172.10.10.2");//login to server_two, password=1234
system("ssh 172.10.10.3");//login to server_three,password=12345
system("ssh 172.10.10.4");//login to server_four, password=123456
return 0;
}
Now,my Question is:
can i load and send the remote_ip of the servers and password at the
same time, something like: system("ssh 172.10.10.4 ,123456")
password=123456? if yes, how?
if am done with (1) above, i will have another question. thanks.
Calling system("ssh ...") will ONLY work if you have set up public keys for the machine you want to log in on.
The reason is that the system() does not allow you to interact with the process you started, it will just spawn a new shell and pass the relevant string to the shell for execution, and ssh does not itself have a way to pass the password to the application, you have to actually type it in (or send it to the stdin side of ssh if you use popen - but I would really suggest that public keys are the right way to go in an automated system).
If you still need to interact with the created process, you will need to use something like popen, which will allow you to read stdout or write to stdin on the - or even pipe() and fork() if you need the ability to do stuff to both stdin and stdout.

GPIO Pins RaspberryPi Using C++

I'm writing a program to control the GPIO pins on my raspberryPi with C++ and having difficulty I'm able to export with the following code:
char pathString[256];
sprintf(pathString, "%s/export", "/sys/class/gpio");
ofstream exporterFile(pathString);
exporterFile << pinNumber;
exporterFile.close()
This works an successfully exports the pin but this does not set the direction:
sprintf(pathString, "%sgpio%d/direction", "/sys/class/gpio", pinNumber);
ofstream directionFile(pathString);
directionFile << pinDirection;
directionFile.close();
For some reason I cannot write to the file, perhaps I do not have the right privileges. My question is, is that the problem and if so how do I solve it so I can write to the file.
Thanks in advance
You need to be root or run your program with sudo in order to use the GPIO pins.
However, I'd recommend using the wiringpi library http://wiringpi.com/ to access GPIO from c/c++. It is easy to use and raises the abstraction level a bit. It also lets you do things like PWM. A program using wiringpi also needs to be run with sudo.

Read/Write files with UNC path - in c++

I wrote a bit of code that reads/writes stuff...
I would like to add an option to read/write to UNC paths.
A bit of code:
if (boost::filesystem::exists (file_name))
{
std::ifstream in_file(file_name.c_str(), std::ios::in|std::ios::binary|std::ios::ate);
if(in_file.is_open())
{
in_file.read(...);
in_file.close();
}
}
If the network share I am trying to use has been used before, this works.
But if I try with a share from a computer that I have not seen before, I get error:
boost::filesystem::status: Logon failure: unknown user name or bad password: "\\xx\test.txt"
I'd like to avoid the exception, check the boost::filesystem::status for... what ? Looking in documentation, it seems that it can tell me if I have a regular file, or a directory... but how can I check if I have the correct permissions ?
Is there a way to actually send in the user name and password ?
Edit: found that I could call
Net Use \\yourUNC\path /user:uname password
also:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa375187(v=vs.85).aspx
I think either of these would make the code platform dependent ?
Also, if I do log in every time - in a sequence of 10000 calls, this would result in serious slowing down ?
Is there any way to check if the user is logged in ?
Note: I am using boost 1.47 - mostly windows but I'd like to be platform independent.
Thank you.
The only way I found that I can check rights was to try... catch surrounding a check for file exist call.
If the try fails, it means I don't have rights and can call system("Net Use...")
This way, I only have to log in once even if I read/write 10,000 files...
I don't like the fact that I have to use try... catch, if there is a better way, and I'll find it, I'll update - if anyone knows of a better way, please let me know.

How to programmatically gain root privileges?

I am writing some software (in C++, for Linux/Mac OSX) which runs as a non-privileged user but needs root privileges at some point (to create a new virtual device).
Running this program as root is not a option (mainly for security issues) and I need to know the identity (uid) of the "real" user.
Is there a way to mimic the "sudo" command behavior (ask for user password) to temporarily gain root privileges and perform the particular task ? If so, which functions would I use ?
Thank you very much for your help !
If you need root privileges every time, the best thing is to start your program as root and drop them (in a subprocess) with setuid and setgid. That's what apache does when it needs to bind to the restricted port 80.
If gaining root rights is the exception instead of the rule and the program is run interactively, another way is to write a program add_interface and execute
sudo add_interface args
and let sudo handle authentication for you. Instead of sudo, you may want to use a graphical frontend like gksu, gksudo, kdesu, or kdesudo. I wouldn't try to implement secure password input myself; it can be a tricky problem and you'll probably leave gaping security holes and functionality problems (Do you support fingerprint readers?).
Another alternative is polkit, previously called PolicyKit.
Original answer
You might consider the setuid switch on the executable itself. Wikipedia has an article on it which even shows you the difference between geteuid() and getuid() quite effectively, the former being for finding out who you're "emulating" and the latter for who you "are". The sudo process, for example, geteuid should return 0 (root) and getuid your user's id, however, its sub-processes do truly run as root (you can verify this with sudo id -u -r).
I don't think there's a way to easily programmatically gain root access - after all, applying the principle of least privilege, why would you need to? Common practise is to run only limited parts of code with elevated privileges. A lot of daemons etc are also set up under modern systems to run as their own user with most of the privileges they need. It's only for very specific operations (mounting etc) that root privileges are truly needed.
2013 update
My original answer stands (although my 2013 self might make a better job of it than my 2010 one), but if you are designing an application that requires root access, you may want to consider exactly what sort of root access is needed and consider the use of POSIX Capabilities (man page). These are different to capability-based security as implemented in L4 et al. POSIX capabilities allow your application to be granted a subset of root's powers. For example CAP_SYS_MODULE will allow you to insert kernel modules, but give you no other root powers. This is in use in distributions e.g. Fedora has a feature to completely remove setuid binaries with indiscriminate root access.
This matters because as a programmer, your code is obviously perfect! But, the libraries on which you depend (sigh, if only you'd written them!) might have vulnerabilities in them. Using capabilities, you can limit the use of this exploit, and save yourself and your company from security-related scrutiny. This makes everyone happier.
You can't gain root privileges, you must start out with them and reduce your privileges as needed. The usual way that you do this is to install the program with the "setuid" bit set: this runs the program with the effective userid of the file owner. If you run ls -l on sudo, you'll see that it is installed that way:
-rwsr-xr-x 2 root root 123504 2010-02-25 18:22 /usr/bin/sudo
While your program is running with root privileges, you can call the setuid(2) system call to change your effective userid to some non-privileged user. I believe (but haven't tried this) that you could install your program as root with the setuid bit on, immediately reduce privilege, and then restore privilege as needed (it's possible, however, that once you lower your privilege you won't be able to restore it).
A better solution is to break out the piece of your program that needs to run as root, and install it with the setuid bit turned on. You will, of course, need to take reasonable precautions that it can't be invoked outside of your master program.
Normally this is done by making your binary suid-root.
One way of managing this so that attacks against your program are hard is to minimize the code that runs as root like so:
int privileged_server(int argc, char **argv);
int unprivileged_client(int argc, char **argv, int comlink);
int main(int argc, char **argv) {
int sockets[2];
pid_t child;
socketpair(AF_INET, SOCK_STREAM, 0); /* or is it AF_UNIX? */
child = fork();
if (child < 0) {
perror("fork");
exit(3);
} elseif (child == 0) {
close(sockets[0]);
dup2(sockets[1], 0);
close(sockets[1]);
dup2(0, 1);
dup2(0, 2); /* or not */
_exit(privileged_server(argc, argv));
} else {
close(sockets[1]);
int rtn;
setuid(getuid());
rtn = unprivileged_client(argc, argv, sockets[0]);
wait(child);
return rtn;
}
}
Now the unprivileged code talks to the privileged code via the fd comlink (which is a connected socket). The corresponding privileged code uses stdin/stdout as its end of the comlink.
The privileged code needs to verify the security of every operation it needs to do but as this code is small compared to the unprivileged code this should be reasonably easy.
You might want to take a look at these APIs:
setuid, seteuid, setgid, setegid, ...
They're defined in the header <unistd.h> in Linux systems (don't know much about MAC, but you should have a similar header there too).
One problem that I can see is that the process must have sufficient privileges to change its user-/group- IDs. Otherwise calls to the above functions will result in an error with errorno set to EPERM.
I would suggest that you run your program as the root user, change effective user ID (using seteuid) to an underprivileged user at the very beginning. Then, whenever you need to elevate permissions, prompt for a password then use seteuid again to revert to the root user.
On OS X, you can use the AuthorizationExecuteWithPrivileges function. The page on Authorization Services Tasks has some elaborate discussion of this (and related) functions.
Here's a bit of C++ code to execute a program with administrator privileges:
static bool execute(const std::string &program, const std::vector<std::string> &arguments)
{
AuthorizationRef ref;
if (AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &ref) != errAuthorizationSuccess) {
return false;
}
AuthorizationItem item = {
kAuthorizationRightExecute, 0, 0, 0
};
AuthorizationRights rights = { 1, &item };
const AuthorizationFlags flags = kAuthorizationFlagDefaults
| kAuthorizationFlagInteractionAllowed
| kAuthorizationFlagPreAuthorize
| kAuthorizationFlagExtendRights;
if (AuthorizationCopyRights(ref, &rights, kAuthorizationEmptyEnvironment, flags, 0) != errAuthorizationSuccess) {
AuthorizationFree(ref, kAuthorizationFlagDestroyRights);
return false;
}
std::vector<char*> args;
for (std::vector<std::string>::const_iterator it = arguments.begin(); it != arguments.end(); ++it) {
args.push_back(it->c_str());
}
args.push_back(0);
OSStatus status = AuthorizationExecuteWithPrivileges(ref, program.c_str(), kAuthorizationFlagDefaults, &args[0], 0);
AuthorizationFree(ref, kAuthorizationFlagDestroyRights);
return status == errAuthorizationSuccess;
}
You can try launching the command to create the virtual device (including sudo) through a background shell. Ask for the users password in a dialog of your own and pipe that into the shell when sudo asks for it. There are other solutions like using gksu, but those are not guaranteed to be available on every machine.
You don't run your entire program as root, but only the small part of it that needs root. You should spawn a separate process for that and sudo may be of assistance to you.