jail.c 69 KB

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