qrexec-agent.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. /*
  2. * The Qubes OS Project, http://www.qubes-os.org
  3. *
  4. * Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU General Public License
  8. * as published by the Free Software Foundation; either version 2
  9. * of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. *
  20. */
  21. #define _GNU_SOURCE
  22. #define HAVE_PAM
  23. #include <sys/select.h>
  24. #include <sys/socket.h>
  25. #include <sys/un.h>
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <signal.h>
  29. #include <unistd.h>
  30. #include <errno.h>
  31. #include <sys/wait.h>
  32. #include <fcntl.h>
  33. #include <string.h>
  34. #include <pwd.h>
  35. #include <grp.h>
  36. #include <sys/stat.h>
  37. #include <assert.h>
  38. #ifdef HAVE_PAM
  39. #include <security/pam_appl.h>
  40. #endif
  41. #include "qrexec.h"
  42. #include <libvchan.h>
  43. #include "libqrexec-utils.h"
  44. #include "qrexec-agent.h"
  45. struct _connection_info {
  46. int pid; /* pid of child process handling the data */
  47. int fd; /* socket to process handling the data (wait for EOF here) */
  48. int connect_domain;
  49. int connect_port;
  50. };
  51. int max_process_fd = -1;
  52. /* */
  53. struct _connection_info connection_info[MAX_FDS];
  54. libvchan_t *ctrl_vchan;
  55. int trigger_fd;
  56. int meminfo_write_started = 0;
  57. void no_colon_in_cmd()
  58. {
  59. fprintf(stderr,
  60. "cmdline is supposed to be in user:command form\n");
  61. exit(1);
  62. }
  63. #ifdef HAVE_PAM
  64. int pam_conv_callback(int num_msg, const struct pam_message **msg,
  65. struct pam_response **resp, void *appdata_ptr __attribute__((__unused__)))
  66. {
  67. int i;
  68. struct pam_response *resp_array =
  69. calloc(sizeof(struct pam_response), num_msg);
  70. if (resp_array == NULL)
  71. return PAM_BUF_ERR;
  72. for (i=0; i<num_msg; i++) {
  73. if (msg[i]->msg_style == PAM_ERROR_MSG)
  74. fprintf(stderr, "%s", msg[i]->msg);
  75. if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF ||
  76. msg[i]->msg_style == PAM_PROMPT_ECHO_ON) {
  77. resp_array[i].resp = strdup("");
  78. resp_array[i].resp_retcode = 0;
  79. }
  80. }
  81. *resp = resp_array;
  82. return PAM_SUCCESS;
  83. }
  84. static struct pam_conv conv = {
  85. pam_conv_callback,
  86. NULL
  87. };
  88. #endif
  89. /* Start program requested by dom0 in already prepared process
  90. * (stdin/stdout/stderr already set, etc)
  91. * Called in two cases:
  92. * MSG_JUST_EXEC - from qrexec-agent-data.c:handle_new_process_common->handle_just_exec
  93. * MSG_EXEC_CMDLINE - from
  94. * qrexec-agent-data.c:handle_new_process_common->do_fork_exec (callback
  95. * registerd with register_exec_func in init() here)
  96. *
  97. * cmd parameter came from dom0 (MSG_JUST_EXEC or MSG_EXEC_CMDLINE messages), so
  98. * is trusted. Even in VM-VM service request, the command here is controlled by
  99. * dom0 - it will be in form:
  100. * RPC_REQUEST_COMMAND " " service_name " " source_vm_name
  101. * where service_name is already validated against Qrexec RPC policy
  102. *
  103. * If dom0 sends overly long cmd, it will probably crash qrexec-agent (unless
  104. * process can allocate up to 4GB on both stack and heap), sorry.
  105. */
  106. void do_exec(const char *cmd)
  107. {
  108. char buf[strlen(QUBES_RPC_MULTIPLEXER_PATH) + strlen(cmd) - RPC_REQUEST_COMMAND_LEN + 1];
  109. char *realcmd = index(cmd, ':'), *user;
  110. #ifdef HAVE_PAM
  111. int retval, status;
  112. pam_handle_t *pamh=NULL;
  113. struct passwd *pw;
  114. struct passwd pw_copy;
  115. pid_t child, pid;
  116. char **env;
  117. char pid_s[32];
  118. #endif
  119. if (!realcmd)
  120. no_colon_in_cmd();
  121. /* mark end of username and move to command */
  122. user=strndup(cmd,realcmd-cmd);
  123. realcmd++;
  124. /* ignore "nogui:" prefix in linux agent */
  125. if (strncmp(realcmd, NOGUI_CMD_PREFIX, NOGUI_CMD_PREFIX_LEN) == 0)
  126. realcmd += NOGUI_CMD_PREFIX_LEN;
  127. /* replace magic RPC cmd with RPC multiplexer path */
  128. if (strncmp(realcmd, RPC_REQUEST_COMMAND " ", RPC_REQUEST_COMMAND_LEN+1)==0) {
  129. strcpy(buf, QUBES_RPC_MULTIPLEXER_PATH);
  130. strcpy(buf + strlen(QUBES_RPC_MULTIPLEXER_PATH), realcmd + RPC_REQUEST_COMMAND_LEN);
  131. realcmd = buf;
  132. }
  133. signal(SIGCHLD, SIG_DFL);
  134. signal(SIGPIPE, SIG_DFL);
  135. #ifdef HAVE_PAM
  136. pw = getpwnam (user);
  137. if (! (pw && pw->pw_name && pw->pw_name[0] && pw->pw_dir && pw->pw_dir[0]
  138. && pw->pw_passwd)) {
  139. fprintf(stderr, "user %s does not exist", user);
  140. exit(1);
  141. }
  142. /* Make a copy of the password information and point pw at the local
  143. * copy instead. Otherwise, some systems (e.g. Linux) would clobber
  144. * the static data through the getlogin call.
  145. */
  146. pw_copy = *pw;
  147. pw = &pw_copy;
  148. pw->pw_name = strdup(pw->pw_name);
  149. pw->pw_passwd = strdup(pw->pw_passwd);
  150. pw->pw_dir = strdup(pw->pw_dir);
  151. pw->pw_shell = strdup(pw->pw_shell);
  152. endpwent();
  153. retval = pam_start("qrexec", user, &conv, &pamh);
  154. if (retval != PAM_SUCCESS)
  155. goto error;
  156. retval = pam_authenticate(pamh, 0);
  157. if (retval != PAM_SUCCESS)
  158. goto error;
  159. retval = initgroups(pw->pw_name, pw->pw_gid);
  160. if (retval == -1) {
  161. perror("initgroups");
  162. goto error;
  163. }
  164. retval = pam_setcred(pamh, PAM_ESTABLISH_CRED);
  165. if (retval != PAM_SUCCESS)
  166. goto error;
  167. retval = pam_open_session(pamh, 0);
  168. if (retval != PAM_SUCCESS)
  169. goto error;
  170. /* provide this variable to child process */
  171. snprintf(pid_s, sizeof(pid_s), "QREXEC_AGENT_PID=%d", getppid());
  172. retval = pam_putenv(pamh, pid_s);
  173. if (retval != PAM_SUCCESS)
  174. goto error;
  175. /* FORK HERE */
  176. child = fork ();
  177. switch (child) {
  178. case -1:
  179. goto error;
  180. case 0:
  181. /* child */
  182. if (setgid (pw->pw_gid))
  183. exit(126);
  184. if (setuid (pw->pw_uid))
  185. exit(126);
  186. setsid();
  187. /* This is a copy but don't care to free as we exec later anyways. */
  188. env = pam_getenvlist (pamh);
  189. execle("/bin/sh", "-sh", "-c", realcmd, (char*)NULL, env);
  190. exit(127);
  191. default:
  192. /* parent */
  193. /* close std*, so when child process closes them, qrexec-agent will receive EOF */
  194. /* this is the main purpose of this reimplementation of /bin/su... */
  195. close(0);
  196. close(1);
  197. close(2);
  198. }
  199. /* reachable only in parent */
  200. pid = waitpid (child, &status, 0);
  201. if (pid != (pid_t)-1) {
  202. if (WIFSIGNALED (status))
  203. status = WTERMSIG (status) + 128;
  204. else
  205. status = WEXITSTATUS (status);
  206. } else
  207. status = 1;
  208. retval = pam_close_session (pamh, 0);
  209. retval = pam_setcred (pamh, PAM_DELETE_CRED | PAM_SILENT);
  210. if (pam_end(pamh, retval) != PAM_SUCCESS) { /* close Linux-PAM */
  211. pamh = NULL;
  212. exit(1);
  213. }
  214. exit(status);
  215. error:
  216. pam_end(pamh, PAM_ABORT);
  217. exit(1);
  218. #else
  219. execl("/bin/su", "su", "-", user, "-c", realcmd, NULL);
  220. perror("execl");
  221. exit(1);
  222. #endif
  223. }
  224. void handle_vchan_error(const char *op)
  225. {
  226. fprintf(stderr, "Error while vchan %s, exiting\n", op);
  227. exit(1);
  228. }
  229. void init()
  230. {
  231. mode_t old_umask;
  232. /* FIXME: This 0 is remote domain ID */
  233. ctrl_vchan = libvchan_server_init(0, VCHAN_BASE_PORT, 4096, 4096);
  234. if (!ctrl_vchan)
  235. handle_vchan_error("server_init");
  236. if (handle_handshake(ctrl_vchan) < 0)
  237. exit(1);
  238. old_umask = umask(0);
  239. trigger_fd = get_server_socket(QREXEC_AGENT_TRIGGER_PATH);
  240. umask(old_umask);
  241. register_exec_func(do_exec);
  242. /* wait for qrexec daemon */
  243. while (!libvchan_is_open(ctrl_vchan))
  244. libvchan_wait(ctrl_vchan);
  245. }
  246. void wake_meminfo_writer()
  247. {
  248. FILE *f;
  249. int pid;
  250. if (meminfo_write_started)
  251. /* wake meminfo-writer only once */
  252. return;
  253. f = fopen(MEMINFO_WRITER_PIDFILE, "r");
  254. if (f == NULL) {
  255. /* no meminfo-writer found, ignoring */
  256. return;
  257. }
  258. if (fscanf(f, "%d", &pid) < 1) {
  259. fclose(f);
  260. /* no meminfo-writer found, ignoring */
  261. return;
  262. }
  263. fclose(f);
  264. if (pid <= 1 || pid > 0xffff) {
  265. /* check within acceptable range */
  266. return;
  267. }
  268. if (kill(pid, SIGUSR1) < 0) {
  269. /* Can't send signal */
  270. return;
  271. }
  272. meminfo_write_started = 1;
  273. }
  274. int try_fork_server(int type, int connect_domain, int connect_port,
  275. char *cmdline, int cmdline_len) {
  276. char username[cmdline_len];
  277. char *colon;
  278. char *fork_server_socket_path;
  279. int s, len;
  280. struct sockaddr_un remote;
  281. struct qrexec_cmd_info info;
  282. strncpy(username, cmdline, cmdline_len);
  283. colon = index(username, ':');
  284. if (!colon)
  285. return -1;
  286. *colon = '\0';
  287. if (asprintf(&fork_server_socket_path, QREXEC_FORK_SERVER_SOCKET, username) < 0) {
  288. fprintf(stderr, "Memory allocation failed\n");
  289. return -1;
  290. }
  291. remote.sun_family = AF_UNIX;
  292. strncpy(remote.sun_path, fork_server_socket_path,
  293. sizeof(remote.sun_path));
  294. free(fork_server_socket_path);
  295. if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
  296. perror("socket");
  297. return -1;
  298. }
  299. len = strlen(remote.sun_path) + sizeof(remote.sun_family);
  300. if (connect(s, (struct sockaddr *) &remote, len) == -1) {
  301. if (errno != ECONNREFUSED && errno != ENOENT)
  302. perror("connect");
  303. close(s);
  304. return -1;
  305. }
  306. info.type = type;
  307. info.connect_domain = connect_domain;
  308. info.connect_port = connect_port;
  309. info.cmdline_len = cmdline_len-(strlen(username)+1);
  310. if (!write_all(s, &info, sizeof(info))) {
  311. perror("write");
  312. close(s);
  313. return -1;
  314. }
  315. if (!write_all(s, colon+1, info.cmdline_len)) {
  316. perror("write");
  317. close(s);
  318. return -1;
  319. }
  320. return s;
  321. }
  322. void register_vchan_connection(pid_t pid, int fd, int domain, int port)
  323. {
  324. int i;
  325. for (i = 0; i < MAX_FDS; i++) {
  326. if (connection_info[i].pid == 0) {
  327. connection_info[i].pid = pid;
  328. connection_info[i].fd = fd;
  329. connection_info[i].connect_domain = domain;
  330. connection_info[i].connect_port = port;
  331. return;
  332. }
  333. }
  334. fprintf(stderr, "No free slot for child %d (connection to %d:%d)\n", pid, domain, port);
  335. }
  336. /* hdr parameter is received from dom0, so it is trusted */
  337. void handle_server_exec_request(struct msg_header *hdr)
  338. {
  339. struct exec_params params;
  340. int buf_len = hdr->len-sizeof(params);
  341. char buf[buf_len];
  342. pid_t child_agent;
  343. int client_fd;
  344. assert(hdr->len >= sizeof(params));
  345. if (libvchan_recv(ctrl_vchan, &params, sizeof(params)) < 0)
  346. handle_vchan_error("read exec params");
  347. if (libvchan_recv(ctrl_vchan, buf, buf_len) < 0)
  348. handle_vchan_error("read exec cmd");
  349. if ((hdr->type == MSG_EXEC_CMDLINE || hdr->type == MSG_JUST_EXEC) &&
  350. !strstr(buf, ":nogui:")) {
  351. int child_socket = try_fork_server(hdr->type,
  352. params.connect_domain, params.connect_port,
  353. buf, buf_len);
  354. if (child_socket >= 0) {
  355. register_vchan_connection(-1, child_socket,
  356. params.connect_domain, params.connect_port);
  357. return;
  358. }
  359. }
  360. if (hdr->type == MSG_SERVICE_CONNECT && sscanf(buf, "SOCKET%d", &client_fd)) {
  361. /* FIXME: Maybe add some check if client_fd is really FD to some
  362. * qrexec-client-vm process; but this data comes from qrexec-daemon
  363. * (which sends back what it got from us earlier), so it isn't critical.
  364. */
  365. if (write(client_fd, &params, sizeof(params)) < 0) {
  366. /* ignore */
  367. }
  368. /* No need to send request_id (buf) - the client don't need it, there
  369. * is only meaningless (for the client) socket FD */
  370. /* Register connection even if there was an error sending params to
  371. * qrexec-client-vm. This way the mainloop will clean the things up
  372. * (close socket, send MSG_CONNECTION_TERMINATED) when qrexec-client-vm
  373. * will close the socket (terminate itself). */
  374. register_vchan_connection(-1, client_fd,
  375. params.connect_domain, params.connect_port);
  376. return;
  377. }
  378. /* No fork server case */
  379. child_agent = handle_new_process(hdr->type,
  380. params.connect_domain, params.connect_port,
  381. buf, buf_len);
  382. register_vchan_connection(child_agent, -1,
  383. params.connect_domain, params.connect_port);
  384. }
  385. void handle_service_refused(struct msg_header *hdr)
  386. {
  387. struct service_params params;
  388. int socket_fd;
  389. if (hdr->len != sizeof(params)) {
  390. fprintf(stderr, "Invalid msg 0x%x length (%d)\n", MSG_SERVICE_REFUSED, hdr->len);
  391. exit(1);
  392. }
  393. if (libvchan_recv(ctrl_vchan, &params, sizeof(params)) < 0)
  394. handle_vchan_error("read exec params");
  395. if (sscanf(params.ident, "SOCKET%d", &socket_fd))
  396. close(socket_fd);
  397. else
  398. fprintf(stderr, "Received REFUSED for unknown service request '%s'\n", params.ident);
  399. }
  400. void handle_server_cmd()
  401. {
  402. struct msg_header s_hdr;
  403. if (libvchan_recv(ctrl_vchan, &s_hdr, sizeof(s_hdr)) < 0)
  404. handle_vchan_error("read s_hdr");
  405. // fprintf(stderr, "got %x %x %x\n", s_hdr.type, s_hdr.client_id,
  406. // s_hdr.len);
  407. switch (s_hdr.type) {
  408. case MSG_EXEC_CMDLINE:
  409. case MSG_JUST_EXEC:
  410. case MSG_SERVICE_CONNECT:
  411. wake_meminfo_writer();
  412. handle_server_exec_request(&s_hdr);
  413. break;
  414. case MSG_SERVICE_REFUSED:
  415. handle_service_refused(&s_hdr);
  416. break;
  417. default:
  418. fprintf(stderr, "msg type from daemon is %d ?\n",
  419. s_hdr.type);
  420. exit(1);
  421. }
  422. }
  423. volatile int child_exited;
  424. void sigchld_handler(int x __attribute__((__unused__)))
  425. {
  426. child_exited = 1;
  427. signal(SIGCHLD, sigchld_handler);
  428. }
  429. int find_connection(int pid)
  430. {
  431. int i;
  432. for (i = 0; i < MAX_FDS; i++)
  433. if (connection_info[i].pid == pid)
  434. return i;
  435. return -1;
  436. }
  437. void release_connection(int id) {
  438. struct msg_header hdr;
  439. struct exec_params params;
  440. hdr.type = MSG_CONNECTION_TERMINATED;
  441. hdr.len = sizeof(struct exec_params);
  442. params.connect_domain = connection_info[id].connect_domain;
  443. params.connect_port = connection_info[id].connect_port;
  444. if (libvchan_send(ctrl_vchan, &hdr, sizeof(hdr)) < 0)
  445. handle_vchan_error("send");
  446. if (libvchan_send(ctrl_vchan, &params, sizeof(params)) < 0)
  447. handle_vchan_error("send");
  448. connection_info[id].pid = 0;
  449. }
  450. void reap_children()
  451. {
  452. int status;
  453. int pid;
  454. int id;
  455. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  456. id = find_connection(pid);
  457. if (id < 0)
  458. continue;
  459. release_connection(id);
  460. }
  461. child_exited = 0;
  462. }
  463. int fill_fds_for_select(fd_set * rdset, fd_set * wrset)
  464. {
  465. int max = -1;
  466. int i;
  467. FD_ZERO(rdset);
  468. FD_ZERO(wrset);
  469. FD_SET(trigger_fd, rdset);
  470. if (trigger_fd > max)
  471. max = trigger_fd;
  472. for (i = 0; i < MAX_FDS; i++) {
  473. if (connection_info[i].pid != 0 && connection_info[i].fd != -1) {
  474. FD_SET(connection_info[i].fd, rdset);
  475. if (connection_info[i].fd > max)
  476. max = connection_info[i].fd;
  477. }
  478. }
  479. return max;
  480. }
  481. void handle_trigger_io()
  482. {
  483. struct msg_header hdr;
  484. struct trigger_service_params params;
  485. int ret;
  486. int client_fd;
  487. client_fd = do_accept(trigger_fd);
  488. if (client_fd < 0)
  489. return;
  490. hdr.len = sizeof(params);
  491. ret = read(client_fd, &params, sizeof(params));
  492. if (ret == sizeof(params)) {
  493. hdr.type = MSG_TRIGGER_SERVICE;
  494. snprintf(params.request_id.ident, sizeof(params.request_id), "SOCKET%d", client_fd);
  495. if (libvchan_send(ctrl_vchan, &hdr, sizeof(hdr)) < 0)
  496. handle_vchan_error("write hdr");
  497. if (libvchan_send(ctrl_vchan, &params, sizeof(params)) < 0)
  498. handle_vchan_error("write params");
  499. }
  500. if (ret <= 0) {
  501. close(client_fd);
  502. }
  503. /* do not close client_fd - we'll need it to send the connection details
  504. * later (when dom0 accepts the request) */
  505. }
  506. void handle_terminated_fork_client(fd_set *rdset) {
  507. int i, ret;
  508. char buf[2];
  509. for (i = 0; i < MAX_FDS; i++) {
  510. if (connection_info[i].pid && connection_info[i].fd >= 0 &&
  511. FD_ISSET(connection_info[i].fd, rdset)) {
  512. ret = read(connection_info[i].fd, buf, sizeof(buf));
  513. if (ret == 0 || (ret == -1 && errno == ECONNRESET)) {
  514. close(connection_info[i].fd);
  515. release_connection(i);
  516. } else {
  517. fprintf(stderr, "Unexpected read on fork-server connection: %d(%s)\n", ret, strerror(errno));
  518. close(connection_info[i].fd);
  519. release_connection(i);
  520. }
  521. }
  522. }
  523. }
  524. int main()
  525. {
  526. fd_set rdset, wrset;
  527. int max;
  528. sigset_t chld_set;
  529. init();
  530. signal(SIGCHLD, sigchld_handler);
  531. signal(SIGPIPE, SIG_IGN);
  532. sigemptyset(&chld_set);
  533. sigaddset(&chld_set, SIGCHLD);
  534. for (;;) {
  535. sigprocmask(SIG_BLOCK, &chld_set, NULL);
  536. if (child_exited)
  537. reap_children();
  538. max = fill_fds_for_select(&rdset, &wrset);
  539. if (libvchan_buffer_space(ctrl_vchan) <=
  540. (int)sizeof(struct msg_header))
  541. FD_ZERO(&rdset);
  542. wait_for_vchan_or_argfd(ctrl_vchan, max, &rdset, &wrset);
  543. sigprocmask(SIG_UNBLOCK, &chld_set, NULL);
  544. while (libvchan_data_ready(ctrl_vchan))
  545. handle_server_cmd();
  546. if (FD_ISSET(trigger_fd, &rdset))
  547. handle_trigger_io();
  548. handle_terminated_fork_client(&rdset);
  549. }
  550. }