Example use of memfd_create+fexecve

 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
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
int main(int argc, char** argv, char** envp)
{
const int fd=memfd_create("test-executable", MFD_CLOEXEC);
if(fd==-1)
{
perror("memfd_create");
return 1;
}
const char binary[]={
0x7f,0x45,0x4c,0x46,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x02,0x00,0x3e,0x00,0x01,0x00,0x00,0x00,0x78,0x00,0x40,0x00,0x00,0x00,0x00,0x00,
0x40,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x40,0x00,0x38,0x00,0x01,0x00,0x40,0x00,0x00,0x00,0x00,0x00,
0x01,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x78,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x78,0x00,0x40,0x00,0x00,0x00,0x00,0x00,0x78,0x00,0x40,0x00,0x00,0x00,0x00,0x00,
0x0f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x0f,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x48,0xb8,0x76,0x45,0x36,0x34,0x23,0x01,
0x00,0x00,0x48,0xff,0xc0,0xeb,0xfb};
if(write(fd,binary,sizeof binary)==-1)
{
perror("write");
return 2;
}
if(fexecve(fd, argv, envp)==-1)
{
perror("fexecve");
return 3;
}
}