jail.c 74 KB

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