Add qrexec back, use qubes-utils libraries for common code

release2 mm_158bfff3
Marek Marczykowski 11 years ago
parent 3bfe0014a8
commit 158bfff3cf

@ -1,4 +1,4 @@
CC=gcc
CFLAGS=-g -I. -Wall -fPIC -pie
qfile-dom0-unpacker: qfile-dom0-unpacker.o ioall.o copy-file.o unpack.o crc32.o
$(CC) -pie -g -o $@ $^
qfile-dom0-unpacker: qfile-dom0-unpacker.o
$(CC) -pie -g -o $@ $^ -lqubes-rpc-filecopy

@ -1,44 +0,0 @@
#include <unistd.h>
#include <ioall.h>
#include "filecopy.h"
#include "crc32.h"
extern void notify_progress(int, int);
int copy_file(int outfd, int infd, long long size, unsigned long *crc32)
{
char buf[4096];
long long written = 0;
int ret;
int count;
while (written < size) {
if (size - written > sizeof(buf))
count = sizeof buf;
else
count = size - written;
ret = read(infd, buf, count);
if (!ret)
return COPY_FILE_READ_EOF;
if (ret < 0)
return COPY_FILE_READ_ERROR;
/* acumulate crc32 if requested */
if (crc32)
*crc32 = Crc32_ComputeBuf(*crc32, buf, ret);
if (!write_all(outfd, buf, ret))
return COPY_FILE_WRITE_ERROR;
notify_progress(ret, 0);
written += ret;
}
return COPY_FILE_OK;
}
char * copy_file_status_to_str(int status)
{
switch (status) {
case COPY_FILE_OK: return "OK";
case COPY_FILE_READ_EOF: return "Unexpected end of data while reading";
case COPY_FILE_READ_ERROR: return "Error reading";
case COPY_FILE_WRITE_ERROR: return "Error writing";
default: return "????????";
}
}

@ -1,146 +0,0 @@
/*----------------------------------------------------------------------------*\
* CRC-32 version 2.0.0 by Craig Bruce, 2006-04-29.
*
* This program generates the CRC-32 values for the files named in the
* command-line arguments. These are the same CRC-32 values used by GZIP,
* PKZIP, and ZMODEM. The Crc32_ComputeBuf() can also be detached and
* used independently.
*
* THIS PROGRAM IS PUBLIC-DOMAIN SOFTWARE.
*
* Based on the byte-oriented implementation "File Verification Using CRC"
* by Mark R. Nelson in Dr. Dobb's Journal, May 1992, pp. 64-67.
*
* v1.0.0: original release.
* v1.0.1: fixed printf formats.
* v1.0.2: fixed something else.
* v1.0.3: replaced CRC constant table by generator function.
* v1.0.4: reformatted code, made ANSI C. 1994-12-05.
* v2.0.0: rewrote to use memory buffer & static table, 2006-04-29.
\*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
/*----------------------------------------------------------------------------*\
* Local functions
\*----------------------------------------------------------------------------*/
unsigned long Crc32_ComputeBuf( unsigned long inCrc32, const void *buf,
size_t bufLen );
/*----------------------------------------------------------------------------*\
* NAME:
* Crc32_ComputeFile() - compute CRC-32 value for a file
* DESCRIPTION:
* Computes the CRC-32 value for an opened file.
* ARGUMENTS:
* file - file pointer
* outCrc32 - (out) result CRC-32 value
* RETURNS:
* err - 0 on success or -1 on error
* ERRORS:
* - file errors
\*----------------------------------------------------------------------------*/
int Crc32_ComputeFile( FILE *file, unsigned long *outCrc32 )
{
# define CRC_BUFFER_SIZE 8192
unsigned char buf[CRC_BUFFER_SIZE];
size_t bufLen;
/** accumulate crc32 from file **/
*outCrc32 = 0;
while (1) {
bufLen = fread( buf, 1, CRC_BUFFER_SIZE, file );
if (bufLen == 0) {
if (ferror(file)) {
fprintf( stderr, "error reading file\n" );
goto ERR_EXIT;
}
break;
}
*outCrc32 = Crc32_ComputeBuf( *outCrc32, buf, bufLen );
}
return( 0 );
/** error exit **/
ERR_EXIT:
return( -1 );
}
/*----------------------------------------------------------------------------*\
* NAME:
* Crc32_ComputeBuf() - computes the CRC-32 value of a memory buffer
* DESCRIPTION:
* Computes or accumulates the CRC-32 value for a memory buffer.
* The 'inCrc32' gives a previously accumulated CRC-32 value to allow
* a CRC to be generated for multiple sequential buffer-fuls of data.
* The 'inCrc32' for the first buffer must be zero.
* ARGUMENTS:
* inCrc32 - accumulated CRC-32 value, must be 0 on first call
* buf - buffer to compute CRC-32 value for
* bufLen - number of bytes in buffer
* RETURNS:
* crc32 - computed CRC-32 value
* ERRORS:
* (no errors are possible)
\*----------------------------------------------------------------------------*/
unsigned long Crc32_ComputeBuf( unsigned long inCrc32, const void *buf,
size_t bufLen )
{
static const unsigned long crcTable[256] = {
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,
0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,
0xE7B82D07,0x90BF1D91,0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,
0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,
0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,0x3B6E20C8,0x4C69105E,0xD56041E4,
0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,
0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,0x26D930AC,
0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,
0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,
0xB6662D3D,0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,
0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,
0x086D3D2D,0x91646C97,0xE6635C01,0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,
0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,
0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,0x4DB26158,0x3AB551CE,
0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,
0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,
0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,
0xB7BD5C3B,0xC0BA6CAD,0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,
0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,
0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,0xF00F9344,0x8708A3D2,0x1E01F268,
0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,
0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,0xD6D6A3E8,
0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,
0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,
0x4669BE79,0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,
0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,
0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,
0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,
0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,0x86D3D2D4,0xF1D4E242,
0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,
0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,
0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,
0x47B2CF7F,0x30B5FFE9,0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,
0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,
0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D };
unsigned long crc32;
unsigned char *byteBuf;
size_t i;
/** accumulate crc32 for buffer **/
crc32 = inCrc32 ^ 0xFFFFFFFF;
byteBuf = (unsigned char*) buf;
for (i=0; i < bufLen; i++) {
crc32 = (crc32 >> 8) ^ crcTable[ (crc32 ^ byteBuf[i]) & 0xFF ];
}
return( crc32 ^ 0xFFFFFFFF );
}
/*----------------------------------------------------------------------------*\
* END OF MODULE: crc32.c
\*----------------------------------------------------------------------------*/

@ -1,7 +0,0 @@
#ifndef _CRC32_H
#define _CRC32_H
extern unsigned long Crc32_ComputeBuf( unsigned long inCrc32, const void *buf,
size_t bufLen );
#endif /* _CRC32_H */

@ -1,32 +0,0 @@
#define FILECOPY_SPOOL "/home/user/.filecopyspool"
#define FILECOPY_VMNAME_SIZE 32
#define PROGRESS_NOTIFY_DELTA (15*1000*1000)
#define MAX_PATH_LENGTH 16384
#define LEGAL_EOF 31415926
struct file_header {
unsigned int namelen;
unsigned int mode;
unsigned long long filelen;
unsigned int atime;
unsigned int atime_nsec;
unsigned int mtime;
unsigned int mtime_nsec;
};
struct result_header {
unsigned int error_code;
unsigned long crc32;
};
enum {
COPY_FILE_OK,
COPY_FILE_READ_EOF,
COPY_FILE_READ_ERROR,
COPY_FILE_WRITE_ERROR
};
int copy_file(int outfd, int infd, long long size, unsigned long *crc32);
char *copy_file_status_to_str(int status);
void set_size_limit(long long new_bytes_limit, long long new_files_limit);

@ -1,112 +0,0 @@
/*
* The Qubes OS Project, http://www.qubes-os.org
*
* Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
void perror_wrapper(char * msg)
{
int prev=errno;
perror(msg);
errno=prev;
}
void set_nonblock(int fd)
{
int fl = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}
void set_block(int fd)
{
int fl = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, fl & ~O_NONBLOCK);
}
int write_all(int fd, void *buf, int size)
{
int written = 0;
int ret;
while (written < size) {
ret = write(fd, (char *) buf + written, size - written);
if (ret == -1 && errno == EINTR)
continue;
if (ret <= 0) {
return 0;
}
written += ret;
}
// fprintf(stderr, "sent %d bytes\n", size);
return 1;
}
int read_all(int fd, void *buf, int size)
{
int got_read = 0;
int ret;
while (got_read < size) {
ret = read(fd, (char *) buf + got_read, size - got_read);
if (ret == -1 && errno == EINTR)
continue;
if (ret == 0) {
errno = 0;
fprintf(stderr, "EOF\n");
return 0;
}
if (ret < 0) {
if (errno != EAGAIN)
perror_wrapper("read");
return 0;
}
if (got_read == 0) {
// force blocking operation on further reads
set_block(fd);
}
got_read += ret;
}
// fprintf(stderr, "read %d bytes\n", size);
return 1;
}
int copy_fd_all(int fdout, int fdin)
{
int ret;
char buf[4096];
for (;;) {
ret = read(fdin, buf, sizeof(buf));
if (ret == -1 && errno == EINTR)
continue;
if (!ret)
break;
if (ret < 0) {
perror_wrapper("read");
return 0;
}
if (!write_all(fdout, buf, ret)) {
perror_wrapper("write");
return 0;
}
}
return 1;
}

@ -1,5 +0,0 @@
int write_all(int fd, void *buf, int size);
int read_all(int fd, void *buf, int size);
int copy_fd_all(int fdout, int fdin);
void set_nonblock(int fd);
void set_block(int fd);

@ -1,5 +1,4 @@
#define _GNU_SOURCE
#include <ioall.h>
#include <grp.h>
#include <unistd.h>
#include <stdio.h>
@ -10,10 +9,14 @@
#include <unistd.h>
#include <sys/fsuid.h>
#include <errno.h>
#include "filecopy.h"
#include <libqubes-rpc-filecopy.h>
#define DEFAULT_MAX_UPDATES_BYTES (2L<<30)
#define DEFAULT_MAX_UPDATES_FILES 2048
void notify_progress(int p1, int p2)
{
}
int prepare_creds_return_uid(char *username)
{
@ -36,8 +39,6 @@ int prepare_creds_return_uid(char *username)
return pwd->pw_uid;
}
extern int do_unpack(void);
int main(int argc, char ** argv)
{
char *incoming_dir;

@ -1,161 +0,0 @@
#define _GNU_SOURCE /* For O_NOFOLLOW. */
#include <errno.h>
#include <ioall.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include "filecopy.h"
#include "crc32.h"
char untrusted_namebuf[MAX_PATH_LENGTH];
long long bytes_limit = 0;
long long files_limit = 0;
long long total_bytes = 0;
long long total_files = 0;
void notify_progress(int p1, int p2)
{
}
void set_size_limit(long long new_bytes_limit, long long new_files_limit)
{
bytes_limit = new_bytes_limit;
files_limit = new_files_limit;
}
unsigned long crc32_sum = 0;
int read_all_with_crc(int fd, void *buf, int size) {
int ret;
ret = read_all(fd, buf, size);
if (ret)
crc32_sum = Crc32_ComputeBuf(crc32_sum, buf, size);
return ret;
}
void send_status_and_crc(int code) {
struct result_header hdr;
int saved_errno;
saved_errno = errno;
hdr.error_code = code;
hdr.crc32 = crc32_sum;
if (!write_all(1, &hdr, sizeof(hdr)))
perror("write status");
errno = saved_errno;
}
void do_exit(int code)
{
close(0);
send_status_and_crc(code);
exit(code);
}
void fix_times_and_perms(struct file_header *untrusted_hdr,
char *untrusted_name)
{
struct timeval times[2] =
{ {untrusted_hdr->atime, untrusted_hdr->atime_nsec / 1000},
{untrusted_hdr->mtime,
untrusted_hdr->mtime_nsec / 1000}
};
if (chmod(untrusted_name, untrusted_hdr->mode & 07777)) /* safe because of chroot */
do_exit(errno);
if (utimes(untrusted_name, times)) /* as above */
do_exit(errno);
}
void process_one_file_reg(struct file_header *untrusted_hdr,
char *untrusted_name)
{
int ret;
int fdout = open(untrusted_name, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0700); /* safe because of chroot */
if (fdout < 0)
do_exit(errno);
total_bytes += untrusted_hdr->filelen;
if (bytes_limit && total_bytes > bytes_limit)
do_exit(EDQUOT);
ret = copy_file(fdout, 0, untrusted_hdr->filelen, &crc32_sum);
if (ret != COPY_FILE_OK) {
if (ret == COPY_FILE_READ_EOF
|| ret == COPY_FILE_READ_ERROR)
do_exit(LEGAL_EOF); // hopefully remote will produce error message
else
do_exit(errno);
}
close(fdout);
fix_times_and_perms(untrusted_hdr, untrusted_name);
}
void process_one_file_dir(struct file_header *untrusted_hdr,
char *untrusted_name)
{
// fix perms only when the directory is sent for the second time
// it allows to transfer r.x directory contents, as we create it rwx initially
if (!mkdir(untrusted_name, 0700)) /* safe because of chroot */
return;
if (errno != EEXIST)
do_exit(errno);
fix_times_and_perms(untrusted_hdr, untrusted_name);
}
void process_one_file_link(struct file_header *untrusted_hdr,
char *untrusted_name)
{
char untrusted_content[MAX_PATH_LENGTH];
unsigned int filelen;
if (untrusted_hdr->filelen > MAX_PATH_LENGTH - 1)
do_exit(ENAMETOOLONG);
filelen = untrusted_hdr->filelen; /* sanitized above */
if (!read_all_with_crc(0, untrusted_content, filelen))
do_exit(LEGAL_EOF); // hopefully remote has produced error message
untrusted_content[filelen] = 0;
if (symlink(untrusted_content, untrusted_name)) /* safe because of chroot */
do_exit(errno);
}
void process_one_file(struct file_header *untrusted_hdr)
{
unsigned int namelen;
if (untrusted_hdr->namelen > MAX_PATH_LENGTH - 1)
do_exit(ENAMETOOLONG);
namelen = untrusted_hdr->namelen; /* sanitized above */
if (!read_all_with_crc(0, untrusted_namebuf, namelen))
do_exit(LEGAL_EOF); // hopefully remote has produced error message
untrusted_namebuf[namelen] = 0;
if (S_ISREG(untrusted_hdr->mode))
process_one_file_reg(untrusted_hdr, untrusted_namebuf);
else if (S_ISLNK(untrusted_hdr->mode))
process_one_file_link(untrusted_hdr, untrusted_namebuf);
else if (S_ISDIR(untrusted_hdr->mode))
process_one_file_dir(untrusted_hdr, untrusted_namebuf);
else
do_exit(EINVAL);
}
int do_unpack()
{
struct file_header untrusted_hdr;
/* initialize checksum */
crc32_sum = 0;
while (read_all_with_crc(0, &untrusted_hdr, sizeof untrusted_hdr)) {
/* check for end of transfer marker */
if (untrusted_hdr.namelen == 0) {
errno = 0;
break;
}
process_one_file(&untrusted_hdr);
total_files++;
if (files_limit && total_files > files_limit)
do_exit(EDQUOT);
}
send_status_and_crc(errno);
return errno;
}

@ -0,0 +1,12 @@
CC=gcc
CFLAGS+=-I. -g -Wall -pie -fPIC
XENLIBS=-lvchan -lxenstore -lxenctrl
LIBS=$(XENLIBS) -lqrexec-utils
all: qrexec-daemon qrexec-client
qrexec-daemon: qrexec-daemon.o
$(CC) -pie -g -o qrexec-daemon qrexec-daemon.o $(LIBS)
qrexec-client: qrexec-client.o
$(CC) -pie -g -o qrexec-client qrexec-client.o $(LIBS)
clean:
rm -f *.o *~ qrexec-daemon qrexec-client

@ -0,0 +1,64 @@
Currently (after commit 2600134e3bb781fca25fe77e464f8b875741dc83),
qrexec_agent can request a service (specified by a "exec_index") to be
executed on a different VM or dom0. Access control is enforced in dom0 via
files in /etc/qubes_rpc/policy. File copy, Open in Dispvm, sync appmenus,
upload updates to dom0 - they all have been ported to the new API.
See the quick HOWTO section on how to add a new service. Note we have
qvm-open-in-vm utility practically for free.
CHANGES
Besides flexibility offered by /etc/qubes_rpc/policy, writing a client
is much simpler now. The workflow used to be (using "filecopy" service as
an example):
a) "filecopy_ui" process places job description in some spool directory,
signals qrexec_agent to signal qrexec_daemon
b) qrexec_daemon executes "qrexec_client -d domain filecopy_worker ...."
and "filecopy_worker" process needed to parse spool and retrieve job
description from there. Particularly, "filecopy_ui" had no connection to
remote.
Now, the flow is:
a) qrexec_client_vm process obtains 3 unix socket descriptors from
qrexec_agent, dup stdin/out/err to them; forms "existing_process_handle" from
them
b) qrexec_client_vm signals qrexec_agent to signal qrexec_daemon, with a
"exec_index" (so, type of service) as an argument
c) qrexec_daemon executed "qrexec_client -d domain -c existing_process_handle ...."
d) qrexec_client_vm execve filecopy_program.
Thus, there is only one service program, and it has direct access to remote via
stdin/stdout.
HOWTO
Let's add a new "test.Add" service, that will add two numbers. We need the
following files in the template fs:
==========================
/usr/bin/our_test_add_client:
#!/bin/sh
echo $1 $2
exec cat >&2
# more correct: exec cat >&$SAVED_FD_1, but do not scare the reader
==========================
/usr/bin/our_test_add_server:
#!/bin/sh
read arg1 arg2
echo $(($arg1+$arg2))
==========================
/etc/qubes_rpc/test.Add:
/usr/bin/our_test_add_server
Now, on the client side, we start the client via
/usr/lib/qubes/qrexec_client_vm target_vm test.Add /usr/bin/our_test_add_client 11 22
Because there is no policy yet, dom0 will ask you to create one (of cource you
can do it before the first run of our_test_add_client). So, in dom0, create (by now,
with a file editor) the /etc/qubes_rpc/policy/test.Add file with
anyvm anyvm ask
content. The format of the /etc/qubes_rpc/policy/* files is
srcvm destvm (allow|deny|ask)[,user=user_to_run_as][,target=VM_to_redirect_to]
You can specify srcvm and destvm by name, or by one of "anyvm", "dispvm", "dom0"
reserved keywords.
Then, when you confirm the operation, you will get the result in the client vm.

@ -0,0 +1,293 @@
/*
* The Qubes OS Project, http://www.qubes-os.org
*
* Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <getopt.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include "qrexec.h"
#include "libqrexec-utils.h"
int connect_unix_socket(char *domname)
{
int s, len;
struct sockaddr_un remote;
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
return -1;
}
remote.sun_family = AF_UNIX;
snprintf(remote.sun_path, sizeof remote.sun_path,
QREXEC_DAEMON_SOCKET_DIR "/qrexec.%s", domname);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
if (connect(s, (struct sockaddr *) &remote, len) == -1) {
perror("connect");
exit(1);
}
return s;
}
void do_exec(char *prog)
{
execl("/bin/bash", "bash", "-c", prog, NULL);
}
int local_stdin_fd, local_stdout_fd;
void do_exit(int code)
{
int status;
// sever communication lines; wait for child, if any
// so that qrexec-daemon can count (recursively) spawned processes correctly
close(local_stdin_fd);
close(local_stdout_fd);
waitpid(-1, &status, 0);
exit(code);
}
void prepare_local_fds(char *cmdline)
{
int pid;
if (!cmdline) {
local_stdin_fd = 1;
local_stdout_fd = 0;
return;
}
do_fork_exec(cmdline, &pid, &local_stdin_fd, &local_stdout_fd,
NULL);
}
void send_cmdline(int s, int type, char *cmdline)
{
struct client_header hdr;
hdr.type = type;
hdr.len = strlen(cmdline) + 1;
if (!write_all(s, &hdr, sizeof(hdr))
|| !write_all(s, cmdline, hdr.len)) {
perror("write daemon");
do_exit(1);
}
}
void handle_input(int s)
{
char buf[MAX_DATA_CHUNK];
int ret;
ret = read(local_stdout_fd, buf, sizeof(buf));
if (ret < 0) {
perror("read");
do_exit(1);
}
if (ret == 0) {
close(local_stdout_fd);
local_stdout_fd = -1;
shutdown(s, SHUT_WR);
if (local_stdin_fd == -1) {
// if pipe in opposite direction already closed, no need to stay alive
do_exit(0);
}
}
if (!write_all(s, buf, ret)) {
if (errno == EPIPE) {
// daemon disconnected its end of socket, so no future data will be
// send there; there is no sense to read from child stdout
//
// since AF_UNIX socket is buffered it doesn't mean all data was
// received from the agent
close(local_stdout_fd);
local_stdout_fd = -1;
if (local_stdin_fd == -1) {
// since child does no longer accept data on its stdin, doesn't
// make sense to process the data from the daemon
//
// we don't know real exit VM process code (exiting here, before
// MSG_SERVER_TO_CLIENT_EXIT_CODE message)
do_exit(1);
}
} else
perror("write daemon");
}
}
void handle_daemon_data(int s)
{
int status;
struct client_header hdr;
char buf[MAX_DATA_CHUNK];
if (!read_all(s, &hdr, sizeof hdr)) {
perror("read daemon");
do_exit(1);
}
if (hdr.len > MAX_DATA_CHUNK) {
fprintf(stderr, "client_header.len=%d\n", hdr.len);
do_exit(1);
}
if (!read_all(s, buf, hdr.len)) {
perror("read daemon");
do_exit(1);
}
switch (hdr.type) {
case MSG_SERVER_TO_CLIENT_STDOUT:
if (local_stdin_fd == -1)
break;
if (hdr.len == 0) {
close(local_stdin_fd);
local_stdin_fd = -1;
} else if (!write_all(local_stdin_fd, buf, hdr.len)) {
if (errno == EPIPE) {
// remote side have closed its stdin, handle data in oposite
// direction (if any) before exit
local_stdin_fd = -1;
} else {
perror("write local stdout");
do_exit(1);
}
}
break;
case MSG_SERVER_TO_CLIENT_STDERR:
write_all(2, buf, hdr.len);
break;
case MSG_SERVER_TO_CLIENT_EXIT_CODE:
status = *(unsigned int *) buf;
if (WIFEXITED(status))
do_exit(WEXITSTATUS(status));
else
do_exit(255);
break;
default:
fprintf(stderr, "unknown msg %d\n", hdr.type);
do_exit(1);
}
}
// perhaps we could save a syscall if we include both sides in both
// rdset and wrset; to be investigated
void handle_daemon_only_until_writable(s)
{
fd_set rdset, wrset;
do {
FD_ZERO(&rdset);
FD_ZERO(&wrset);
FD_SET(s, &rdset);
FD_SET(s, &wrset);
if (select(s + 1, &rdset, &wrset, NULL, NULL) < 0) {
perror("select");
do_exit(1);
}
if (FD_ISSET(s, &rdset))
handle_daemon_data(s);
} while (!FD_ISSET(s, &wrset));
}
void select_loop(int s)
{
fd_set select_set;
int max;
for (;;) {
handle_daemon_only_until_writable(s);
FD_ZERO(&select_set);
FD_SET(s, &select_set);
max = s;
if (local_stdout_fd != -1) {
FD_SET(local_stdout_fd, &select_set);
if (s < local_stdout_fd)
max = local_stdout_fd;
}
if (select(max + 1, &select_set, NULL, NULL, NULL) < 0) {
perror("select");
do_exit(1);
}
if (FD_ISSET(s, &select_set))
handle_daemon_data(s);
if (local_stdout_fd != -1
&& FD_ISSET(local_stdout_fd, &select_set))
handle_input(s);
}
}
void usage(char *name)
{
fprintf(stderr,
"usage: %s -d domain_num [-l local_prog] -e -c remote_cmdline\n"
"-e means exit after sending cmd, -c: connect to existing process\n",
name);
exit(1);
}
int main(int argc, char **argv)
{
int opt;
char *domname = NULL;
int s;
int just_exec = 0;
int connect_existing = 0;
char *local_cmdline = NULL;
while ((opt = getopt(argc, argv, "d:l:ec")) != -1) {
switch (opt) {
case 'd':
domname = strdup(optarg);
break;
case 'l':
local_cmdline = strdup(optarg);
break;
case 'e':
just_exec = 1;
break;
case 'c':
connect_existing = 1;
break;
default:
usage(argv[0]);
}
}
if (optind >= argc || !domname)
usage(argv[0]);
s = connect_unix_socket(domname);
setenv("QREXEC_REMOTE_DOMAIN", domname, 1);
prepare_local_fds(local_cmdline);
if (just_exec)
send_cmdline(s, MSG_CLIENT_TO_SERVER_JUST_EXEC,
argv[optind]);
else {
int cmd;
if (connect_existing)
cmd = MSG_CLIENT_TO_SERVER_CONNECT_EXISTING;
else
cmd = MSG_CLIENT_TO_SERVER_EXEC_CMDLINE;
send_cmdline(s, cmd, argv[optind]);
select_loop(s);
}
return 0;
}

@ -0,0 +1,685 @@
/*
* The Qubes OS Project, http://www.qubes-os.org
*
* Copyright (C) 2010 Rafal Wojtczuk <rafal@invisiblethingslab.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include <sys/select.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <string.h>
#include "qrexec.h"
#include "libqrexec-utils.h"
enum client_flags {
CLIENT_INVALID = 0, // table slot not used
CLIENT_CMDLINE = 1, // waiting for cmdline from client
CLIENT_DATA = 2, // waiting for data from client
CLIENT_DONT_READ = 4, // don't read from the client, the other side pipe is full, or EOF (additionally marked with CLIENT_EOF)
CLIENT_OUTQ_FULL = 8, // don't write to client, its stdin pipe is full
CLIENT_EOF = 16, // got EOF
CLIENT_EXITED = 32 // only send remaining data from client and remove from list
};
struct _client {
int state; // combination of above enum client_flags
struct buffer buffer; // buffered data to client, if any
};
/*
The "clients" array is indexed by client's fd.
Thus its size must be equal MAX_FDS; defining MAX_CLIENTS for clarity.
*/
#define MAX_CLIENTS MAX_FDS
struct _client clients[MAX_CLIENTS]; // data on all qrexec_client connections
int max_client_fd = -1; // current max fd of all clients; so that we need not to scan all the "clients" table
int qrexec_daemon_unix_socket_fd; // /var/run/qubes/qrexec.xid descriptor
char *default_user = "user";
char default_user_keyword[] = "DEFAULT:";
#define default_user_keyword_len_without_colon (sizeof(default_user_keyword)-2)
void sigusr1_handler(int x)
{
fprintf(stderr, "connected\n");
exit(0);
}
void sigchld_handler(int x);
char *remote_domain_name; // guess what
int create_qrexec_socket(int domid, char *domname)
{
char socket_address[40];
char link_to_socket_name[strlen(domname) + sizeof(socket_address)];
snprintf(socket_address, sizeof(socket_address),
QREXEC_DAEMON_SOCKET_DIR "/qrexec.%d", domid);
snprintf(link_to_socket_name, sizeof link_to_socket_name,
QREXEC_DAEMON_SOCKET_DIR "/qrexec.%s", domname);
unlink(link_to_socket_name);
symlink(socket_address, link_to_socket_name);
return get_server_socket(socket_address);
}
#define MAX_STARTUP_TIME_DEFAULT 60
/* ask on qrexec connect timeout */
int ask_on_connect_timeout(int xid, int timeout)
{
char text[1024];
int ret;
struct stat buf;
ret=stat("/usr/bin/kdialog", &buf);
#define KDIALOG_CMD "kdialog --title 'Qrexec daemon' --warningyesno "
#define ZENITY_CMD "zenity --title 'Qrexec daemon' --question --text "
snprintf(text, sizeof(text),
"%s"
"'Timeout while trying connecting to qrexec agent (Xen domain ID: %d). Do you want to wait next %d seconds?'",
ret==0 ? KDIALOG_CMD : ZENITY_CMD,
xid, timeout);
#undef KDIALOG_CMD
#undef ZENITY_CMD
ret = system(text);
ret = WEXITSTATUS(ret);
// fprintf(stderr, "ret=%d\n", ret);
switch (ret) {
case 1: /* NO */
return 0;
case 0: /*YES */
return 1;
default:
// this can be the case at system startup (netvm), when Xorg isn't running yet
// so just don't give possibility to extend the timeout
return 0;
}
}
/* do the preparatory tasks, needed before entering the main event loop */
void init(int xid)
{
char qrexec_error_log_name[256];
int logfd;
int i;
pid_t pid;
int startup_timeout = MAX_STARTUP_TIME_DEFAULT;
char *startup_timeout_str = NULL;
if (xid <= 0) {
fprintf(stderr, "domain id=0?\n");
exit(1);
}
startup_timeout_str = getenv("QREXEC_STARTUP_TIMEOUT");
if (startup_timeout_str) {
startup_timeout = atoi(startup_timeout_str);
if (startup_timeout == 0)
// invalid number
startup_timeout = MAX_STARTUP_TIME_DEFAULT;
}
signal(SIGUSR1, sigusr1_handler);
switch (pid=fork()) {
case -1:
perror("fork");
exit(1);
case 0:
break;
default:
fprintf(stderr, "Waiting for VM's qrexec agent.");
for (i=0;i<startup_timeout;i++) {
sleep(1);
fprintf(stderr, ".");
if (i==startup_timeout-1) {
if (ask_on_connect_timeout(xid, startup_timeout))
i=0;
}
}
fprintf(stderr, "Cannot connect to qrexec agent for %d seconds, giving up\n", startup_timeout);
kill(pid, SIGTERM);
exit(1);
}
close(0);
snprintf(qrexec_error_log_name, sizeof(qrexec_error_log_name),
"/var/log/qubes/qrexec.%d.log", xid);
umask(0007); // make the log readable by the "qubes" group
logfd =
open(qrexec_error_log_name, O_WRONLY | O_CREAT | O_TRUNC,
0640);
if (logfd < 0) {
perror("open");
exit(1);
}
dup2(logfd, 1);
dup2(logfd, 2);
chdir("/var/run/qubes");
if (setsid() < 0) {
perror("setsid()");
exit(1);
}
remote_domain_name = peer_client_init(xid, REXEC_PORT);
setuid(getuid());
/* When running as root, make the socket accessible; perms on /var/run/qubes still apply */
umask(0);
qrexec_daemon_unix_socket_fd =
create_qrexec_socket(xid, remote_domain_name);
umask(0077);
signal(SIGPIPE, SIG_IGN);
signal(SIGCHLD, sigchld_handler);
signal(SIGUSR1, SIG_DFL);
kill(getppid(), SIGUSR1); // let the parent know we are ready
}
void handle_new_client()
{
int fd = do_accept(qrexec_daemon_unix_socket_fd);
if (fd >= MAX_CLIENTS) {
fprintf(stderr, "too many clients ?\n");
exit(1);
}
clients[fd].state = CLIENT_CMDLINE;
buffer_init(&clients[fd].buffer);
if (fd > max_client_fd)
max_client_fd = fd;
}
/*
we need to track the number of children, so that excessive QREXEC_EXECUTE_*
commands do not fork-bomb dom0
*/
int children_count;
void terminate_client_and_flush_data(int fd)
{
int i;
struct server_header s_hdr;
if (!(clients[fd].state & CLIENT_EXITED) && fork_and_flush_stdin(fd, &clients[fd].buffer))
children_count++;
close(fd);
clients[fd].state = CLIENT_INVALID;
buffer_free(&clients[fd].buffer);
if (max_client_fd == fd) {
for (i = fd; clients[i].state == CLIENT_INVALID && i >= 0;
i--);
max_client_fd = i;
}
s_hdr.type = MSG_SERVER_TO_AGENT_CLIENT_END;
s_hdr.client_id = fd;
s_hdr.len = 0;
write_all_vchan_ext(&s_hdr, sizeof(s_hdr));
}
int get_cmdline_body_from_client_and_pass_to_agent(int fd, struct server_header
*s_hdr)
{
int len = s_hdr->len;
char buf[len];
int use_default_user = 0;
if (!read_all(fd, buf, len)) {
terminate_client_and_flush_data(fd);
return 0;
}
if (!strncmp(buf, default_user_keyword, default_user_keyword_len_without_colon+1)) {
use_default_user = 1;
s_hdr->len -= default_user_keyword_len_without_colon; // -1 because of colon
s_hdr->len += strlen(default_user);
}
write_all_vchan_ext(s_hdr, sizeof(*s_hdr));
if (use_default_user) {
write_all_vchan_ext(default_user, strlen(default_user));
write_all_vchan_ext(buf+default_user_keyword_len_without_colon, len-default_user_keyword_len_without_colon);
} else
write_all_vchan_ext(buf, len);
return 1;
}
void handle_cmdline_message_from_client(int fd)
{
struct client_header hdr;
struct server_header s_hdr;
if (!read_all(fd, &hdr, sizeof hdr)) {
terminate_client_and_flush_data(fd);
return;
}
switch (hdr.type) {
case MSG_CLIENT_TO_SERVER_EXEC_CMDLINE:
s_hdr.type = MSG_SERVER_TO_AGENT_EXEC_CMDLINE;
break;
case MSG_CLIENT_TO_SERVER_JUST_EXEC:
s_hdr.type = MSG_SERVER_TO_AGENT_JUST_EXEC;
break;
case MSG_CLIENT_TO_SERVER_CONNECT_EXISTING:
s_hdr.type = MSG_SERVER_TO_AGENT_CONNECT_EXISTING;
break;
default:
terminate_client_and_flush_data(fd);
return;
}
s_hdr.client_id = fd;
s_hdr.len = hdr.len;
if (!get_cmdline_body_from_client_and_pass_to_agent(fd, &s_hdr))
// client disconnected while sending cmdline, above call already
// cleaned up client info
return;
clients[fd].state = CLIENT_DATA;
set_nonblock(fd); // so that we can detect full queue without blocking
if (hdr.type == MSG_CLIENT_TO_SERVER_JUST_EXEC)
terminate_client_and_flush_data(fd);
}
/* handle data received from one of qrexec_client processes */
void handle_message_from_client(int fd)
{
struct server_header s_hdr;
char buf[MAX_DATA_CHUNK];
int len, ret;
if (clients[fd].state == CLIENT_CMDLINE) {
handle_cmdline_message_from_client(fd);
return;
}
// We have already passed cmdline from client.
// Now the client passes us raw data from its stdin.
len = buffer_space_vchan_ext();
if (len <= sizeof s_hdr)
return;
/* Read at most the amount of data that we have room for in vchan */
ret = read(fd, buf, len - sizeof(s_hdr));
if (ret < 0) {
perror("read client");
terminate_client_and_flush_data(fd);
return;
}
s_hdr.client_id = fd;
s_hdr.len = ret;
s_hdr.type = MSG_SERVER_TO_AGENT_INPUT;
write_all_vchan_ext(&s_hdr, sizeof(s_hdr));
write_all_vchan_ext(buf, ret);
if (ret == 0) // EOF - so don't select() on this client
clients[fd].state |= CLIENT_DONT_READ | CLIENT_EOF;
if (clients[fd].state & CLIENT_EXITED)
//client already exited and all data sent - cleanup now
terminate_client_and_flush_data(fd);
}
/*
Called when there is buffered data for this client, and select() reports
that client's pipe is writable; so we should be able to flush some
buffered data.
*/
void write_buffered_data_to_client(int client_id)
{
switch (flush_client_data
(client_id, client_id, &clients[client_id].buffer)) {
case WRITE_STDIN_OK: // no more buffered data
clients[client_id].state &= ~CLIENT_OUTQ_FULL;
break;
case WRITE_STDIN_ERROR:
// do not write to this fd anymore
clients[client_id].state |= CLIENT_EXITED;
if (clients[client_id].state & CLIENT_EOF)
terminate_client_and_flush_data(client_id);
else
// client will be removed when read returns 0 (EOF)
// clear CLIENT_OUTQ_FULL flag to no select on this fd anymore
clients[client_id].state &= ~CLIENT_OUTQ_FULL;
break;
case WRITE_STDIN_BUFFERED: // no room for all data, don't clear CLIENT_OUTQ_FULL flag
break;
default:
fprintf(stderr, "unknown flush_client_data?\n");
exit(1);
}
}
/*
The header (hdr argument) is already built. Just read the raw data from
the packet, and pass it along with the header to the client.
*/
void get_packet_data_from_agent_and_pass_to_client(int client_id, struct client_header
*hdr)
{
int len = hdr->len;
char buf[sizeof(*hdr) + len];
/* make both the header and data be consecutive in the buffer */
*(struct client_header *) buf = *hdr;
read_all_vchan_ext(buf + sizeof(*hdr), len);
if (clients[client_id].state & CLIENT_EXITED)
// ignore data for no longer running client
return;
switch (write_stdin
(client_id, client_id, buf, len + sizeof(*hdr),
&clients[client_id].buffer)) {
case WRITE_STDIN_OK:
break;
case WRITE_STDIN_BUFFERED: // some data have been buffered
clients[client_id].state |= CLIENT_OUTQ_FULL;
break;
case WRITE_STDIN_ERROR:
// do not write to this fd anymore
clients[client_id].state |= CLIENT_EXITED;
// if already got EOF, remove client
if (clients[client_id].state & CLIENT_EOF)
terminate_client_and_flush_data(client_id);
break;
default:
fprintf(stderr, "unknown write_stdin?\n");
exit(1);
}
}
/*
The signal handler executes asynchronously; therefore all it should do is
to set a flag "signal has arrived", and let the main even loop react to this
flag in appropriate moment.
*/
int child_exited;
void sigchld_handler(int x)
{
child_exited = 1;
signal(SIGCHLD, sigchld_handler);
}
/* clean zombies, update children_count */
void reap_children()
{
int status;
while (waitpid(-1, &status, WNOHANG) > 0)
children_count--;
child_exited = 0;
}
/* too many children - wait for one of them to terminate */
void wait_for_child()
{
int status;
waitpid(-1, &status, 0);
children_count--;
}
#define MAX_CHILDREN 10
void check_children_count_and_wait_if_too_many()
{
if (children_count > MAX_CHILDREN) {
fprintf(stderr,
"max number of children reached, waiting for child exit...\n");
wait_for_child();
fprintf(stderr, "now children_count=%d, continuing.\n",
children_count);
}
}
void sanitize_name(char * untrusted_s_signed)
{
unsigned char * untrusted_s;
for (untrusted_s=(unsigned char*)untrusted_s_signed; *untrusted_s; untrusted_s++) {
if (*untrusted_s >= 'a' && *untrusted_s <= 'z')
continue;
if (*untrusted_s >= 'A' && *untrusted_s <= 'Z')
continue;
if (*untrusted_s >= '0' && *untrusted_s <= '9')
continue;
if (*untrusted_s == '$' || *untrusted_s == '_' || *untrusted_s == '-' || *untrusted_s == '.' || *untrusted_s == ' ')
continue;
*untrusted_s = '_';
}
}
#define ENSURE_NULL_TERMINATED(x) x[sizeof(x)-1] = 0
/*
Called when agent sends a message asking to execute a predefined command.
*/
void handle_execute_predefined_command()
{
int i;
struct trigger_connect_params untrusted_params, params;
check_children_count_and_wait_if_too_many();
read_all_vchan_ext(&untrusted_params, sizeof(params));
/* sanitize start */
ENSURE_NULL_TERMINATED(untrusted_params.exec_index);
ENSURE_NULL_TERMINATED(untrusted_params.target_vmname);
ENSURE_NULL_TERMINATED(untrusted_params.process_fds.ident);
sanitize_name(untrusted_params.exec_index);
sanitize_name(untrusted_params.target_vmname);
sanitize_name(untrusted_params.process_fds.ident);
params = untrusted_params;
/* sanitize end */
switch (fork()) {
case -1:
perror("fork");
exit(1);
case 0:
break;
default:
children_count++;
return;
}
for (i = 3; i < MAX_FDS; i++)
close(i);
signal(SIGCHLD, SIG_DFL);
signal(SIGPIPE, SIG_DFL);
execl("/usr/lib/qubes/qrexec-policy", "qrexec-policy",
remote_domain_name, params.target_vmname,
params.exec_index, params.process_fds.ident, NULL);
perror("execl");
exit(1);
}
void check_client_id_in_range(unsigned int untrusted_client_id)
{
if (untrusted_client_id >= MAX_CLIENTS || untrusted_client_id < 0) {
fprintf(stderr, "from agent: client_id=%d\n",
untrusted_client_id);
exit(1);
}
}
void sanitize_message_from_agent(struct server_header *untrusted_header)
{
switch (untrusted_header->type) {
case MSG_AGENT_TO_SERVER_TRIGGER_CONNECT_EXISTING:
break;
case MSG_AGENT_TO_SERVER_STDOUT:
case MSG_AGENT_TO_SERVER_STDERR:
case MSG_AGENT_TO_SERVER_EXIT_CODE:
check_client_id_in_range(untrusted_header->client_id);
if (untrusted_header->len > MAX_DATA_CHUNK
|| untrusted_header->len < 0) {
fprintf(stderr, "agent feeded %d of data bytes?\n",
untrusted_header->len);
exit(1);
}
break;
case MSG_XOFF:
case MSG_XON:
check_client_id_in_range(untrusted_header->client_id);
break;
default:
fprintf(stderr, "unknown mesage type %d from agent\n",
untrusted_header->type);
exit(1);
}
}
void handle_message_from_agent()
{
struct client_header hdr;
struct server_header s_hdr, untrusted_s_hdr;
read_all_vchan_ext(&untrusted_s_hdr, sizeof untrusted_s_hdr);
/* sanitize start */
sanitize_message_from_agent(&untrusted_s_hdr);
s_hdr = untrusted_s_hdr;
/* sanitize end */
// fprintf(stderr, "got %x %x %x\n", s_hdr.type, s_hdr.client_id,
// s_hdr.len);
if (s_hdr.type == MSG_AGENT_TO_SERVER_TRIGGER_CONNECT_EXISTING) {
handle_execute_predefined_command();
return;
}
if (s_hdr.type == MSG_XOFF) {
clients[s_hdr.client_id].state |= CLIENT_DONT_READ;
return;
}
if (s_hdr.type == MSG_XON) {
clients[s_hdr.client_id].state &= ~CLIENT_DONT_READ;
return;
}
switch (s_hdr.type) {
case MSG_AGENT_TO_SERVER_STDOUT:
hdr.type = MSG_SERVER_TO_CLIENT_STDOUT;
break;
case MSG_AGENT_TO_SERVER_STDERR:
hdr.type = MSG_SERVER_TO_CLIENT_STDERR;
break;
case MSG_AGENT_TO_SERVER_EXIT_CODE:
hdr.type = MSG_SERVER_TO_CLIENT_EXIT_CODE;
break;
default: /* cannot happen, already sanitized */
fprintf(stderr, "from agent: type=%d\n", s_hdr.type);
exit(1);
}
hdr.len = s_hdr.len;
if (clients[s_hdr.client_id].state == CLIENT_INVALID) {
// benefit of doubt - maybe client exited earlier
// just eat the packet data and continue
char buf[MAX_DATA_CHUNK];
read_all_vchan_ext(buf, s_hdr.len);
return;
}
get_packet_data_from_agent_and_pass_to_client(s_hdr.client_id,
&hdr);
if (s_hdr.type == MSG_AGENT_TO_SERVER_EXIT_CODE)
terminate_client_and_flush_data(s_hdr.client_id);
}
/*
Scan the "clients" table, add ones we want to read from (because the other
end has not send MSG_XOFF on them) to read_fdset, add ones we want to write
to (because its pipe is full) to write_fdset. Return the highest used file
descriptor number, needed for the first select() parameter.
*/
int fill_fdsets_for_select(fd_set * read_fdset, fd_set * write_fdset)
{
int i;
int max = -1;
FD_ZERO(read_fdset);
FD_ZERO(write_fdset);
for (i = 0; i <= max_client_fd; i++) {
if (clients[i].state != CLIENT_INVALID
&& !(clients[i].state & CLIENT_DONT_READ)) {
FD_SET(i, read_fdset);
max = i;
}
if (clients[i].state != CLIENT_INVALID
&& clients[i].state & CLIENT_OUTQ_FULL) {
FD_SET(i, write_fdset);
max = i;
}
}
FD_SET(qrexec_daemon_unix_socket_fd, read_fdset);
if (qrexec_daemon_unix_socket_fd > max)
max = qrexec_daemon_unix_socket_fd;
return max;
}
int main(int argc, char **argv)
{
fd_set read_fdset, write_fdset;
int i;
int max;
sigset_t chld_set;
if (argc != 2 && argc != 3) {
fprintf(stderr, "usage: %s domainid [default user]\n", argv[0]);
exit(1);
}
if (argc == 3)
default_user = argv[2];
init(atoi(argv[1]));
sigemptyset(&chld_set);
sigaddset(&chld_set, SIGCHLD);
/*
The main event loop. Waits for one of the following events:
- message from client
- message from agent
- new client
- child exited
*/
for (;;) {
max = fill_fdsets_for_select(&read_fdset, &write_fdset);
if (buffer_space_vchan_ext() <=
sizeof(struct server_header))
FD_ZERO(&read_fdset); // vchan full - don't read from clients
sigprocmask(SIG_BLOCK, &chld_set, NULL);
if (child_exited)
reap_children();
wait_for_vchan_or_argfd(max, &read_fdset, &write_fdset);
sigprocmask(SIG_UNBLOCK, &chld_set, NULL);
if (FD_ISSET(qrexec_daemon_unix_socket_fd, &read_fdset))
handle_new_client();
while (read_ready_vchan_ext())
handle_message_from_agent();
for (i = 0; i <= max_client_fd; i++)
if (clients[i].state != CLIENT_INVALID
&& FD_ISSET(i, &read_fdset))
handle_message_from_client(i);
for (i = 0; i <= max_client_fd; i++)
if (clients[i].state != CLIENT_INVALID
&& FD_ISSET(i, &write_fdset))
write_buffered_data_to_client(i);
}
}

@ -0,0 +1,187 @@
#!/usr/bin/python
import sys
import os
import os.path
import subprocess
import xen.lowlevel.xl
import qubes.guihelpers
from optparse import OptionParser
import fcntl
POLICY_FILE_DIR="/etc/qubes-rpc/policy"
# XXX: Backward compatibility, to be removed soon
DEPRECATED_POLICY_FILE_DIR="/etc/qubes_rpc/policy"
QREXEC_CLIENT="/usr/lib/qubes/qrexec-client"
class UserChoice:
ALLOW=0
DENY=1
ALWAYS_ALLOW=2
def line_to_dict(line):
tokens=line.split()
if len(tokens) < 3:
return None
if tokens[0][0] == '#':
return None
dict={}
dict['source']=tokens[0]
dict['dest']=tokens[1]
dict['full-action']=tokens[2]
action_list=tokens[2].split(',')
dict['action']=action_list.pop(0)
for iter in action_list:
paramval=iter.split("=")
dict["action."+paramval[0]]=paramval[1]
return dict
def read_policy_file(exec_index):
policy_file=POLICY_FILE_DIR+"/"+exec_index
if not os.path.isfile(policy_file):
policy_file=DEPRECATED_POLICY_FILE_DIR+"/"+exec_index
if not os.path.isfile(policy_file):
return None
print >>sys.stderr, "RPC service '%s' uses deprecated policy location, please move to %s" % (exec_index, POLICY_FILE_DIR)
policy_list=list()
f = open(policy_file)
fcntl.flock(f, fcntl.LOCK_SH)
for iter in f.readlines():
dict = line_to_dict(iter)
if dict is not None:
policy_list.append(dict)
f.close()
return policy_list
def is_match(item, config_term):
return (item is not "dom0" and config_term == "$anyvm") or item == config_term
def get_default_policy():
dict={}
dict["action"]="deny"
return dict
def find_policy(policy, domain, target):
for iter in policy:
if not is_match(domain, iter["source"]):
continue
if not is_match(target, iter["dest"]):
continue
return iter
return get_default_policy()
def is_domain_running(target):
xl_ctx = xen.lowlevel.xl.ctx()
domains = xl_ctx.list_domains()
for dominfo in domains:
domname = xl_ctx.domid_to_name(dominfo.domid)
if domname == target:
return True
return False
def spawn_target_if_necessary(target):
if is_domain_running(target):
return
null=open("/dev/null", "r+")
subprocess.call(["qvm-run", "-a", "-q", target, "true"], stdin=null, stdout=null)
null.close()
def do_execute(domain, target, user, exec_index, process_ident):
if target == "dom0":
cmd="/usr/lib/qubes/qubes-rpc-multiplexer "+exec_index + " " + domain
elif target == "$dispvm":
cmd = "/usr/lib/qubes/qfile-daemon-dvm " + exec_index + " " + domain + " " +user
else:
# see the previous commit why "qvm-run -a" is broken and dangerous
# also, dangling "xl" would keep stderr open and may prevent closing connection
spawn_target_if_necessary(target)
cmd= QREXEC_CLIENT + " -d " + target + " '" + user
cmd+=":QUBESRPC "+ exec_index + " " + domain + "'"
os.execl(QREXEC_CLIENT, "qrexec-client", "-d", domain, "-l", cmd, "-c", process_ident)
def confirm_execution(domain, target, exec_index):
text = "Do you allow domain \"" +domain + "\" to execute " + exec_index
text+= " operation on the domain \"" + target +"\"?<br>"
text+= " \"Yes to All\" option will automatically allow this operation in the future."
return qubes.guihelpers.ask(text, yestoall=True)
def add_always_allow(domain, target, exec_index, options):
policy_file=POLICY_FILE_DIR+"/"+exec_index
if not os.path.isfile(policy_file):
return None
f = open(policy_file, 'r+')
fcntl.flock(f, fcntl.LOCK_EX)
lines = []
for l in f.readlines():
lines.append(l)
lines.insert(0, "%s\t%s\tallow%s\n" % (domain, target, options))
f.seek(0)
f.write("".join(lines))
f.close()
def policy_editor(domain, target, exec_index):
text = "No policy definition found for " + exec_index + " action. "
text+= "Please create a policy file in Dom0 in " + POLICY_FILE_DIR + "/" + exec_index
subprocess.call(["/usr/bin/zenity", "--info", "--text", text])
def main():
usage = "usage: %prog [options] <src-domain> <target-domain> <service> <process-ident>"
parser = OptionParser (usage)
parser.add_option ("--assume-yes-for-ask", action="store_true", dest="assume_yes_for_ask", default=False,
help="Allow run of service without confirmation if policy say 'ask'")
parser.add_option ("--just-evaluate", action="store_true", dest="just_evaluate", default=False,
help="Do not run the service, only evaluate policy; retcode=0 means 'allow'")
(options, args) = parser.parse_args ()
domain=args[0]
target=args[1]
exec_index=args[2]
process_ident=args[3]
policy_list=read_policy_file(exec_index)
if policy_list==None:
policy_editor(domain, target, exec_index)
policy_list=read_policy_file(exec_index)
if policy_list==None:
policy_list=list()
policy_dict=find_policy(policy_list, domain, target)
if policy_dict["action"] == "ask" and options.assume_yes_for_ask:
policy_dict["action"] = "allow"
if policy_dict["action"] == "ask":
user_choice = confirm_execution(domain, target, exec_index)
if user_choice == UserChoice.ALWAYS_ALLOW:
add_always_allow(domain, target, exec_index, policy_dict["full-action"].lstrip('ask'))
policy_dict["action"] = "allow"
elif user_choice == UserChoice.ALLOW:
policy_dict["action"] = "allow"
else:
policy_dict["action"] = "deny"
if options.just_evaluate:
if policy_dict["action"] == "allow":
exit(0)
else:
exit(1)
if policy_dict["action"] == "allow":
if policy_dict.has_key("action.target"):
target=policy_dict["action.target"]
if policy_dict.has_key("action.user"):
user=policy_dict["action.user"]
else:
user="DEFAULT"
do_execute(domain, target, user, exec_index, process_ident)
print >> sys.stderr, "Rpc denied:", domain, target, exec_index
os.execl(QREXEC_CLIENT, "qrexec-client", "-d", domain, "-l", "/bin/false", "-c", process_ident)
main()

@ -0,0 +1,24 @@
#!/bin/sh
QUBES_RPC=/etc/qubes-rpc
# XXX: Backward compatibility
DEPRECATED_QUBES_RPC=/etc/qubes_rpc
if ! [ $# = 2 ] ; then
echo $0: bad argument count >&2
exit 1
fi
export QREXEC_REMOTE_DOMAIN="$2"
CFG_FILE=$QUBES_RPC/"$1"
if [ -s "$CFG_FILE" ] ; then
exec /bin/sh "$CFG_FILE"
echo "$0: failed to execute handler for" "$1" >&2
exit 1
fi
CFG_FILE=$DEPRECATED_QUBES_RPC/"$1"
if [ -s "$CFG_FILE" ] ; then
echo "$0: RPC service '$1' uses deprecated directory, please move to $QUBES_RPC" >&2
exec /bin/sh "$CFG_FILE"
echo "$0: failed to execute handler for" "$1" >&2
exit 1
fi
echo "$0: nonexistent or empty" "$CFG_FILE" file >&2
exit 1

@ -43,7 +43,9 @@ URL: http://www.qubes-os.org
BuildRequires: ImageMagick
BuildRequires: pandoc
BuildRequires: qubes-utils-devel
Requires: qubes-core-dom0
Requires: qubes-utils
%define _builddir %(pwd)
@ -63,6 +65,7 @@ ln -sf . %{name}-%{version}
python -m compileall appmenus-scripts
python -O -m compileall appmenus-scripts
(cd dom0-updates; make)
(cd qrexec; make)
(cd doc; make manpages)
%install
@ -98,17 +101,14 @@ install -m 0664 -D dom0-updates/qubes.ReceiveUpdates.policy $RPM_BUILD_ROOT/etc/
install -d $RPM_BUILD_ROOT/var/lib/qubes/updates
### Udev config
mkdir -p $RPM_BUILD_ROOT/etc/udev/rules.d
cp udev/udev-qubes-block.rules $RPM_BUILD_ROOT/etc/udev/rules.d/99-qubes-block.rules
cp udev/udev-qubes-usb.rules $RPM_BUILD_ROOT/etc/udev/rules.d/99-qubes-usb.rules
mkdir -p $RPM_BUILD_ROOT/usr/libexec/qubes
cp udev/udev-block-add-change $RPM_BUILD_ROOT/usr/libexec/qubes/
cp udev/udev-block-remove $RPM_BUILD_ROOT/usr/libexec/qubes/
cp udev/udev-block-cleanup $RPM_BUILD_ROOT/usr/libexec/qubes/
cp udev/udev-usb-add-change $RPM_BUILD_ROOT/usr/libexec/qubes/
cp udev/udev-usb-remove $RPM_BUILD_ROOT/usr/libexec/qubes/
# Qrexec
mkdir -p $RPM_BUILD_ROOT/usr/lib/qubes/
cp qrexec/qrexec-daemon $RPM_BUILD_ROOT/usr/lib/qubes/
cp qrexec/qrexec-client $RPM_BUILD_ROOT/usr/lib/qubes/
# XXX: Backward compatibility
ln -s qrexec-client $RPM_BUILD_ROOT/usr/lib/qubes/qrexec_client
cp qrexec/qrexec-policy $RPM_BUILD_ROOT/usr/lib/qubes/
cp qrexec/qubes-rpc-multiplexer $RPM_BUILD_ROOT/usr/lib/qubes
### pm-utils
mkdir -p $RPM_BUILD_ROOT/usr/lib64/pm-utils/sleep.d
@ -212,14 +212,12 @@ mv -f /lib/udev/rules.d/69-xorg-vmmouse.rules /var/lib/qubes/removed-udev-script
/etc/dracut.conf.d/*
%dir %{_dracutmoddir}/90qubes-pciback
%{_dracutmoddir}/90qubes-pciback/*
# Udev
/usr/libexec/qubes/udev-block-add-change
/usr/libexec/qubes/udev-block-cleanup
/usr/libexec/qubes/udev-block-remove
/usr/libexec/qubes/udev-usb-add-change
/usr/libexec/qubes/udev-usb-remove
/etc/udev/rules.d/99-qubes-block.rules
/etc/udev/rules.d/99-qubes-usb.rules
# Qrexec
%attr(4750,root,qubes) /usr/lib/qubes/qrexec-daemon
/usr/lib/qubes/qrexec-client
/usr/lib/qubes/qrexec_client
/usr/lib/qubes/qubes-rpc-multiplexer
/usr/lib/qubes/qrexec-policy
# pm-utils
/usr/lib64/pm-utils/sleep.d/01qubes-sync-vms-clock
/usr/lib64/pm-utils/sleep.d/51qubes-suspend-netvm

@ -1,61 +0,0 @@
#!/bin/bash
NAME=${DEVNAME#/dev/}
DESC="${ID_MODEL} (${ID_FS_LABEL})"
SIZE=$[ $(cat /sys/$DEVPATH/size) * 512 ]
MODE=w
XS_KEY="qubes-block-devices/$NAME"
xs_remove() {
if [ "$QUBES_EXPOSED" == "1" ]; then
xenstore-rm "$XS_KEY"
fi
echo QUBES_EXPOSED=0
}
# Ignore mounted...
if fgrep -q $DEVNAME /proc/mounts; then
xs_remove
exit 0
fi
# ... and used by device-mapper
if [ -n "`ls -A /sys/$DEVPATH/holders 2> /dev/null`" ]; then
xs_remove
exit 0
fi
# ... and "empty" loop devices
if [ "$MAJOR" -eq 7 -a ! -d /sys/$DEVPATH/loop ]; then
xs_remove
exit 0
fi
# Special case for CD
if [ "$ID_TYPE" = "cd" ]; then
if [ "$ID_CDROM_MEDIA" != "1" ]; then
# Hide empty cdrom drive
xs_remove
exit 0
fi
MODE=r
fi
# Special description for loop devices
if [ -d /sys/$DEVPATH/loop ]; then
DESC=$(cat /sys/$DEVPATH/loop/backing_file)
fi
# Get lock only in dom0 - there are so many block devices so it causes xenstore
# deadlocks sometimes.
if [ -f /etc/qubes-release ]; then
# Skip xenstore-write if cannot obtain lock. This can mean very early system startup
# stage without /run mounted (or populated). Devices will be rediscovered later
# by qubes-core startup script.
exec 9>>/var/run/qubes/block-xenstore.lock || exit 0
flock 9
fi
xenstore-write "$XS_KEY/desc" "$DESC" "$XS_KEY/size" "$SIZE" "$XS_KEY/mode" "$MODE"
echo QUBES_EXPOSED=1
# Make sure that block backend is loaded
/sbin/modprobe xen-blkback 2> /dev/null || /sbin/modprobe blkbk

@ -1,8 +0,0 @@
#!/bin/sh
DEVID=$[ $MAJOR * 256 + $MINOR ]
XS_PATH="device/vbd/$DEVID"
# Double check that DEVID is not empty
[ -n "$DEVID" ] && xenstore-rm $XS_PATH

@ -1,32 +0,0 @@
#!/bin/sh
NAME=${DEVNAME#/dev/}
XS_KEY="qubes-block-devices/$NAME"
xenstore-rm "$XS_KEY"
# If device was connected to some VM - detach it
# Notice: this can be run also in VM, so we cannot use xl...
device_detach() {
xs_path=$1
xenstore-write $xs_path/online 0 $xs_path/state 5
# Wait for backend to finish dev shutdown
try=30
# -lt will break loop also when 'state' will be empty
while [ "`xenstore-read $xs_path/state 2> /dev/null`" -lt 6 ]; do
try=$[ $try - 1 ]
[ "$try" -le 0 ] && break
sleep 0.1
done
xenstore-rm $xs_path
}
for XS_DEV_PATH in `xenstore-ls -f backend/vbd | grep 'backend/vbd/[0-9]*/[0-9]* ' | cut -f 1 -d ' '`; do
CUR_DEVICE=`xenstore-read "$XS_DEV_PATH/params"`
if [ "$CUR_DEVICE" == "$DEVNAME" ]; then
device_detach "$XS_DEV_PATH"
exit 0
fi
done

@ -1,20 +0,0 @@
# Expose all (except xen-frontend) block devices via xenstore
# Only block devices are interesting
SUBSYSTEM!="block", GOTO="qubes_block_end"
# Skip xen-blkfront devices
ENV{MAJOR}=="202", GOTO="qubes_block_end"
# Skip device-mapper devices
ENV{MAJOR}=="253", GOTO="qubes_block_end"
IMPORT{db}="QUBES_EXPOSED"
ACTION=="add", IMPORT{program}="/usr/libexec/qubes/udev-block-add-change"
ACTION=="change", IMPORT{program}="/usr/libexec/qubes/udev-block-add-change"
ACTION=="remove", RUN+="/usr/libexec/qubes/udev-block-remove"
LABEL="qubes_block_end"
# Cleanup disconnected frontend from xenstore
ACTION=="remove", SUBSYSTEM=="block", ENV{MAJOR}=="202", RUN+="/usr/libexec/qubes/udev-block-cleanup"

@ -1,10 +0,0 @@
# Expose all USB devices (except block) via xenstore
# Handle only USB devices
SUBSYSTEM!="usb", GOTO="qubes_usb_end"
ACTION=="add", IMPORT{program}="/usr/libexec/qubes/udev-usb-add-change"
ACTION=="change", IMPORT{program}="/usr/libexec/qubes/udev-usb-add-change"
ACTION=="remove", RUN+="/usr/libexec/qubes/udev-usb-remove"
LABEL="qubes_usb_end"

@ -1,40 +0,0 @@
#!/bin/sh
##
## This script is invoked by udev rules whenever USB device appears or
## changes. This happens in usbvm domain (or dom0 if USB controller
## drivers are in dom0). The script records information about available
## USB devices into XS directory, making it available to qvm-usb tool
## running in dom0.
##
# FIXME: Ignore USB hubs and other wierd devices (see also in udev-usb-remove).
[ "`echo $TYPE | cut -f1 -d/`" = "9" ] && exit 0
[ "$DEVTYPE" != "usb_device" ] && exit 0
# xenstore doesn't allow dot in key name
XSNAME=`basename ${DEVPATH} | tr . _`
# FIXME: For some devices (my Cherry keyboard) ID_SERIAL does not
# contain proper human-readable name, should find better method to
# build devide description.
#DESC=`python -c "dev='%d-%d' % (int('${BUSNUM}'.lstrip('0')), (int('${DEVNUM}'.lstrip('0'))-1)); from xen.util import vusb_util; print vusb_util.get_usbdevice_info(dev);"`
DESC="${ID_VENDOR_ID}:${ID_MODEL_ID} ${ID_SERIAL}"
VERSION=`cat /sys/$DEVPATH/version`
if [ "${VERSION}" = " 1.00" -o "${VERSION}" = " 1.10" ] ; then
VERSION=1
elif [ "${VERSION}" = " 2.00" ] ; then
VERSION=2
else
# FIXME: silently ignoring devices with unexpected USB version
exit 0
fi
XS_KEY="qubes-usb-devices/$XSNAME"
xenstore-write "$XS_KEY/desc" "$DESC"
xenstore-write "$XS_KEY/usb-ver" "$VERSION"
# Make sure PVUSB backend driver is loaded.
/sbin/modprobe xen-usbback 2> /dev/null || /sbin/modprobe usbbk

@ -1,9 +0,0 @@
#!/bin/sh
# FIXME: Ignore USB hubs.
[ "`echo $TYPE | cut -f1 -d/`" = "9" ] && exit 0
NAME=`basename ${DEVPATH} | tr . _`
XS_KEY="qubes-usb-devices/$NAME"
xenstore-rm "$XS_KEY"
Loading…
Cancel
Save