summaryrefslogtreecommitdiff
path: root/main.c
blob: 8d079530cb128a07a71789992b4262614e395f37 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#define _GNU_SOURCE

#include <assert.h>
#include <errno.h>
#include <grp.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main( int argc, char *argv[] ) {

  if ( argc < 4 ) {
    fprintf( stderr, "Usage: %s user group cmd [args..]\n", argv[0] );
    return 1;
  };

  char *user = argv[1];
  char *group = argv[2];
  char *cmd = argv[3];
  char **args = argv + 3;

  char *end;
  unsigned long tmp;

  struct passwd *userpw;
  struct group *grouppw;

  tmp = strtoul( user, &end, 10 );
  if ( end != user && ! *end ) {
    userpw = getpwuid( tmp );
  } else {
    userpw = getpwnam( user );
  };
  assert( userpw != NULL );

  tmp = strtoul( group, &end, 10 );
  if ( end != user && ! *end ) {
    grouppw = getgrgid( tmp );
  } else {
    grouppw = getgrnam( group );
  };
  assert( grouppw != NULL );

  // literally the only security check
  assert( grouppw->gr_gid != 0 );
  assert( userpw->pw_uid != 0 );

  if ( setgroups( 0, NULL ) != 0 )
    assert_perror( errno );

  if ( setregid( grouppw->gr_gid, grouppw->gr_gid ) != 0 )
    assert_perror( errno );

  if ( setreuid( userpw->pw_uid, userpw->pw_uid ) != 0 )
    assert_perror( errno );

  execv( cmd, args );
  assert_perror( errno );

}