jail.c 68 KB

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