jail.c 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823
  1. /*
  2. * Copyright (C) 2015 John Crispin <blogic@openwrt.org>
  3. * Copyright (C) 2020 Daniel Golle <daniel@makrotopia.org>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU Lesser General Public License version 2.1
  7. * as published by the Free Software Foundation
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. */
  14. #define _GNU_SOURCE
  15. #include <sys/mount.h>
  16. #include <sys/prctl.h>
  17. #include <sys/wait.h>
  18. #include <sys/types.h>
  19. #include <sys/time.h>
  20. #include <sys/resource.h>
  21. #include <sys/stat.h>
  22. #include <sys/sysmacros.h>
  23. /* musl only defined 15 limit types, make sure all 16 are supported */
  24. #ifndef RLIMIT_RTTIME
  25. #define RLIMIT_RTTIME 15
  26. #undef RLIMIT_NLIMITS
  27. #define RLIMIT_NLIMITS 16
  28. #undef RLIM_NLIMITS
  29. #define RLIM_NLIMITS 16
  30. #endif
  31. #include <stdlib.h>
  32. #include <unistd.h>
  33. #include <errno.h>
  34. #include <pwd.h>
  35. #include <grp.h>
  36. #include <string.h>
  37. #include <fcntl.h>
  38. #include <sched.h>
  39. #include <linux/filter.h>
  40. #include <linux/limits.h>
  41. #include <linux/nsfs.h>
  42. #include <linux/securebits.h>
  43. #include <signal.h>
  44. #include <inttypes.h>
  45. #include "capabilities.h"
  46. #include "elf.h"
  47. #include "fs.h"
  48. #include "jail.h"
  49. #include "log.h"
  50. #include "seccomp-oci.h"
  51. #include "cgroups.h"
  52. #include <libubox/utils.h>
  53. #include <libubox/blobmsg.h>
  54. #include <libubox/blobmsg_json.h>
  55. #include <libubox/list.h>
  56. #include <libubox/vlist.h>
  57. #include <libubox/uloop.h>
  58. #include <libubus.h>
  59. #ifndef CLONE_NEWCGROUP
  60. #define CLONE_NEWCGROUP 0x02000000
  61. #endif
  62. #define STACK_SIZE (1024 * 1024)
  63. #define OPT_ARGS "S:C:n:h:r:w:d:psulocU:G:NR:fFO:T:EyJ:i"
  64. #define OCI_VERSION_STRING "1.0.2"
  65. struct hook_execvpe {
  66. char *file;
  67. char **argv;
  68. char **envp;
  69. int timeout;
  70. };
  71. struct sysctl_val {
  72. char *entry;
  73. char *value;
  74. };
  75. struct mknod_args {
  76. char *path;
  77. mode_t mode;
  78. dev_t dev;
  79. uid_t uid;
  80. gid_t gid;
  81. };
  82. static struct {
  83. char *name;
  84. char *hostname;
  85. char **jail_argv;
  86. char *cwd;
  87. char *seccomp;
  88. struct sock_fprog *ociseccomp;
  89. char *capabilities;
  90. struct jail_capset capset;
  91. char *user;
  92. char *group;
  93. char *extroot;
  94. char *overlaydir;
  95. char *tmpoverlaysize;
  96. char **envp;
  97. char *uidmap;
  98. char *gidmap;
  99. struct sysctl_val **sysctl;
  100. int no_new_privs;
  101. int namespace;
  102. struct {
  103. int pid;
  104. int net;
  105. int ns;
  106. int ipc;
  107. int uts;
  108. int user;
  109. int cgroup;
  110. #ifdef CLONE_NEWTIME
  111. int time;
  112. #endif
  113. } setns;
  114. int procfs;
  115. int ronly;
  116. int sysfs;
  117. int console;
  118. int pw_uid;
  119. int pw_gid;
  120. int gr_gid;
  121. gid_t *additional_gids;
  122. size_t num_additional_gids;
  123. mode_t umask;
  124. bool set_umask;
  125. int require_jail;
  126. struct {
  127. struct hook_execvpe **createRuntime;
  128. struct hook_execvpe **createContainer;
  129. struct hook_execvpe **startContainer;
  130. struct hook_execvpe **poststart;
  131. struct hook_execvpe **poststop;
  132. } hooks;
  133. struct rlimit *rlimits[RLIM_NLIMITS];
  134. int oom_score_adj;
  135. bool set_oom_score_adj;
  136. struct mknod_args **devices;
  137. char *ocibundle;
  138. bool immediately;
  139. struct blob_attr *annotations;
  140. } opts;
  141. static struct blob_buf ocibuf;
  142. extern int pivot_root(const char *new_root, const char *put_old);
  143. int debug = 0;
  144. static char child_stack[STACK_SIZE];
  145. static struct ubus_context *parent_ctx;
  146. int console_fd;
  147. static inline bool has_namespaces(void)
  148. {
  149. return ((opts.setns.pid != -1) ||
  150. (opts.setns.net != -1) ||
  151. (opts.setns.ns != -1) ||
  152. (opts.setns.ipc != -1) ||
  153. (opts.setns.uts != -1) ||
  154. (opts.setns.user != -1) ||
  155. (opts.setns.cgroup != -1) ||
  156. #ifdef CLONE_NEWTIME
  157. (opts.setns.time != -1) ||
  158. #endif
  159. opts.namespace);
  160. }
  161. static void free_hooklist(struct hook_execvpe **hooklist)
  162. {
  163. struct hook_execvpe *cur;
  164. char **tmp;
  165. if (!hooklist)
  166. return;
  167. cur = *hooklist;
  168. while (cur) {
  169. free(cur->file);
  170. tmp = cur->argv;
  171. while (tmp)
  172. free(*(tmp++));
  173. free(cur->argv);
  174. tmp = cur->envp;
  175. while (tmp)
  176. free(*(tmp++));
  177. free(cur->envp);
  178. free(cur++);
  179. }
  180. free(hooklist);
  181. }
  182. static void free_sysctl(void) {
  183. struct sysctl_val *cur;
  184. cur = *opts.sysctl;
  185. while (cur) {
  186. free(cur->entry);
  187. free(cur->value);
  188. free(cur++);
  189. }
  190. free(opts.sysctl);
  191. }
  192. static void free_devices(void) {
  193. struct mknod_args **cur;
  194. if (!opts.devices)
  195. return;
  196. cur = opts.devices;
  197. while (*cur) {
  198. free((*cur)->path);
  199. free(*(cur++));
  200. }
  201. free(opts.devices);
  202. }
  203. static void free_rlimits(void) {
  204. int type;
  205. for (type = 0; type < RLIM_NLIMITS; ++type)
  206. free(opts.rlimits[type]);
  207. }
  208. static void free_opts(bool parent) {
  209. char **tmp;
  210. /* we need to keep argv, envp and seccomp filter in child */
  211. if (parent) { /* parent-only */
  212. if (opts.ociseccomp) {
  213. free(opts.ociseccomp->filter);
  214. free(opts.ociseccomp);
  215. }
  216. tmp = opts.jail_argv;
  217. while(tmp)
  218. free(*(tmp++));
  219. free(opts.jail_argv);
  220. tmp = opts.envp;
  221. while (tmp)
  222. free(*(tmp++));
  223. free(opts.envp);
  224. } else { /* child-only */
  225. if (opts.ocibundle)
  226. cgroups_free();
  227. }
  228. free_rlimits();
  229. free_sysctl();
  230. free_devices();
  231. free(opts.hostname);
  232. free(opts.cwd);
  233. free(opts.extroot);
  234. free(opts.uidmap);
  235. free(opts.gidmap);
  236. free(opts.annotations);
  237. free(opts.ocibundle);
  238. free_hooklist(opts.hooks.createRuntime);
  239. free_hooklist(opts.hooks.createContainer);
  240. free_hooklist(opts.hooks.startContainer);
  241. free_hooklist(opts.hooks.poststart);
  242. free_hooklist(opts.hooks.poststop);
  243. }
  244. static int mount_overlay(char *jail_root, char *overlaydir) {
  245. char *upperdir, *workdir, *optsstr, *upperetc, *upperresolvconf;
  246. const char mountoptsformat[] = "lowerdir=%s,upperdir=%s,workdir=%s";
  247. int ret = -1, fd;
  248. if (asprintf(&upperdir, "%s%s", overlaydir, "/upper") < 0)
  249. goto out;
  250. if (asprintf(&workdir, "%s%s", overlaydir, "/work") < 0)
  251. goto upper_printf;
  252. if (asprintf(&optsstr, mountoptsformat, jail_root, upperdir, workdir) < 0)
  253. goto work_printf;
  254. if (mkdir_p(upperdir, 0755) || mkdir_p(workdir, 0755))
  255. goto opts_printf;
  256. /*
  257. * make sure /etc/resolv.conf exists in overlay and is owned by jail userns root
  258. * this is to work-around a bug in overlayfs described in the overlayfs-userns
  259. * patch:
  260. * 3. modification of a file 'hithere' which is in l but not yet
  261. * in u, and which is not owned by T, is not allowed, even if
  262. * writes to u are allowed. This may be a bug in overlayfs,
  263. * but it is safe behavior.
  264. */
  265. if (asprintf(&upperetc, "%s/etc", upperdir) < 0)
  266. goto opts_printf;
  267. if (mkdir_p(upperetc, 0755))
  268. goto upper_etc_printf;
  269. if (asprintf(&upperresolvconf, "%s/resolv.conf", upperetc) < 0)
  270. goto upper_etc_printf;
  271. fd = creat(upperresolvconf, 0644);
  272. if (fd == -1) {
  273. ERROR("creat(%s) failed: %m\n", upperresolvconf);
  274. goto upper_resolvconf_printf;
  275. }
  276. close(fd);
  277. DEBUG("mount -t overlay %s %s (%s)\n", jail_root, jail_root, optsstr);
  278. if (mount(jail_root, jail_root, "overlay", MS_NOATIME, optsstr))
  279. goto opts_printf;
  280. ret = 0;
  281. upper_resolvconf_printf:
  282. free(upperresolvconf);
  283. upper_etc_printf:
  284. free(upperetc);
  285. opts_printf:
  286. free(optsstr);
  287. work_printf:
  288. free(workdir);
  289. upper_printf:
  290. free(upperdir);
  291. out:
  292. return ret;
  293. }
  294. static void pass_console(int console_fd)
  295. {
  296. struct ubus_context *child_ctx = ubus_connect(NULL);
  297. static struct blob_buf req;
  298. uint32_t id;
  299. if (!child_ctx)
  300. return;
  301. blob_buf_init(&req, 0);
  302. blobmsg_add_string(&req, "name", opts.name);
  303. if (ubus_lookup_id(child_ctx, "container", &id) ||
  304. ubus_invoke_fd(child_ctx, id, "console_set", req.head, NULL, NULL, 3000, console_fd))
  305. INFO("ubus request failed\n");
  306. else
  307. close(console_fd);
  308. blob_buf_free(&req);
  309. ubus_free(child_ctx);
  310. }
  311. static int create_dev_console(const char *jail_root)
  312. {
  313. char *console_fname;
  314. char dev_console_path[PATH_MAX];
  315. int slave_console_fd;
  316. /* Open UNIX/98 virtual console */
  317. console_fd = posix_openpt(O_RDWR | O_NOCTTY);
  318. if (console_fd == -1)
  319. return -1;
  320. console_fname = ptsname(console_fd);
  321. DEBUG("got console fd %d and PTS client name %s\n", console_fd, console_fname);
  322. if (!console_fname)
  323. goto no_console;
  324. grantpt(console_fd);
  325. unlockpt(console_fd);
  326. /* pass PTY master to procd */
  327. pass_console(console_fd);
  328. /* mount-bind PTY slave to /dev/console in jail */
  329. snprintf(dev_console_path, sizeof(dev_console_path), "%s/dev/console", jail_root);
  330. close(creat(dev_console_path, 0620));
  331. if (mount(console_fname, dev_console_path, NULL, MS_BIND, NULL))
  332. goto no_console;
  333. /* use PTY slave for stdio */
  334. slave_console_fd = open(console_fname, O_RDWR); /* | O_NOCTTY */
  335. dup2(slave_console_fd, 0);
  336. dup2(slave_console_fd, 1);
  337. dup2(slave_console_fd, 2);
  338. close(slave_console_fd);
  339. INFO("using guest console %s\n", console_fname);
  340. return 0;
  341. no_console:
  342. close(console_fd);
  343. return 1;
  344. }
  345. static int hook_running = 0;
  346. static int hook_return_code = 0;
  347. static struct hook_execvpe **current_hook = NULL;
  348. typedef void (*hook_return_handler)(void);
  349. static hook_return_handler hook_return_cb = NULL;
  350. static void hook_process_timeout_cb(struct uloop_timeout *t);
  351. static struct uloop_timeout hook_process_timeout = {
  352. .cb = hook_process_timeout_cb,
  353. };
  354. static void run_hooklist(void);
  355. static void hook_process_handler(struct uloop_process *c, int ret)
  356. {
  357. uloop_timeout_cancel(&hook_process_timeout);
  358. if (WIFEXITED(ret)) {
  359. hook_return_code = WEXITSTATUS(ret);
  360. if (hook_return_code)
  361. ERROR("hook (%d) exited with exit: %d\n", c->pid, hook_return_code);
  362. else
  363. DEBUG("hook (%d) exited with exit: %d\n", c->pid, hook_return_code);
  364. } else {
  365. hook_return_code = WTERMSIG(ret);
  366. ERROR("hook (%d) exited with signal: %d\n", c->pid, hook_return_code);
  367. }
  368. hook_running = 0;
  369. ++current_hook;
  370. run_hooklist();
  371. }
  372. static struct uloop_process hook_process = {
  373. .cb = hook_process_handler,
  374. };
  375. static void hook_process_timeout_cb(struct uloop_timeout *t)
  376. {
  377. DEBUG("hook process failed to stop, sending SIGKILL\n");
  378. kill(hook_process.pid, SIGKILL);
  379. }
  380. static void run_hooklist(void)
  381. {
  382. struct hook_execvpe *hook = *current_hook;
  383. struct stat s;
  384. if (!hook)
  385. hook_return_cb();
  386. DEBUG("executing hook %s\n", hook->file);
  387. if (stat(hook->file, &s))
  388. hook_process_handler(&hook_process, ENOENT);
  389. if (!((unsigned long)s.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
  390. hook_process_handler(&hook_process, EPERM);
  391. if (!((unsigned long)s.st_mode & (S_IRUSR | S_IRGRP | S_IROTH)))
  392. hook_process_handler(&hook_process, EPERM);
  393. hook_running = 1;
  394. hook_process.pid = fork();
  395. if (hook_process.pid == 0) {
  396. /* child */
  397. execve(hook->file, hook->argv, hook->envp);
  398. ERROR("execve error %m\n");
  399. _exit(errno);
  400. } else if (hook_process.pid < 0) {
  401. /* fork error */
  402. ERROR("hook fork error\n");
  403. hook_running = 0;
  404. hook_process_handler(&hook_process, errno);
  405. }
  406. /* parent */
  407. uloop_process_add(&hook_process);
  408. if (hook->timeout > 0)
  409. uloop_timeout_set(&hook_process_timeout, 1000 * hook->timeout);
  410. uloop_run();
  411. if (hook_running) {
  412. DEBUG("uloop interrupted, killing jail process\n");
  413. kill(hook_process.pid, SIGTERM);
  414. uloop_timeout_set(&hook_process_timeout, 1000);
  415. uloop_run();
  416. }
  417. }
  418. static void run_hooks(struct hook_execvpe **hooklist, hook_return_handler return_cb)
  419. {
  420. if (!hooklist)
  421. return_cb();
  422. current_hook = hooklist;
  423. hook_return_cb = return_cb;
  424. run_hooklist();
  425. }
  426. static int apply_sysctl(const char *jail_root)
  427. {
  428. struct sysctl_val **cur;
  429. char *procdir, *fname;
  430. int f;
  431. if (!opts.sysctl)
  432. return 0;
  433. asprintf(&procdir, "%s/proc", jail_root);
  434. if (!procdir)
  435. return ENOMEM;
  436. mkdir(procdir, 0700);
  437. if (mount("proc", procdir, "proc", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, 0))
  438. return EPERM;
  439. cur = opts.sysctl;
  440. while (*cur) {
  441. asprintf(&fname, "%s/sys/%s", procdir, (*cur)->entry);
  442. if (!fname)
  443. return ENOMEM;
  444. DEBUG("sysctl: writing '%s' to %s\n", (*cur)->value, fname);
  445. f = open(fname, O_WRONLY);
  446. if (f == -1) {
  447. ERROR("sysctl: can't open %s\n", fname);
  448. return errno;
  449. }
  450. write(f, (*cur)->value, strlen((*cur)->value));
  451. free(fname);
  452. close(f);
  453. ++cur;
  454. }
  455. umount(procdir);
  456. rmdir(procdir);
  457. free(procdir);
  458. return 0;
  459. }
  460. /* glibc defines makedev calling a function. make sure it's a pure macro */
  461. #if defined(__GLIBC__)
  462. #undef makedev
  463. /* from musl's sys/sysmacros.h */
  464. #define makedev(x,y) ( \
  465. (((x)&0xfffff000ULL) << 32) | \
  466. (((x)&0x00000fffULL) << 8) | \
  467. (((y)&0xffffff00ULL) << 12) | \
  468. (((y)&0x000000ffULL)) )
  469. #endif
  470. static struct mknod_args default_devices[] = {
  471. { .path = "/dev/null", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH), .dev = makedev(1, 3) },
  472. { .path = "/dev/zero", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH), .dev = makedev(1, 5) },
  473. { .path = "/dev/full", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH), .dev = makedev(1, 7) },
  474. { .path = "/dev/random", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH), .dev = makedev(1, 8) },
  475. { .path = "/dev/urandom", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH), .dev = makedev(1, 9) },
  476. { .path = "/dev/tty", .mode = (S_IFCHR|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP), .dev = makedev(5, 0), .gid = 5 },
  477. { 0 },
  478. };
  479. static int create_devices(void)
  480. {
  481. struct mknod_args **cur, *curdef;
  482. if (!opts.devices)
  483. goto only_default_devices;
  484. cur = opts.devices;
  485. while (*cur) {
  486. DEBUG("creating %s (mode=%08o)\n", (*cur)->path, (*cur)->mode);
  487. if (mknod((*cur)->path, (*cur)->mode, (*cur)->dev))
  488. return errno;
  489. if (((*cur)->uid || (*cur)->gid) &&
  490. chown((*cur)->path, (*cur)->uid, (*cur)->gid))
  491. return errno;
  492. ++cur;
  493. }
  494. only_default_devices:
  495. curdef = default_devices;
  496. while(curdef->path) {
  497. DEBUG("creating %s (mode=%08o)\n", curdef->path, curdef->mode);
  498. if (mknod(curdef->path, curdef->mode, curdef->dev)) {
  499. ++curdef;
  500. continue; /* may already exist, eg. due to a bind-mount */
  501. }
  502. if ((curdef->uid || curdef->gid) &&
  503. chown(curdef->path, curdef->uid, curdef->gid))
  504. return errno;
  505. ++curdef;
  506. }
  507. /* Dev symbolic links as defined in OCI spec */
  508. symlink("/dev/pts/ptmx", "/dev/ptmx");
  509. symlink("/proc/self/fd", "/dev/fd");
  510. symlink("/proc/self/fd/0", "/dev/stdin");
  511. symlink("/proc/self/fd/1", "/dev/stdout");
  512. symlink("/proc/self/fd/2", "/dev/stderr");
  513. return 0;
  514. }
  515. static char jail_root[] = "/tmp/ujail-XXXXXX";
  516. static char tmpovdir[] = "/tmp/ujail-overlay-XXXXXX";
  517. static mode_t old_umask;
  518. static void enter_jail_fs(void);
  519. static int build_jail_fs(void)
  520. {
  521. char *overlaydir = NULL;
  522. old_umask = umask(0);
  523. if (mkdtemp(jail_root) == NULL) {
  524. ERROR("mkdtemp(%s) failed: %m\n", jail_root);
  525. return -1;
  526. }
  527. if (apply_sysctl(jail_root)) {
  528. ERROR("failed to apply sysctl values\n");
  529. return -1;
  530. }
  531. /* oldroot can't be MS_SHARED else pivot_root() fails */
  532. if (mount("none", "/", NULL, MS_REC|MS_PRIVATE, NULL)) {
  533. ERROR("private mount failed %m\n");
  534. return -1;
  535. }
  536. if (opts.extroot) {
  537. if (mount(opts.extroot, jail_root, NULL, MS_BIND, NULL)) {
  538. ERROR("extroot mount failed %m\n");
  539. return -1;
  540. }
  541. } else {
  542. if (mount("tmpfs", jail_root, "tmpfs", MS_NOATIME, "mode=0755")) {
  543. ERROR("tmpfs mount failed %m\n");
  544. return -1;
  545. }
  546. }
  547. if (opts.tmpoverlaysize) {
  548. char mountoptsstr[] = "mode=0755,size=XXXXXXXX";
  549. snprintf(mountoptsstr, sizeof(mountoptsstr),
  550. "mode=0755,size=%s", opts.tmpoverlaysize);
  551. if (mkdtemp(tmpovdir) == NULL) {
  552. ERROR("mkdtemp(%s) failed: %m\n", jail_root);
  553. return -1;
  554. }
  555. if (mount("tmpfs", tmpovdir, "tmpfs", MS_NOATIME,
  556. mountoptsstr)) {
  557. ERROR("failed to mount tmpfs for overlay (size=%s)\n", opts.tmpoverlaysize);
  558. return -1;
  559. }
  560. overlaydir = tmpovdir;
  561. }
  562. if (opts.overlaydir)
  563. overlaydir = opts.overlaydir;
  564. if (overlaydir)
  565. mount_overlay(jail_root, overlaydir);
  566. if (chdir(jail_root)) {
  567. ERROR("chdir(%s) (jail_root) failed: %m\n", jail_root);
  568. return -1;
  569. }
  570. if (mount_all(jail_root)) {
  571. ERROR("mount_all() failed\n");
  572. return -1;
  573. }
  574. if (opts.console)
  575. create_dev_console(jail_root);
  576. /* make sure /etc/resolv.conf exists if in new network namespace */
  577. if (opts.namespace & CLONE_NEWNET) {
  578. char jailetc[PATH_MAX], jaillink[PATH_MAX];
  579. snprintf(jailetc, PATH_MAX, "%s/etc", jail_root);
  580. mkdir_p(jailetc, 0755);
  581. snprintf(jaillink, PATH_MAX, "%s/etc/resolv.conf", jail_root);
  582. if (overlaydir)
  583. unlink(jaillink);
  584. symlink("../dev/resolv.conf.d/resolv.conf.auto", jaillink);
  585. }
  586. run_hooks(opts.hooks.createContainer, enter_jail_fs);
  587. return 0;
  588. }
  589. static void post_jail_fs(void);
  590. static void enter_jail_fs(void)
  591. {
  592. char dirbuf[sizeof(jail_root) + 4];
  593. snprintf(dirbuf, sizeof(dirbuf), "%s/old", jail_root);
  594. mkdir(dirbuf, 0755);
  595. if (pivot_root(jail_root, dirbuf) == -1) {
  596. ERROR("pivot_root(%s, %s) failed: %m\n", jail_root, dirbuf);
  597. exit(-1);
  598. }
  599. if (chdir("/")) {
  600. ERROR("chdir(/) (after pivot_root) failed: %m\n");
  601. exit(-1);
  602. }
  603. snprintf(dirbuf, sizeof(dirbuf), "/old%s", jail_root);
  604. umount2(dirbuf, MNT_DETACH);
  605. rmdir(dirbuf);
  606. if (opts.tmpoverlaysize) {
  607. char tmpdirbuf[sizeof(tmpovdir) + 4];
  608. snprintf(tmpdirbuf, sizeof(tmpdirbuf), "/old%s", tmpovdir);
  609. umount2(tmpdirbuf, MNT_DETACH);
  610. rmdir(tmpdirbuf);
  611. }
  612. umount2("/old", MNT_DETACH);
  613. rmdir("/old");
  614. if (create_devices()) {
  615. ERROR("create_devices() failed\n");
  616. exit(-1);
  617. }
  618. if (opts.ronly)
  619. mount(NULL, "/", NULL, MS_REMOUNT | MS_BIND | MS_RDONLY, 0);
  620. umask(old_umask);
  621. post_jail_fs();
  622. }
  623. static int write_uid_gid_map(pid_t child_pid, bool gidmap, char *mapstr)
  624. {
  625. int map_file;
  626. char map_path[64];
  627. if (snprintf(map_path, sizeof(map_path), "/proc/%d/%s",
  628. child_pid, gidmap?"gid_map":"uid_map") < 0)
  629. return -1;
  630. if ((map_file = open(map_path, O_WRONLY)) == -1)
  631. return -1;
  632. if (dprintf(map_file, "%s", mapstr)) {
  633. close(map_file);
  634. return -1;
  635. }
  636. close(map_file);
  637. free(mapstr);
  638. return 0;
  639. }
  640. static int write_single_uid_gid_map(pid_t child_pid, bool gidmap, int id)
  641. {
  642. int map_file;
  643. char map_path[64];
  644. const char *map_format = "%d %d %d\n";
  645. if (snprintf(map_path, sizeof(map_path), "/proc/%d/%s",
  646. child_pid, gidmap?"gid_map":"uid_map") < 0)
  647. return -1;
  648. if ((map_file = open(map_path, O_WRONLY)) == -1)
  649. return -1;
  650. if (dprintf(map_file, map_format, 0, id, 1) == -1) {
  651. close(map_file);
  652. return -1;
  653. }
  654. close(map_file);
  655. return 0;
  656. }
  657. static int write_setgroups(pid_t child_pid, bool allow)
  658. {
  659. int setgroups_file;
  660. char setgroups_path[64];
  661. if (snprintf(setgroups_path, sizeof(setgroups_path), "/proc/%d/setgroups",
  662. child_pid) < 0) {
  663. return -1;
  664. }
  665. if ((setgroups_file = open(setgroups_path, O_WRONLY)) == -1) {
  666. return -1;
  667. }
  668. if (dprintf(setgroups_file, "%s", allow?"allow":"deny") == -1) {
  669. close(setgroups_file);
  670. return -1;
  671. }
  672. close(setgroups_file);
  673. return 0;
  674. }
  675. static void get_jail_user(int *user, int *user_gid, int *gr_gid)
  676. {
  677. struct passwd *p = NULL;
  678. struct group *g = NULL;
  679. if (opts.user) {
  680. p = getpwnam(opts.user);
  681. if (!p) {
  682. ERROR("failed to get uid/gid for user %s: %d (%s)\n",
  683. opts.user, errno, strerror(errno));
  684. exit(EXIT_FAILURE);
  685. }
  686. *user = p->pw_uid;
  687. *user_gid = p->pw_gid;
  688. } else {
  689. *user = -1;
  690. *user_gid = -1;
  691. }
  692. if (opts.group) {
  693. g = getgrnam(opts.group);
  694. if (!g) {
  695. ERROR("failed to get gid for group %s: %m\n", opts.group);
  696. exit(EXIT_FAILURE);
  697. }
  698. *gr_gid = g->gr_gid;
  699. } else {
  700. *gr_gid = -1;
  701. }
  702. };
  703. static void set_jail_user(int pw_uid, int user_gid, int gr_gid)
  704. {
  705. if (opts.user && (user_gid != -1) && initgroups(opts.user, user_gid)) {
  706. ERROR("failed to initgroups() for user %s: %m\n", opts.user);
  707. exit(EXIT_FAILURE);
  708. }
  709. if ((gr_gid != -1) && setregid(gr_gid, gr_gid)) {
  710. ERROR("failed to set group id %d: %m\n", gr_gid);
  711. exit(EXIT_FAILURE);
  712. }
  713. if ((pw_uid != -1) && setreuid(pw_uid, pw_uid)) {
  714. ERROR("failed to set user id %d: %m\n", pw_uid);
  715. exit(EXIT_FAILURE);
  716. }
  717. }
  718. static int apply_rlimits(void)
  719. {
  720. int resource;
  721. for (resource = 0; resource < RLIM_NLIMITS; ++resource) {
  722. if (opts.rlimits[resource])
  723. DEBUG("applying limits to resource %u\n", resource);
  724. if (opts.rlimits[resource] &&
  725. setrlimit(resource, opts.rlimits[resource]))
  726. return errno;
  727. }
  728. return 0;
  729. }
  730. #define MAX_ENVP 8
  731. static char** build_envp(const char *seccomp, char **ocienvp)
  732. {
  733. static char *envp[MAX_ENVP];
  734. static char preload_var[PATH_MAX];
  735. static char seccomp_var[PATH_MAX];
  736. static char debug_var[] = "LD_DEBUG=all";
  737. static char container_var[] = "container=ujail";
  738. const char *preload_lib = find_lib("libpreload-seccomp.so");
  739. char **addenv;
  740. int count = 0;
  741. if (seccomp && !preload_lib) {
  742. ERROR("failed to add preload-lib to env\n");
  743. return NULL;
  744. }
  745. if (seccomp) {
  746. snprintf(seccomp_var, sizeof(seccomp_var), "SECCOMP_FILE=%s", seccomp);
  747. envp[count++] = seccomp_var;
  748. snprintf(preload_var, sizeof(preload_var), "LD_PRELOAD=%s", preload_lib);
  749. envp[count++] = preload_var;
  750. }
  751. envp[count++] = container_var;
  752. if (debug > 1)
  753. envp[count++] = debug_var;
  754. addenv = ocienvp;
  755. while (addenv && *addenv) {
  756. envp[count++] = *(addenv++);
  757. if (count >= MAX_ENVP) {
  758. ERROR("environment limited to %d extra records, truncating\n", MAX_ENVP);
  759. break;
  760. }
  761. }
  762. return envp;
  763. }
  764. static void usage(void)
  765. {
  766. fprintf(stderr, "ujail <options> -- <binary> <params ...>\n");
  767. fprintf(stderr, " -d <num>\tshow debug log (increase num to increase verbosity)\n");
  768. fprintf(stderr, " -S <file>\tseccomp filter config\n");
  769. fprintf(stderr, " -C <file>\tcapabilities drop config\n");
  770. fprintf(stderr, " -c\t\tset PR_SET_NO_NEW_PRIVS\n");
  771. fprintf(stderr, " -n <name>\tthe name of the jail\n");
  772. fprintf(stderr, "namespace jail options:\n");
  773. fprintf(stderr, " -h <hostname>\tchange the hostname of the jail\n");
  774. fprintf(stderr, " -N\t\tjail has network namespace\n");
  775. fprintf(stderr, " -f\t\tjail has user namespace\n");
  776. fprintf(stderr, " -F\t\tjail has cgroups namespace\n");
  777. fprintf(stderr, " -r <file>\treadonly files that should be staged\n");
  778. fprintf(stderr, " -w <file>\twriteable files that should be staged\n");
  779. fprintf(stderr, " -p\t\tjail has /proc\n");
  780. fprintf(stderr, " -s\t\tjail has /sys\n");
  781. fprintf(stderr, " -l\t\tjail has /dev/log\n");
  782. fprintf(stderr, " -u\t\tjail has a ubus socket\n");
  783. fprintf(stderr, " -U <name>\tuser to run jailed process\n");
  784. fprintf(stderr, " -G <name>\tgroup to run jailed process\n");
  785. fprintf(stderr, " -o\t\tremont jail root (/) read only\n");
  786. fprintf(stderr, " -R <dir>\texternal jail rootfs (system container)\n");
  787. fprintf(stderr, " -O <dir>\tdirectory for r/w overlayfs\n");
  788. fprintf(stderr, " -T <size>\tuse tmpfs r/w overlayfs with <size>\n");
  789. fprintf(stderr, " -E\t\tfail if jail cannot be setup\n");
  790. fprintf(stderr, " -y\t\tprovide jail console\n");
  791. fprintf(stderr, " -J <dir>\tcreate container from OCI bundle\n");
  792. fprintf(stderr, " -j\t\tstart container immediately\n");
  793. fprintf(stderr, "\nWarning: by default root inside the jail is the same\n\
  794. and he has the same powers as root outside the jail,\n\
  795. thus he can escape the jail and/or break stuff.\n\
  796. Please use seccomp/capabilities (-S/-C) to restrict his powers\n\n\
  797. If you use none of the namespace jail options,\n\
  798. ujail will not use namespace/build a jail,\n\
  799. and will only drop capabilities/apply seccomp filter.\n\n");
  800. }
  801. static int* get_namespace_fd(const unsigned int nstype)
  802. {
  803. switch (nstype) {
  804. case CLONE_NEWPID:
  805. return &opts.setns.pid;
  806. case CLONE_NEWNET:
  807. return &opts.setns.net;
  808. case CLONE_NEWNS:
  809. return &opts.setns.ns;
  810. case CLONE_NEWIPC:
  811. return &opts.setns.ipc;
  812. case CLONE_NEWUTS:
  813. return &opts.setns.uts;
  814. case CLONE_NEWUSER:
  815. return &opts.setns.user;
  816. case CLONE_NEWCGROUP:
  817. return &opts.setns.cgroup;
  818. #ifdef CLONE_NEWTIME
  819. case CLONE_NEWTIME:
  820. return &opts.setns.time;
  821. #endif
  822. default:
  823. return NULL;
  824. }
  825. }
  826. static int setns_open(unsigned long nstype)
  827. {
  828. int *fd = get_namespace_fd(nstype);
  829. if (!*fd)
  830. return EFAULT;
  831. if (*fd == -1)
  832. return 0;
  833. if (setns(*fd, nstype) == -1) {
  834. close(*fd);
  835. return errno;
  836. }
  837. close(*fd);
  838. return 0;
  839. }
  840. static int jail_running = 0;
  841. static int jail_return_code = 0;
  842. static void jail_process_timeout_cb(struct uloop_timeout *t);
  843. static struct uloop_timeout jail_process_timeout = {
  844. .cb = jail_process_timeout_cb,
  845. };
  846. static void poststop(void);
  847. static void jail_process_handler(struct uloop_process *c, int ret)
  848. {
  849. uloop_timeout_cancel(&jail_process_timeout);
  850. if (WIFEXITED(ret)) {
  851. jail_return_code = WEXITSTATUS(ret);
  852. INFO("jail (%d) exited with exit: %d\n", c->pid, jail_return_code);
  853. } else {
  854. jail_return_code = WTERMSIG(ret);
  855. INFO("jail (%d) exited with signal: %d\n", c->pid, jail_return_code);
  856. }
  857. jail_running = 0;
  858. poststop();
  859. }
  860. static struct uloop_process jail_process = {
  861. .cb = jail_process_handler,
  862. };
  863. static void jail_process_timeout_cb(struct uloop_timeout *t)
  864. {
  865. DEBUG("jail process failed to stop, sending SIGKILL\n");
  866. kill(jail_process.pid, SIGKILL);
  867. }
  868. static void jail_handle_signal(int signo)
  869. {
  870. if (hook_running) {
  871. DEBUG("forwarding signal %d to the hook process\n", signo);
  872. kill(hook_process.pid, signo);
  873. }
  874. if (jail_running) {
  875. DEBUG("forwarding signal %d to the jailed process\n", signo);
  876. kill(jail_process.pid, signo);
  877. }
  878. }
  879. static void signals_init(void)
  880. {
  881. int i;
  882. sigset_t sigmask;
  883. sigfillset(&sigmask);
  884. for (i = 0; i < _NSIG; i++) {
  885. struct sigaction s = { 0 };
  886. if (!sigismember(&sigmask, i))
  887. continue;
  888. if ((i == SIGCHLD) || (i == SIGPIPE) || (i == SIGSEGV))
  889. continue;
  890. s.sa_handler = jail_handle_signal;
  891. sigaction(i, &s, NULL);
  892. }
  893. }
  894. static void pre_exec_jail(struct uloop_timeout *t);
  895. static struct uloop_timeout pre_exec_timeout = {
  896. .cb = pre_exec_jail,
  897. };
  898. int pipes[4];
  899. static int exec_jail(void *arg)
  900. {
  901. char buf[1];
  902. uloop_init();
  903. signals_init();
  904. close(pipes[0]);
  905. close(pipes[3]);
  906. setns_open(CLONE_NEWUSER);
  907. setns_open(CLONE_NEWNET);
  908. setns_open(CLONE_NEWNS);
  909. setns_open(CLONE_NEWIPC);
  910. setns_open(CLONE_NEWUTS);
  911. buf[0] = 'i';
  912. if (write(pipes[1], buf, 1) < 1) {
  913. ERROR("can't write to parent\n");
  914. return EXIT_FAILURE;
  915. }
  916. close(pipes[1]);
  917. if (read(pipes[2], buf, 1) < 1) {
  918. ERROR("can't read from parent\n");
  919. return EXIT_FAILURE;
  920. }
  921. if (buf[0] != 'O') {
  922. ERROR("parent had an error, child exiting\n");
  923. return EXIT_FAILURE;
  924. }
  925. if (opts.namespace & CLONE_NEWCGROUP)
  926. unshare(CLONE_NEWCGROUP);
  927. if ((opts.namespace & CLONE_NEWUSER) || (opts.setns.user != -1)) {
  928. if (setregid(0, 0) < 0) {
  929. ERROR("setgid\n");
  930. exit(EXIT_FAILURE);
  931. }
  932. if (setreuid(0, 0) < 0) {
  933. ERROR("setuid\n");
  934. exit(EXIT_FAILURE);
  935. }
  936. if (setgroups(0, NULL) < 0) {
  937. ERROR("setgroups\n");
  938. exit(EXIT_FAILURE);
  939. }
  940. }
  941. if (opts.namespace && opts.hostname && strlen(opts.hostname) > 0
  942. && sethostname(opts.hostname, strlen(opts.hostname))) {
  943. ERROR("sethostname(%s) failed: %m\n", opts.hostname);
  944. exit(EXIT_FAILURE);
  945. }
  946. uloop_timeout_add(&pre_exec_timeout);
  947. uloop_run();
  948. exit(-1);
  949. }
  950. static void pre_exec_jail(struct uloop_timeout *t)
  951. {
  952. if ((opts.namespace & CLONE_NEWNS) && build_jail_fs()) {
  953. ERROR("failed to build jail fs\n");
  954. exit(EXIT_FAILURE);
  955. } else {
  956. run_hooks(opts.hooks.createContainer, post_jail_fs);
  957. }
  958. }
  959. static void post_start_hook(void);
  960. static void post_jail_fs(void)
  961. {
  962. char buf[1];
  963. if (read(pipes[2], buf, 1) < 1) {
  964. ERROR("can't read from parent\n");
  965. exit(EXIT_FAILURE);
  966. }
  967. if (buf[0] != '!') {
  968. ERROR("parent had an error, child exiting\n");
  969. exit(EXIT_FAILURE);
  970. }
  971. close(pipes[2]);
  972. run_hooks(opts.hooks.startContainer, post_start_hook);
  973. }
  974. static void post_start_hook(void)
  975. {
  976. int pw_uid, pw_gid, gr_gid;
  977. if (prctl(PR_SET_SECUREBITS, SECBIT_NO_SETUID_FIXUP)) {
  978. ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
  979. exit(EXIT_FAILURE);
  980. }
  981. /* drop capabilities, retain those still needed to further setup jail */
  982. if (applyOCIcapabilities(opts.capset, (1LLU << CAP_SETGID) | (1LLU << CAP_SETUID) | (1LLU << CAP_SETPCAP)))
  983. exit(EXIT_FAILURE);
  984. /* use either cmdline-supplied user/group or uid/gid from OCI spec */
  985. get_jail_user(&pw_uid, &pw_gid, &gr_gid);
  986. set_jail_user(opts.pw_uid?:pw_uid, opts.pw_gid?:pw_gid, opts.gr_gid?:gr_gid);
  987. if (opts.additional_gids &&
  988. (setgroups(opts.num_additional_gids, opts.additional_gids) < 0)) {
  989. ERROR("setgroups failed: %m\n");
  990. exit(EXIT_FAILURE);
  991. }
  992. if (opts.set_umask)
  993. umask(opts.umask);
  994. if (prctl(PR_SET_SECUREBITS, 0)) {
  995. ERROR("prctl(PR_SET_SECUREBITS) failed: %m\n");
  996. exit(EXIT_FAILURE);
  997. }
  998. /* drop remaining capabilities to end up with specified sets */
  999. if (applyOCIcapabilities(opts.capset, 0))
  1000. exit(EXIT_FAILURE);
  1001. if (opts.no_new_privs && prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0)) {
  1002. ERROR("prctl(PR_SET_NO_NEW_PRIVS) failed: %m\n");
  1003. exit(EXIT_FAILURE);
  1004. }
  1005. char **envp = build_envp(opts.seccomp, opts.envp);
  1006. if (!envp)
  1007. exit(EXIT_FAILURE);
  1008. if (opts.cwd && chdir(opts.cwd))
  1009. exit(EXIT_FAILURE);
  1010. if (opts.ociseccomp && applyOCIlinuxseccomp(opts.ociseccomp))
  1011. exit(EXIT_FAILURE);
  1012. uloop_end();
  1013. free_opts(false);
  1014. INFO("exec-ing %s\n", *opts.jail_argv);
  1015. if (opts.envp) /* respect PATH if potentially set in ENV */
  1016. execvpe(*opts.jail_argv, opts.jail_argv, envp);
  1017. else
  1018. execve(*opts.jail_argv, opts.jail_argv, envp);
  1019. /* we get there only if execve fails */
  1020. ERROR("failed to execve %s: %m\n", *opts.jail_argv);
  1021. exit(EXIT_FAILURE);
  1022. }
  1023. static int ns_open_pid(const char *nstype, const pid_t target_ns)
  1024. {
  1025. char pid_pid_path[PATH_MAX];
  1026. snprintf(pid_pid_path, sizeof(pid_pid_path), "/proc/%u/ns/%s", target_ns, nstype);
  1027. return open(pid_pid_path, O_RDONLY);
  1028. }
  1029. static void netns_updown(pid_t pid, bool start)
  1030. {
  1031. static struct blob_buf req;
  1032. uint32_t id;
  1033. if (!parent_ctx)
  1034. return;
  1035. blob_buf_init(&req, 0);
  1036. blobmsg_add_string(&req, "jail", opts.name);
  1037. blobmsg_add_u32(&req, "pid", pid);
  1038. blobmsg_add_u8(&req, "start", start);
  1039. if (ubus_lookup_id(parent_ctx, "network", &id) ||
  1040. ubus_invoke(parent_ctx, id, "netns_updown", req.head, NULL, NULL, 3000))
  1041. INFO("ubus request failed\n");
  1042. blob_buf_free(&req);
  1043. }
  1044. static int parseOCIenvarray(struct blob_attr *msg, char ***envp)
  1045. {
  1046. struct blob_attr *cur;
  1047. int sz = 0, rem;
  1048. blobmsg_for_each_attr(cur, msg, rem)
  1049. ++sz;
  1050. if (sz > 0) {
  1051. *envp = calloc(1 + sz, sizeof(char*));
  1052. if (!(*envp))
  1053. return ENOMEM;
  1054. } else {
  1055. *envp = NULL;
  1056. return 0;
  1057. }
  1058. sz = 0;
  1059. blobmsg_for_each_attr(cur, msg, rem)
  1060. (*envp)[sz++] = strdup(blobmsg_get_string(cur));
  1061. if (sz)
  1062. (*envp)[sz] = NULL;
  1063. return 0;
  1064. }
  1065. enum {
  1066. OCI_ROOT_PATH,
  1067. OCI_ROOT_READONLY,
  1068. __OCI_ROOT_MAX,
  1069. };
  1070. static const struct blobmsg_policy oci_root_policy[] = {
  1071. [OCI_ROOT_PATH] = { "path", BLOBMSG_TYPE_STRING },
  1072. [OCI_ROOT_READONLY] = { "readonly", BLOBMSG_TYPE_BOOL },
  1073. };
  1074. static int parseOCIroot(const char *jsonfile, struct blob_attr *msg)
  1075. {
  1076. static char rootpath[PATH_MAX] = { 0 };
  1077. struct blob_attr *tb[__OCI_ROOT_MAX];
  1078. char *cur;
  1079. blobmsg_parse(oci_root_policy, __OCI_ROOT_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
  1080. if (!tb[OCI_ROOT_PATH])
  1081. return ENODATA;
  1082. strncpy(rootpath, jsonfile, PATH_MAX);
  1083. cur = strrchr(rootpath, '/');
  1084. if (!cur)
  1085. return ENOTDIR;
  1086. *(++cur) = '\0';
  1087. strncat(rootpath, blobmsg_get_string(tb[OCI_ROOT_PATH]), PATH_MAX - (strlen(rootpath) + 1));
  1088. opts.extroot = rootpath;
  1089. opts.ronly = blobmsg_get_bool(tb[OCI_ROOT_READONLY]);
  1090. return 0;
  1091. }
  1092. enum {
  1093. OCI_HOOK_PATH,
  1094. OCI_HOOK_ARGS,
  1095. OCI_HOOK_ENV,
  1096. OCI_HOOK_TIMEOUT,
  1097. __OCI_HOOK_MAX,
  1098. };
  1099. static const struct blobmsg_policy oci_hook_policy[] = {
  1100. [OCI_HOOK_PATH] = { "path", BLOBMSG_TYPE_STRING },
  1101. [OCI_HOOK_ARGS] = { "args", BLOBMSG_TYPE_ARRAY },
  1102. [OCI_HOOK_ENV] = { "env", BLOBMSG_TYPE_ARRAY },
  1103. [OCI_HOOK_TIMEOUT] = { "timeout", BLOBMSG_TYPE_INT32 },
  1104. };
  1105. static int parseOCIhook(struct hook_execvpe ***hooklist, struct blob_attr *msg)
  1106. {
  1107. struct blob_attr *tb[__OCI_HOOK_MAX];
  1108. struct blob_attr *cur;
  1109. int rem, ret = 0;
  1110. int idx = 0;
  1111. blobmsg_for_each_attr(cur, msg, rem)
  1112. ++idx;
  1113. if (!idx)
  1114. return 0;
  1115. *hooklist = calloc(idx + 1, sizeof(struct hook_execvpe *));
  1116. idx = 0;
  1117. if (!(*hooklist))
  1118. return ENOMEM;
  1119. blobmsg_for_each_attr(cur, msg, rem) {
  1120. blobmsg_parse(oci_hook_policy, __OCI_HOOK_MAX, tb, blobmsg_data(cur), blobmsg_len(cur));
  1121. if (!tb[OCI_HOOK_PATH]) {
  1122. ret = EINVAL;
  1123. goto errout;
  1124. }
  1125. (*hooklist)[idx] = calloc(1, sizeof(struct hook_execvpe));
  1126. if (tb[OCI_HOOK_ARGS]) {
  1127. ret = parseOCIenvarray(tb[OCI_HOOK_ARGS], &((*hooklist)[idx]->argv));
  1128. if (ret)
  1129. goto errout;
  1130. } else {
  1131. (*hooklist)[idx]->argv = calloc(2, sizeof(char *));
  1132. ((*hooklist)[idx]->argv)[0] = strdup(blobmsg_get_string(tb[OCI_HOOK_PATH]));
  1133. ((*hooklist)[idx]->argv)[1] = NULL;
  1134. };
  1135. if (tb[OCI_HOOK_ENV]) {
  1136. ret = parseOCIenvarray(tb[OCI_HOOK_ENV], &((*hooklist)[idx]->envp));
  1137. if (ret)
  1138. goto errout;
  1139. }
  1140. if (tb[OCI_HOOK_TIMEOUT])
  1141. (*hooklist)[idx]->timeout = blobmsg_get_u32(tb[OCI_HOOK_TIMEOUT]);
  1142. (*hooklist)[idx]->file = strdup(blobmsg_get_string(tb[OCI_HOOK_PATH]));
  1143. ++idx;
  1144. }
  1145. (*hooklist)[idx] = NULL;
  1146. DEBUG("added %d hooks\n", idx);
  1147. return 0;
  1148. errout:
  1149. free_hooklist(*hooklist);
  1150. *hooklist = NULL;
  1151. return ret;
  1152. };
  1153. enum {
  1154. OCI_HOOKS_PRESTART,
  1155. OCI_HOOKS_CREATERUNTIME,
  1156. OCI_HOOKS_CREATECONTAINER,
  1157. OCI_HOOKS_STARTCONTAINER,
  1158. OCI_HOOKS_POSTSTART,
  1159. OCI_HOOKS_POSTSTOP,
  1160. __OCI_HOOKS_MAX,
  1161. };
  1162. static const struct blobmsg_policy oci_hooks_policy[] = {
  1163. [OCI_HOOKS_PRESTART] = { "prestart", BLOBMSG_TYPE_ARRAY },
  1164. [OCI_HOOKS_CREATERUNTIME] = { "createRuntime", BLOBMSG_TYPE_ARRAY },
  1165. [OCI_HOOKS_CREATECONTAINER] = { "createContainer", BLOBMSG_TYPE_ARRAY },
  1166. [OCI_HOOKS_STARTCONTAINER] = { "startContainer", BLOBMSG_TYPE_ARRAY },
  1167. [OCI_HOOKS_POSTSTART] = { "poststart", BLOBMSG_TYPE_ARRAY },
  1168. [OCI_HOOKS_POSTSTOP] = { "poststop", BLOBMSG_TYPE_ARRAY },
  1169. };
  1170. static int parseOCIhooks(struct blob_attr *msg)
  1171. {
  1172. struct blob_attr *tb[__OCI_HOOKS_MAX];
  1173. int ret;
  1174. blobmsg_parse(oci_hooks_policy, __OCI_HOOKS_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
  1175. if (tb[OCI_HOOKS_PRESTART])
  1176. INFO("warning: ignoring deprecated prestart hook\n");
  1177. if (tb[OCI_HOOKS_CREATERUNTIME]) {
  1178. ret = parseOCIhook(&opts.hooks.createRuntime, tb[OCI_HOOKS_CREATERUNTIME]);
  1179. if (ret)
  1180. return ret;
  1181. }
  1182. if (tb[OCI_HOOKS_CREATECONTAINER]) {
  1183. ret = parseOCIhook(&opts.hooks.createContainer, tb[OCI_HOOKS_CREATECONTAINER]);
  1184. if (ret)
  1185. goto out_createruntime;
  1186. }
  1187. if (tb[OCI_HOOKS_STARTCONTAINER]) {
  1188. ret = parseOCIhook(&opts.hooks.startContainer, tb[OCI_HOOKS_STARTCONTAINER]);
  1189. if (ret)
  1190. goto out_createcontainer;
  1191. }
  1192. if (tb[OCI_HOOKS_POSTSTART]) {
  1193. ret = parseOCIhook(&opts.hooks.poststart, tb[OCI_HOOKS_POSTSTART]);
  1194. if (ret)
  1195. goto out_startcontainer;
  1196. }
  1197. if (tb[OCI_HOOKS_POSTSTOP]) {
  1198. ret = parseOCIhook(&opts.hooks.poststop, tb[OCI_HOOKS_POSTSTOP]);
  1199. if (ret)
  1200. goto out_poststart;
  1201. }
  1202. return 0;
  1203. out_poststart:
  1204. free_hooklist(opts.hooks.poststart);
  1205. out_startcontainer:
  1206. free_hooklist(opts.hooks.startContainer);
  1207. out_createcontainer:
  1208. free_hooklist(opts.hooks.createContainer);
  1209. out_createruntime:
  1210. free_hooklist(opts.hooks.createRuntime);
  1211. return ret;
  1212. };
  1213. enum {
  1214. OCI_PROCESS_USER_UID,
  1215. OCI_PROCESS_USER_GID,
  1216. OCI_PROCESS_USER_UMASK,
  1217. OCI_PROCESS_USER_ADDITIONALGIDS,
  1218. __OCI_PROCESS_USER_MAX,
  1219. };
  1220. static const struct blobmsg_policy oci_process_user_policy[] = {
  1221. [OCI_PROCESS_USER_UID] = { "uid", BLOBMSG_TYPE_INT32 },
  1222. [OCI_PROCESS_USER_GID] = { "gid", BLOBMSG_TYPE_INT32 },
  1223. [OCI_PROCESS_USER_UMASK] = { "umask", BLOBMSG_TYPE_INT32 },
  1224. [OCI_PROCESS_USER_ADDITIONALGIDS] = { "additionalGids", BLOBMSG_TYPE_ARRAY },
  1225. };
  1226. static int parseOCIprocessuser(struct blob_attr *msg) {
  1227. struct blob_attr *tb[__OCI_PROCESS_USER_MAX];
  1228. struct blob_attr *cur;
  1229. int rem;
  1230. int has_gid = 0;
  1231. blobmsg_parse(oci_process_user_policy, __OCI_PROCESS_USER_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
  1232. if (tb[OCI_PROCESS_USER_UID])
  1233. opts.pw_uid = blobmsg_get_u32(tb[OCI_PROCESS_USER_UID]);
  1234. if (tb[OCI_PROCESS_USER_GID]) {
  1235. opts.pw_gid = blobmsg_get_u32(tb[OCI_PROCESS_USER_GID]);
  1236. opts.gr_gid = blobmsg_get_u32(tb[OCI_PROCESS_USER_GID]);
  1237. has_gid = 1;
  1238. }
  1239. if (tb[OCI_PROCESS_USER_ADDITIONALGIDS]) {
  1240. size_t gidcnt = 0;
  1241. blobmsg_for_each_attr(cur, tb[OCI_PROCESS_USER_ADDITIONALGIDS], rem) {
  1242. ++gidcnt;
  1243. if (has_gid && (blobmsg_get_u32(cur) == opts.gr_gid))
  1244. continue;
  1245. }
  1246. if (gidcnt) {
  1247. opts.additional_gids = calloc(gidcnt + has_gid, sizeof(gid_t));
  1248. gidcnt = 0;
  1249. /* always add primary GID to set of GIDs if set */
  1250. if (has_gid)
  1251. opts.additional_gids[gidcnt++] = opts.gr_gid;
  1252. blobmsg_for_each_attr(cur, tb[OCI_PROCESS_USER_ADDITIONALGIDS], rem) {
  1253. if (has_gid && (blobmsg_get_u32(cur) == opts.gr_gid))
  1254. continue;
  1255. opts.additional_gids[gidcnt++] = blobmsg_get_u32(cur);
  1256. }
  1257. opts.num_additional_gids = gidcnt;
  1258. }
  1259. DEBUG("read %zu additional groups\n", gidcnt);
  1260. }
  1261. if (tb[OCI_PROCESS_USER_UMASK]) {
  1262. opts.umask = blobmsg_get_u32(tb[OCI_PROCESS_USER_UMASK]);
  1263. opts.set_umask = true;
  1264. }
  1265. return 0;
  1266. }
  1267. enum {
  1268. OCI_PROCESS_RLIMIT_TYPE,
  1269. OCI_PROCESS_RLIMIT_SOFT,
  1270. OCI_PROCESS_RLIMIT_HARD,
  1271. __OCI_PROCESS_RLIMIT_MAX,
  1272. };
  1273. static const struct blobmsg_policy oci_process_rlimit_policy[] = {
  1274. [OCI_PROCESS_RLIMIT_TYPE] = { "type", BLOBMSG_TYPE_STRING },
  1275. [OCI_PROCESS_RLIMIT_SOFT] = { "soft", BLOBMSG_CAST_INT64 },
  1276. [OCI_PROCESS_RLIMIT_HARD] = { "hard", BLOBMSG_CAST_INT64 },
  1277. };
  1278. /* from manpage GETRLIMIT(2) */
  1279. static const char* const rlimit_names[RLIM_NLIMITS] = {
  1280. [RLIMIT_AS] = "AS",
  1281. [RLIMIT_CORE] = "CORE",
  1282. [RLIMIT_CPU] = "CPU",
  1283. [RLIMIT_DATA] = "DATA",
  1284. [RLIMIT_FSIZE] = "FSIZE",
  1285. [RLIMIT_LOCKS] = "LOCKS",
  1286. [RLIMIT_MEMLOCK] = "MEMLOCK",
  1287. [RLIMIT_MSGQUEUE] = "MSGQUEUE",
  1288. [RLIMIT_NICE] = "NICE",
  1289. [RLIMIT_NOFILE] = "NOFILE",
  1290. [RLIMIT_NPROC] = "NPROC",
  1291. [RLIMIT_RSS] = "RSS",
  1292. [RLIMIT_RTPRIO] = "RTPRIO",
  1293. [RLIMIT_RTTIME] = "RTTIME",
  1294. [RLIMIT_SIGPENDING] = "SIGPENDING",
  1295. [RLIMIT_STACK] = "STACK",
  1296. };
  1297. static int resolve_rlimit(char *type) {
  1298. unsigned int rltype;
  1299. for (rltype = 0; rltype < RLIM_NLIMITS; ++rltype)
  1300. if (rlimit_names[rltype] &&
  1301. !strncmp("RLIMIT_", type, 7) &&
  1302. !strcmp(rlimit_names[rltype], type + 7))
  1303. return rltype;
  1304. return -1;
  1305. }
  1306. static int parseOCIrlimit(struct blob_attr *msg)
  1307. {
  1308. struct blob_attr *tb[__OCI_PROCESS_RLIMIT_MAX];
  1309. int limtype = -1;
  1310. struct rlimit *curlim;
  1311. blobmsg_parse(oci_process_rlimit_policy, __OCI_PROCESS_RLIMIT_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
  1312. if (!tb[OCI_PROCESS_RLIMIT_TYPE] ||
  1313. !tb[OCI_PROCESS_RLIMIT_SOFT] ||
  1314. !tb[OCI_PROCESS_RLIMIT_HARD])
  1315. return ENODATA;
  1316. limtype = resolve_rlimit(blobmsg_get_string(tb[OCI_PROCESS_RLIMIT_TYPE]));
  1317. if (limtype < 0)
  1318. return EINVAL;
  1319. if (opts.rlimits[limtype])
  1320. return ENOTUNIQ;
  1321. curlim = malloc(sizeof(struct rlimit));
  1322. curlim->rlim_cur = blobmsg_cast_u64(tb[OCI_PROCESS_RLIMIT_SOFT]);
  1323. curlim->rlim_max = blobmsg_cast_u64(tb[OCI_PROCESS_RLIMIT_HARD]);
  1324. opts.rlimits[limtype] = curlim;
  1325. return 0;
  1326. };
  1327. enum {
  1328. OCI_PROCESS_ARGS,
  1329. OCI_PROCESS_CAPABILITIES,
  1330. OCI_PROCESS_CWD,
  1331. OCI_PROCESS_ENV,
  1332. OCI_PROCESS_OOMSCOREADJ,
  1333. OCI_PROCESS_NONEWPRIVILEGES,
  1334. OCI_PROCESS_RLIMITS,
  1335. OCI_PROCESS_TERMINAL,
  1336. OCI_PROCESS_USER,
  1337. __OCI_PROCESS_MAX,
  1338. };
  1339. static const struct blobmsg_policy oci_process_policy[] = {
  1340. [OCI_PROCESS_ARGS] = { "args", BLOBMSG_TYPE_ARRAY },
  1341. [OCI_PROCESS_CAPABILITIES] = { "capabilities", BLOBMSG_TYPE_TABLE },
  1342. [OCI_PROCESS_CWD] = { "cwd", BLOBMSG_TYPE_STRING },
  1343. [OCI_PROCESS_ENV] = { "env", BLOBMSG_TYPE_ARRAY },
  1344. [OCI_PROCESS_OOMSCOREADJ] = { "oomScoreAdj", BLOBMSG_TYPE_INT32 },
  1345. [OCI_PROCESS_NONEWPRIVILEGES] = { "noNewPrivileges", BLOBMSG_TYPE_BOOL },
  1346. [OCI_PROCESS_RLIMITS] = { "rlimits", BLOBMSG_TYPE_ARRAY },
  1347. [OCI_PROCESS_TERMINAL] = { "terminal", BLOBMSG_TYPE_BOOL },
  1348. [OCI_PROCESS_USER] = { "user", BLOBMSG_TYPE_TABLE },
  1349. };
  1350. static int parseOCIprocess(struct blob_attr *msg)
  1351. {
  1352. struct blob_attr *tb[__OCI_PROCESS_MAX], *cur;
  1353. int rem, res;
  1354. blobmsg_parse(oci_process_policy, __OCI_PROCESS_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
  1355. if (!tb[OCI_PROCESS_ARGS])
  1356. return ENOENT;
  1357. res = parseOCIenvarray(tb[OCI_PROCESS_ARGS], &opts.jail_argv);
  1358. if (res)
  1359. return res;
  1360. opts.console = blobmsg_get_bool(tb[OCI_PROCESS_TERMINAL]);
  1361. opts.no_new_privs = blobmsg_get_bool(tb[OCI_PROCESS_NONEWPRIVILEGES]);
  1362. if (tb[OCI_PROCESS_CWD])
  1363. opts.cwd = strdup(blobmsg_get_string(tb[OCI_PROCESS_CWD]));
  1364. if (tb[OCI_PROCESS_ENV]) {
  1365. res = parseOCIenvarray(tb[OCI_PROCESS_ENV], &opts.envp);
  1366. if (res)
  1367. return res;
  1368. }
  1369. if (tb[OCI_PROCESS_USER] && (res = parseOCIprocessuser(tb[OCI_PROCESS_USER])))
  1370. return res;
  1371. if (tb[OCI_PROCESS_CAPABILITIES] &&
  1372. (res = parseOCIcapabilities(&opts.capset, tb[OCI_PROCESS_CAPABILITIES])))
  1373. return res;
  1374. if (tb[OCI_PROCESS_RLIMITS]) {
  1375. blobmsg_for_each_attr(cur, tb[OCI_PROCESS_RLIMITS], rem) {
  1376. res = parseOCIrlimit(cur);
  1377. if (res)
  1378. return res;
  1379. }
  1380. }
  1381. if (tb[OCI_PROCESS_OOMSCOREADJ]) {
  1382. opts.oom_score_adj = blobmsg_get_u32(tb[OCI_PROCESS_OOMSCOREADJ]);
  1383. opts.set_oom_score_adj = true;
  1384. }
  1385. return 0;
  1386. }
  1387. enum {
  1388. OCI_LINUX_NAMESPACE_TYPE,
  1389. OCI_LINUX_NAMESPACE_PATH,
  1390. __OCI_LINUX_NAMESPACE_MAX,
  1391. };
  1392. static const struct blobmsg_policy oci_linux_namespace_policy[] = {
  1393. [OCI_LINUX_NAMESPACE_TYPE] = { "type", BLOBMSG_TYPE_STRING },
  1394. [OCI_LINUX_NAMESPACE_PATH] = { "path", BLOBMSG_TYPE_STRING },
  1395. };
  1396. static int resolve_nstype(char *type) {
  1397. if (!strcmp("pid", type))
  1398. return CLONE_NEWPID;
  1399. else if (!strcmp("network", type))
  1400. return CLONE_NEWNET;
  1401. else if (!strcmp("mount", type))
  1402. return CLONE_NEWNS;
  1403. else if (!strcmp("ipc", type))
  1404. return CLONE_NEWIPC;
  1405. else if (!strcmp("uts", type))
  1406. return CLONE_NEWUTS;
  1407. else if (!strcmp("user", type))
  1408. return CLONE_NEWUSER;
  1409. else if (!strcmp("cgroup", type))
  1410. return CLONE_NEWCGROUP;
  1411. #ifdef CLONE_NEWTIME
  1412. else if (!strcmp("time", type))
  1413. return CLONE_NEWTIME;
  1414. #endif
  1415. else
  1416. return 0;
  1417. }
  1418. static int parseOCIlinuxns(struct blob_attr *msg)
  1419. {
  1420. struct blob_attr *tb[__OCI_LINUX_NAMESPACE_MAX];
  1421. int nstype;
  1422. int *setns;
  1423. int fd;
  1424. blobmsg_parse(oci_linux_namespace_policy, __OCI_LINUX_NAMESPACE_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
  1425. if (!tb[OCI_LINUX_NAMESPACE_TYPE])
  1426. return EINVAL;
  1427. nstype = resolve_nstype(blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_TYPE]));
  1428. if (!nstype)
  1429. return EINVAL;
  1430. if (opts.namespace & nstype)
  1431. return ENOTUNIQ;
  1432. setns = get_namespace_fd(nstype);
  1433. if (!setns)
  1434. return EFAULT;
  1435. if (*setns != -1)
  1436. return ENOTUNIQ;
  1437. if (tb[OCI_LINUX_NAMESPACE_PATH]) {
  1438. DEBUG("opening existing %s namespace from path %s\n",
  1439. blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_TYPE]),
  1440. blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_PATH]));
  1441. fd = open(blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_PATH]), O_RDONLY);
  1442. if (fd == -1)
  1443. return errno?:ESTALE;
  1444. if (ioctl(fd, NS_GET_NSTYPE) != nstype)
  1445. return EINVAL;
  1446. DEBUG("opened existing %s namespace got filehandler %u\n",
  1447. blobmsg_get_string(tb[OCI_LINUX_NAMESPACE_TYPE]),
  1448. fd);
  1449. *setns = fd;
  1450. } else {
  1451. opts.namespace |= nstype;
  1452. }
  1453. return 0;
  1454. };
  1455. enum {
  1456. OCI_LINUX_UIDGIDMAP_CONTAINERID,
  1457. OCI_LINUX_UIDGIDMAP_HOSTID,
  1458. OCI_LINUX_UIDGIDMAP_SIZE,
  1459. __OCI_LINUX_UIDGIDMAP_MAX,
  1460. };
  1461. static const struct blobmsg_policy oci_linux_uidgidmap_policy[] = {
  1462. [OCI_LINUX_UIDGIDMAP_CONTAINERID] = { "containerID", BLOBMSG_TYPE_INT32 },
  1463. [OCI_LINUX_UIDGIDMAP_HOSTID] = { "hostID", BLOBMSG_TYPE_INT32 },
  1464. [OCI_LINUX_UIDGIDMAP_SIZE] = { "size", BLOBMSG_TYPE_INT32 },
  1465. };
  1466. static int parseOCIuidgidmappings(struct blob_attr *msg, bool is_gidmap)
  1467. {
  1468. const char *map_format = "%d %d %d\n";
  1469. struct blob_attr *tb[__OCI_LINUX_UIDGIDMAP_MAX];
  1470. struct blob_attr *cur;
  1471. int rem, len;
  1472. char **mappings;
  1473. char *map, *curstr;
  1474. unsigned int cnt = 0;
  1475. size_t totallen = 0;
  1476. /* count number of mappings */
  1477. blobmsg_for_each_attr(cur, msg, rem)
  1478. cnt++;
  1479. if (!cnt)
  1480. return 0;
  1481. /* allocate array for mappings */
  1482. mappings = calloc(1 + cnt, sizeof(char*));
  1483. if (!mappings)
  1484. return ENOMEM;
  1485. mappings[cnt] = NULL;
  1486. cnt = 0;
  1487. blobmsg_for_each_attr(cur, msg, rem) {
  1488. blobmsg_parse(oci_linux_uidgidmap_policy, __OCI_LINUX_UIDGIDMAP_MAX, tb, blobmsg_data(cur), blobmsg_len(cur));
  1489. if (!tb[OCI_LINUX_UIDGIDMAP_CONTAINERID] ||
  1490. !tb[OCI_LINUX_UIDGIDMAP_HOSTID] ||
  1491. !tb[OCI_LINUX_UIDGIDMAP_SIZE])
  1492. return EINVAL;
  1493. /* write mapping line into allocated string */
  1494. len = asprintf(&mappings[cnt++], map_format,
  1495. blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_CONTAINERID]),
  1496. blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_HOSTID]),
  1497. blobmsg_get_u32(tb[OCI_LINUX_UIDGIDMAP_SIZE]));
  1498. if (len < 0)
  1499. return ENOMEM;
  1500. totallen += len;
  1501. }
  1502. /* allocate combined mapping string */
  1503. map = calloc(1 + totallen, sizeof(char));
  1504. if (!map)
  1505. return ENOMEM;
  1506. map[0] = '\0';
  1507. /* concatenate mapping strings into combined string */
  1508. curstr = mappings[0];
  1509. while (curstr) {
  1510. strcat(map, curstr);
  1511. free(curstr++);
  1512. }
  1513. free(mappings);
  1514. if (is_gidmap)
  1515. opts.gidmap = map;
  1516. else
  1517. opts.uidmap = map;
  1518. return 0;
  1519. }
  1520. enum {
  1521. OCI_DEVICES_TYPE,
  1522. OCI_DEVICES_PATH,
  1523. OCI_DEVICES_MAJOR,
  1524. OCI_DEVICES_MINOR,
  1525. OCI_DEVICES_FILEMODE,
  1526. OCI_DEVICES_UID,
  1527. OCI_DEVICES_GID,
  1528. __OCI_DEVICES_MAX,
  1529. };
  1530. static const struct blobmsg_policy oci_devices_policy[] = {
  1531. [OCI_DEVICES_TYPE] = { "type", BLOBMSG_TYPE_STRING },
  1532. [OCI_DEVICES_PATH] = { "path", BLOBMSG_TYPE_STRING },
  1533. [OCI_DEVICES_MAJOR] = { "major", BLOBMSG_TYPE_INT32 },
  1534. [OCI_DEVICES_MINOR] = { "minor", BLOBMSG_TYPE_INT32 },
  1535. [OCI_DEVICES_FILEMODE] = { "fileMode", BLOBMSG_TYPE_INT32 },
  1536. [OCI_DEVICES_UID] = { "uid", BLOBMSG_TYPE_INT32 },
  1537. [OCI_DEVICES_GID] = { "uid", BLOBMSG_TYPE_INT32 },
  1538. };
  1539. static mode_t resolve_devtype(char *tstr)
  1540. {
  1541. if (!strcmp("c", tstr) ||
  1542. !strcmp("u", tstr))
  1543. return S_IFCHR;
  1544. else if (!strcmp("b", tstr))
  1545. return S_IFBLK;
  1546. else if (!strcmp("p", tstr))
  1547. return S_IFIFO;
  1548. else
  1549. return 0;
  1550. }
  1551. static int parseOCIdevices(struct blob_attr *msg)
  1552. {
  1553. struct blob_attr *tb[__OCI_DEVICES_MAX];
  1554. struct blob_attr *cur;
  1555. int rem;
  1556. size_t cnt = 0;
  1557. struct mknod_args *tmp;
  1558. blobmsg_for_each_attr(cur, msg, rem)
  1559. ++cnt;
  1560. opts.devices = calloc(cnt + 1, sizeof(struct mknod_args *));
  1561. cnt = 0;
  1562. blobmsg_for_each_attr(cur, msg, rem) {
  1563. blobmsg_parse(oci_devices_policy, __OCI_DEVICES_MAX, tb, blobmsg_data(cur), blobmsg_len(cur));
  1564. if (!tb[OCI_DEVICES_TYPE] ||
  1565. !tb[OCI_DEVICES_PATH])
  1566. return ENODATA;
  1567. tmp = calloc(1, sizeof(struct mknod_args));
  1568. if (!tmp)
  1569. return ENOMEM;
  1570. tmp->mode = resolve_devtype(blobmsg_get_string(tb[OCI_DEVICES_TYPE]));
  1571. if (!tmp->mode)
  1572. return EINVAL;
  1573. if (tmp->mode != S_IFIFO) {
  1574. if (!tb[OCI_DEVICES_MAJOR] || !tb[OCI_DEVICES_MINOR])
  1575. return ENODATA;
  1576. tmp->dev = makedev(blobmsg_get_u32(tb[OCI_DEVICES_MAJOR]),
  1577. blobmsg_get_u32(tb[OCI_DEVICES_MINOR]));
  1578. }
  1579. if (tb[OCI_DEVICES_FILEMODE]) {
  1580. if (~(S_IRWXU|S_IRWXG|S_IRWXO) & blobmsg_get_u32(tb[OCI_DEVICES_FILEMODE]))
  1581. return EINVAL;
  1582. tmp->mode |= blobmsg_get_u32(tb[OCI_DEVICES_FILEMODE]);
  1583. } else {
  1584. tmp->mode |= (S_IRUSR|S_IWUSR); /* 0600 */
  1585. }
  1586. tmp->path = strdup(blobmsg_get_string(tb[OCI_DEVICES_PATH]));
  1587. if (tb[OCI_DEVICES_UID])
  1588. tmp->uid = blobmsg_get_u32(tb[OCI_DEVICES_UID]);
  1589. else
  1590. tmp->uid = -1;
  1591. if (tb[OCI_DEVICES_GID])
  1592. tmp->gid = blobmsg_get_u32(tb[OCI_DEVICES_GID]);
  1593. else
  1594. tmp->gid = -1;
  1595. DEBUG("read device %s (%s)\n", blobmsg_get_string(tb[OCI_DEVICES_PATH]), blobmsg_get_string(tb[OCI_DEVICES_TYPE]));
  1596. opts.devices[cnt++] = tmp;
  1597. }
  1598. opts.devices[cnt] = NULL;
  1599. return 0;
  1600. }
  1601. static int parseOCIsysctl(struct blob_attr *msg)
  1602. {
  1603. struct blob_attr *cur;
  1604. int rem;
  1605. char *tmp, *tc;
  1606. size_t cnt = 0;
  1607. blobmsg_for_each_attr(cur, msg, rem) {
  1608. if (!blobmsg_name(cur) || !blobmsg_get_string(cur))
  1609. return EINVAL;
  1610. ++cnt;
  1611. }
  1612. if (!cnt)
  1613. return 0;
  1614. opts.sysctl = calloc(cnt + 1, sizeof(struct sysctl_val *));
  1615. if (!opts.sysctl)
  1616. return ENOMEM;
  1617. cnt = 0;
  1618. blobmsg_for_each_attr(cur, msg, rem) {
  1619. opts.sysctl[cnt] = malloc(sizeof(struct sysctl_val));
  1620. if (!opts.sysctl[cnt])
  1621. return ENOMEM;
  1622. /* replace '.' with '/' in entry name */
  1623. tc = tmp = strdup(blobmsg_name(cur));
  1624. while ((tc = strchr(tc, '.')))
  1625. *tc = '/';
  1626. opts.sysctl[cnt]->value = strdup(blobmsg_get_string(cur));
  1627. opts.sysctl[cnt]->entry = tmp;
  1628. ++cnt;
  1629. }
  1630. opts.sysctl[cnt] = NULL;
  1631. return 0;
  1632. }
  1633. enum {
  1634. OCI_LINUX_CGROUPSPATH,
  1635. OCI_LINUX_RESOURCES,
  1636. OCI_LINUX_SECCOMP,
  1637. OCI_LINUX_SYSCTL,
  1638. OCI_LINUX_NAMESPACES,
  1639. OCI_LINUX_DEVICES,
  1640. OCI_LINUX_UIDMAPPINGS,
  1641. OCI_LINUX_GIDMAPPINGS,
  1642. OCI_LINUX_MASKEDPATHS,
  1643. OCI_LINUX_READONLYPATHS,
  1644. OCI_LINUX_ROOTFSPROPAGATION,
  1645. __OCI_LINUX_MAX,
  1646. };
  1647. static const struct blobmsg_policy oci_linux_policy[] = {
  1648. [OCI_LINUX_CGROUPSPATH] = { "cgroupsPath", BLOBMSG_TYPE_STRING },
  1649. [OCI_LINUX_RESOURCES] = { "resources", BLOBMSG_TYPE_TABLE },
  1650. [OCI_LINUX_SECCOMP] = { "seccomp", BLOBMSG_TYPE_TABLE },
  1651. [OCI_LINUX_SYSCTL] = { "sysctl", BLOBMSG_TYPE_TABLE },
  1652. [OCI_LINUX_NAMESPACES] = { "namespaces", BLOBMSG_TYPE_ARRAY },
  1653. [OCI_LINUX_DEVICES] = { "devices", BLOBMSG_TYPE_ARRAY },
  1654. [OCI_LINUX_UIDMAPPINGS] = { "uidMappings", BLOBMSG_TYPE_ARRAY },
  1655. [OCI_LINUX_GIDMAPPINGS] = { "gidMappings", BLOBMSG_TYPE_ARRAY },
  1656. [OCI_LINUX_MASKEDPATHS] = { "maskedPaths", BLOBMSG_TYPE_ARRAY },
  1657. [OCI_LINUX_READONLYPATHS] = { "readonlyPaths", BLOBMSG_TYPE_ARRAY },
  1658. [OCI_LINUX_ROOTFSPROPAGATION] = { "rootfsPropagation", BLOBMSG_TYPE_STRING },
  1659. };
  1660. static int parseOCIlinux(struct blob_attr *msg)
  1661. {
  1662. struct blob_attr *tb[__OCI_LINUX_MAX];
  1663. struct blob_attr *cur;
  1664. int rem;
  1665. int res = 0;
  1666. char *cgpath;
  1667. char cgfullpath[256] = "/sys/fs/cgroup";
  1668. blobmsg_parse(oci_linux_policy, __OCI_LINUX_MAX, tb, blobmsg_data(msg), blobmsg_len(msg));
  1669. if (tb[OCI_LINUX_NAMESPACES]) {
  1670. blobmsg_for_each_attr(cur, tb[OCI_LINUX_NAMESPACES], rem) {
  1671. res = parseOCIlinuxns(cur);
  1672. if (res)
  1673. return res;
  1674. }
  1675. }
  1676. if (tb[OCI_LINUX_UIDMAPPINGS]) {
  1677. res = parseOCIuidgidmappings(tb[OCI_LINUX_GIDMAPPINGS], 0);
  1678. if (res)
  1679. return res;
  1680. }
  1681. if (tb[OCI_LINUX_GIDMAPPINGS]) {
  1682. res = parseOCIuidgidmappings(tb[OCI_LINUX_GIDMAPPINGS], 1);
  1683. if (res)
  1684. return res;
  1685. }
  1686. if (tb[OCI_LINUX_READONLYPATHS]) {
  1687. blobmsg_for_each_attr(cur, tb[OCI_LINUX_READONLYPATHS], rem) {
  1688. res = add_mount(NULL, blobmsg_get_string(cur), NULL, MS_BIND | MS_REC | MS_RDONLY, NULL, 0);
  1689. if (res)
  1690. return res;
  1691. }
  1692. }
  1693. if (tb[OCI_LINUX_MASKEDPATHS]) {
  1694. blobmsg_for_each_attr(cur, tb[OCI_LINUX_MASKEDPATHS], rem) {
  1695. res = add_mount((void *)(-1), blobmsg_get_string(cur), NULL, 0, NULL, 1);
  1696. if (res)
  1697. return res;
  1698. }
  1699. }
  1700. if (tb[OCI_LINUX_SYSCTL]) {
  1701. res = parseOCIsysctl(tb[OCI_LINUX_SYSCTL]);
  1702. if (res)
  1703. return res;
  1704. }
  1705. if (tb[OCI_LINUX_SECCOMP]) {
  1706. opts.ociseccomp = parseOCIlinuxseccomp(tb[OCI_LINUX_SECCOMP]);
  1707. if (!opts.ociseccomp)
  1708. return EINVAL;
  1709. }
  1710. if (tb[OCI_LINUX_DEVICES]) {
  1711. res = parseOCIdevices(tb[OCI_LINUX_DEVICES]);
  1712. if (res)
  1713. return res;
  1714. }
  1715. if (tb[OCI_LINUX_CGROUPSPATH]) {
  1716. cgpath = blobmsg_get_string(tb[OCI_LINUX_CGROUPSPATH]);
  1717. if (cgpath[0] == '/') {
  1718. if (strlen(cgpath) >= (sizeof(cgfullpath) - strlen(cgfullpath)))
  1719. return E2BIG;
  1720. strcat(cgfullpath, cgpath);
  1721. } else {
  1722. strcat(cgfullpath, "/containers/");
  1723. strcat(cgfullpath, opts.name); /* should be container name rather than jail name */
  1724. strcat(cgfullpath, "/");
  1725. if (strlen(cgpath) >= (sizeof(cgfullpath) - strlen(cgfullpath)))
  1726. return E2BIG;
  1727. strcat(cgfullpath, cgpath);
  1728. }
  1729. } else {
  1730. strcat(cgfullpath, "/containers/");
  1731. strcat(cgfullpath, opts.name); /* should be container name rather than jail name */
  1732. strcat(cgfullpath, "/");
  1733. strcat(cgfullpath, opts.name); /* should be container instance name rather than jail name */
  1734. }
  1735. cgroups_init(cgfullpath);
  1736. if (tb[OCI_LINUX_RESOURCES]) {
  1737. res = parseOCIlinuxcgroups(tb[OCI_LINUX_RESOURCES]);
  1738. if (res)
  1739. return res;
  1740. }
  1741. return 0;
  1742. }
  1743. enum {
  1744. OCI_VERSION,
  1745. OCI_HOSTNAME,
  1746. OCI_PROCESS,
  1747. OCI_ROOT,
  1748. OCI_MOUNTS,
  1749. OCI_HOOKS,
  1750. OCI_LINUX,
  1751. OCI_ANNOTATIONS,
  1752. __OCI_MAX,
  1753. };
  1754. static const struct blobmsg_policy oci_policy[] = {
  1755. [OCI_VERSION] = { "ociVersion", BLOBMSG_TYPE_STRING },
  1756. [OCI_HOSTNAME] = { "hostname", BLOBMSG_TYPE_STRING },
  1757. [OCI_PROCESS] = { "process", BLOBMSG_TYPE_TABLE },
  1758. [OCI_ROOT] = { "root", BLOBMSG_TYPE_TABLE },
  1759. [OCI_MOUNTS] = { "mounts", BLOBMSG_TYPE_ARRAY },
  1760. [OCI_HOOKS] = { "hooks", BLOBMSG_TYPE_TABLE },
  1761. [OCI_LINUX] = { "linux", BLOBMSG_TYPE_TABLE },
  1762. [OCI_ANNOTATIONS] = { "annotations", BLOBMSG_TYPE_TABLE },
  1763. };
  1764. static int parseOCI(const char *jsonfile)
  1765. {
  1766. struct blob_attr *tb[__OCI_MAX];
  1767. struct blob_attr *cur;
  1768. int rem;
  1769. int res;
  1770. blob_buf_init(&ocibuf, 0);
  1771. if (!blobmsg_add_json_from_file(&ocibuf, jsonfile))
  1772. return ENOENT;
  1773. blobmsg_parse(oci_policy, __OCI_MAX, tb, blob_data(ocibuf.head), blob_len(ocibuf.head));
  1774. if (!tb[OCI_VERSION])
  1775. return ENOMSG;
  1776. if (strncmp("1.0", blobmsg_get_string(tb[OCI_VERSION]), 3)) {
  1777. ERROR("unsupported ociVersion %s\n", blobmsg_get_string(tb[OCI_VERSION]));
  1778. return ENOTSUP;
  1779. }
  1780. if (tb[OCI_HOSTNAME])
  1781. opts.hostname = strdup(blobmsg_get_string(tb[OCI_HOSTNAME]));
  1782. if (!tb[OCI_PROCESS])
  1783. return ENODATA;
  1784. if ((res = parseOCIprocess(tb[OCI_PROCESS])))
  1785. return res;
  1786. if (!tb[OCI_ROOT])
  1787. return ENODATA;
  1788. if ((res = parseOCIroot(jsonfile, tb[OCI_ROOT])))
  1789. return res;
  1790. if (!tb[OCI_MOUNTS])
  1791. return ENODATA;
  1792. blobmsg_for_each_attr(cur, tb[OCI_MOUNTS], rem)
  1793. if ((res = parseOCImount(cur)))
  1794. return res;
  1795. if (tb[OCI_LINUX] && (res = parseOCIlinux(tb[OCI_LINUX])))
  1796. return res;
  1797. if (tb[OCI_HOOKS] && (res = parseOCIhooks(tb[OCI_HOOKS])))
  1798. return res;
  1799. if (tb[OCI_ANNOTATIONS])
  1800. opts.annotations = blob_memdup(tb[OCI_ANNOTATIONS]);
  1801. blob_buf_free(&ocibuf);
  1802. return 0;
  1803. }
  1804. static int set_oom_score_adj(void)
  1805. {
  1806. int f;
  1807. char fname[32];
  1808. if (!opts.set_oom_score_adj)
  1809. return 0;
  1810. snprintf(fname, sizeof(fname), "/proc/%u/oom_score_adj", jail_process.pid);
  1811. f = open(fname, O_WRONLY | O_TRUNC);
  1812. if (f == -1)
  1813. return errno;
  1814. dprintf(f, "%d", opts.oom_score_adj);
  1815. close(f);
  1816. return 0;
  1817. }
  1818. enum {
  1819. OCI_STATE_CREATING,
  1820. OCI_STATE_CREATED,
  1821. OCI_STATE_RUNNING,
  1822. OCI_STATE_STOPPED,
  1823. };
  1824. static int jail_oci_state = OCI_STATE_CREATED;
  1825. static void pipe_send_start_container(struct uloop_timeout *t);
  1826. static struct uloop_timeout start_container_timeout = {
  1827. .cb = pipe_send_start_container,
  1828. };
  1829. static int handle_start(struct ubus_context *ctx, struct ubus_object *obj,
  1830. struct ubus_request_data *req, const char *method,
  1831. struct blob_attr *msg)
  1832. {
  1833. if (jail_oci_state != OCI_STATE_CREATED)
  1834. return UBUS_STATUS_INVALID_ARGUMENT;
  1835. uloop_timeout_add(&start_container_timeout);
  1836. return UBUS_STATUS_OK;
  1837. }
  1838. static struct blob_buf bb;
  1839. static int handle_state(struct ubus_context *ctx, struct ubus_object *obj,
  1840. struct ubus_request_data *req, const char *method,
  1841. struct blob_attr *msg)
  1842. {
  1843. char *statusstr;
  1844. switch (jail_oci_state) {
  1845. case OCI_STATE_CREATING:
  1846. statusstr = "creating";
  1847. break;
  1848. case OCI_STATE_CREATED:
  1849. statusstr = "created";
  1850. break;
  1851. case OCI_STATE_RUNNING:
  1852. statusstr = "running";
  1853. break;
  1854. case OCI_STATE_STOPPED:
  1855. statusstr = "stopped";
  1856. break;
  1857. default:
  1858. statusstr = "unknown";
  1859. }
  1860. blob_buf_init(&bb, 0);
  1861. blobmsg_add_string(&bb, "ociVersion", OCI_VERSION_STRING);
  1862. blobmsg_add_string(&bb, "id", opts.name);
  1863. blobmsg_add_string(&bb, "status", statusstr);
  1864. if (jail_oci_state == OCI_STATE_CREATED ||
  1865. jail_oci_state == OCI_STATE_RUNNING)
  1866. blobmsg_add_u32(&bb, "pid", jail_process.pid);
  1867. blobmsg_add_string(&bb, "bundle", opts.ocibundle);
  1868. if (opts.annotations)
  1869. blobmsg_add_blob(&bb, opts.annotations);
  1870. ubus_send_reply(ctx, req, bb.head);
  1871. return UBUS_STATUS_OK;
  1872. }
  1873. enum {
  1874. CONTAINER_KILL_ATTR_SIGNAL,
  1875. __CONTAINER_KILL_ATTR_MAX,
  1876. };
  1877. static const struct blobmsg_policy container_kill_attrs[__CONTAINER_KILL_ATTR_MAX] = {
  1878. [CONTAINER_KILL_ATTR_SIGNAL] = { "signal", BLOBMSG_TYPE_INT32 },
  1879. };
  1880. static int
  1881. container_handle_kill(struct ubus_context *ctx, struct ubus_object *obj,
  1882. struct ubus_request_data *req, const char *method,
  1883. struct blob_attr *msg)
  1884. {
  1885. struct blob_attr *tb[__CONTAINER_KILL_ATTR_MAX], *cur;
  1886. int sig = SIGTERM;
  1887. blobmsg_parse(container_kill_attrs, __CONTAINER_KILL_ATTR_MAX, tb, blobmsg_data(msg), blobmsg_data_len(msg));
  1888. cur = tb[CONTAINER_KILL_ATTR_SIGNAL];
  1889. if (cur)
  1890. sig = blobmsg_get_u32(cur);
  1891. if (jail_oci_state == OCI_STATE_CREATING)
  1892. return UBUS_STATUS_NOT_FOUND;
  1893. if (kill(jail_process.pid, sig) == 0)
  1894. return 0;
  1895. switch (errno) {
  1896. case EINVAL: return UBUS_STATUS_INVALID_ARGUMENT;
  1897. case EPERM: return UBUS_STATUS_PERMISSION_DENIED;
  1898. case ESRCH: return UBUS_STATUS_NOT_FOUND;
  1899. }
  1900. return UBUS_STATUS_UNKNOWN_ERROR;
  1901. }
  1902. static struct ubus_method container_methods[] = {
  1903. UBUS_METHOD_NOARG("start", handle_start),
  1904. UBUS_METHOD_NOARG("state", handle_state),
  1905. UBUS_METHOD("kill", container_handle_kill, container_kill_attrs),
  1906. };
  1907. static struct ubus_object_type container_object_type =
  1908. UBUS_OBJECT_TYPE("container", container_methods);
  1909. static struct ubus_object container_object = {
  1910. .type = &container_object_type,
  1911. .methods = container_methods,
  1912. .n_methods = ARRAY_SIZE(container_methods),
  1913. };
  1914. static void post_main(struct uloop_timeout *t);
  1915. static struct uloop_timeout post_main_timeout = {
  1916. .cb = post_main,
  1917. };
  1918. static int netns_fd;
  1919. static int pidns_fd;
  1920. #ifdef CLONE_NEWTIME
  1921. static int timens_fd;
  1922. #endif
  1923. static void post_create_runtime(void);
  1924. int main(int argc, char **argv)
  1925. {
  1926. uid_t uid = getuid();
  1927. const char log[] = "/dev/log";
  1928. const char ubus[] = "/var/run/ubus/ubus.sock";
  1929. int ch, ret;
  1930. if (uid) {
  1931. ERROR("not root, aborting: %m\n");
  1932. return EXIT_FAILURE;
  1933. }
  1934. umask(022);
  1935. mount_list_init();
  1936. init_library_search();
  1937. while ((ch = getopt(argc, argv, OPT_ARGS)) != -1) {
  1938. switch (ch) {
  1939. case 'd':
  1940. debug = atoi(optarg);
  1941. break;
  1942. case 'p':
  1943. opts.namespace |= CLONE_NEWNS;
  1944. opts.procfs = 1;
  1945. break;
  1946. case 'o':
  1947. opts.namespace |= CLONE_NEWNS;
  1948. opts.ronly = 1;
  1949. break;
  1950. case 'f':
  1951. opts.namespace |= CLONE_NEWUSER;
  1952. break;
  1953. case 'F':
  1954. opts.namespace |= CLONE_NEWCGROUP;
  1955. break;
  1956. case 'R':
  1957. opts.extroot = strdup(optarg);
  1958. break;
  1959. case 's':
  1960. opts.namespace |= CLONE_NEWNS;
  1961. opts.sysfs = 1;
  1962. break;
  1963. case 'S':
  1964. opts.seccomp = optarg;
  1965. add_mount_bind(optarg, 1, -1);
  1966. break;
  1967. case 'C':
  1968. opts.capabilities = optarg;
  1969. break;
  1970. case 'c':
  1971. opts.no_new_privs = 1;
  1972. break;
  1973. case 'n':
  1974. opts.name = optarg;
  1975. break;
  1976. case 'N':
  1977. opts.namespace |= CLONE_NEWNET;
  1978. break;
  1979. case 'h':
  1980. opts.namespace |= CLONE_NEWUTS;
  1981. opts.hostname = strdup(optarg);
  1982. break;
  1983. case 'r':
  1984. opts.namespace |= CLONE_NEWNS;
  1985. add_path_and_deps(optarg, 1, 0, 0);
  1986. break;
  1987. case 'w':
  1988. opts.namespace |= CLONE_NEWNS;
  1989. add_path_and_deps(optarg, 0, 0, 0);
  1990. break;
  1991. case 'u':
  1992. opts.namespace |= CLONE_NEWNS;
  1993. add_mount_bind(ubus, 0, -1);
  1994. break;
  1995. case 'l':
  1996. opts.namespace |= CLONE_NEWNS;
  1997. add_mount_bind(log, 0, -1);
  1998. break;
  1999. case 'U':
  2000. opts.user = optarg;
  2001. break;
  2002. case 'G':
  2003. opts.group = optarg;
  2004. break;
  2005. case 'O':
  2006. opts.overlaydir = optarg;
  2007. break;
  2008. case 'T':
  2009. opts.tmpoverlaysize = optarg;
  2010. break;
  2011. case 'E':
  2012. opts.require_jail = 1;
  2013. break;
  2014. case 'y':
  2015. opts.console = 1;
  2016. break;
  2017. case 'J':
  2018. opts.ocibundle = strdup(optarg);
  2019. break;
  2020. case 'i':
  2021. opts.immediately = true;
  2022. break;
  2023. }
  2024. }
  2025. if (opts.namespace && !opts.ocibundle)
  2026. opts.namespace |= CLONE_NEWIPC | CLONE_NEWPID;
  2027. /* those are filehandlers, so -1 indicates unused */
  2028. opts.setns.pid = -1;
  2029. opts.setns.net = -1;
  2030. opts.setns.ns = -1;
  2031. opts.setns.ipc = -1;
  2032. opts.setns.uts = -1;
  2033. opts.setns.user = -1;
  2034. opts.setns.cgroup = -1;
  2035. #ifdef CLONE_NEWTIME
  2036. opts.setns.time = -1;
  2037. #endif
  2038. if (opts.capabilities && parseOCIcapabilities_from_file(&opts.capset, opts.capabilities)) {
  2039. ERROR("failed to read capabilities from file %s\n", opts.capabilities);
  2040. return -1;
  2041. }
  2042. if (opts.ocibundle) {
  2043. char *jsonfile;
  2044. int ocires;
  2045. asprintf(&jsonfile, "%s/config.json", opts.ocibundle);
  2046. ocires = parseOCI(jsonfile);
  2047. free(jsonfile);
  2048. if (ocires) {
  2049. ERROR("parsing of OCI JSON spec has failed: %s (%d)\n", strerror(ocires), ocires);
  2050. return ocires;
  2051. }
  2052. }
  2053. if (opts.tmpoverlaysize && strlen(opts.tmpoverlaysize) > 8) {
  2054. ERROR("size parameter too long: \"%s\"\n", opts.tmpoverlaysize);
  2055. return -1;
  2056. }
  2057. /* no <binary> param found */
  2058. if (!opts.ocibundle && (argc - optind < 1)) {
  2059. usage();
  2060. return EXIT_FAILURE;
  2061. }
  2062. if (!(opts.ocibundle||opts.namespace||opts.capabilities||opts.seccomp)) {
  2063. ERROR("Not using namespaces, capabilities or seccomp !!!\n\n");
  2064. usage();
  2065. return EXIT_FAILURE;
  2066. }
  2067. DEBUG("Using namespaces(0x%08x), capabilities(%d), seccomp(%d)\n",
  2068. opts.namespace,
  2069. opts.capset.apply,
  2070. opts.seccomp != 0 || opts.ociseccomp != 0);
  2071. uloop_init();
  2072. signals_init();
  2073. parent_ctx = ubus_connect(NULL);
  2074. ubus_add_uloop(parent_ctx);
  2075. if (opts.ocibundle) {
  2076. char *objname;
  2077. if (asprintf(&objname, "container.%s", opts.name) < 0)
  2078. exit(-ENOMEM);
  2079. container_object.name = objname;
  2080. ret = ubus_add_object(parent_ctx, &container_object);
  2081. if (ret) {
  2082. ERROR("Failed to add object: %s\n", ubus_strerror(ret));
  2083. exit(-1);
  2084. }
  2085. }
  2086. /* deliberately not using 'else' on unrelated conditional branches */
  2087. if (!opts.ocibundle) {
  2088. /* allocate NULL-terminated array for argv */
  2089. opts.jail_argv = calloc(1 + argc - optind, sizeof(char**));
  2090. if (!opts.jail_argv)
  2091. return EXIT_FAILURE;
  2092. for (size_t s = optind; s < argc; s++)
  2093. opts.jail_argv[s - optind] = strdup(argv[s]);
  2094. if (opts.namespace & CLONE_NEWUSER)
  2095. get_jail_user(&opts.pw_uid, &opts.pw_gid, &opts.gr_gid);
  2096. }
  2097. if (!opts.extroot) {
  2098. if (opts.namespace && add_path_and_deps(*opts.jail_argv, 1, -1, 0)) {
  2099. ERROR("failed to load dependencies\n");
  2100. return -1;
  2101. }
  2102. }
  2103. if (opts.namespace && opts.seccomp && add_path_and_deps("libpreload-seccomp.so", 1, -1, 1)) {
  2104. ERROR("failed to load libpreload-seccomp.so\n");
  2105. opts.seccomp = 0;
  2106. if (opts.require_jail)
  2107. return -1;
  2108. }
  2109. uloop_timeout_add(&post_main_timeout);
  2110. uloop_run();
  2111. /* unreachable */
  2112. return 0;
  2113. }
  2114. static void post_main(struct uloop_timeout *t)
  2115. {
  2116. if (apply_rlimits()) {
  2117. ERROR("error applying resource limits\n");
  2118. exit(EXIT_FAILURE);
  2119. }
  2120. if (opts.name)
  2121. prctl(PR_SET_NAME, opts.name, NULL, NULL, NULL);
  2122. if (pipe(&pipes[0]) < 0 || pipe(&pipes[2]) < 0)
  2123. exit(-1);
  2124. if (has_namespaces()) {
  2125. if (opts.namespace & CLONE_NEWNS) {
  2126. if (!opts.extroot && (opts.user || opts.group)) {
  2127. add_mount_bind("/etc/passwd", 0, -1);
  2128. add_mount_bind("/etc/group", 0, -1);
  2129. }
  2130. #if defined(__GLIBC__)
  2131. if (!opts.extroot)
  2132. add_mount_bind("/etc/nsswitch.conf", 0, -1);
  2133. #endif
  2134. if (!(opts.namespace & CLONE_NEWNET)) {
  2135. add_mount_bind("/etc/resolv.conf", 0, -1);
  2136. } else if (opts.setns.net == -1) {
  2137. char hostdir[PATH_MAX];
  2138. snprintf(hostdir, PATH_MAX, "/tmp/resolv.conf-%s.d", opts.name);
  2139. mkdir_p(hostdir, 0755);
  2140. add_mount(hostdir, "/dev/resolv.conf.d", NULL, MS_BIND | MS_NOEXEC | MS_NOATIME | MS_NOSUID | MS_NODEV | MS_RDONLY, NULL, -1);
  2141. }
  2142. /* default mounts */
  2143. add_mount(NULL, "/dev", "tmpfs", MS_NOATIME | MS_NOEXEC | MS_NOSUID, "size=1M", -1);
  2144. add_mount(NULL, "/dev/pts", "devpts", MS_NOATIME | MS_NOEXEC | MS_NOSUID, "newinstance,ptmxmode=0666,mode=0620,gid=5", 0);
  2145. if (opts.procfs || opts.ocibundle) {
  2146. add_mount("proc", "/proc", "proc", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID, NULL, -1);
  2147. /*
  2148. * hack to make /proc/sys/net read-write while the rest of /proc/sys is read-only
  2149. * which cannot be expressed with OCI spec, but happends to be very useful.
  2150. * Only apply it if '/proc/sys' is not already listed as mount, maskedPath or
  2151. * readonlyPath.
  2152. * If not running in a new network namespace, only make /proc/sys read-only.
  2153. * If running in a new network namespace, temporarily stash (ie. mount-bind)
  2154. * /proc/sys/net into (totally unrelated, but surely existing) /proc/self/net.
  2155. * Then we mount-bind /proc/sys read-only and then mount-move /proc/self/net into
  2156. * /proc/sys/net.
  2157. * This works because mounts are executed in incrementing strcmp() order and
  2158. * /proc/self/net appears there before /proc/sys/net and hence the operation
  2159. * succeeds as the bind-mount of /proc/self/net is performed first and then
  2160. * move-mount of /proc/sys/net follows because 'e' preceeds 'y' in the ASCII
  2161. * table (and in the alphabet).
  2162. */
  2163. if (!add_mount(NULL, "/proc/sys", NULL, MS_BIND | MS_RDONLY, NULL, -1))
  2164. if (opts.namespace & CLONE_NEWNET)
  2165. if (!add_mount_inner("/proc/self/net", "/proc/sys/net", NULL, MS_MOVE, NULL, -1))
  2166. add_mount_inner("/proc/sys/net", "/proc/self/net", NULL, MS_BIND, NULL, -1);
  2167. }
  2168. if (opts.sysfs || opts.ocibundle)
  2169. add_mount("sysfs", "/sys", "sysfs", MS_NOATIME | MS_NODEV | MS_NOEXEC | MS_NOSUID | MS_RDONLY, NULL, -1);
  2170. if (opts.ocibundle)
  2171. add_mount("shm", "/dev/shm", "tmpfs", MS_NOSUID | MS_NOEXEC | MS_NODEV, "mode=1777", -1);
  2172. }
  2173. if (opts.setns.pid != -1) {
  2174. pidns_fd = ns_open_pid("pid", getpid());
  2175. setns_open(CLONE_NEWPID);
  2176. } else {
  2177. pidns_fd = -1;
  2178. }
  2179. #ifdef CLONE_NEWTIME
  2180. if (opts.setns.time != -1) {
  2181. timens_fd = ns_open_pid("time", getpid());
  2182. setns_open(CLONE_NEWTIME);
  2183. }
  2184. #endif
  2185. jail_process.pid = clone(exec_jail, child_stack + STACK_SIZE, SIGCHLD | (opts.namespace & (~CLONE_NEWCGROUP)), NULL);
  2186. } else {
  2187. jail_process.pid = fork();
  2188. }
  2189. if (jail_process.pid > 0) {
  2190. /* parent process */
  2191. char sig_buf[1];
  2192. uloop_process_add(&jail_process);
  2193. jail_running = 1;
  2194. seteuid(0);
  2195. if (pidns_fd != -1) {
  2196. setns(pidns_fd, CLONE_NEWPID);
  2197. close(pidns_fd);
  2198. }
  2199. #ifdef CLONE_NEWTIME
  2200. if (timens_fd != -1)
  2201. setns(timens_fd, CLONE_NEWTIME);
  2202. close(timens_fd);
  2203. }
  2204. #endif
  2205. if (opts.setns.net != -1)
  2206. close(opts.setns.net);
  2207. if (opts.setns.ns != -1)
  2208. close(opts.setns.ns);
  2209. if (opts.setns.ipc != -1)
  2210. close(opts.setns.ipc);
  2211. if (opts.setns.uts != -1)
  2212. close(opts.setns.uts);
  2213. if (opts.setns.user != -1)
  2214. close(opts.setns.user);
  2215. if (opts.setns.cgroup != -1)
  2216. close(opts.setns.cgroup);
  2217. close(pipes[1]);
  2218. close(pipes[2]);
  2219. if (read(pipes[0], sig_buf, 1) < 1) {
  2220. ERROR("can't read from child\n");
  2221. exit(-1);
  2222. }
  2223. close(pipes[0]);
  2224. set_oom_score_adj();
  2225. if (opts.ocibundle)
  2226. cgroups_apply(jail_process.pid);
  2227. if (opts.namespace & CLONE_NEWUSER) {
  2228. if (write_setgroups(jail_process.pid, true)) {
  2229. ERROR("can't write setgroups\n");
  2230. exit(-1);
  2231. }
  2232. if (!opts.uidmap) {
  2233. bool has_gr = (opts.gr_gid != -1);
  2234. if (opts.pw_uid != -1) {
  2235. write_single_uid_gid_map(jail_process.pid, 0, opts.pw_uid);
  2236. write_single_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:opts.pw_gid);
  2237. } else {
  2238. write_single_uid_gid_map(jail_process.pid, 0, 65534);
  2239. write_single_uid_gid_map(jail_process.pid, 1, has_gr?opts.gr_gid:65534);
  2240. }
  2241. } else {
  2242. write_uid_gid_map(jail_process.pid, 0, opts.uidmap);
  2243. if (opts.gidmap)
  2244. write_uid_gid_map(jail_process.pid, 1, opts.gidmap);
  2245. }
  2246. }
  2247. if (opts.namespace & CLONE_NEWNET) {
  2248. if (!opts.name) {
  2249. ERROR("netns needs a named jail\n");
  2250. exit(-1);
  2251. }
  2252. netns_fd = ns_open_pid("net", jail_process.pid);
  2253. netns_updown(jail_process.pid, true);
  2254. }
  2255. } else if (jail_process.pid == 0) {
  2256. /* fork child process */
  2257. exit(exec_jail(NULL));
  2258. } else {
  2259. ERROR("failed to clone/fork: %m\n");
  2260. exit(EXIT_FAILURE);
  2261. }
  2262. run_hooks(opts.hooks.createRuntime, post_create_runtime);
  2263. }
  2264. static void post_poststart(void);
  2265. static void post_create_runtime(void)
  2266. {
  2267. char sig_buf[1];
  2268. sig_buf[0] = 'O';
  2269. if (write(pipes[3], sig_buf, 1) < 0) {
  2270. ERROR("can't write to child\n");
  2271. exit(-1);
  2272. }
  2273. jail_oci_state = OCI_STATE_CREATED;
  2274. if (opts.ocibundle && !opts.immediately)
  2275. uloop_run(); /* wait for 'start' command via ubus */
  2276. else
  2277. pipe_send_start_container(NULL);
  2278. }
  2279. static void pipe_send_start_container(struct uloop_timeout *t)
  2280. {
  2281. char sig_buf[1];
  2282. jail_oci_state = OCI_STATE_RUNNING;
  2283. sig_buf[0] = '!';
  2284. if (write(pipes[3], sig_buf, 1) < 0) {
  2285. ERROR("can't write to child\n");
  2286. exit(-1);
  2287. }
  2288. close(pipes[3]);
  2289. run_hooks(opts.hooks.poststart, post_poststart);
  2290. }
  2291. static void post_poststart(void)
  2292. {
  2293. uloop_run(); /* idle here while jail is running */
  2294. if (jail_running) {
  2295. DEBUG("uloop interrupted, killing jail process\n");
  2296. kill(jail_process.pid, SIGTERM);
  2297. uloop_timeout_set(&jail_process_timeout, 1000);
  2298. uloop_run();
  2299. }
  2300. uloop_done();
  2301. poststop();
  2302. }
  2303. static void post_poststop(void);
  2304. static void poststop(void) {
  2305. if (opts.namespace & CLONE_NEWNET) {
  2306. setns(netns_fd, CLONE_NEWNET);
  2307. netns_updown(getpid(), false);
  2308. close(netns_fd);
  2309. }
  2310. run_hooks(opts.hooks.poststop, post_poststop);
  2311. }
  2312. static void post_poststop(void)
  2313. {
  2314. free_opts(true);
  2315. if (parent_ctx)
  2316. ubus_free(parent_ctx);
  2317. exit(jail_return_code);
  2318. }