ethercat_grant.cpp
Go to the documentation of this file.
1 
6 #include <stdio.h>
7 #include <unistd.h>
8 #include <errno.h>
9 #include <string.h>
10 #include <sys/capability.h>
11 #include <string>
12 #include <cstdlib>
13 #include <sys/prctl.h>
14 
15 using namespace std;
16 
17 #define EXECUTABLE "/var/tmp/granted"
18 
19 int main(int argc, char *argv[])
20 {
21  // Remove old executable, if it exists
22  unlink(EXECUTABLE);
23 
24  // Copy new executable to /var/tmp
25  string cmd;
26  cmd = string("cp ") + string(argv[1]) + string(" " EXECUTABLE);
27  if (system(cmd.c_str()) == -1) {
28  perror("cp");
29  return -1;
30  }
31  if (chown(EXECUTABLE, getuid(), getgid()) < 0) {
32  perror("chown");
33  return -1;
34  }
35 
36  // Create capability set
37  const char *cap_text = "cap_ipc_lock=ep cap_net_raw=ep cap_sys_nice=ep cap_net_admin=ep";
38  cap_t cap_d = cap_from_text(cap_text);
39  if (cap_d == NULL) {
40  perror("cap_from_text");
41  return -1;
42  }
43 
44  // Set file capability
45  int retval = cap_set_file(EXECUTABLE, cap_d);
46  if (retval != 0) {
47  fprintf(stderr, "Failed to set capabilities on file `%s' (%s)\n", argv[1], strerror(errno));
48  return -1;
49  }
50 
51  // Free capability
52  if (cap_d) {
53  cap_free(cap_d);
54  }
55 
56 
57  // Drop privileges
58  retval = setuid(getuid());
59  retval = setgid(getgid());
60 
61  // Allow core dumps
62  prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
63 
64  // Exec executable
65  if (execv(EXECUTABLE, argv + 1) < 0) {
66  perror("execv");
67  return -1;
68  }
69 
70  return 0;
71 }
#define EXECUTABLE
int main(int argc, char *argv[])


ethercat_grant
Author(s): Ugo Cupcic
autogenerated on Mon Jun 10 2019 13:12:31