i am trying to write a linux program that uses the c++ mount function (code below),
however, the mount operation requires permmissions, and running the program throws the errno 'Operation not permitted' (printed using perror)
tried some SO solutions but non was helpful, the alternative is to use the system("sudo mount..") but i prefer the c++ function.
is ther a way to use this function with permmissions?
IDE: Clion 2020.2.4
relevant code below
int returnValue = mount(sourcePath,targetPath,"", MS_SHARED, ""); //mounting the device
if (returnValue==0){
//mount completed
//somecode
}else{
//mount failed
std::cout<<"mount failed\n";
perror("");
}
output
mount failed
Operation not permitted
After you compile the code, change the ownership of the file to the superuser with chown root filename and add "set user or group ID on execution" to the mode of the executable file with chmod u+s filename.
Some options I see:
Just run the binary as root or under sudo;
Use setcap cap_sys_admin+ep on your binary to grant it the CAP_SYS_ADMIN capability;
If the set of possible targetPaths is fixed, edit /etc/fstab to give these paths the userflag.
#include <fstream>
#include <iostream>
#include <string>
int main(int argc, char *argv[]){
std::ifstream tmpfile;
std::string tmpfile_name = ".mytempfile.tmp";
std::string command = "groups>";
std::string searchv[] = {"disk", "sudo", "root"};
int searchc = sizeof(searchv)/sizeof(searchv[0]);
int search_matches = 0;
char data_buffer[128];
if(!system(NULL)) goto ERROR;
command += tmpfile_name;
if(system(command.c_str()) != 0) goto ERROR;
std::cout << "executed external command: \"" << command << "\"" << std::endl;
tmpfile.open(tmpfile_name, std::ios::in);
if(!tmpfile.is_open()) goto ERROR;
std::cout << tmpfile_name << " opened" << std::endl;
do{
tmpfile >> data_buffer;
if(tmpfile.eof()) break;
if(tmpfile.fail()) goto ERROR;
for(int i = 0; i < searchc; i++){
if(!searchv[i].compare(data_buffer)){
search_matches++;
std::cout << "found group " << searchv[i] << std::endl;
}
}
}
while(tmpfile.good());
tmpfile.close();
std::cout << "found " << search_matches << " groups" << std::endl;
return EXIT_SUCCESS;
ERROR:
std::cerr << "something bad happened" << std::endl;
return EXIT_FAILURE;
}
This answer may be off-topic, sorry for that.
This program calls the external Linux program "groups" and searches for keywords "disk", "sudo", "root", which indicating user access rights for mounting a disk.
accessing an os function implies complying with that os's security model.
so short answer, no. you can't override security models in your user-run code
Related
On Linux, I am trying to detect a bluetooth controller being connected and start reading from it. I know there's SDL to do that, but I just wanted to learn how to do it specifically on Linux. So I'm using the inotify api to wait for the file /dev/input/js0 to show up. But when I detect the file I cannot open it. I have the following c++ code:
#include <iostream>
#include <fstream>
#include <sys/inotify.h>
#include <unistd.h>
#include <linux/joystick.h>
#include <string.h>
constexpr int NAME_MAX = 16;
int main(int argc, char **argv) {
std::string path = std::string(argv[1]);
std::string directory = path.substr(0, path.find_last_of("/"));
std::string file = path.substr(path.find_last_of("/") + 1);
std::cout << "Directory is " << directory << ", file is " << file << std::endl;
int fd = inotify_init();
if (inotify_add_watch(fd, directory.c_str(), IN_CREATE) < 0) {
std::cout << "Could not watch: " << file << std::endl;
return -1;
}
else
std::cout << "Watching: " << file << std::endl;
char buffer[sizeof(struct inotify_event) + NAME_MAX + 1];
while (true) {
if (read(fd, buffer, sizeof(buffer)) < 0) {
std::cout << "Error reading event" << std::endl;
break;
}
struct inotify_event &event = (struct inotify_event &) buffer;
std::cout << event.name << std::endl;
if ((strcmp(event.name, file.c_str()) == 0) && (event.mask & IN_CREATE)) {
std::cout << "File has been created" << std::endl;
close(fd);
break;
}
}
std::fstream file_stream(file, std::fstream::in);
std::cout << file_stream.is_open() << std::endl;
}
If I run it to detect a regular file, it works, it waits for the file creation event, and when trying to open it with a std::fstream, is_open returns true. But if I run it to detect /dev/input/js0, even when the event comes and the file is detected, opening the fstream does not work, as is_open returns false. Is inotify appropriate to detect device files? If not, what would be the right way to do so?
According to inotify(7)
Inotify reports only events that a user-space program triggers
through the filesystem API. As a result, it does not catch
remote events that occur on network filesystems. (Applications
must fall back to polling the filesystem to catch such events.)
Furthermore, various pseudo-filesystems such as /proc, /sys, and
/dev/pts are not monitorable with inotify.
I would say that /dev/input/ also falls into this bucket.
I wonder if udev could be used: you should get info about the device using udevinfo -a -p /dev/input/js0, but also see what events connecting the peripheral generates using udevadm monitor --environment --udev.
Edit: if you successfuly get an inotify event but can't read the file:
Did you try reading the file with another simpler program when the BT device is already connected?
Is there a difference between fstream::open and open from <cstdio>?
Have you checked the permissions on the device? Also what does cat /dev/input/js0 produces?
I am attempting to write a program that can append text to a given host file on MacOS, but due to permission issues I am not allowed to do so.
Here's my code:
#include <iostream>
#include <fstream>
int main(int argc, const char * argv[]) {
std::ofstream myfile;
myfile.open("/private/etc/hosts.txt", std::ios::app);
if(!myfile.is_open()){
std::cout << "Host file could not be opened or located" << std::endl;
} else {
myfile << "data to be appended" << std::endl;
std::cout << "Host file has been modified" << std::endl;
myfile.close();
}
return 0;
}
I created a public folder with a mock of the hosts.txt file in the same root directory and it worked so I'm positive it is a permission error but I am BRAND new to working with files in C++ and have no idea how to proceed or if what I'm doing is even possible.
Thanks
I have basic logging process. When an error occured in the program, it has to been logging to a .txt file. I use following code for this:
#include <fstream>
fileName = "logs/error_log.txt";
ofstream myfile;
myfile.open (fileName,fstream::app);
myfile << serialized_string << endl;
myfile.close();
When an error occured it goes to error_log.txt file successfully. But when program crashed and is restarted afterward, new logs are not logged as append. As expected the way I am using creates a new file which has same name existed file and write on it. Can someone explain me how should I write older logs as well?
Edit: These are steps I have faced:
I am using raspbian and I compile with following:
g++ main.cpp -lwiringPi -lpthread -lcurl -o test
That is the whole function.
int putLog(const char* process, int logType, string logData) {
isLoggerBusy = true;
string fileName;
std::string color;
switch (logType) {
case 0:
fileName = "logs/error_log.txt";
// color = "\033[0;31m";
break;
case 1:
fileName = "logs/info_log.txt";
// color = "\033[0;36m";
break;
case 2:
fileName = "logs/state_log.txt";
// color = "\033[1;33m";
break;
}
if (process == "WebSocket") {
color = "\033[1;32m";
}
json j = {
{"Process", process}, {"Time", currentDateTime()}, {"Log", logData}};
string serialized_string = j.dump();
fix_utf8_string(serialized_string);
ofstream myfile;
myfile.open(fileName, fstream::app);
cout << color << serialized_string << '\n';
myfile << serialized_string << endl;
myfile.close();
isLoggerBusy = false;
cout << "\033[0m" << endl;
return 0;
}
I started the program. It write downs these lines to the state_logs.txt
{"Log":"Incoming
Message{\"Action\":\"Heartbeat\",\"Data\":null}","Process":"WebSocket","Time":"2018-08-16.14:53:52"}
{"Log":"GSM Setup
Finished","Process":"SMSService","Time":"2018-08-16.14:54:13"}
Stopped the program with CTRL-C and control the state_logs.txt and I can see now two lines there.
Restart the program and interrupt with CTRC-C again in 10 seconds (before a new line logging.)
I check the state_logs.txt again and now I can not see nothing. Re-did this process but this time waiting a bit more before interrupt program(just a bit more to get only one line of log.). So now I can see only one and timestamps has been changed.
I cannot reproduce what OP describes.
I just tested on cygwin/Windows 10. (I didn't know how to make this test on an online compiler.)
testFStreamApp.cc:
#include <iostream>
#include <fstream>
int main()
{
std::cout << "Log error...\n";
{ std::ofstream log("testFStream.log", std::ios::out | std::ios::app);
log << "Error happened!" << std::endl;
}
std::cout << "Going to die...\n";
abort();
return 0; // should never be reached
}
Test Session:
$ g++ -std=c++11 -o testFStreamApp testFStreamApp.cc
$ rm testFStream.log
$ for i in 1 2 3; do
> echo "$i. start:"
> ./testFStreamApp
> done
1. start:
Log error...
Going to die...
Aborted (core dumped)
2. start:
Log error...
Going to die...
Aborted (core dumped)
3. start:
Log error...
Going to die...
Aborted (core dumped)
$ cat <testFStream.log
Error happened!
Error happened!
Error happened!
$
YSC pointed out that I made some silent changes. I did it assuming no relevance.
However, to erase any excuses, I tried also:
#include <iostream>
#include <fstream>
int main()
{
std::cout << "Log error...\n";
std::ofstream log;
log.open("testFStream.log", std::fstream::app);
log << "Error happened!" << std::endl;
log.close();
std::cout << "Going to die...\n";
abort();
return 0; // should never be reached
}
The output was exactly as above.
I hadn't dared to test this but doctorlove encouraged me:
#include <iostream>
#include <fstream>
int main()
{
std::cout << "Log error...\n";
std::ofstream log;
log.open("testFStream.log", std::fstream::app);
log << "Error happened!" << std::endl;
std::cout << "Going to die...\n";
abort();
log.close();
return 0; // should never be reached
}
Even in this case, I got the same result.
At this point, I must admit that cygwin is just a wrapper around the win32 API. So, in this case, I wouldn't wonder if this behaves different on other OSes.
I'm aware that std::endl does a flush() insight. The question is how far down (into the system) the flush() is effective. (In daily work, I try to write the code in a way that it is not necessary to rely on such details...) ;-)
I am new at C/C++,
So basically I want to call an .exe file that displays 2 numbers and be able to grab those two numbers to use them in my code.
To call the .exe file I've used the system command, but I am still not able to grab those two numbers that are displayed by the .exe file
char *files = "MyPath\file.exe";
system (files);
I think this is better aproach:
Here you just create new process, and you read data that process gives you. I tested this on OS X 10.11 with .sh file and works like a charm. I think that this would probably work on Windows also.
FILE *fp = popen("path to exe","r");
if (fp == NULL)
{
std::cout << "Popen is null" << std::endl;
}else
{
char buff[100];
while ( fgets( buff, sizeof(buff), fp ) != NULL )
{
std::cout << buff;
}
}
You need to escapr back slashes in C++ string literals so:
// note the double "\\"
char* files = "MyPath\\file.exe";
Or just use forward slashes:
char* files = "MyPath/file.exe";
Its not very efficient but one thing you can to with std::system is redirect the output to a file and then read the file:
#include <cstdlib>
#include <fstream>
#include <iostream>
int main()
{
// redirect > the output to a file called output.txt
if(std::system("MyPath\\file.exe > output.txt") != 0)
{
std::cerr << "ERROR: calling system\n";
return 1; // error code
}
// open a file to the output data
std::ifstream ifs("output.txt");
if(!ifs.is_open())
{
std::cerr << "ERROR: opening output file\n";
return 1; // error code
}
int num1, num2;
if(!(ifs >> num1 >> num2))
{
std::cerr << "ERROR: reading numbers\n";
return 1; // error code
}
// do something with the numbers here
std::cout << "num1: " << num1 << '\n';
std::cout << "num2: " << num2 << '\n';
}
NOTE: (thnx #VermillionAzure)
Note that system doesn't always work everywhere because unicorn
environments. Also, shells can differ from each other, like cmd.exe
and bash. – VermillionAzure
When using std::system the results are platform dependant and not all shells will have redirection or use the same syntax or even exist!
Changing a Linux C++ program which gives the user limited file access. Thus the program chroots itself to a sandbox with the files the user can get at. All worked well.
Now, however, the program needs to access some files for its own needs (not the user's) but they are outside the sandbox. I know chroot allows access to files opened before the chroot but in this case the needed files could a few among many hundreds so it is obviously impractical to open them all just for the couple that might be required.
Is there any way to get at the files?
Copy them into the sandbox or open them all before chrooting. Seriously. If there was a way to do this, there would be a way to suborn it to allow other access and make your protection useless.
The whole point of the sandbox is to prevent exactly what you're trying to achieve.
If the files are all in 1 directory, you could use mount to bind them to a directory inside the sandbox.
mount --bind /path/to/files /sandbox/files
The you can access the files through /sandbox/files/. If you don't want the user to see them, do mount --bind /path/to/files /sandbox/.files so the .files directory is hidden
I guess that you ought to be able to split your program into two parts, one which is chroot'ed and one which isn't, and have the chroot'ed portion request files' contents from the non-chroot'ed portion via the IPC mechanism of your choice.
This is a hack, and it may be easy to get wrong, negating any benefit of a chroot. Like paxdiablo says, you're trying to get around the whole purpose of a chroot sandbox, so your options are very, very limited.
Maybe if you explained a bit more what you're trying to accomplish, we might be able to offer some other ideas. For example, SELinux and AppArmor are more flexible than chroot and may be able to give you the security you seek.
If the files you need to access are within a few directories you could open those directories before you chroot and save the file descriptors. You can then use the so-called *at functions (e.g. openat(), renameat(), etc.) to get at the individual files. Basically you are opening the files relative to the already open directory file descriptors rather than the chrooted directory.
Whether this is a safe thing to do is open to question but it should work in Linux.
EDIT: This is on the ugly side but it seems to work. You should poke around a lot more for vulnerabilities than I have. I haven't tested how dropping privileges and so forth will effect things.
#include <iostream>
#include <string>
using namespace std;
#include <cstdio>
#include <cstdlib>
#include <cerrno>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *argv[])
{
if (argc < 4)
{
cerr << "USAGE: " << argv[0] << " <jail directory> <freeworld directory> <filename>\n";
exit(EXIT_FAILURE);
}
const string JAILDIR(argv[1]);
const string FREEDIR(argv[2]);
string freefilename(argv[3]);
while (freefilename[0] == '/')
freefilename.erase(0, 1);
DIR *pDir;
if ((pDir = opendir(FREEDIR.c_str())) == NULL)
{
perror("Could not open outside dir");
exit(EXIT_FAILURE);
}
int freeFD = dirfd(pDir);
//cd to jail dir
if (chdir(JAILDIR.c_str()) == -1)
{
perror("cd before chroot");
exit(EXIT_FAILURE);
}
//lock in jail
if (chroot(JAILDIR.c_str()) < 0)
{
cerr << "Failed to chroot to " << JAILDIR << " - " << strerror(errno) << endl;
exit(EXIT_FAILURE);
}
//
//in jail, won't work
//
string JailFile(FREEDIR);
JailFile += "/";
JailFile += freefilename;
int jailFD;
if ((jailFD = open(JailFile.c_str(), O_RDONLY)) == -1)
{
cout << "as expected, could not open " << JailFile << endl;
perror("exected open fail");
}
else
{
cout << "defying all logic, opened " << JailFile << endl;
exit(EXIT_FAILURE);
}
//
//using this works
//
if ((jailFD = openat(freeFD, freefilename.c_str(), O_RDONLY)) == -1)
{
cout << "example did not work. Could not open " << freefilename << " Sorry!" << endl;
exit(EXIT_FAILURE);
}
else
cout << "opened " << freefilename << " from inside jail" << endl;
char buff[255];
ssize_t numread;
while (1)
{
if ((numread = read(jailFD, buff, sizeof(buff) - 1)) == -1)
{
perror("read");
exit(EXIT_FAILURE);
}
if (numread == 0)
break;
buff[numread] = '\0';
cout << buff << endl;
}
return 0;
}
To test:
echo "Hello World" >/tmp/mystuff.dat
mkdir /tmp/jail
sudo ./myprog /tmp/jail /tmp mystuff.dat