summaryrefslogtreecommitdiffstats
path: root/comm/third_party/botan/src/cli/sandbox.cpp
blob: 6ac8007af2e47456035fab83424d834319bd1b09 (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
* (C) 2019 David Carlier <devnexen@gmail.com>
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "sandbox.h"
#include <botan/mem_ops.h>

#if defined(BOTAN_TARGET_OS_HAS_PLEDGE)
  #include <unistd.h>
#elif defined(BOTAN_TARGET_OS_HAS_CAP_ENTER)
  #include <sys/capsicum.h>
  #include <unistd.h>
#elif defined(BOTAN_TARGET_OS_HAS_SETPPRIV)
  #include <priv.h>
#endif

namespace Botan_CLI {

#if defined(BOTAN_TARGET_OS_HAS_SETPPRIV)
struct SandboxPrivDelete {
  void operator()(priv_set_t *ps)
    {
  ::priv_emptyset(ps);
  ::priv_freeset(ps);
    }
};
#endif

Sandbox::Sandbox()
   {
#if defined(BOTAN_TARGET_OS_HAS_PLEDGE)
   m_name = "pledge";
#elif defined(BOTAN_TARGET_OS_HAS_CAP_ENTER)
   m_name = "capsicum";
#elif defined(BOTAN_TARGET_OS_HAS_SETPPRIV)
   m_name = "privilege";
#else
   m_name = "<none>";
#endif
   }

bool Sandbox::init()
   {
   Botan::initialize_allocator();

#if defined(BOTAN_TARGET_OS_HAS_PLEDGE)
   const static char *opts = "stdio rpath inet error";
   return (::pledge(opts, nullptr) == 0);
#elif defined(BOTAN_TARGET_OS_HAS_CAP_ENTER)
   cap_rights_t wt, rd;

   if (::cap_rights_init(&wt, CAP_READ, CAP_WRITE) == nullptr)
      {
      return false;
      }

   if (::cap_rights_init(&rd, CAP_FCNTL, CAP_EVENT, CAP_READ) == nullptr)
      {
      return false;
      }

   if (::cap_rights_limit(STDOUT_FILENO, &wt) == -1)
      {
      return false;
      }

   if (::cap_rights_limit(STDERR_FILENO, &wt) == -1)
      {
      return false;
      }

   if (::cap_rights_limit(STDIN_FILENO, &rd) == -1)
      {
      return false;
      }

   return (::cap_enter() == 0);
#elif defined(BOTAN_TARGET_OS_HAS_SETPPRIV)
   priv_set_t *tmp;
   std::unique_ptr<priv_set_t, SandboxPrivDelete> ps;
   const char *const priv_perms[] = {
	   PRIV_PROC_FORK,
	   PRIV_PROC_EXEC,
	   PRIV_PROC_INFO,
	   PRIV_PROC_SESSION,
   };

   if ((tmp = ::priv_allocset()) == nullptr)
      {
      return false;
      }

   ps = std::unique_ptr<priv_set_t, SandboxPrivDelete>(tmp);
   ::priv_basicset(ps.get());

   for (auto perm: priv_perms)
   {
     if (::priv_delset(ps.get(), perm) == -1)
     {
        return false;
     }
   }

   return true;
#else
   return true;
#endif
   }

Sandbox::~Sandbox()
   {
   }
}