Database example with Capsicum sandbox
1 /* Title: Database example with Capsicum sandbox */ 2 3 #include <sys/resource.h> 4 #include <sys/capability.h> 5 6 #include <err.h> 7 #include <inttypes.h> 8 #include <stdlib.h> 9 #include <stdio.h> 10 #include <unistd.h> 11 12 #include <ksql.h> 13 14 int 15 main(void) 16 { 17 struct ksql *sql; 18 struct ksqlstmt *stmt; 19 int64_t hits; 20 cap_rights_t rights; 21 22 /* 23 * We can't use any Capsicum here. 24 * The reason is that we don't know the files beforehand. 25 * So we can't work with pre-opened file descriptors. 26 */ 27 28 sql = ksql_alloc(NULL); 29 ksql_open(sql, "simple.db"); 30 ksql_stmt_alloc(sql, &stmt, 31 "UPDATE hits SET hits=hits+1", 0); 32 ksql_stmt_step(stmt); 33 ksql_stmt_free(stmt); 34 ksql_stmt_alloc(sql, &stmt, 35 "SELECT hits FROM hits", 0); 36 ksql_stmt_step(stmt); 37 hits = ksql_stmt_int(stmt, 0); 38 ksql_stmt_free(stmt); 39 ksql_free(sql); 40 41 /* Now we can uselessly use Capsicum. */ 42 43 cap_rights_init(&rights, CAP_EVENT, 44 CAP_WRITE, CAP_FSTAT); 45 if (cap_rights_limit(STDOUT_FILENO, &rights) < 0) 46 err(EXIT_FAILURE, NULL); 47 cap_rights_init(&rights, CAP_EVENT, 48 CAP_WRITE, CAP_FSTAT); 49 if (cap_rights_limit(STDERR_FILENO, &rights) < 0) 50 err(EXIT_FAILURE, NULL); 51 cap_rights_init(&rights, CAP_EVENT, 52 CAP_READ, CAP_FSTAT); 53 if (cap_rights_limit(STDIN_FILENO, &rights) < 0) 54 err(EXIT_FAILURE, NULL); 55 if (cap_enter()) 56 err(EXIT_FAILURE, NULL); 57 58 puts("Status: 200 OK\r"); 59 puts("Content-Type: text/html\r"); 60 puts("\r"); 61 printf("Hello, world: %" PRId64 "\n", hits); 62 return(EXIT_SUCCESS); 63 }
gcc -I/usr/local/include -static -o database-capsicum database-capsicum.c -L/usr/local/lib -lksql -lsqlite3