jail.c 73 KB

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