jail.c 69 KB

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