jail.c 74 KB

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