From nobody Sun May 5 13:38:15 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Authentication-Results: mx.zohomail.com; spf=pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1550246788192641.4775592776328; Fri, 15 Feb 2019 08:06:28 -0800 (PST) Received: from localhost ([127.0.0.1]:42101 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gug0P-0002z0-00 for importer@patchew.org; Fri, 15 Feb 2019 11:06:25 -0500 Received: from eggs.gnu.org ([209.51.188.92]:46968) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufsP-0005Cr-K4 for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:13 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1gufsE-0002vo-FG for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:09 -0500 Received: from mx1.redhat.com ([209.132.183.28]:52552) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1gufsE-0002Sk-0w for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:57:58 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id EEF0E5F793; Fri, 15 Feb 2019 15:57:25 +0000 (UTC) Received: from localhost.localdomain.com (ovpn-112-65.ams2.redhat.com [10.36.112.65]) by smtp.corp.redhat.com (Postfix) with ESMTP id F41F310018FB; Fri, 15 Feb 2019 15:57:22 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Date: Fri, 15 Feb 2019 15:56:59 +0000 Message-Id: <20190215155709.15777-2-berrange@redhat.com> In-Reply-To: <20190215155709.15777-1-berrange@redhat.com> References: <20190215155709.15777-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.84 on 10.5.11.22 X-Greylist: Sender IP whitelisted, not delayed by milter-greylist-4.5.16 (mx1.redhat.com [10.5.110.39]); Fri, 15 Feb 2019 15:57:26 +0000 (UTC) Content-Transfer-Encoding: quoted-printable X-detected-operating-system: by eggs.gnu.org: GNU/Linux 2.2.x-3.x [generic] X-Received-From: 209.132.183.28 Subject: [Qemu-devel] [PATCH v8 01/11] util: add helper APIs for dealing with inotify in portable manner X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Markus Armbruster , "Dr. David Alan Gilbert" , Gerd Hoffmann , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , =?UTF-8?q?Andreas=20F=C3=A4rber?= Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Content-Type: text/plain; charset="utf-8" The inotify userspace API for reading events is quite horrible, so it is useful to wrap it in a more friendly API to avoid duplicating code across many users in QEMU. Wrapping it also allows introduction of a platform portability layer, so that we can add impls for non-Linux based equivalents in future. Signed-off-by: Daniel P. Berrang=C3=A9 --- MAINTAINERS | 7 + Makefile.objs | 2 +- include/qemu/filemonitor.h | 128 +++++++ tests/Makefile.include | 3 + tests/test-util-filemonitor.c | 685 ++++++++++++++++++++++++++++++++++ util/Makefile.objs | 3 + util/filemonitor-inotify.c | 338 +++++++++++++++++ util/filemonitor-stub.c | 59 +++ util/trace-events | 9 + 9 files changed, 1233 insertions(+), 1 deletion(-) create mode 100644 include/qemu/filemonitor.h create mode 100644 tests/test-util-filemonitor.c create mode 100644 util/filemonitor-inotify.c create mode 100644 util/filemonitor-stub.c diff --git a/MAINTAINERS b/MAINTAINERS index ffb029f63a..5989796fa9 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2080,6 +2080,13 @@ F: include/qemu/sockets.h F: util/qemu-sockets.c F: qapi/sockets.json =20 +File monitor +M: Daniel P. Berrange +S: Odd fixes +F: util/filemonitor*.c +F: include/qemu/filemonitor.h +F: tests/test-util-filemonitor.c + Throttling infrastructure M: Alberto Garcia S: Supported diff --git a/Makefile.objs b/Makefile.objs index b7aae33367..fee0ce9fc5 100644 --- a/Makefile.objs +++ b/Makefile.objs @@ -4,7 +4,7 @@ QAPI_MODULES +=3D ui =20 ####################################################################### # Common libraries for tools and emulators -stub-obj-y =3D stubs/ crypto/ +stub-obj-y =3D stubs/ util/ crypto/ util-obj-y =3D util/ qobject/ qapi/ util-obj-y +=3D qapi/qapi-builtin-types.o util-obj-y +=3D qapi/qapi-types.o diff --git a/include/qemu/filemonitor.h b/include/qemu/filemonitor.h new file mode 100644 index 0000000000..cd031832ed --- /dev/null +++ b/include/qemu/filemonitor.h @@ -0,0 +1,128 @@ +/* + * QEMU file monitor helper + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#ifndef QEMU_FILE_MONITOR_H +#define QEMU_FILE_MONITOR_H + +#include "qemu-common.h" + + +typedef struct QFileMonitor QFileMonitor; + +typedef enum { + /* File has been created in a dir */ + QFILE_MONITOR_EVENT_CREATED, + /* File has been modified in a dir */ + QFILE_MONITOR_EVENT_MODIFIED, + /* File has been deleted in a dir */ + QFILE_MONITOR_EVENT_DELETED, + /* File has attributes changed */ + QFILE_MONITOR_EVENT_ATTRIBUTES, + /* Dir is no longer being monitored (due to deletion) */ + QFILE_MONITOR_EVENT_IGNORED, +} QFileMonitorEvent; + + +/** + * QFileMonitorHandler: + * @id: id from qemu_file_monitor_add_watch() + * @event: the file change that occurred + * @filename: the name of the file affected + * @opaque: opaque data provided to qemu_file_monitor_add_watch() + * + * Invoked whenever a file changes. If @event is + * QFILE_MONITOR_EVENT_IGNORED, @filename will be + * empty. + * + */ +typedef void (*QFileMonitorHandler)(int id, + QFileMonitorEvent event, + const char *filename, + void *opaque); + +/** + * qemu_file_monitor_new: + * @errp: pointer to a NULL-initialized error object + * + * Create a handle for a file monitoring object. + * + * This object does locking internally to enable it to be + * safe to use from multiple threads + * + * If the platform does not support file monitoring, an + * error will be reported. Likewise if file monitoring + * is supported, but cannot be initialized + * + * Currently this is implemented on Linux platforms with + * the inotify subsystem. + * + * Returns: the new monitoring object, or NULL on error + */ +QFileMonitor *qemu_file_monitor_new(Error **errp); + +/** + * qemu_file_monitor_free: + * @mon: the file monitor context + * + * Free resources associated with the file monitor, + * including any currently registered watches. + */ +void qemu_file_monitor_free(QFileMonitor *mon); + +/** + * qemu_file_monitor_add_watch: + * @mon: the file monitor context + * @dirpath: the directory whose contents to watch + * @filename: optional filename to filter on + * @cb: the function to invoke when @dirpath has changes + * @opaque: data to pass to @cb + * @errp: pointer to a NULL-initialized error object + * + * Register to receive notifications of changes + * in the directory @dirpath. All files in the + * directory will be monitored. If the caller is + * only interested in one specific file, @filename + * can be used to filter events. + * + * Returns: a positive integer watch ID, or -1 on error + */ +int qemu_file_monitor_add_watch(QFileMonitor *mon, + const char *dirpath, + const char *filename, + QFileMonitorHandler cb, + void *opaque, + Error **errp); + +/** + * qemu_file_monitor_remove_watch: + * @mon: the file monitor context + * @dirpath: the directory whose contents to unwatch + * @id: id of the watch to remove + * + * Removes the file monitoring watch @id, associated + * with the directory @dirpath. This must never be + * called from a QFileMonitorHandler callback, or a + * deadlock will result. + */ +void qemu_file_monitor_remove_watch(QFileMonitor *mon, + const char *dirpath, + int id); + +#endif /* QEMU_FILE_MONITOR_H */ diff --git a/tests/Makefile.include b/tests/Makefile.include index b39e989f72..3a6a8d4b17 100644 --- a/tests/Makefile.include +++ b/tests/Makefile.include @@ -114,6 +114,7 @@ ifneq (,$(findstring qemu-ga,$(TOOLS))) check-unit-$(land,$(CONFIG_LINUX),$(CONFIG_VIRTIO_SERIAL)) +=3D tests/test= -qga$(EXESUF) endif check-unit-y +=3D tests/test-timed-average$(EXESUF) +check-unit-$(CONFIG_INOTIFY1) +=3D tests/test-util-filemonitor$(EXESUF) check-unit-y +=3D tests/test-util-sockets$(EXESUF) check-unit-y +=3D tests/test-io-task$(EXESUF) check-unit-y +=3D tests/test-io-channel-socket$(EXESUF) @@ -657,6 +658,8 @@ tests/test-crypto-tlssession$(EXESUF): tests/test-crypt= o-tlssession.o \ tests/crypto-tls-x509-helpers.o tests/pkix_asn1_tab.o \ tests/crypto-tls-psk-helpers.o \ $(test-crypto-obj-y) +tests/test-util-filemonitor$(EXESUF): tests/test-util-filemonitor.o \ + $(test-util-obj-y) tests/test-util-sockets$(EXESUF): tests/test-util-sockets.o \ tests/socket-helpers.o $(test-util-obj-y) tests/test-io-task$(EXESUF): tests/test-io-task.o $(test-io-obj-y) diff --git a/tests/test-util-filemonitor.c b/tests/test-util-filemonitor.c new file mode 100644 index 0000000000..5d95cea5ee --- /dev/null +++ b/tests/test-util-filemonitor.c @@ -0,0 +1,685 @@ +/* + * Tests for util/filemonitor-*.c + * + * Copyright 2018 Red Hat, Inc. + * + * 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 library; if not, see . + * + */ + +#include "qemu/osdep.h" +#include "qemu/main-loop.h" +#include "qapi/error.h" +#include "qemu/filemonitor.h" + +#include + +enum { + QFILE_MONITOR_TEST_OP_CREATE, + QFILE_MONITOR_TEST_OP_APPEND, + QFILE_MONITOR_TEST_OP_TRUNC, + QFILE_MONITOR_TEST_OP_RENAME, + QFILE_MONITOR_TEST_OP_TOUCH, + QFILE_MONITOR_TEST_OP_UNLINK, +}; + +typedef struct { + int type; + const char *filesrc; + const char *filedst; +} QFileMonitorTestOp; + +typedef struct { + const char *file; +} QFileMonitorTestWatch; + +typedef struct { + gsize nwatches; + const QFileMonitorTestWatch *watches; + + gsize nops; + const QFileMonitorTestOp *ops; +} QFileMonitorTestPlan; + +typedef struct { + int id; + QFileMonitorEvent event; + char *filename; +} QFileMonitorTestRecord; + + +typedef struct { + QemuMutex lock; + GList *records; +} QFileMonitorTestData; + +static QemuMutex evlock; +static bool evstopping; +static bool evrunning; + +/* + * Main function for a background thread that is + * running the event loop during the test + */ +static void * +qemu_file_monitor_test_event_loop(void *opaque G_GNUC_UNUSED) +{ + qemu_mutex_lock(&evlock); + + while (!evstopping) { + qemu_mutex_unlock(&evlock); + main_loop_wait(true); + qemu_mutex_lock(&evlock); + } + + evrunning =3D false; + qemu_mutex_unlock(&evlock); + return NULL; +} + + +/* + * File monitor event handler which simply maintains + * an ordered list of all events that it receives + */ +static void +qemu_file_monitor_test_handler(int id, + QFileMonitorEvent event, + const char *filename, + void *opaque) +{ + QFileMonitorTestData *data =3D opaque; + QFileMonitorTestRecord *rec =3D g_new0(QFileMonitorTestRecord, 1); + + rec->id =3D id; + rec->event =3D event; + rec->filename =3D g_strdup(filename); + + qemu_mutex_lock(&data->lock); + data->records =3D g_list_append(data->records, rec); + qemu_mutex_unlock(&data->lock); +} + + +static void +qemu_file_monitor_test_record_free(QFileMonitorTestRecord *rec) +{ + g_free(rec->filename); + g_free(rec); +} + + +/* + * Get the next event record that has been received by + * the file monitor event handler. Since events are + * emitted in the background thread running the event + * loop, we can't assume there is a record available + * immediately. Thus we will sleep for upto 5 seconds + * to wait for the event to be queued for us. + */ +static QFileMonitorTestRecord * +qemu_file_monitor_test_next_record(QFileMonitorTestData *data) +{ + GTimer *timer =3D g_timer_new(); + QFileMonitorTestRecord *record =3D NULL; + GList *tmp; + + qemu_mutex_lock(&data->lock); + while (!data->records && g_timer_elapsed(timer, NULL) < 5) { + qemu_mutex_unlock(&data->lock); + usleep(10 * 1000); + qemu_mutex_lock(&data->lock); + } + if (data->records) { + record =3D data->records->data; + tmp =3D data->records; + data->records =3D g_list_remove_link(data->records, tmp); + g_list_free(tmp); + } + qemu_mutex_unlock(&data->lock); + + g_timer_destroy(timer); + return record; +} + + +/* + * Check whether the event record we retrieved matches + * data we were expecting to see for the event + */ +static bool +qemu_file_monitor_test_expect(QFileMonitorTestData *data, + int id, + QFileMonitorEvent event, + const char *filename) +{ + QFileMonitorTestRecord *rec; + bool ret =3D false; + + rec =3D qemu_file_monitor_test_next_record(data); + + if (!rec) { + g_printerr("Missing event watch id %d event %d file %s\n", + id, event, filename); + return false; + } + + if (id !=3D rec->id) { + g_printerr("Expected watch id %d but got %d\n", id, rec->id); + goto cleanup; + } + + if (event !=3D rec->event) { + g_printerr("Expected event %d but got %d\n", event, rec->event); + goto cleanup; + } + + if (!g_str_equal(filename, rec->filename)) { + g_printerr("Expected filename %s but got %s\n", + filename, rec->filename); + goto cleanup; + } + + ret =3D true; + + cleanup: + qemu_file_monitor_test_record_free(rec); + return ret; +} + + +static void +test_file_monitor_events(const void *opaque) +{ + const QFileMonitorTestPlan *plan =3D opaque; + Error *local_err =3D NULL; + GError *gerr =3D NULL; + QFileMonitor *mon =3D qemu_file_monitor_new(&local_err); + QemuThread th; + GTimer *timer; + gchar *dir =3D NULL; + int err =3D -1; + gsize i, j; + char *pathsrc =3D NULL; + char *pathdst =3D NULL; + QFileMonitorTestData data; + + qemu_mutex_init(&data.lock); + data.records =3D NULL; + + /* + * The file monitor needs the main loop running in + * order to receive events from inotify. We must + * thus spawn a background thread to run an event + * loop impl, while this thread triggers the + * actual file operations we're testing + */ + evrunning =3D 1; + evstopping =3D 0; + qemu_thread_create(&th, "event-loop", + qemu_file_monitor_test_event_loop, NULL, + QEMU_THREAD_JOINABLE); + + if (local_err) { + g_printerr("File monitoring not available: %s", + error_get_pretty(local_err)); + error_free(local_err); + return; + } + + dir =3D g_dir_make_tmp("test-util-filemonitor-XXXXXX", + &gerr); + if (!dir) { + g_printerr("Unable to create tmp dir %s", + gerr->message); + g_error_free(gerr); + abort(); + } + + /* + * First register all the directory / file watches + * we're interested in seeing events against + */ + for (i =3D 0; i < plan->nwatches; i++) { + int watchid; + watchid =3D qemu_file_monitor_add_watch(mon, + dir, + plan->watches[i].file, + qemu_file_monitor_test_handl= er, + &data, + &local_err); + if (watchid < 0) { + g_printerr("Unable to add watch %s", + error_get_pretty(local_err)); + goto cleanup; + } + } + + + /* + * Now invoke all the file operations (create, + * delete, rename, chmod, etc). These operations + * will trigger the various file monitor events + */ + for (i =3D 0; i < plan->nops; i++) { + const QFileMonitorTestOp *op =3D &(plan->ops[i]); + int fd; + struct utimbuf ubuf; + + pathsrc =3D g_strdup_printf("%s/%s", dir, op->filesrc); + if (op->filedst) { + pathdst =3D g_strdup_printf("%s/%s", dir, op->filedst); + } + + switch (op->type) { + case QFILE_MONITOR_TEST_OP_CREATE: + fd =3D open(pathsrc, O_WRONLY | O_CREAT, 0700); + if (fd < 0) { + g_printerr("Unable to create %s: %s", + pathsrc, strerror(errno)); + goto cleanup; + } + close(fd); + break; + + case QFILE_MONITOR_TEST_OP_APPEND: + fd =3D open(pathsrc, O_WRONLY | O_APPEND, 0700); + if (fd < 0) { + g_printerr("Unable to open %s: %s", + pathsrc, strerror(errno)); + goto cleanup; + } + + if (write(fd, "Hello World", 10) !=3D 10) { + g_printerr("Unable to write %s: %s", + pathsrc, strerror(errno)); + close(fd); + goto cleanup; + } + close(fd); + break; + + case QFILE_MONITOR_TEST_OP_TRUNC: + if (truncate(pathsrc, 4) < 0) { + g_printerr("Unable to truncate %s: %s", + pathsrc, strerror(errno)); + goto cleanup; + } + break; + + case QFILE_MONITOR_TEST_OP_RENAME: + if (rename(pathsrc, pathdst) < 0) { + g_printerr("Unable to rename %s to %s: %s", + pathsrc, pathdst, strerror(errno)); + goto cleanup; + } + break; + + case QFILE_MONITOR_TEST_OP_UNLINK: + if (unlink(pathsrc) < 0) { + g_printerr("Unable to unlink %s: %s", + pathsrc, strerror(errno)); + goto cleanup; + } + break; + + case QFILE_MONITOR_TEST_OP_TOUCH: + ubuf.actime =3D 1024; + ubuf.modtime =3D 1025; + if (utime(pathsrc, &ubuf) < 0) { + g_printerr("Unable to touch %s: %s", + pathsrc, strerror(errno)); + goto cleanup; + } + break; + + default: + g_assert_not_reached(); + } + + g_free(pathsrc); + g_free(pathdst); + pathsrc =3D pathdst =3D NULL; + } + + + /* + * Finally validate that we have received all the events + * we expect to see for the combination of watches and + * file operations + */ + for (i =3D 0; i < plan->nops; i++) { + const QFileMonitorTestOp *op =3D &(plan->ops[i]); + + switch (op->type) { + case QFILE_MONITOR_TEST_OP_CREATE: + for (j =3D 0; j < plan->nwatches; j++) { + if (plan->watches[j].file && + !g_str_equal(plan->watches[j].file, op->filesrc)) + continue; + + if (!qemu_file_monitor_test_expect( + &data, j, QFILE_MONITOR_EVENT_CREATED, op->filesrc= )) + goto cleanup; + } + break; + + case QFILE_MONITOR_TEST_OP_APPEND: + case QFILE_MONITOR_TEST_OP_TRUNC: + for (j =3D 0; j < plan->nwatches; j++) { + if (plan->watches[j].file && + !g_str_equal(plan->watches[j].file, op->filesrc)) + continue; + + if (!qemu_file_monitor_test_expect( + &data, j, QFILE_MONITOR_EVENT_MODIFIED, op->filesr= c)) + goto cleanup; + } + break; + + case QFILE_MONITOR_TEST_OP_RENAME: + for (j =3D 0; j < plan->nwatches; j++) { + if (plan->watches[j].file && + !g_str_equal(plan->watches[j].file, op->filesrc)) + continue; + + if (!qemu_file_monitor_test_expect( + &data, j, QFILE_MONITOR_EVENT_DELETED, op->filesrc= )) + goto cleanup; + } + + for (j =3D 0; j < plan->nwatches; j++) { + if (plan->watches[j].file && + !g_str_equal(plan->watches[j].file, op->filedst)) + continue; + + if (!qemu_file_monitor_test_expect( + &data, j, QFILE_MONITOR_EVENT_CREATED, op->filedst= )) + goto cleanup; + } + break; + + case QFILE_MONITOR_TEST_OP_TOUCH: + for (j =3D 0; j < plan->nwatches; j++) { + if (plan->watches[j].file && + !g_str_equal(plan->watches[j].file, op->filesrc)) + continue; + + if (!qemu_file_monitor_test_expect( + &data, j, QFILE_MONITOR_EVENT_ATTRIBUTES, op->file= src)) + goto cleanup; + } + break; + + case QFILE_MONITOR_TEST_OP_UNLINK: + for (j =3D 0; j < plan->nwatches; j++) { + if (plan->watches[j].file && + !g_str_equal(plan->watches[j].file, op->filesrc)) + continue; + + if (!qemu_file_monitor_test_expect( + &data, j, QFILE_MONITOR_EVENT_DELETED, op->filesrc= )) + goto cleanup; + } + break; + + default: + g_assert_not_reached(); + } + } + + err =3D 0; + + cleanup: + g_free(pathsrc); + g_free(pathdst); + + qemu_mutex_lock(&evlock); + evstopping =3D 1; + timer =3D g_timer_new(); + while (evrunning && g_timer_elapsed(timer, NULL) < 5) { + qemu_mutex_unlock(&evlock); + usleep(10 * 1000); + qemu_mutex_lock(&evlock); + } + qemu_mutex_unlock(&evlock); + + if (g_timer_elapsed(timer, NULL) >=3D 5) { + g_printerr("Event loop failed to quit after 5 seconds\n"); + } + g_timer_destroy(timer); + + for (i =3D 0; i < plan->nops; i++) { + const QFileMonitorTestOp *op =3D &(plan->ops[i]); + pathsrc =3D g_strdup_printf("%s/%s", dir, op->filesrc); + unlink(pathsrc); + g_free(pathsrc); + if (op->filedst) { + pathdst =3D g_strdup_printf("%s/%s", dir, op->filedst); + unlink(pathdst); + g_free(pathdst); + } + } + + qemu_file_monitor_free(mon); + g_list_foreach(data.records, + (GFunc)qemu_file_monitor_test_record_free, NULL); + g_list_free(data.records); + qemu_mutex_destroy(&data.lock); + if (dir) { + rmdir(dir); + } + g_free(dir); + g_assert(err =3D=3D 0); +} + + +/* + * Set of structs which define which file name patterns + * we're trying to watch against. NULL, means all files + * in the directory + */ +static const QFileMonitorTestWatch watches_any[] =3D { + { NULL }, +}; + +static const QFileMonitorTestWatch watches_one[] =3D { + { "one.txt" }, +}; + +static const QFileMonitorTestWatch watches_two[] =3D { + { "two.txt" }, +}; + +static const QFileMonitorTestWatch watches_many[] =3D { + { NULL }, + { "one.txt" }, + { "two.txt" }, +}; + + +/* + * Various sets of file operations we're going to + * trigger and validate events for + */ +static const QFileMonitorTestOp ops_create_one[] =3D { + { .type =3D QFILE_MONITOR_TEST_OP_CREATE, + .filesrc =3D "one.txt", } +}; + +static const QFileMonitorTestOp ops_delete_one[] =3D { + { .type =3D QFILE_MONITOR_TEST_OP_CREATE, + .filesrc =3D "one.txt", }, + { .type =3D QFILE_MONITOR_TEST_OP_UNLINK, + .filesrc =3D "one.txt", } +}; + +static const QFileMonitorTestOp ops_create_many[] =3D { + { .type =3D QFILE_MONITOR_TEST_OP_CREATE, + .filesrc =3D "one.txt", }, + { .type =3D QFILE_MONITOR_TEST_OP_CREATE, + .filesrc =3D "two.txt", }, + { .type =3D QFILE_MONITOR_TEST_OP_CREATE, + .filesrc =3D "three.txt", } +}; + +static const QFileMonitorTestOp ops_rename_one[] =3D { + { .type =3D QFILE_MONITOR_TEST_OP_CREATE, + .filesrc =3D "one.txt", }, + { .type =3D QFILE_MONITOR_TEST_OP_RENAME, + .filesrc =3D "one.txt", .filedst =3D "two.txt" } +}; + +static const QFileMonitorTestOp ops_rename_many[] =3D { + { .type =3D QFILE_MONITOR_TEST_OP_CREATE, + .filesrc =3D "one.txt", }, + { .type =3D QFILE_MONITOR_TEST_OP_CREATE, + .filesrc =3D "two.txt", }, + { .type =3D QFILE_MONITOR_TEST_OP_RENAME, + .filesrc =3D "one.txt", .filedst =3D "two.txt" } +}; + +static const QFileMonitorTestOp ops_append_one[] =3D { + { .type =3D QFILE_MONITOR_TEST_OP_CREATE, + .filesrc =3D "one.txt", }, + { .type =3D QFILE_MONITOR_TEST_OP_APPEND, + .filesrc =3D "one.txt", }, +}; + +static const QFileMonitorTestOp ops_trunc_one[] =3D { + { .type =3D QFILE_MONITOR_TEST_OP_CREATE, + .filesrc =3D "one.txt", }, + { .type =3D QFILE_MONITOR_TEST_OP_TRUNC, + .filesrc =3D "one.txt", }, +}; + +static const QFileMonitorTestOp ops_touch_one[] =3D { + { .type =3D QFILE_MONITOR_TEST_OP_CREATE, + .filesrc =3D "one.txt", }, + { .type =3D QFILE_MONITOR_TEST_OP_TOUCH, + .filesrc =3D "one.txt", }, +}; + + +/* + * No we define data sets for the combinatorial + * expansion of file watches and operation sets + */ +#define PLAN_DATA(o, w) \ + static const QFileMonitorTestPlan plan_ ## o ## _ ## w =3D { \ + .nops =3D G_N_ELEMENTS(ops_ ##o), \ + .ops =3D ops_ ##o, \ + .nwatches =3D G_N_ELEMENTS(watches_ ##w), \ + .watches =3D watches_ ## w, \ + } + +PLAN_DATA(create_one, any); +PLAN_DATA(create_one, one); +PLAN_DATA(create_one, two); +PLAN_DATA(create_one, many); + +PLAN_DATA(delete_one, any); +PLAN_DATA(delete_one, one); +PLAN_DATA(delete_one, two); +PLAN_DATA(delete_one, many); + +PLAN_DATA(create_many, any); +PLAN_DATA(create_many, one); +PLAN_DATA(create_many, two); +PLAN_DATA(create_many, many); + +PLAN_DATA(rename_one, any); +PLAN_DATA(rename_one, one); +PLAN_DATA(rename_one, two); +PLAN_DATA(rename_one, many); + +PLAN_DATA(rename_many, any); +PLAN_DATA(rename_many, one); +PLAN_DATA(rename_many, two); +PLAN_DATA(rename_many, many); + +PLAN_DATA(append_one, any); +PLAN_DATA(append_one, one); +PLAN_DATA(append_one, two); +PLAN_DATA(append_one, many); + +PLAN_DATA(trunc_one, any); +PLAN_DATA(trunc_one, one); +PLAN_DATA(trunc_one, two); +PLAN_DATA(trunc_one, many); + +PLAN_DATA(touch_one, any); +PLAN_DATA(touch_one, one); +PLAN_DATA(touch_one, two); +PLAN_DATA(touch_one, many); + + +int main(int argc, char **argv) +{ + g_test_init(&argc, &argv, NULL); + + qemu_init_main_loop(&error_abort); + + qemu_mutex_init(&evlock); + + /* + * Register test cases for the combinatorial + * expansion of file watches and operation sets + */ + #define PLAN_REGISTER(o, w) \ + g_test_add_data_func("/util/filemonitor/" # o "/" # w, \ + &plan_ ## o ## _ ## w, test_file_monitor_even= ts) + + PLAN_REGISTER(create_one, any); + PLAN_REGISTER(create_one, one); + PLAN_REGISTER(create_one, two); + PLAN_REGISTER(create_one, many); + + PLAN_REGISTER(delete_one, any); + PLAN_REGISTER(delete_one, one); + PLAN_REGISTER(delete_one, two); + PLAN_REGISTER(delete_one, many); + + PLAN_REGISTER(create_many, any); + PLAN_REGISTER(create_many, one); + PLAN_REGISTER(create_many, two); + PLAN_REGISTER(create_many, many); + + PLAN_REGISTER(rename_one, any); + PLAN_REGISTER(rename_one, one); + PLAN_REGISTER(rename_one, two); + PLAN_REGISTER(rename_one, many); + + PLAN_REGISTER(rename_many, any); + PLAN_REGISTER(rename_many, one); + PLAN_REGISTER(rename_many, two); + PLAN_REGISTER(rename_many, many); + + PLAN_REGISTER(append_one, any); + PLAN_REGISTER(append_one, one); + PLAN_REGISTER(append_one, two); + PLAN_REGISTER(append_one, many); + + PLAN_REGISTER(trunc_one, any); + PLAN_REGISTER(trunc_one, one); + PLAN_REGISTER(trunc_one, two); + PLAN_REGISTER(trunc_one, many); + + PLAN_REGISTER(touch_one, any); + PLAN_REGISTER(touch_one, one); + PLAN_REGISTER(touch_one, two); + PLAN_REGISTER(touch_one, many); + + return g_test_run(); +} diff --git a/util/Makefile.objs b/util/Makefile.objs index 0820923c18..c1dd746902 100644 --- a/util/Makefile.objs +++ b/util/Makefile.objs @@ -50,5 +50,8 @@ util-obj-y +=3D range.o util-obj-y +=3D stats64.o util-obj-y +=3D systemd.o util-obj-y +=3D iova-tree.o +util-obj-$(CONFIG_INOTIFY1) +=3D filemonitor-inotify.o util-obj-$(CONFIG_LINUX) +=3D vfio-helpers.o util-obj-$(CONFIG_OPENGL) +=3D drm.o + +stub-obj-y +=3D filemonitor-stub.o diff --git a/util/filemonitor-inotify.c b/util/filemonitor-inotify.c new file mode 100644 index 0000000000..c5e0a6fee0 --- /dev/null +++ b/util/filemonitor-inotify.c @@ -0,0 +1,338 @@ +/* + * QEMU file monitor Linux inotify impl + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#include "qemu/osdep.h" +#include "qemu/filemonitor.h" +#include "qemu/main-loop.h" +#include "qemu/error-report.h" +#include "qapi/error.h" +#include "trace.h" + +#include + +struct QFileMonitor { + int fd; + + QemuMutex lock; /* protects dirs & idmap */ + GHashTable *dirs; /* dirname =3D> QFileMonitorDir */ + GHashTable *idmap; /* inotify ID =3D> dirname */ +}; + + +typedef struct { + int id; /* watch ID */ + char *filename; /* optional filter */ + QFileMonitorHandler cb; + void *opaque; +} QFileMonitorWatch; + + +typedef struct { + char *path; + int id; /* inotify ID */ + int nextid; /* watch ID counter */ + GArray *watches; /* QFileMonitorWatch elements */ +} QFileMonitorDir; + + +static void qemu_file_monitor_watch(void *arg) +{ + QFileMonitor *mon =3D arg; + char buf[4096] + __attribute__ ((aligned(__alignof__(struct inotify_event)))); + int used =3D 0; + int len; + + qemu_mutex_lock(&mon->lock); + + if (mon->fd =3D=3D -1) { + qemu_mutex_unlock(&mon->lock); + return; + } + + len =3D read(mon->fd, buf, sizeof(buf)); + + if (len < 0) { + if (errno !=3D EAGAIN) { + error_report("Failure monitoring inotify FD '%s'," + "disabling events", strerror(errno)); + goto cleanup; + } + + /* no more events right now */ + goto cleanup; + } + + /* Loop over all events in the buffer */ + while (used < len) { + struct inotify_event *ev =3D + (struct inotify_event *)(buf + used); + const char *name =3D ev->len ? ev->name : ""; + QFileMonitorDir *dir =3D g_hash_table_lookup(mon->idmap, + GINT_TO_POINTER(ev->wd)= ); + uint32_t iev =3D ev->mask & + (IN_CREATE | IN_MODIFY | IN_DELETE | IN_IGNORED | + IN_MOVED_TO | IN_MOVED_FROM | IN_ATTRIB); + int qev; + gsize i; + + used +=3D sizeof(struct inotify_event) + ev->len; + + if (!dir) { + continue; + } + + /* + * During a rename operation, the old name gets + * IN_MOVED_FROM and the new name gets IN_MOVED_TO. + * To simplify life for callers, we turn these into + * DELETED and CREATED events + */ + switch (iev) { + case IN_CREATE: + case IN_MOVED_TO: + qev =3D QFILE_MONITOR_EVENT_CREATED; + break; + case IN_MODIFY: + qev =3D QFILE_MONITOR_EVENT_MODIFIED; + break; + case IN_DELETE: + case IN_MOVED_FROM: + qev =3D QFILE_MONITOR_EVENT_DELETED; + break; + case IN_ATTRIB: + qev =3D QFILE_MONITOR_EVENT_ATTRIBUTES; + break; + case IN_IGNORED: + qev =3D QFILE_MONITOR_EVENT_IGNORED; + break; + default: + g_assert_not_reached(); + } + + trace_qemu_file_monitor_event(mon, dir->path, name, ev->mask, dir-= >id); + for (i =3D 0; i < dir->watches->len; i++) { + QFileMonitorWatch *watch =3D &g_array_index(dir->watches, + QFileMonitorWatch, + i); + + if (watch->filename =3D=3D NULL || + (name && g_str_equal(watch->filename, name))) { + trace_qemu_file_monitor_dispatch(mon, dir->path, name, + qev, watch->cb, + watch->opaque, watch->id); + watch->cb(watch->id, qev, name, watch->opaque); + } + } + } + + cleanup: + qemu_mutex_unlock(&mon->lock); +} + + +static void +qemu_file_monitor_dir_free(void *data) +{ + QFileMonitorDir *dir =3D data; + gsize i; + + for (i =3D 0; i < dir->watches->len; i++) { + QFileMonitorWatch *watch =3D &g_array_index(dir->watches, + QFileMonitorWatch, i); + g_free(watch->filename); + } + g_array_unref(dir->watches); + g_free(dir->path); + g_free(dir); +} + + +QFileMonitor * +qemu_file_monitor_new(Error **errp) +{ + int fd; + QFileMonitor *mon; + + fd =3D inotify_init1(IN_NONBLOCK); + if (fd < 0) { + error_setg_errno(errp, errno, + "Unable to initialize inotify"); + return NULL; + } + + mon =3D g_new0(QFileMonitor, 1); + qemu_mutex_init(&mon->lock); + mon->fd =3D fd; + + mon->dirs =3D g_hash_table_new_full(g_str_hash, g_str_equal, NULL, + qemu_file_monitor_dir_free); + mon->idmap =3D g_hash_table_new(g_direct_hash, g_direct_equal); + + trace_qemu_file_monitor_new(mon, mon->fd); + + return mon; +} + +static gboolean +qemu_file_monitor_free_idle(void *opaque) +{ + QFileMonitor *mon =3D opaque; + + if (!mon) { + return G_SOURCE_REMOVE; + } + + qemu_mutex_lock(&mon->lock); + + g_hash_table_unref(mon->idmap); + g_hash_table_unref(mon->dirs); + + qemu_mutex_unlock(&mon->lock); + + qemu_mutex_destroy(&mon->lock); + g_free(mon); + + return G_SOURCE_REMOVE; +} + +void +qemu_file_monitor_free(QFileMonitor *mon) +{ + if (!mon) { + return; + } + + qemu_mutex_lock(&mon->lock); + if (mon->fd !=3D -1) { + qemu_set_fd_handler(mon->fd, NULL, NULL, NULL); + close(mon->fd); + mon->fd =3D -1; + } + qemu_mutex_unlock(&mon->lock); + + /* Can't free it yet, because another thread + * may be running event loop, so the inotify + * callback might be pending. Using an idle + * source ensures we'll only free after the + * pending callback is done + */ + g_idle_add((GSourceFunc)qemu_file_monitor_free_idle, mon); +} + +int +qemu_file_monitor_add_watch(QFileMonitor *mon, + const char *dirpath, + const char *filename, + QFileMonitorHandler cb, + void *opaque, + Error **errp) +{ + QFileMonitorDir *dir; + QFileMonitorWatch watch; + int ret =3D -1; + + qemu_mutex_lock(&mon->lock); + dir =3D g_hash_table_lookup(mon->dirs, dirpath); + if (!dir) { + int rv =3D inotify_add_watch(mon->fd, dirpath, + IN_CREATE | IN_DELETE | IN_MODIFY | + IN_MOVED_TO | IN_MOVED_FROM | IN_ATTRIB= ); + + if (rv < 0) { + error_setg_errno(errp, errno, "Unable to watch '%s'", dirpath); + goto cleanup; + } + + trace_qemu_file_monitor_enable_watch(mon, dirpath, rv); + + dir =3D g_new0(QFileMonitorDir, 1); + dir->path =3D g_strdup(dirpath); + dir->id =3D rv; + dir->watches =3D g_array_new(FALSE, TRUE, sizeof(QFileMonitorWatch= )); + + g_hash_table_insert(mon->dirs, dir->path, dir); + g_hash_table_insert(mon->idmap, GINT_TO_POINTER(rv), dir); + + if (g_hash_table_size(mon->dirs) =3D=3D 1) { + qemu_set_fd_handler(mon->fd, qemu_file_monitor_watch, NULL, mo= n); + } + } + + watch.id =3D dir->nextid++; + watch.filename =3D g_strdup(filename); + watch.cb =3D cb; + watch.opaque =3D opaque; + + g_array_append_val(dir->watches, watch); + + trace_qemu_file_monitor_add_watch(mon, dirpath, + filename ? filename : "", + cb, opaque, watch.id); + + ret =3D watch.id; + + cleanup: + qemu_mutex_unlock(&mon->lock); + return ret; +} + + +void qemu_file_monitor_remove_watch(QFileMonitor *mon, + const char *dirpath, + int id) +{ + QFileMonitorDir *dir; + gsize i; + + qemu_mutex_lock(&mon->lock); + + trace_qemu_file_monitor_remove_watch(mon, dirpath, id); + + dir =3D g_hash_table_lookup(mon->dirs, dirpath); + if (!dir) { + goto cleanup; + } + + for (i =3D 0; i < dir->watches->len; i++) { + QFileMonitorWatch *watch =3D &g_array_index(dir->watches, + QFileMonitorWatch, i); + if (watch->id =3D=3D id) { + g_free(watch->filename); + g_array_remove_index(dir->watches, i); + break; + } + } + + if (dir->watches->len =3D=3D 0) { + inotify_rm_watch(mon->fd, dir->id); + trace_qemu_file_monitor_disable_watch(mon, dir->path, dir->id); + + g_hash_table_remove(mon->idmap, GINT_TO_POINTER(dir->id)); + g_hash_table_remove(mon->dirs, dir->path); + + if (g_hash_table_size(mon->dirs) =3D=3D 0) { + qemu_set_fd_handler(mon->fd, NULL, NULL, NULL); + } + } + + cleanup: + qemu_mutex_unlock(&mon->lock); +} diff --git a/util/filemonitor-stub.c b/util/filemonitor-stub.c new file mode 100644 index 0000000000..48268b2bb6 --- /dev/null +++ b/util/filemonitor-stub.c @@ -0,0 +1,59 @@ +/* + * QEMU file monitor stub impl + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#include "qemu/osdep.h" +#include "qemu/filemonitor.h" +#include "qemu/error-report.h" +#include "qapi/error.h" + + +QFileMonitor * +qemu_file_monitor_new(Error **errp) +{ + error_setg(errp, "File monitoring not available on this platform"); + return NULL; +} + + +void +qemu_file_monitor_free(QFileMonitor *mon G_GNUC_UNUSED) +{ +} + + +int +qemu_file_monitor_add_watch(QFileMonitor *mon G_GNUC_UNUSED, + const char *dirpath G_GNUC_UNUSED, + const char *filename G_GNUC_UNUSED, + QFileMonitorHandler cb G_GNUC_UNUSED, + void *opaque G_GNUC_UNUSED, + Error **errp) +{ + error_setg(errp, "File monitoring not available on this platform"); + return -1; +} + + +void +qemu_file_monitor_remove_watch(QFileMonitor *mon G_GNUC_UNUSED, + const char *dirpath G_GNUC_UNUSED, + int id G_GNUC_UNUSED) +{ +} diff --git a/util/trace-events b/util/trace-events index 79569b7fdf..ff19b253e2 100644 --- a/util/trace-events +++ b/util/trace-events @@ -21,6 +21,15 @@ buffer_move_empty(const char *buf, size_t len, const cha= r *from) "%s: %zd bytes buffer_move(const char *buf, size_t len, const char *from) "%s: %zd bytes = from %s" buffer_free(const char *buf, size_t len) "%s: capacity %zd" =20 +# util/filemonitor.c +qemu_file_monitor_add_watch(void *mon, const char *dirpath, const char *fi= lename, void *cb, void *opaque, int id) "File monitor %p add watch dir=3D'%= s' file=3D'%s' cb=3D%p opaque=3D%p id=3D%u" +qemu_file_monitor_remove_watch(void *mon, const char *dirpath, int id) "Fi= le monitor %p remove watch dir=3D'%s' id=3D%u" +qemu_file_monitor_new(void *mon, int fd) "File monitor %p created fd=3D%d" +qemu_file_monitor_enable_watch(void *mon, const char *dirpath, int id) "Fi= le monitor %p enable watch dir=3D'%s' id=3D%u" +qemu_file_monitor_disable_watch(void *mon, const char *dirpath, int id) "F= le monitor %p disable watch dir=3D'%s' id=3D%u" +qemu_file_monitor_event(void *mon, const char *dirpath, const char *filena= me, int mask, unsigned int id) "File monitor %p event dir=3D'%s' file=3D'%s= ' mask=3D0x%x id=3D%u" +qemu_file_monitor_dispatch(void *mon, const char *dirpath, const char *fil= ename, int ev, void *cb, void *opaque, unsigned int id) "File monitor %p di= spatch dir=3D'%s' file=3D'%s' ev=3D%d cb=3D%p opaque=3D%p id=3D%u" + # util/qemu-coroutine.c qemu_aio_coroutine_enter(void *ctx, void *from, void *to, void *opaque) "c= tx %p from %p to %p opaque %p" qemu_coroutine_yield(void *from, void *to) "from %p to %p" --=20 2.20.1 From nobody Sun May 5 13:38:15 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Authentication-Results: mx.zohomail.com; spf=pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1550246471224321.573371341355; Fri, 15 Feb 2019 08:01:11 -0800 (PST) Received: from localhost ([127.0.0.1]:42036 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufvK-0007SY-5X for importer@patchew.org; Fri, 15 Feb 2019 11:01:10 -0500 Received: from eggs.gnu.org ([209.51.188.92]:46851) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufsF-000540-TF for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:02 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1gufsE-0002vU-CK for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:57:59 -0500 Received: from mx1.redhat.com ([209.132.183.28]:55912) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1gufsE-0002VV-2L for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:57:58 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id F21097AEAF; Fri, 15 Feb 2019 15:57:28 +0000 (UTC) Received: from localhost.localdomain.com (ovpn-112-65.ams2.redhat.com [10.36.112.65]) by smtp.corp.redhat.com (Postfix) with ESMTP id 49316101E848; Fri, 15 Feb 2019 15:57:26 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Date: Fri, 15 Feb 2019 15:57:00 +0000 Message-Id: <20190215155709.15777-3-berrange@redhat.com> In-Reply-To: <20190215155709.15777-1-berrange@redhat.com> References: <20190215155709.15777-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.84 on 10.5.11.22 X-Greylist: Sender IP whitelisted, not delayed by milter-greylist-4.5.16 (mx1.redhat.com [10.5.110.25]); Fri, 15 Feb 2019 15:57:29 +0000 (UTC) Content-Transfer-Encoding: quoted-printable X-detected-operating-system: by eggs.gnu.org: GNU/Linux 2.2.x-3.x [generic] X-Received-From: 209.132.183.28 Subject: [Qemu-devel] [PATCH v8 02/11] qom: don't require user creatable objects to be registered X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Markus Armbruster , "Dr. David Alan Gilbert" , Gerd Hoffmann , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , =?UTF-8?q?Andreas=20F=C3=A4rber?= Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Content-Type: text/plain; charset="utf-8" When an object is in turn owned by another user object, it is not desirable to expose this in the QOM object hierarchy. It is just an internal implementation detail, we should be free to change without exposure to apps managing QEMU. Reviewed-by: Marc-Andr=C3=A9 Lureau Reviewed-by: Philippe Mathieu-Daud=C3=A9 Tested-by: Philippe Mathieu-Daud=C3=A9 Signed-off-by: Daniel P. Berrang=C3=A9 --- qom/object.c | 12 ++++++++---- qom/object_interfaces.c | 16 ++++++++++------ 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/qom/object.c b/qom/object.c index b8c732063b..05a8567041 100644 --- a/qom/object.c +++ b/qom/object.c @@ -646,16 +646,20 @@ Object *object_new_with_propv(const char *typename, goto error; } =20 - object_property_add_child(parent, id, obj, &local_err); - if (local_err) { - goto error; + if (id !=3D NULL) { + object_property_add_child(parent, id, obj, &local_err); + if (local_err) { + goto error; + } } =20 uc =3D (UserCreatable *)object_dynamic_cast(obj, TYPE_USER_CREATABLE); if (uc) { user_creatable_complete(uc, &local_err); if (local_err) { - object_unparent(obj); + if (id !=3D NULL) { + object_unparent(obj); + } goto error; } } diff --git a/qom/object_interfaces.c b/qom/object_interfaces.c index db85d1eb75..cb5809934a 100644 --- a/qom/object_interfaces.c +++ b/qom/object_interfaces.c @@ -75,16 +75,20 @@ Object *user_creatable_add_type(const char *type, const= char *id, goto out; } =20 - object_property_add_child(object_get_objects_root(), - id, obj, &local_err); - if (local_err) { - goto out; + if (id !=3D NULL) { + object_property_add_child(object_get_objects_root(), + id, obj, &local_err); + if (local_err) { + goto out; + } } =20 user_creatable_complete(USER_CREATABLE(obj), &local_err); if (local_err) { - object_property_del(object_get_objects_root(), - id, &error_abort); + if (id !=3D NULL) { + object_property_del(object_get_objects_root(), + id, &error_abort); + } goto out; } out: --=20 2.20.1 From nobody Sun May 5 13:38:15 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Authentication-Results: mx.zohomail.com; spf=pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1550246760128358.8234347175379; Fri, 15 Feb 2019 08:06:00 -0800 (PST) Received: from localhost ([127.0.0.1]:42089 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufzx-0002cg-4g for importer@patchew.org; Fri, 15 Feb 2019 11:05:57 -0500 Received: from eggs.gnu.org ([209.51.188.92]:46811) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufsF-00051r-2t for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:00 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1gufsE-0002vH-6h for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:57:58 -0500 Received: from mx1.redhat.com ([209.132.183.28]:50648) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1gufsE-0002Zg-0E for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:57:58 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id 4BF7F53409; Fri, 15 Feb 2019 15:57:32 +0000 (UTC) Received: from localhost.localdomain.com (ovpn-112-65.ams2.redhat.com [10.36.112.65]) by smtp.corp.redhat.com (Postfix) with ESMTP id 4EA1010018FB; Fri, 15 Feb 2019 15:57:29 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Date: Fri, 15 Feb 2019 15:57:01 +0000 Message-Id: <20190215155709.15777-4-berrange@redhat.com> In-Reply-To: <20190215155709.15777-1-berrange@redhat.com> References: <20190215155709.15777-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.84 on 10.5.11.22 X-Greylist: Sender IP whitelisted, not delayed by milter-greylist-4.5.16 (mx1.redhat.com [10.5.110.27]); Fri, 15 Feb 2019 15:57:32 +0000 (UTC) Content-Transfer-Encoding: quoted-printable X-detected-operating-system: by eggs.gnu.org: GNU/Linux 2.2.x-3.x [generic] X-Received-From: 209.132.183.28 Subject: [Qemu-devel] [PATCH v8 03/11] hw/usb: don't set IN_ISDIR for inotify watch in MTP driver X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Markus Armbruster , "Dr. David Alan Gilbert" , Gerd Hoffmann , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , =?UTF-8?q?Andreas=20F=C3=A4rber?= Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Content-Type: text/plain; charset="utf-8" IN_ISDIR is not a bit that one can request when registering a watch with inotify_add_watch. Rather it is a bit that is set automatically when reading events from the kernel. Reviewed-by: Marc-Andr=C3=A9 Lureau Reviewed-by: Philippe Mathieu-Daud=C3=A9 Signed-off-by: Daniel P. Berrang=C3=A9 --- hw/usb/dev-mtp.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/hw/usb/dev-mtp.c b/hw/usb/dev-mtp.c index f1d20fa1b9..f0c52a476a 100644 --- a/hw/usb/dev-mtp.c +++ b/hw/usb/dev-mtp.c @@ -653,8 +653,7 @@ static void usb_mtp_inotify_cleanup(MTPState *s) =20 static int usb_mtp_add_watch(int inotifyfd, char *path) { - uint32_t mask =3D IN_CREATE | IN_DELETE | IN_MODIFY | - IN_ISDIR; + uint32_t mask =3D IN_CREATE | IN_DELETE | IN_MODIFY; =20 return inotify_add_watch(inotifyfd, path, mask); } --=20 2.20.1 From nobody Sun May 5 13:38:15 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Authentication-Results: mx.zohomail.com; spf=pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1550246568848594.2073712098887; Fri, 15 Feb 2019 08:02:48 -0800 (PST) Received: from localhost ([127.0.0.1]:42054 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufwr-0000EM-RN for importer@patchew.org; Fri, 15 Feb 2019 11:02:45 -0500 Received: from eggs.gnu.org ([209.51.188.92]:46762) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufsC-00050i-0p for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:57:58 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1gufs9-0002rm-Ve for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:57:55 -0500 Received: from mx1.redhat.com ([209.132.183.28]:45174) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1gufs8-0002mB-4s for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:57:53 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id 9FB8F2FE552; Fri, 15 Feb 2019 15:57:46 +0000 (UTC) Received: from localhost.localdomain.com (ovpn-112-65.ams2.redhat.com [10.36.112.65]) by smtp.corp.redhat.com (Postfix) with ESMTP id B3DF610018FB; Fri, 15 Feb 2019 15:57:32 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Date: Fri, 15 Feb 2019 15:57:02 +0000 Message-Id: <20190215155709.15777-5-berrange@redhat.com> In-Reply-To: <20190215155709.15777-1-berrange@redhat.com> References: <20190215155709.15777-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.84 on 10.5.11.22 X-Greylist: Sender IP whitelisted, not delayed by milter-greylist-4.5.16 (mx1.redhat.com [10.5.110.29]); Fri, 15 Feb 2019 15:57:46 +0000 (UTC) Content-Transfer-Encoding: quoted-printable X-detected-operating-system: by eggs.gnu.org: GNU/Linux 2.2.x-3.x [generic] X-Received-From: 209.132.183.28 Subject: [Qemu-devel] [PATCH v8 04/11] hw/usb: fix const-ness for string params in MTP driver X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Markus Armbruster , "Dr. David Alan Gilbert" , Gerd Hoffmann , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , =?UTF-8?q?Andreas=20F=C3=A4rber?= Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Content-Type: text/plain; charset="utf-8" Various functions accepting 'char *' string parameters were missing 'const' qualifiers. Reviewed-by: Marc-Andr=C3=A9 Lureau Reviewed-by: Philippe Mathieu-Daud=C3=A9 Signed-off-by: Daniel P. Berrang=C3=A9 --- hw/usb/dev-mtp.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/hw/usb/dev-mtp.c b/hw/usb/dev-mtp.c index f0c52a476a..169ee50c02 100644 --- a/hw/usb/dev-mtp.c +++ b/hw/usb/dev-mtp.c @@ -383,7 +383,7 @@ static const USBDesc desc =3D { /* -----------------------------------------------------------------------= */ =20 static MTPObject *usb_mtp_object_alloc(MTPState *s, uint32_t handle, - MTPObject *parent, char *name) + MTPObject *parent, const char *name) { MTPObject *o =3D g_new0(MTPObject, 1); =20 @@ -465,7 +465,7 @@ static MTPObject *usb_mtp_object_lookup(MTPState *s, ui= nt32_t handle) } =20 static MTPObject *usb_mtp_add_child(MTPState *s, MTPObject *o, - char *name) + const char *name) { MTPObject *child =3D usb_mtp_object_alloc(s, s->next_handle++, o, name); @@ -484,7 +484,7 @@ static MTPObject *usb_mtp_add_child(MTPState *s, MTPObj= ect *o, } =20 static MTPObject *usb_mtp_object_lookup_name(MTPObject *parent, - char *name, int len) + const char *name, int len) { MTPObject *iter; =20 @@ -651,7 +651,7 @@ static void usb_mtp_inotify_cleanup(MTPState *s) } } =20 -static int usb_mtp_add_watch(int inotifyfd, char *path) +static int usb_mtp_add_watch(int inotifyfd, const char *path) { uint32_t mask =3D IN_CREATE | IN_DELETE | IN_MODIFY; =20 --=20 2.20.1 From nobody Sun May 5 13:38:15 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Authentication-Results: mx.zohomail.com; spf=pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1550246402373944.9976021854211; Fri, 15 Feb 2019 08:00:02 -0800 (PST) Received: from localhost ([127.0.0.1]:41997 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufuB-0006OF-7y for importer@patchew.org; Fri, 15 Feb 2019 10:59:59 -0500 Received: from eggs.gnu.org ([209.51.188.92]:46854) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufsF-00054C-Ts for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:03 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1gufsD-0002uR-Ns for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:57:59 -0500 Received: from mx1.redhat.com ([209.132.183.28]:52868) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1gufsB-0002nj-O6 for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:57:56 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id 7AF2E127941; Fri, 15 Feb 2019 15:57:50 +0000 (UTC) Received: from localhost.localdomain.com (ovpn-112-65.ams2.redhat.com [10.36.112.65]) by smtp.corp.redhat.com (Postfix) with ESMTP id EFDDB10018FB; Fri, 15 Feb 2019 15:57:46 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Date: Fri, 15 Feb 2019 15:57:03 +0000 Message-Id: <20190215155709.15777-6-berrange@redhat.com> In-Reply-To: <20190215155709.15777-1-berrange@redhat.com> References: <20190215155709.15777-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.84 on 10.5.11.22 X-Greylist: Sender IP whitelisted, not delayed by milter-greylist-4.5.16 (mx1.redhat.com [10.5.110.39]); Fri, 15 Feb 2019 15:57:50 +0000 (UTC) Content-Transfer-Encoding: quoted-printable X-detected-operating-system: by eggs.gnu.org: GNU/Linux 2.2.x-3.x [generic] X-Received-From: 209.132.183.28 Subject: [Qemu-devel] [PATCH v8 05/11] hw/usb: switch MTP to use new inotify APIs X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Markus Armbruster , "Dr. David Alan Gilbert" , Gerd Hoffmann , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , =?UTF-8?q?Andreas=20F=C3=A4rber?= Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Content-Type: text/plain; charset="utf-8" The internal inotify APIs allow a lot of conditional statements to be cleared out, and provide a simpler callback for handling events. Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Marc-Andr=C3=A9 Lureau --- hw/usb/dev-mtp.c | 274 ++++++++++++++++++-------------------------- hw/usb/trace-events | 2 +- 2 files changed, 111 insertions(+), 165 deletions(-) diff --git a/hw/usb/dev-mtp.c b/hw/usb/dev-mtp.c index 169ee50c02..4ee4fc5a89 100644 --- a/hw/usb/dev-mtp.c +++ b/hw/usb/dev-mtp.c @@ -11,17 +11,16 @@ =20 #include "qemu/osdep.h" #include "qapi/error.h" +#include "qemu/error-report.h" #include #include =20 #include -#ifdef CONFIG_INOTIFY1 -#include -#include "qemu/main-loop.h" -#endif + =20 #include "qemu-common.h" #include "qemu/iov.h" +#include "qemu/filemonitor.h" #include "trace.h" #include "hw/usb.h" #include "desc.h" @@ -132,7 +131,6 @@ enum { EP_EVENT, }; =20 -#ifdef CONFIG_INOTIFY1 typedef struct MTPMonEntry MTPMonEntry; =20 struct MTPMonEntry { @@ -141,7 +139,6 @@ struct MTPMonEntry { =20 QTAILQ_ENTRY(MTPMonEntry) next; }; -#endif =20 struct MTPControl { uint16_t code; @@ -172,10 +169,8 @@ struct MTPObject { char *name; char *path; struct stat stat; -#ifdef CONFIG_INOTIFY1 - /* inotify watch cookie */ - int watchfd; -#endif + /* file monitor watch id */ + int watchid; MTPObject *parent; uint32_t nchildren; QLIST_HEAD(, MTPObject) children; @@ -198,11 +193,8 @@ struct MTPState { bool readonly; =20 QTAILQ_HEAD(, MTPObject) objects; -#ifdef CONFIG_INOTIFY1 - /* inotify descriptor */ - int inotifyfd; + QFileMonitor *file_monitor; QTAILQ_HEAD(, MTPMonEntry) events; -#endif /* Responder is expecting a write operation */ bool write_pending; struct { @@ -391,6 +383,7 @@ static MTPObject *usb_mtp_object_alloc(MTPState *s, uin= t32_t handle, goto ignore; } =20 + o->watchid =3D -1; o->handle =3D handle; o->parent =3D parent; o->name =3D g_strdup(name); @@ -437,6 +430,10 @@ static void usb_mtp_object_free(MTPState *s, MTPObject= *o) =20 trace_usb_mtp_object_free(s->dev.addr, o->handle, o->path); =20 + if (o->watchid !=3D -1 && s->file_monitor) { + qemu_file_monitor_remove_watch(s->file_monitor, o->path, o->watchi= d); + } + QTAILQ_REMOVE(&s->objects, o, next); if (o->parent) { QLIST_REMOVE(o, list); @@ -488,6 +485,10 @@ static MTPObject *usb_mtp_object_lookup_name(MTPObject= *parent, { MTPObject *iter; =20 + if (len =3D=3D -1) { + len =3D strlen(name); + } + QLIST_FOREACH(iter, &parent->children, list) { if (strncmp(iter->name, name, len) =3D=3D 0) { return iter; @@ -497,13 +498,12 @@ static MTPObject *usb_mtp_object_lookup_name(MTPObjec= t *parent, return NULL; } =20 -#ifdef CONFIG_INOTIFY1 -static MTPObject *usb_mtp_object_lookup_wd(MTPState *s, int wd) +static MTPObject *usb_mtp_object_lookup_id(MTPState *s, int id) { MTPObject *iter; =20 QTAILQ_FOREACH(iter, &s->objects, next) { - if (iter->watchfd =3D=3D wd) { + if (iter->watchid =3D=3D id) { return iter; } } @@ -511,159 +511,103 @@ static MTPObject *usb_mtp_object_lookup_wd(MTPState= *s, int wd) return NULL; } =20 -static void inotify_watchfn(void *arg) +static void file_monitor_event(int id, + QFileMonitorEvent ev, + const char *name, + void *opaque) { - MTPState *s =3D arg; - ssize_t bytes; - /* From the man page: atleast one event can be read */ - int pos; - char buf[sizeof(struct inotify_event) + NAME_MAX + 1]; - - for (;;) { - bytes =3D read(s->inotifyfd, buf, sizeof(buf)); - pos =3D 0; - - if (bytes <=3D 0) { - /* Better luck next time */ + MTPState *s =3D opaque; + MTPObject *parent =3D usb_mtp_object_lookup_id(s, id); + MTPMonEntry *entry =3D NULL; + MTPObject *o; + + if (!parent) { + return; + } + + switch (ev) { + case QFILE_MONITOR_EVENT_CREATED: + if (usb_mtp_object_lookup_name(parent, name, -1)) { + /* Duplicate create event */ return; } + entry =3D g_new0(MTPMonEntry, 1); + entry->handle =3D s->next_handle; + entry->event =3D EVT_OBJ_ADDED; + o =3D usb_mtp_add_child(s, parent, name); + if (!o) { + g_free(entry); + return; + } + trace_usb_mtp_file_monitor_event(s->dev.addr, name, "Obj Added"); + break; =20 + case QFILE_MONITOR_EVENT_DELETED: /* - * TODO: Ignore initiator initiated events. - * For now we are good because the store is RO + * The kernel issues a IN_IGNORED event + * when a dir containing a watchpoint is + * deleted, so we don't have to delete the + * watchpoint */ - while (bytes > 0) { - char *p =3D buf + pos; - struct inotify_event *event =3D (struct inotify_event *)p; - int watchfd =3D 0; - uint32_t mask =3D event->mask & (IN_CREATE | IN_DELETE | - IN_MODIFY | IN_IGNORED); - MTPObject *parent =3D usb_mtp_object_lookup_wd(s, event->wd); - MTPMonEntry *entry =3D NULL; - MTPObject *o; - - pos =3D pos + sizeof(struct inotify_event) + event->len; - bytes =3D bytes - pos; - - if (!parent) { - continue; - } - - switch (mask) { - case IN_CREATE: - if (usb_mtp_object_lookup_name - (parent, event->name, event->len)) { - /* Duplicate create event */ - continue; - } - entry =3D g_new0(MTPMonEntry, 1); - entry->handle =3D s->next_handle; - entry->event =3D EVT_OBJ_ADDED; - o =3D usb_mtp_add_child(s, parent, event->name); - if (!o) { - g_free(entry); - continue; - } - o->watchfd =3D watchfd; - trace_usb_mtp_inotify_event(s->dev.addr, event->name, - event->mask, "Obj Added"); - break; - - case IN_DELETE: - /* - * The kernel issues a IN_IGNORED event - * when a dir containing a watchpoint is - * deleted, so we don't have to delete the - * watchpoint - */ - o =3D usb_mtp_object_lookup_name(parent, event->name, even= t->len); - if (!o) { - continue; - } - entry =3D g_new0(MTPMonEntry, 1); - entry->handle =3D o->handle; - entry->event =3D EVT_OBJ_REMOVED; - trace_usb_mtp_inotify_event(s->dev.addr, o->path, - event->mask, "Obj Deleted"); - usb_mtp_object_free(s, o); - break; - - case IN_MODIFY: - o =3D usb_mtp_object_lookup_name(parent, event->name, even= t->len); - if (!o) { - continue; - } - entry =3D g_new0(MTPMonEntry, 1); - entry->handle =3D o->handle; - entry->event =3D EVT_OBJ_INFO_CHANGED; - trace_usb_mtp_inotify_event(s->dev.addr, o->path, - event->mask, "Obj Modified"); - break; - - case IN_IGNORED: - trace_usb_mtp_inotify_event(s->dev.addr, parent->path, - event->mask, "Obj parent dir ignored= "); - break; - - default: - fprintf(stderr, "usb-mtp: failed to parse inotify event\n"= ); - continue; - } - - if (entry) { - QTAILQ_INSERT_HEAD(&s->events, entry, next); - } + o =3D usb_mtp_object_lookup_name(parent, name, -1); + if (!o) { + return; } - } -} + entry =3D g_new0(MTPMonEntry, 1); + entry->handle =3D o->handle; + entry->event =3D EVT_OBJ_REMOVED; + trace_usb_mtp_file_monitor_event(s->dev.addr, o->path, "Obj Delete= d"); + usb_mtp_object_free(s, o); + break; =20 -static int usb_mtp_inotify_init(MTPState *s) -{ - int fd; + case QFILE_MONITOR_EVENT_MODIFIED: + o =3D usb_mtp_object_lookup_name(parent, name, -1); + if (!o) { + return; + } + entry =3D g_new0(MTPMonEntry, 1); + entry->handle =3D o->handle; + entry->event =3D EVT_OBJ_INFO_CHANGED; + trace_usb_mtp_file_monitor_event(s->dev.addr, o->path, "Obj Modifi= ed"); + break; =20 - fd =3D inotify_init1(IN_NONBLOCK); - if (fd =3D=3D -1) { - return 1; - } + case QFILE_MONITOR_EVENT_IGNORED: + trace_usb_mtp_file_monitor_event(s->dev.addr, parent->path, + "Obj parent dir ignored"); + break; =20 - QTAILQ_INIT(&s->events); - s->inotifyfd =3D fd; + case QFILE_MONITOR_EVENT_ATTRIBUTES: + break; =20 - qemu_set_fd_handler(fd, inotify_watchfn, NULL, s); + default: + g_assert_not_reached(); + } =20 - return 0; + if (entry) { + QTAILQ_INSERT_HEAD(&s->events, entry, next); + } } =20 -static void usb_mtp_inotify_cleanup(MTPState *s) +static void usb_mtp_file_monitor_cleanup(MTPState *s) { MTPMonEntry *e, *p; =20 - if (!s->inotifyfd) { - return; - } - - qemu_set_fd_handler(s->inotifyfd, NULL, NULL, s); - close(s->inotifyfd); - QTAILQ_FOREACH_SAFE(e, &s->events, next, p) { QTAILQ_REMOVE(&s->events, e, next); g_free(e); } -} =20 -static int usb_mtp_add_watch(int inotifyfd, const char *path) -{ - uint32_t mask =3D IN_CREATE | IN_DELETE | IN_MODIFY; - - return inotify_add_watch(inotifyfd, path, mask); + qemu_file_monitor_free(s->file_monitor); + s->file_monitor =3D NULL; } -#endif + =20 static void usb_mtp_object_readdir(MTPState *s, MTPObject *o) { struct dirent *entry; DIR *dir; int fd; + Error *err =3D NULL; =20 if (o->have_children) { return; @@ -679,16 +623,21 @@ static void usb_mtp_object_readdir(MTPState *s, MTPOb= ject *o) close(fd); return; } -#ifdef CONFIG_INOTIFY1 - int watchfd =3D usb_mtp_add_watch(s->inotifyfd, o->path); - if (watchfd =3D=3D -1) { - fprintf(stderr, "usb-mtp: failed to add watch for %s\n", o->path); - } else { - trace_usb_mtp_inotify_event(s->dev.addr, o->path, - 0, "Watch Added"); - o->watchfd =3D watchfd; + + if (s->file_monitor) { + int id =3D qemu_file_monitor_add_watch(s->file_monitor, o->path, N= ULL, + file_monitor_event, s, &err); + if (id =3D=3D -1) { + error_report("usb-mtp: failed to add watch for %s: %s", o->pat= h, + error_get_pretty(err)); + error_free(err); + } else { + trace_usb_mtp_file_monitor_event(s->dev.addr, o->path, + "Watch Added"); + o->watchid =3D id; + } } -#endif + while ((entry =3D readdir(dir)) !=3D NULL) { usb_mtp_add_child(s, o, entry->d_name); } @@ -1196,13 +1145,11 @@ enum { /* Assumes that children, if any, have been already freed */ static void usb_mtp_object_free_one(MTPState *s, MTPObject *o) { -#ifndef CONFIG_INOTIFY1 assert(o->nchildren =3D=3D 0); QTAILQ_REMOVE(&s->objects, o, next); g_free(o->name); g_free(o->path); g_free(o); -#endif } =20 static int usb_mtp_deletefn(MTPState *s, MTPObject *o, uint32_t trans) @@ -1301,6 +1248,7 @@ static void usb_mtp_command(MTPState *s, MTPControl *= c) MTPData *data_in =3D NULL; MTPObject *o =3D NULL; uint32_t nres =3D 0, res0 =3D 0; + Error *err =3D NULL; =20 /* sanity checks */ if (c->code >=3D CMD_CLOSE_SESSION && s->session =3D=3D 0) { @@ -1328,19 +1276,21 @@ static void usb_mtp_command(MTPState *s, MTPControl= *c) trace_usb_mtp_op_open_session(s->dev.addr); s->session =3D c->argv[0]; usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root); -#ifdef CONFIG_INOTIFY1 - if (usb_mtp_inotify_init(s)) { - fprintf(stderr, "usb-mtp: file monitoring init failed\n"); + + s->file_monitor =3D qemu_file_monitor_new(&err); + if (err) { + error_report("usb-mtp: file monitoring init failed: %s", + error_get_pretty(err)); + error_free(err); + } else { + QTAILQ_INIT(&s->events); } -#endif break; case CMD_CLOSE_SESSION: trace_usb_mtp_op_close_session(s->dev.addr); s->session =3D 0; s->next_handle =3D 0; -#ifdef CONFIG_INOTIFY1 - usb_mtp_inotify_cleanup(s); -#endif + usb_mtp_file_monitor_cleanup(s); usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects)); assert(QTAILQ_EMPTY(&s->objects)); break; @@ -1553,9 +1503,7 @@ static void usb_mtp_handle_reset(USBDevice *dev) =20 trace_usb_mtp_reset(s->dev.addr); =20 -#ifdef CONFIG_INOTIFY1 - usb_mtp_inotify_cleanup(s); -#endif + usb_mtp_file_monitor_cleanup(s); usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects)); s->session =3D 0; usb_mtp_data_free(s->data_in); @@ -2026,7 +1974,6 @@ static void usb_mtp_handle_data(USBDevice *dev, USBPa= cket *p) } break; case EP_EVENT: -#ifdef CONFIG_INOTIFY1 if (!QTAILQ_EMPTY(&s->events)) { struct MTPMonEntry *e =3D QTAILQ_LAST(&s->events); uint32_t handle; @@ -2050,7 +1997,6 @@ static void usb_mtp_handle_data(USBDevice *dev, USBPa= cket *p) g_free(e); return; } -#endif p->status =3D USB_RET_NAK; return; default: diff --git a/hw/usb/trace-events b/hw/usb/trace-events index 2c18770ca5..99b1e8b8ce 100644 --- a/hw/usb/trace-events +++ b/hw/usb/trace-events @@ -237,7 +237,7 @@ usb_mtp_op_unknown(int dev, uint32_t code) "dev %d, com= mand code 0x%x" usb_mtp_object_alloc(int dev, uint32_t handle, const char *path) "dev %d, = handle 0x%x, path %s" usb_mtp_object_free(int dev, uint32_t handle, const char *path) "dev %d, h= andle 0x%x, path %s" usb_mtp_add_child(int dev, uint32_t handle, const char *path) "dev %d, han= dle 0x%x, path %s" -usb_mtp_inotify_event(int dev, const char *path, uint32_t mask, const char= *s) "dev %d, path %s mask 0x%x event %s" +usb_mtp_file_monitor_event(int dev, const char *path, const char *s) "dev = %d, path %s event %s" =20 # hw/usb/host-libusb.c usb_host_open_started(int bus, int addr) "dev %d:%d" --=20 2.20.1 From nobody Sun May 5 13:38:15 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Authentication-Results: mx.zohomail.com; spf=pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1550246409051213.04489906013305; Fri, 15 Feb 2019 08:00:09 -0800 (PST) Received: from localhost ([127.0.0.1]:41999 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufuD-0006QU-T0 for importer@patchew.org; Fri, 15 Feb 2019 11:00:01 -0500 Received: from eggs.gnu.org ([209.51.188.92]:46929) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufsJ-00057B-JY for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:05 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1gufsG-00030s-Mg for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:03 -0500 Received: from mx1.redhat.com ([209.132.183.28]:49716) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1gufsG-0002yI-B2 for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:00 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id 69DC499D4D; Fri, 15 Feb 2019 15:57:59 +0000 (UTC) Received: from localhost.localdomain.com (ovpn-112-65.ams2.redhat.com [10.36.112.65]) by smtp.corp.redhat.com (Postfix) with ESMTP id CDA191024949; Fri, 15 Feb 2019 15:57:50 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Date: Fri, 15 Feb 2019 15:57:04 +0000 Message-Id: <20190215155709.15777-7-berrange@redhat.com> In-Reply-To: <20190215155709.15777-1-berrange@redhat.com> References: <20190215155709.15777-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.84 on 10.5.11.22 X-Greylist: Sender IP whitelisted, not delayed by milter-greylist-4.5.16 (mx1.redhat.com [10.5.110.38]); Fri, 15 Feb 2019 15:57:59 +0000 (UTC) Content-Transfer-Encoding: quoted-printable X-detected-operating-system: by eggs.gnu.org: GNU/Linux 2.2.x-3.x [generic] X-Received-From: 209.132.183.28 Subject: [Qemu-devel] [PATCH v8 06/11] authz: add QAuthZ object as an authorization base class X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Markus Armbruster , "Dr. David Alan Gilbert" , Gerd Hoffmann , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , =?UTF-8?q?Andreas=20F=C3=A4rber?= Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Content-Type: text/plain; charset="utf-8" From: "Daniel P. Berrange" The current qemu_acl module provides a simple access control list facility inside QEMU, which is used via a set of monitor commands acl_show, acl_policy, acl_add, acl_remove & acl_reset. Note there is no ability to create ACLs - the network services (eg VNC server) were expected to create ACLs that they want to check. There is also no way to define ACLs on the command line, nor potentially integrate with external authorization systems like polkit, pam, ldap lookup, etc. The QAuthZ object defines a minimal abstract QOM class that can be subclassed for creating different authorization providers. Reviewed-by: Marc-Andr=C3=A9 Lureau Reviewed-by: Philippe Mathieu-Daud=C3=A9 Tested-by: Philippe Mathieu-Daud=C3=A9 Signed-off-by: Daniel P. Berrange --- MAINTAINERS | 7 +++ Makefile | 10 ++-- Makefile.objs | 6 +++ Makefile.target | 2 + authz/Makefile.objs | 1 + authz/base.c | 82 +++++++++++++++++++++++++++++++ authz/trace-events | 4 ++ include/authz/base.h | 112 +++++++++++++++++++++++++++++++++++++++++++ 8 files changed, 220 insertions(+), 4 deletions(-) create mode 100644 authz/Makefile.objs create mode 100644 authz/base.c create mode 100644 authz/trace-events create mode 100644 include/authz/base.h diff --git a/MAINTAINERS b/MAINTAINERS index 5989796fa9..3941c1fbe4 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2072,6 +2072,13 @@ F: io/ F: include/io/ F: tests/test-io-* =20 +User authorization +M: Daniel P. Berrange +S: Maintained +F: authz/ +F: include/authz/ +F: tests/test-authz-* + Sockets M: Daniel P. Berrange M: Gerd Hoffmann diff --git a/Makefile b/Makefile index 3658310b95..564def78ee 100644 --- a/Makefile +++ b/Makefile @@ -359,6 +359,7 @@ endif =20 dummy :=3D $(call unnest-vars,, \ stub-obj-y \ + authz-obj-y \ chardev-obj-y \ util-obj-y \ qga-obj-y \ @@ -423,6 +424,7 @@ qemu-options.def: $(SRC_PATH)/qemu-options.hx $(SRC_PAT= H)/scripts/hxtool SUBDIR_RULES=3D$(patsubst %,subdir-%, $(TARGET_DIRS)) SOFTMMU_SUBDIR_RULES=3D$(filter %-softmmu,$(SUBDIR_RULES)) =20 +$(SOFTMMU_SUBDIR_RULES): $(authz-obj-y) $(SOFTMMU_SUBDIR_RULES): $(block-obj-y) $(SOFTMMU_SUBDIR_RULES): $(crypto-obj-y) $(SOFTMMU_SUBDIR_RULES): $(io-obj-y) @@ -485,9 +487,9 @@ COMMON_LDADDS =3D libqemuutil.a =20 qemu-img.o: qemu-img-cmds.h =20 -qemu-img$(EXESUF): qemu-img.o $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $= (qom-obj-y) $(COMMON_LDADDS) -qemu-nbd$(EXESUF): qemu-nbd.o $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $= (qom-obj-y) $(COMMON_LDADDS) -qemu-io$(EXESUF): qemu-io.o $(block-obj-y) $(crypto-obj-y) $(io-obj-y) $(q= om-obj-y) $(COMMON_LDADDS) +qemu-img$(EXESUF): qemu-img.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y= ) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS) +qemu-nbd$(EXESUF): qemu-nbd.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y= ) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS) +qemu-io$(EXESUF): qemu-io.o $(authz-obj-y) $(block-obj-y) $(crypto-obj-y) = $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS) =20 qemu-bridge-helper$(EXESUF): qemu-bridge-helper.o $(COMMON_LDADDS) =20 @@ -498,7 +500,7 @@ qemu-edid$(EXESUF): qemu-edid.o hw/display/edid-generat= e.o $(COMMON_LDADDS) fsdev/virtfs-proxy-helper$(EXESUF): fsdev/virtfs-proxy-helper.o fsdev/9p-m= arshal.o fsdev/9p-iov-marshal.o $(COMMON_LDADDS) fsdev/virtfs-proxy-helper$(EXESUF): LIBS +=3D -lcap =20 -scsi/qemu-pr-helper$(EXESUF): scsi/qemu-pr-helper.o scsi/utils.o $(crypto-= obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS) +scsi/qemu-pr-helper$(EXESUF): scsi/qemu-pr-helper.o scsi/utils.o $(authz-o= bj-y) $(crypto-obj-y) $(io-obj-y) $(qom-obj-y) $(COMMON_LDADDS) ifdef CONFIG_MPATH scsi/qemu-pr-helper$(EXESUF): LIBS +=3D -ludev -lmultipath -lmpathpersist endif diff --git a/Makefile.objs b/Makefile.objs index fee0ce9fc5..68910f8169 100644 --- a/Makefile.objs +++ b/Makefile.objs @@ -19,6 +19,11 @@ util-obj-y +=3D qapi/qapi-introspect.o chardev-obj-y =3D chardev/ slirp-obj-$(CONFIG_SLIRP) =3D slirp/ =20 +####################################################################### +# authz-obj-y is code used by both qemu system emulation and qemu-img + +authz-obj-y =3D authz/ + ####################################################################### # block-obj-y is code used by both qemu system emulation and qemu-img =20 @@ -140,6 +145,7 @@ trace-events-subdirs =3D trace-events-subdirs +=3D accel/kvm trace-events-subdirs +=3D accel/tcg trace-events-subdirs +=3D audio +trace-events-subdirs +=3D authz trace-events-subdirs +=3D block trace-events-subdirs +=3D chardev trace-events-subdirs +=3D crypto diff --git a/Makefile.target b/Makefile.target index 401dc1ea6f..076cb600bb 100644 --- a/Makefile.target +++ b/Makefile.target @@ -178,6 +178,7 @@ include $(SRC_PATH)/Makefile.objs dummy :=3D $(call unnest-vars,,target-obj-y) target-obj-y-save :=3D $(target-obj-y) dummy :=3D $(call unnest-vars,.., \ + authz-obj-y \ block-obj-y \ block-obj-m \ chardev-obj-y \ @@ -192,6 +193,7 @@ target-obj-y :=3D $(target-obj-y-save) all-obj-y +=3D $(common-obj-y) all-obj-y +=3D $(target-obj-y) all-obj-y +=3D $(qom-obj-y) +all-obj-$(CONFIG_SOFTMMU) +=3D $(authz-obj-y) all-obj-$(CONFIG_SOFTMMU) +=3D $(block-obj-y) $(chardev-obj-y) all-obj-$(CONFIG_USER_ONLY) +=3D $(crypto-aes-obj-y) all-obj-$(CONFIG_SOFTMMU) +=3D $(crypto-obj-y) diff --git a/authz/Makefile.objs b/authz/Makefile.objs new file mode 100644 index 0000000000..12597c9528 --- /dev/null +++ b/authz/Makefile.objs @@ -0,0 +1 @@ +authz-obj-y +=3D base.o diff --git a/authz/base.c b/authz/base.c new file mode 100644 index 0000000000..110dfa4195 --- /dev/null +++ b/authz/base.c @@ -0,0 +1,82 @@ +/* + * QEMU authorization framework base class + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#include "qemu/osdep.h" +#include "authz/base.h" +#include "authz/trace.h" + +bool qauthz_is_allowed(QAuthZ *authz, + const char *identity, + Error **errp) +{ + QAuthZClass *cls =3D QAUTHZ_GET_CLASS(authz); + bool allowed; + + allowed =3D cls->is_allowed(authz, identity, errp); + trace_qauthz_is_allowed(authz, identity, allowed); + + return allowed; +} + + +bool qauthz_is_allowed_by_id(const char *authzid, + const char *identity, + Error **errp) +{ + QAuthZ *authz; + Object *obj; + Object *container; + + container =3D object_get_objects_root(); + obj =3D object_resolve_path_component(container, + authzid); + if (!obj) { + error_setg(errp, "Cannot find QAuthZ object ID %s", + authzid); + return false; + } + + if (!object_dynamic_cast(obj, TYPE_QAUTHZ)) { + error_setg(errp, "Object '%s' is not a QAuthZ subclass", + authzid); + return false; + } + + authz =3D QAUTHZ(obj); + + return qauthz_is_allowed(authz, identity, errp); +} + + +static const TypeInfo authz_info =3D { + .parent =3D TYPE_OBJECT, + .name =3D TYPE_QAUTHZ, + .instance_size =3D sizeof(QAuthZ), + .class_size =3D sizeof(QAuthZClass), + .abstract =3D true, +}; + +static void qauthz_register_types(void) +{ + type_register_static(&authz_info); +} + +type_init(qauthz_register_types) + diff --git a/authz/trace-events b/authz/trace-events new file mode 100644 index 0000000000..481c90f511 --- /dev/null +++ b/authz/trace-events @@ -0,0 +1,4 @@ +# See docs/devel/tracing.txt for syntax documentation. + +# authz/base.c +qauthz_is_allowed(void *authz, const char *identity, bool allowed) "AuthZ = %p check identity=3D%s allowed=3D%d" diff --git a/include/authz/base.h b/include/authz/base.h new file mode 100644 index 0000000000..77dcd54c4c --- /dev/null +++ b/include/authz/base.h @@ -0,0 +1,112 @@ +/* + * QEMU authorization framework base class + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#ifndef QAUTHZ_BASE_H__ +#define QAUTHZ_BASE_H__ + +#include "qemu-common.h" +#include "qapi/error.h" +#include "qom/object.h" + + +#define TYPE_QAUTHZ "authz" + +#define QAUTHZ_CLASS(klass) \ + OBJECT_CLASS_CHECK(QAuthZClass, (klass), \ + TYPE_QAUTHZ) +#define QAUTHZ_GET_CLASS(obj) \ + OBJECT_GET_CLASS(QAuthZClass, (obj), \ + TYPE_QAUTHZ) +#define QAUTHZ(obj) \ + INTERFACE_CHECK(QAuthZ, (obj), \ + TYPE_QAUTHZ) + +typedef struct QAuthZ QAuthZ; +typedef struct QAuthZClass QAuthZClass; + +/** + * QAuthZ: + * + * The QAuthZ class defines an API contract to be used + * for providing an authorization driver for services + * with user identities. + */ + +struct QAuthZ { + Object parent_obj; +}; + + +struct QAuthZClass { + ObjectClass parent_class; + + bool (*is_allowed)(QAuthZ *authz, + const char *identity, + Error **errp); +}; + + +/** + * qauthz_is_allowed: + * @authz: the authorization object + * @identity: the user identity to authorize + * @errp: pointer to a NULL initialized error object + * + * Check if a user @identity is authorized. If an error + * occurs this method will return false to indicate + * denial, as well as setting @errp to contain the details. + * Callers are recommended to treat the denial and error + * scenarios identically. Specifically the error info in + * @errp should never be fed back to the user being + * authorized, it is merely for benefit of administrator + * debugging. + * + * Returns: true if @identity is authorized, false if denied or if + * an error occurred. + */ +bool qauthz_is_allowed(QAuthZ *authz, + const char *identity, + Error **errp); + + +/** + * qauthz_is_allowed_by_id: + * @authzid: ID of the authorization object + * @identity: the user identity to authorize + * @errp: pointer to a NULL initialized error object + * + * Check if a user @identity is authorized. If an error + * occurs this method will return false to indicate + * denial, as well as setting @errp to contain the details. + * Callers are recommended to treat the denial and error + * scenarios identically. Specifically the error info in + * @errp should never be fed back to the user being + * authorized, it is merely for benefit of administrator + * debugging. + * + * Returns: true if @identity is authorized, false if denied or if + * an error occurred. + */ +bool qauthz_is_allowed_by_id(const char *authzid, + const char *identity, + Error **errp); + +#endif /* QAUTHZ_BASE_H__ */ + --=20 2.20.1 From nobody Sun May 5 13:38:15 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Authentication-Results: mx.zohomail.com; spf=pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1550246583078354.1326365741952; Fri, 15 Feb 2019 08:03:03 -0800 (PST) Received: from localhost ([127.0.0.1]:42060 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufx7-0000Qv-VM for importer@patchew.org; Fri, 15 Feb 2019 11:03:02 -0500 Received: from eggs.gnu.org ([209.51.188.92]:46975) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufsR-0005EF-3m for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:12 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1gufsP-00039M-91 for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:11 -0500 Received: from mx1.redhat.com ([209.132.183.28]:50070) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1gufsP-00038n-0o for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:09 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id 52A20C03BD4B; Fri, 15 Feb 2019 15:58:08 +0000 (UTC) Received: from localhost.localdomain.com (ovpn-112-65.ams2.redhat.com [10.36.112.65]) by smtp.corp.redhat.com (Postfix) with ESMTP id BC9E310018FB; Fri, 15 Feb 2019 15:57:59 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Date: Fri, 15 Feb 2019 15:57:05 +0000 Message-Id: <20190215155709.15777-8-berrange@redhat.com> In-Reply-To: <20190215155709.15777-1-berrange@redhat.com> References: <20190215155709.15777-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.84 on 10.5.11.22 X-Greylist: Sender IP whitelisted, not delayed by milter-greylist-4.5.16 (mx1.redhat.com [10.5.110.31]); Fri, 15 Feb 2019 15:58:08 +0000 (UTC) Content-Transfer-Encoding: quoted-printable X-detected-operating-system: by eggs.gnu.org: GNU/Linux 2.2.x-3.x [generic] X-Received-From: 209.132.183.28 Subject: [Qemu-devel] [PATCH v8 07/11] authz: add QAuthZSimple object type for easy whitelist auth checks X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Markus Armbruster , "Dr. David Alan Gilbert" , Gerd Hoffmann , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , =?UTF-8?q?Andreas=20F=C3=A4rber?= Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Content-Type: text/plain; charset="utf-8" In many cases a single VM will just need to whilelist a single identity as the allowed user of network services. This is especially the case for TLS live migration (optionally with NBD storage) where we just need to whitelist the x509 certificate distinguished name of the source QEMU host. Via QMP this can be configured with: { "execute": "object-add", "arguments": { "qom-type": "authz-simple", "id": "authz0", "props": { "identity": "fred" } } } Or via the command line -object authz-simple,id=3Dauthz0,identity=3Dfred Reviewed-by: Philippe Mathieu-Daud=C3=A9 Tested-by: Philippe Mathieu-Daud=C3=A9 Signed-off-by: Daniel P. Berrange Reviewed-by: Marc-Andr=C3=A9 Lureau --- authz/Makefile.objs | 1 + authz/simple.c | 115 ++++++++++++++++++++++++++++++++++++++ authz/trace-events | 3 + include/authz/simple.h | 84 ++++++++++++++++++++++++++++ qemu-options.hx | 24 ++++++++ tests/Makefile.include | 3 + tests/test-authz-simple.c | 50 +++++++++++++++++ 7 files changed, 280 insertions(+) create mode 100644 authz/simple.c create mode 100644 include/authz/simple.h create mode 100644 tests/test-authz-simple.c diff --git a/authz/Makefile.objs b/authz/Makefile.objs index 12597c9528..2a75d53840 100644 --- a/authz/Makefile.objs +++ b/authz/Makefile.objs @@ -1 +1,2 @@ authz-obj-y +=3D base.o +authz-obj-y +=3D simple.o diff --git a/authz/simple.c b/authz/simple.c new file mode 100644 index 0000000000..8ab718803e --- /dev/null +++ b/authz/simple.c @@ -0,0 +1,115 @@ +/* + * QEMU simple authorization driver + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#include "qemu/osdep.h" +#include "authz/simple.h" +#include "authz/trace.h" +#include "qom/object_interfaces.h" + +static bool qauthz_simple_is_allowed(QAuthZ *authz, + const char *identity, + Error **errp) +{ + QAuthZSimple *sauthz =3D QAUTHZ_SIMPLE(authz); + + trace_qauthz_simple_is_allowed(authz, sauthz->identity, identity); + return g_str_equal(identity, sauthz->identity); +} + +static void +qauthz_simple_prop_set_identity(Object *obj, + const char *value, + Error **errp G_GNUC_UNUSED) +{ + QAuthZSimple *sauthz =3D QAUTHZ_SIMPLE(obj); + + g_free(sauthz->identity); + sauthz->identity =3D g_strdup(value); +} + + +static char * +qauthz_simple_prop_get_identity(Object *obj, + Error **errp G_GNUC_UNUSED) +{ + QAuthZSimple *sauthz =3D QAUTHZ_SIMPLE(obj); + + return g_strdup(sauthz->identity); +} + + +static void +qauthz_simple_finalize(Object *obj) +{ + QAuthZSimple *sauthz =3D QAUTHZ_SIMPLE(obj); + + g_free(sauthz->identity); +} + + +static void +qauthz_simple_class_init(ObjectClass *oc, void *data) +{ + QAuthZClass *authz =3D QAUTHZ_CLASS(oc); + + authz->is_allowed =3D qauthz_simple_is_allowed; + + object_class_property_add_str(oc, "identity", + qauthz_simple_prop_get_identity, + qauthz_simple_prop_set_identity, + NULL); +} + + +QAuthZSimple *qauthz_simple_new(const char *id, + const char *identity, + Error **errp) +{ + return QAUTHZ_SIMPLE( + object_new_with_props(TYPE_QAUTHZ_SIMPLE, + object_get_objects_root(), + id, errp, + "identity", identity, + NULL)); +} + + +static const TypeInfo qauthz_simple_info =3D { + .parent =3D TYPE_QAUTHZ, + .name =3D TYPE_QAUTHZ_SIMPLE, + .instance_size =3D sizeof(QAuthZSimple), + .instance_finalize =3D qauthz_simple_finalize, + .class_size =3D sizeof(QAuthZSimpleClass), + .class_init =3D qauthz_simple_class_init, + .interfaces =3D (InterfaceInfo[]) { + { TYPE_USER_CREATABLE }, + { } + } +}; + + +static void +qauthz_simple_register_types(void) +{ + type_register_static(&qauthz_simple_info); +} + + +type_init(qauthz_simple_register_types); diff --git a/authz/trace-events b/authz/trace-events index 481c90f511..1ef796c1e1 100644 --- a/authz/trace-events +++ b/authz/trace-events @@ -2,3 +2,6 @@ =20 # authz/base.c qauthz_is_allowed(void *authz, const char *identity, bool allowed) "AuthZ = %p check identity=3D%s allowed=3D%d" + +# auth/simple.c +qauthz_simple_is_allowed(void *authz, const char *wantidentity, const char= *gotidentity) "AuthZ simple %p check want identity=3D%s got identity=3D%s" diff --git a/include/authz/simple.h b/include/authz/simple.h new file mode 100644 index 0000000000..ef13958269 --- /dev/null +++ b/include/authz/simple.h @@ -0,0 +1,84 @@ +/* + * QEMU simple authorization driver + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#ifndef QAUTHZ_SIMPLE_H__ +#define QAUTHZ_SIMPLE_H__ + +#include "authz/base.h" + +#define TYPE_QAUTHZ_SIMPLE "authz-simple" + +#define QAUTHZ_SIMPLE_CLASS(klass) \ + OBJECT_CLASS_CHECK(QAuthZSimpleClass, (klass), \ + TYPE_QAUTHZ_SIMPLE) +#define QAUTHZ_SIMPLE_GET_CLASS(obj) \ + OBJECT_GET_CLASS(QAuthZSimpleClass, (obj), \ + TYPE_QAUTHZ_SIMPLE) +#define QAUTHZ_SIMPLE(obj) \ + INTERFACE_CHECK(QAuthZSimple, (obj), \ + TYPE_QAUTHZ_SIMPLE) + +typedef struct QAuthZSimple QAuthZSimple; +typedef struct QAuthZSimpleClass QAuthZSimpleClass; + + +/** + * QAuthZSimple: + * + * This authorization driver provides a simple mechanism + * for granting access based on an exact matched username. + * + * To create an instance of this class via QMP: + * + * { + * "execute": "object-add", + * "arguments": { + * "qom-type": "authz-simple", + * "id": "authz0", + * "props": { + * "identity": "fred" + * } + * } + * } + * + * Or via the command line + * + * -object authz-simple,id=3Dauthz0,identity=3Dfred + * + */ +struct QAuthZSimple { + QAuthZ parent_obj; + + char *identity; +}; + + +struct QAuthZSimpleClass { + QAuthZClass parent_class; +}; + + +QAuthZSimple *qauthz_simple_new(const char *id, + const char *identity, + Error **errp); + + +#endif /* QAUTHZ_SIMPLE_H__ */ + diff --git a/qemu-options.hx b/qemu-options.hx index 77bd98e20b..a948cacc07 100644 --- a/qemu-options.hx +++ b/qemu-options.hx @@ -4360,6 +4360,30 @@ e.g to launch a SEV guest ..... =20 @end example + + +@item -object authz-simple,id=3D@var{id},identity=3D@var{string} + +Create an authorization object that will control access to network service= s. + +The @option{identity} parameter is identifies the user and its format +depends on the network service that authorization object is associated +with. For authorizing based on TLS x509 certificates, the identity must +be the x509 distinguished name. Note that care must be taken to escape +any commas in the distinguished name. + +An example authorization object to validate a x509 distinguished name +would look like: +@example + # $QEMU \ + ... + -object 'authz-simple,id=3Dauth0,identity=3DCN=3Dlaptop.example.com,,= O=3DExample Org,,L=3DLondon,,ST=3DLondon,,C=3DGB' \ + ... +@end example + +Note the use of quotes due to the x509 distinguished name containing +whitespace, and escaping of ','. + @end table =20 ETEXI diff --git a/tests/Makefile.include b/tests/Makefile.include index 3a6a8d4b17..df1cd255a9 100644 --- a/tests/Makefile.include +++ b/tests/Makefile.include @@ -116,6 +116,7 @@ endif check-unit-y +=3D tests/test-timed-average$(EXESUF) check-unit-$(CONFIG_INOTIFY1) +=3D tests/test-util-filemonitor$(EXESUF) check-unit-y +=3D tests/test-util-sockets$(EXESUF) +check-unit-y +=3D tests/test-authz-simple$(EXESUF) check-unit-y +=3D tests/test-io-task$(EXESUF) check-unit-y +=3D tests/test-io-channel-socket$(EXESUF) check-unit-y +=3D tests/test-io-channel-file$(EXESUF) @@ -536,6 +537,7 @@ test-qapi-obj-y =3D tests/test-qapi-visit.o tests/test-= qapi-types.o \ benchmark-crypto-obj-y =3D $(crypto-obj-y) $(test-qom-obj-y) test-crypto-obj-y =3D $(crypto-obj-y) $(test-qom-obj-y) test-io-obj-y =3D $(io-obj-y) $(test-crypto-obj-y) +test-authz-obj-y =3D $(test-qom-obj-y) $(authz-obj-y) test-block-obj-y =3D $(block-obj-y) $(test-io-obj-y) tests/iothread.o =20 tests/check-qnum$(EXESUF): tests/check-qnum.o $(test-util-obj-y) @@ -662,6 +664,7 @@ tests/test-util-filemonitor$(EXESUF): tests/test-util-f= ilemonitor.o \ $(test-util-obj-y) tests/test-util-sockets$(EXESUF): tests/test-util-sockets.o \ tests/socket-helpers.o $(test-util-obj-y) +tests/test-authz-simple$(EXESUF): tests/test-authz-simple.o $(test-authz-o= bj-y) tests/test-io-task$(EXESUF): tests/test-io-task.o $(test-io-obj-y) tests/test-io-channel-socket$(EXESUF): tests/test-io-channel-socket.o \ tests/io-channel-helpers.o tests/socket-helpers.o $(test-io-obj-y) diff --git a/tests/test-authz-simple.c b/tests/test-authz-simple.c new file mode 100644 index 0000000000..2cf14fb87e --- /dev/null +++ b/tests/test-authz-simple.c @@ -0,0 +1,50 @@ +/* + * QEMU simple authorization object testing + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#include "qemu/osdep.h" +#include "qapi/error.h" + +#include "authz/simple.h" + + +static void test_authz_simple(void) +{ + QAuthZSimple *authz =3D qauthz_simple_new("authz0", + "cthulu", + &error_abort); + + g_assert(!qauthz_is_allowed(QAUTHZ(authz), "cthul", &error_abort)); + g_assert(qauthz_is_allowed(QAUTHZ(authz), "cthulu", &error_abort)); + g_assert(!qauthz_is_allowed(QAUTHZ(authz), "cthuluu", &error_abort)); + g_assert(!qauthz_is_allowed(QAUTHZ(authz), "fred", &error_abort)); + + object_unparent(OBJECT(authz)); +} + + +int main(int argc, char **argv) +{ + g_test_init(&argc, &argv, NULL); + module_call_init(MODULE_INIT_QOM); + + g_test_add_func("/authz/simple", test_authz_simple); + + return g_test_run(); +} --=20 2.20.1 From nobody Sun May 5 13:38:15 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Authentication-Results: mx.zohomail.com; spf=pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1550246589581477.9529080370713; Fri, 15 Feb 2019 08:03:09 -0800 (PST) Received: from localhost ([127.0.0.1]:42062 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufxE-0000VP-C3 for importer@patchew.org; Fri, 15 Feb 2019 11:03:08 -0500 Received: from eggs.gnu.org ([209.51.188.92]:46997) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufsV-0005I4-2W for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:17 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1gufsS-0003DW-Iv for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:15 -0500 Received: from mx1.redhat.com ([209.132.183.28]:56612) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1gufsS-0003Cj-9f for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:12 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id 8D1668E69A; Fri, 15 Feb 2019 15:58:11 +0000 (UTC) Received: from localhost.localdomain.com (ovpn-112-65.ams2.redhat.com [10.36.112.65]) by smtp.corp.redhat.com (Postfix) with ESMTP id AA1CA10018FB; Fri, 15 Feb 2019 15:58:08 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Date: Fri, 15 Feb 2019 15:57:06 +0000 Message-Id: <20190215155709.15777-9-berrange@redhat.com> In-Reply-To: <20190215155709.15777-1-berrange@redhat.com> References: <20190215155709.15777-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.84 on 10.5.11.22 X-Greylist: Sender IP whitelisted, not delayed by milter-greylist-4.5.16 (mx1.redhat.com [10.5.110.25]); Fri, 15 Feb 2019 15:58:11 +0000 (UTC) Content-Transfer-Encoding: quoted-printable X-detected-operating-system: by eggs.gnu.org: GNU/Linux 2.2.x-3.x [generic] X-Received-From: 209.132.183.28 Subject: [Qemu-devel] [PATCH v8 08/11] authz: add QAuthZList object type for an access control list X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Markus Armbruster , "Dr. David Alan Gilbert" , Gerd Hoffmann , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , =?UTF-8?q?Andreas=20F=C3=A4rber?= Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Content-Type: text/plain; charset="utf-8" From: "Daniel P. Berrange" Add a QAuthZList object type that implements the QAuthZ interface. This built-in implementation maintains a trivial access control list with a sequence of match rules and a final default policy. This replicates the functionality currently provided by the qemu_acl module. To create an instance of this object via the QMP monitor, the syntax used would be: { "execute": "object-add", "arguments": { "qom-type": "authz-list", "id": "authz0", "props": { "rules": [ { "match": "fred", "policy": "allow", "format": "exact" }, { "match": "bob", "policy": "allow", "format": "exact" }, { "match": "danb", "policy": "deny", "format": "glob" }, { "match": "dan*", "policy": "allow", "format": "exact" }, ], "policy": "deny" } } } This sets up an authorization rule that allows 'fred', 'bob' and anyone whose name starts with 'dan', except for 'danb'. Everyone unmatched is denied. It is not currently possible to create this via -object, since there is no syntax supported to specify non-scalar properties for objects. This is likely to be addressed by later support for using JSON with -object, or an equivalent approach. In any case the future "authz-listfile" object can be used from the CLI and is likely a better choice, as it allows the ACL to be refreshed automatically on change. Reviewed-by: Philippe Mathieu-Daud=C3=A9 Tested-by: Philippe Mathieu-Daud=C3=A9 Signed-off-by: Daniel P. Berrange Reviewed-by: Marc-Andr=C3=A9 Lureau --- MAINTAINERS | 1 + Makefile.objs | 2 +- authz/Makefile.objs | 1 + authz/list.c | 271 ++++++++++++++++++++++++++++++++++++++++ authz/trace-events | 4 + include/authz/list.h | 106 ++++++++++++++++ qapi/authz.json | 58 +++++++++ qapi/qapi-schema.json | 1 + tests/Makefile.include | 2 + tests/test-authz-list.c | 159 +++++++++++++++++++++++ 10 files changed, 604 insertions(+), 1 deletion(-) create mode 100644 authz/list.c create mode 100644 include/authz/list.h create mode 100644 qapi/authz.json create mode 100644 tests/test-authz-list.c diff --git a/MAINTAINERS b/MAINTAINERS index 3941c1fbe4..8525230a9c 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -2076,6 +2076,7 @@ User authorization M: Daniel P. Berrange S: Maintained F: authz/ +F: qapi/authz.json F: include/authz/ F: tests/test-authz-* =20 diff --git a/Makefile.objs b/Makefile.objs index 68910f8169..dda63341cd 100644 --- a/Makefile.objs +++ b/Makefile.objs @@ -1,6 +1,6 @@ QAPI_MODULES =3D block-core block char common crypto introspect job migrat= ion QAPI_MODULES +=3D misc net rdma rocker run-state sockets tpm trace transac= tion -QAPI_MODULES +=3D ui +QAPI_MODULES +=3D ui authz =20 ####################################################################### # Common libraries for tools and emulators diff --git a/authz/Makefile.objs b/authz/Makefile.objs index 2a75d53840..921fa624d7 100644 --- a/authz/Makefile.objs +++ b/authz/Makefile.objs @@ -1,2 +1,3 @@ authz-obj-y +=3D base.o authz-obj-y +=3D simple.o +authz-obj-y +=3D list.o diff --git a/authz/list.c b/authz/list.c new file mode 100644 index 0000000000..dc6b0fec13 --- /dev/null +++ b/authz/list.c @@ -0,0 +1,271 @@ +/* + * QEMU access control list authorization driver + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#include "qemu/osdep.h" +#include "authz/list.h" +#include "authz/trace.h" +#include "qom/object_interfaces.h" +#include "qapi/qapi-visit-authz.h" + +static bool qauthz_list_is_allowed(QAuthZ *authz, + const char *identity, + Error **errp) +{ + QAuthZList *lauthz =3D QAUTHZ_LIST(authz); + QAuthZListRuleList *rules =3D lauthz->rules; + + while (rules) { + QAuthZListRule *rule =3D rules->value; + QAuthZListFormat format =3D rule->has_format ? rule->format : + QAUTHZ_LIST_FORMAT_EXACT; + + trace_qauthz_list_check_rule(authz, rule->match, identity, + format, rule->policy); + switch (format) { + case QAUTHZ_LIST_FORMAT_EXACT: + if (g_str_equal(rule->match, identity)) { + return rule->policy =3D=3D QAUTHZ_LIST_POLICY_ALLOW; + } + break; + case QAUTHZ_LIST_FORMAT_GLOB: + if (g_pattern_match_simple(rule->match, identity)) { + return rule->policy =3D=3D QAUTHZ_LIST_POLICY_ALLOW; + } + break; + default: + g_warn_if_reached(); + return false; + } + rules =3D rules->next; + } + + trace_qauthz_list_default_policy(authz, identity, lauthz->policy); + return lauthz->policy =3D=3D QAUTHZ_LIST_POLICY_ALLOW; +} + + +static void +qauthz_list_prop_set_policy(Object *obj, + int value, + Error **errp G_GNUC_UNUSED) +{ + QAuthZList *lauthz =3D QAUTHZ_LIST(obj); + + lauthz->policy =3D value; +} + + +static int +qauthz_list_prop_get_policy(Object *obj, + Error **errp G_GNUC_UNUSED) +{ + QAuthZList *lauthz =3D QAUTHZ_LIST(obj); + + return lauthz->policy; +} + + +static void +qauthz_list_prop_get_rules(Object *obj, Visitor *v, const char *name, + void *opaque, Error **errp) +{ + QAuthZList *lauthz =3D QAUTHZ_LIST(obj); + + visit_type_QAuthZListRuleList(v, name, &lauthz->rules, errp); +} + +static void +qauthz_list_prop_set_rules(Object *obj, Visitor *v, const char *name, + void *opaque, Error **errp) +{ + QAuthZList *lauthz =3D QAUTHZ_LIST(obj); + QAuthZListRuleList *oldrules; + + oldrules =3D lauthz->rules; + visit_type_QAuthZListRuleList(v, name, &lauthz->rules, errp); + + qapi_free_QAuthZListRuleList(oldrules); +} + + +static void +qauthz_list_finalize(Object *obj) +{ + QAuthZList *lauthz =3D QAUTHZ_LIST(obj); + + qapi_free_QAuthZListRuleList(lauthz->rules); +} + + +static void +qauthz_list_class_init(ObjectClass *oc, void *data) +{ + QAuthZClass *authz =3D QAUTHZ_CLASS(oc); + + object_class_property_add_enum(oc, "policy", + "QAuthZListPolicy", + &QAuthZListPolicy_lookup, + qauthz_list_prop_get_policy, + qauthz_list_prop_set_policy, + NULL); + + object_class_property_add(oc, "rules", "QAuthZListRule", + qauthz_list_prop_get_rules, + qauthz_list_prop_set_rules, + NULL, NULL, NULL); + + authz->is_allowed =3D qauthz_list_is_allowed; +} + + +QAuthZList *qauthz_list_new(const char *id, + QAuthZListPolicy policy, + Error **errp) +{ + return QAUTHZ_LIST( + object_new_with_props(TYPE_QAUTHZ_LIST, + object_get_objects_root(), + id, errp, + "policy", QAuthZListPolicy_str(policy), + NULL)); +} + +ssize_t qauthz_list_append_rule(QAuthZList *auth, + const char *match, + QAuthZListPolicy policy, + QAuthZListFormat format, + Error **errp) +{ + QAuthZListRule *rule; + QAuthZListRuleList *rules, *tmp; + size_t i =3D 0; + + rule =3D g_new0(QAuthZListRule, 1); + rule->policy =3D policy; + rule->match =3D g_strdup(match); + rule->format =3D format; + rule->has_format =3D true; + + tmp =3D g_new0(QAuthZListRuleList, 1); + tmp->value =3D rule; + + rules =3D auth->rules; + if (rules) { + while (rules->next) { + i++; + rules =3D rules->next; + } + rules->next =3D tmp; + return i + 1; + } else { + auth->rules =3D tmp; + return 0; + } +} + + +ssize_t qauthz_list_insert_rule(QAuthZList *auth, + const char *match, + QAuthZListPolicy policy, + QAuthZListFormat format, + size_t index, + Error **errp) +{ + QAuthZListRule *rule; + QAuthZListRuleList *rules, *tmp; + size_t i =3D 0; + + rule =3D g_new0(QAuthZListRule, 1); + rule->policy =3D policy; + rule->match =3D g_strdup(match); + rule->format =3D format; + rule->has_format =3D true; + + tmp =3D g_new0(QAuthZListRuleList, 1); + tmp->value =3D rule; + + rules =3D auth->rules; + if (rules && index > 0) { + while (rules->next && i < (index - 1)) { + i++; + rules =3D rules->next; + } + tmp->next =3D rules->next; + rules->next =3D tmp; + return i + 1; + } else { + tmp->next =3D auth->rules; + auth->rules =3D tmp; + return 0; + } +} + + +ssize_t qauthz_list_delete_rule(QAuthZList *auth, const char *match) +{ + QAuthZListRule *rule; + QAuthZListRuleList *rules, *prev; + size_t i =3D 0; + + prev =3D NULL; + rules =3D auth->rules; + while (rules) { + rule =3D rules->value; + if (g_str_equal(rule->match, match)) { + if (prev) { + prev->next =3D rules->next; + } else { + auth->rules =3D rules->next; + } + rules->next =3D NULL; + qapi_free_QAuthZListRuleList(rules); + return i; + } + prev =3D rules; + rules =3D rules->next; + i++; + } + + return -1; +} + + +static const TypeInfo qauthz_list_info =3D { + .parent =3D TYPE_QAUTHZ, + .name =3D TYPE_QAUTHZ_LIST, + .instance_size =3D sizeof(QAuthZList), + .instance_finalize =3D qauthz_list_finalize, + .class_size =3D sizeof(QAuthZListClass), + .class_init =3D qauthz_list_class_init, + .interfaces =3D (InterfaceInfo[]) { + { TYPE_USER_CREATABLE }, + { } + } +}; + + +static void +qauthz_list_register_types(void) +{ + type_register_static(&qauthz_list_info); +} + + +type_init(qauthz_list_register_types); diff --git a/authz/trace-events b/authz/trace-events index 1ef796c1e1..a896d876e8 100644 --- a/authz/trace-events +++ b/authz/trace-events @@ -5,3 +5,7 @@ qauthz_is_allowed(void *authz, const char *identity, bool a= llowed) "AuthZ %p che =20 # auth/simple.c qauthz_simple_is_allowed(void *authz, const char *wantidentity, const char= *gotidentity) "AuthZ simple %p check want identity=3D%s got identity=3D%s" + +# auth/list.c +qauthz_list_check_rule(void *authz, const char *identity, const char *rule= , int format, int policy) "AuthZ list %p check rule=3D%s identity=3D%s form= at=3D%d policy=3D%d" +qauthz_list_default_policy(void *authz, const char *identity, int policy) = "AuthZ list %p default identity=3D%s policy=3D%d" diff --git a/include/authz/list.h b/include/authz/list.h new file mode 100644 index 0000000000..a7225a747c --- /dev/null +++ b/include/authz/list.h @@ -0,0 +1,106 @@ +/* + * QEMU list authorization driver + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#ifndef QAUTHZ_LIST_H__ +#define QAUTHZ_LIST_H__ + +#include "authz/base.h" +#include "qapi/qapi-types-authz.h" + +#define TYPE_QAUTHZ_LIST "authz-list" + +#define QAUTHZ_LIST_CLASS(klass) \ + OBJECT_CLASS_CHECK(QAuthZListClass, (klass), \ + TYPE_QAUTHZ_LIST) +#define QAUTHZ_LIST_GET_CLASS(obj) \ + OBJECT_GET_CLASS(QAuthZListClass, (obj), \ + TYPE_QAUTHZ_LIST) +#define QAUTHZ_LIST(obj) \ + INTERFACE_CHECK(QAuthZList, (obj), \ + TYPE_QAUTHZ_LIST) + +typedef struct QAuthZList QAuthZList; +typedef struct QAuthZListClass QAuthZListClass; + + +/** + * QAuthZList: + * + * This authorization driver provides a list mechanism + * for granting access by matching user names against a + * list of globs. Each match rule has an associated policy + * and a catch all policy applies if no rule matches + * + * To create an instance of this class via QMP: + * + * { + * "execute": "object-add", + * "arguments": { + * "qom-type": "authz-list", + * "id": "authz0", + * "props": { + * "rules": [ + * { "match": "fred", "policy": "allow", "format": "exact" }, + * { "match": "bob", "policy": "allow", "format": "exact" }, + * { "match": "danb", "policy": "deny", "format": "exact" }, + * { "match": "dan*", "policy": "allow", "format": "glob" } + * ], + * "policy": "deny" + * } + * } + * } + * + */ +struct QAuthZList { + QAuthZ parent_obj; + + QAuthZListPolicy policy; + QAuthZListRuleList *rules; +}; + + +struct QAuthZListClass { + QAuthZClass parent_class; +}; + + +QAuthZList *qauthz_list_new(const char *id, + QAuthZListPolicy policy, + Error **errp); + +ssize_t qauthz_list_append_rule(QAuthZList *auth, + const char *match, + QAuthZListPolicy policy, + QAuthZListFormat format, + Error **errp); + +ssize_t qauthz_list_insert_rule(QAuthZList *auth, + const char *match, + QAuthZListPolicy policy, + QAuthZListFormat format, + size_t index, + Error **errp); + +ssize_t qauthz_list_delete_rule(QAuthZList *auth, + const char *match); + + +#endif /* QAUTHZ_LIST_H__ */ + diff --git a/qapi/authz.json b/qapi/authz.json new file mode 100644 index 0000000000..55468de8a8 --- /dev/null +++ b/qapi/authz.json @@ -0,0 +1,58 @@ +# -*- Mode: Python -*- +# +# QAPI authz definitions + +## +# @QAuthZListPolicy: +# +# The authorization policy result +# +# @deny: deny access +# @allow: allow access +# +# Since: 4.0 +## +{ 'enum': 'QAuthZListPolicy', + 'prefix': 'QAUTHZ_LIST_POLICY', + 'data': ['deny', 'allow']} + +## +# @QAuthZListFormat: +# +# The authorization policy result +# +# @exact: an exact string match +# @glob: string with ? and * shell wildcard support +# +# Since: 4.0 +## +{ 'enum': 'QAuthZListFormat', + 'prefix': 'QAUTHZ_LIST_FORMAT', + 'data': ['exact', 'glob']} + +## +# @QAuthZListRule: +# +# A single authorization rule. +# +# @match: a glob to match against a user identity +# @policy: the result to return if @match evaluates to true +# @format: (optional) the format of the @match rule (default 'exact') +# +# Since: 4.0 +## +{ 'struct': 'QAuthZListRule', + 'data': {'match': 'str', + 'policy': 'QAuthZListPolicy', + '*format': 'QAuthZListFormat'}} + +## +# @QAuthZListRuleListHack: +# +# Not exposed via QMP; hack to generate QAuthZListRuleList +# for use internally by the code. +# +# Since: 4.0 +## +{ 'struct': 'QAuthZListRuleListHack', + 'data': { 'unused': ['QAuthZListRule'] } } diff --git a/qapi/qapi-schema.json b/qapi/qapi-schema.json index 1845aa78ff..1f7201cd81 100644 --- a/qapi/qapi-schema.json +++ b/qapi/qapi-schema.json @@ -92,6 +92,7 @@ { 'include': 'rocker.json' } { 'include': 'tpm.json' } { 'include': 'ui.json' } +{ 'include': 'authz.json' } { 'include': 'migration.json' } { 'include': 'transaction.json' } { 'include': 'trace.json' } diff --git a/tests/Makefile.include b/tests/Makefile.include index df1cd255a9..c007968805 100644 --- a/tests/Makefile.include +++ b/tests/Makefile.include @@ -117,6 +117,7 @@ check-unit-y +=3D tests/test-timed-average$(EXESUF) check-unit-$(CONFIG_INOTIFY1) +=3D tests/test-util-filemonitor$(EXESUF) check-unit-y +=3D tests/test-util-sockets$(EXESUF) check-unit-y +=3D tests/test-authz-simple$(EXESUF) +check-unit-y +=3D tests/test-authz-list$(EXESUF) check-unit-y +=3D tests/test-io-task$(EXESUF) check-unit-y +=3D tests/test-io-channel-socket$(EXESUF) check-unit-y +=3D tests/test-io-channel-file$(EXESUF) @@ -665,6 +666,7 @@ tests/test-util-filemonitor$(EXESUF): tests/test-util-f= ilemonitor.o \ tests/test-util-sockets$(EXESUF): tests/test-util-sockets.o \ tests/socket-helpers.o $(test-util-obj-y) tests/test-authz-simple$(EXESUF): tests/test-authz-simple.o $(test-authz-o= bj-y) +tests/test-authz-list$(EXESUF): tests/test-authz-list.o $(test-authz-obj-y) tests/test-io-task$(EXESUF): tests/test-io-task.o $(test-io-obj-y) tests/test-io-channel-socket$(EXESUF): tests/test-io-channel-socket.o \ tests/io-channel-helpers.o tests/socket-helpers.o $(test-io-obj-y) diff --git a/tests/test-authz-list.c b/tests/test-authz-list.c new file mode 100644 index 0000000000..24347a6ac3 --- /dev/null +++ b/tests/test-authz-list.c @@ -0,0 +1,159 @@ +/* + * QEMU list file authorization object tests + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#include "qemu/osdep.h" + +#include "authz/list.h" + +static void test_authz_default_deny(void) +{ + QAuthZList *auth =3D qauthz_list_new("auth0", + QAUTHZ_LIST_POLICY_DENY, + &error_abort); + + g_assert(!qauthz_is_allowed(QAUTHZ(auth), "fred", &error_abort)); + + object_unparent(OBJECT(auth)); +} + +static void test_authz_default_allow(void) +{ + QAuthZList *auth =3D qauthz_list_new("auth0", + QAUTHZ_LIST_POLICY_ALLOW, + &error_abort); + + g_assert(qauthz_is_allowed(QAUTHZ(auth), "fred", &error_abort)); + + object_unparent(OBJECT(auth)); +} + +static void test_authz_explicit_deny(void) +{ + QAuthZList *auth =3D qauthz_list_new("auth0", + QAUTHZ_LIST_POLICY_ALLOW, + &error_abort); + + qauthz_list_append_rule(auth, "fred", QAUTHZ_LIST_POLICY_DENY, + QAUTHZ_LIST_FORMAT_EXACT, &error_abort); + + g_assert(!qauthz_is_allowed(QAUTHZ(auth), "fred", &error_abort)); + + object_unparent(OBJECT(auth)); +} + +static void test_authz_explicit_allow(void) +{ + QAuthZList *auth =3D qauthz_list_new("auth0", + QAUTHZ_LIST_POLICY_DENY, + &error_abort); + + qauthz_list_append_rule(auth, "fred", QAUTHZ_LIST_POLICY_ALLOW, + QAUTHZ_LIST_FORMAT_EXACT, &error_abort); + + g_assert(qauthz_is_allowed(QAUTHZ(auth), "fred", &error_abort)); + + object_unparent(OBJECT(auth)); +} + + +static void test_authz_complex(void) +{ + QAuthZList *auth =3D qauthz_list_new("auth0", + QAUTHZ_LIST_POLICY_DENY, + &error_abort); + + qauthz_list_append_rule(auth, "fred", QAUTHZ_LIST_POLICY_ALLOW, + QAUTHZ_LIST_FORMAT_EXACT, &error_abort); + qauthz_list_append_rule(auth, "bob", QAUTHZ_LIST_POLICY_ALLOW, + QAUTHZ_LIST_FORMAT_EXACT, &error_abort); + qauthz_list_append_rule(auth, "dan", QAUTHZ_LIST_POLICY_DENY, + QAUTHZ_LIST_FORMAT_EXACT, &error_abort); + qauthz_list_append_rule(auth, "dan*", QAUTHZ_LIST_POLICY_ALLOW, + QAUTHZ_LIST_FORMAT_GLOB, &error_abort); + + g_assert(qauthz_is_allowed(QAUTHZ(auth), "fred", &error_abort)); + g_assert(qauthz_is_allowed(QAUTHZ(auth), "bob", &error_abort)); + g_assert(!qauthz_is_allowed(QAUTHZ(auth), "dan", &error_abort)); + g_assert(qauthz_is_allowed(QAUTHZ(auth), "danb", &error_abort)); + + object_unparent(OBJECT(auth)); +} + +static void test_authz_add_remove(void) +{ + QAuthZList *auth =3D qauthz_list_new("auth0", + QAUTHZ_LIST_POLICY_ALLOW, + &error_abort); + + g_assert_cmpint(qauthz_list_append_rule(auth, "fred", + QAUTHZ_LIST_POLICY_ALLOW, + QAUTHZ_LIST_FORMAT_EXACT, + &error_abort), + =3D=3D, 0); + g_assert_cmpint(qauthz_list_append_rule(auth, "bob", + QAUTHZ_LIST_POLICY_ALLOW, + QAUTHZ_LIST_FORMAT_EXACT, + &error_abort), + =3D=3D, 1); + g_assert_cmpint(qauthz_list_append_rule(auth, "dan", + QAUTHZ_LIST_POLICY_DENY, + QAUTHZ_LIST_FORMAT_EXACT, + &error_abort), + =3D=3D, 2); + g_assert_cmpint(qauthz_list_append_rule(auth, "frank", + QAUTHZ_LIST_POLICY_DENY, + QAUTHZ_LIST_FORMAT_EXACT, + &error_abort), + =3D=3D, 3); + + g_assert(!qauthz_is_allowed(QAUTHZ(auth), "dan", &error_abort)); + + g_assert_cmpint(qauthz_list_delete_rule(auth, "dan"), + =3D=3D, 2); + + g_assert(qauthz_is_allowed(QAUTHZ(auth), "dan", &error_abort)); + + g_assert_cmpint(qauthz_list_insert_rule(auth, "dan", + QAUTHZ_LIST_POLICY_DENY, + QAUTHZ_LIST_FORMAT_EXACT, + 2, + &error_abort), + =3D=3D, 2); + + g_assert(!qauthz_is_allowed(QAUTHZ(auth), "dan", &error_abort)); + + object_unparent(OBJECT(auth)); +} + +int main(int argc, char **argv) +{ + g_test_init(&argc, &argv, NULL); + + module_call_init(MODULE_INIT_QOM); + + g_test_add_func("/auth/list/default/deny", test_authz_default_deny); + g_test_add_func("/auth/list/default/allow", test_authz_default_allow); + g_test_add_func("/auth/list/explicit/deny", test_authz_explicit_deny); + g_test_add_func("/auth/list/explicit/allow", test_authz_explicit_allow= ); + g_test_add_func("/auth/list/complex", test_authz_complex); + g_test_add_func("/auth/list/add-remove", test_authz_add_remove); + + return g_test_run(); +} --=20 2.20.1 From nobody Sun May 5 13:38:15 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Authentication-Results: mx.zohomail.com; spf=pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1550247171244718.8646375999413; Fri, 15 Feb 2019 08:12:51 -0800 (PST) Received: from localhost ([127.0.0.1]:42227 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gug6a-0007iF-1Y for importer@patchew.org; Fri, 15 Feb 2019 11:12:48 -0500 Received: from eggs.gnu.org ([209.51.188.92]:47011) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufsm-0005XE-Gh for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:36 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1gufsh-0003Lj-Pj for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:32 -0500 Received: from mx1.redhat.com ([209.132.183.28]:43828) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1gufsX-0003GW-CJ for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:20 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id 856FEC3A7C; Fri, 15 Feb 2019 15:58:16 +0000 (UTC) Received: from localhost.localdomain.com (ovpn-112-65.ams2.redhat.com [10.36.112.65]) by smtp.corp.redhat.com (Postfix) with ESMTP id DCE4D101E848; Fri, 15 Feb 2019 15:58:11 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Date: Fri, 15 Feb 2019 15:57:07 +0000 Message-Id: <20190215155709.15777-10-berrange@redhat.com> In-Reply-To: <20190215155709.15777-1-berrange@redhat.com> References: <20190215155709.15777-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.84 on 10.5.11.22 X-Greylist: Sender IP whitelisted, not delayed by milter-greylist-4.5.16 (mx1.redhat.com [10.5.110.30]); Fri, 15 Feb 2019 15:58:16 +0000 (UTC) Content-Transfer-Encoding: quoted-printable X-detected-operating-system: by eggs.gnu.org: GNU/Linux 2.2.x-3.x [generic] X-Received-From: 209.132.183.28 Subject: [Qemu-devel] [PATCH v8 09/11] authz: add QAuthZListFile object type for a file access control list X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Markus Armbruster , "Dr. David Alan Gilbert" , Gerd Hoffmann , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , =?UTF-8?q?Andreas=20F=C3=A4rber?= Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Content-Type: text/plain; charset="utf-8" Add a QAuthZListFile object type that implements the QAuthZ interface. This built-in implementation is a proxy around the QAuthZList object type, initializing it from an external file, and optionally, automatically reloading it whenever it changes. To create an instance of this object via the QMP monitor, the syntax used would be: { "execute": "object-add", "arguments": { "qom-type": "authz-list-file", "id": "authz0", "props": { "filename": "/etc/qemu/vnc.acl", "refresh": true } } } If "refresh" is "yes", inotify is used to monitor the file, automatically reloading changes. If an error occurs during reloading, all authorizations will fail until the file is next successfully loaded. The /etc/qemu/vnc.acl file would contain a JSON representation of a QAuthZList object { "rules": [ { "match": "fred", "policy": "allow", "format": "exact" }, { "match": "bob", "policy": "allow", "format": "exact" }, { "match": "danb", "policy": "deny", "format": "glob" }, { "match": "dan*", "policy": "allow", "format": "exact" }, ], "policy": "deny" } This sets up an authorization rule that allows 'fred', 'bob' and anyone whose name starts with 'dan', except for 'danb'. Everyone unmatched is denied. The object can be loaded on the comand line using -object authz-list-file,id=3Dauthz0,filename=3D/etc/qemu/vnc.acl,refresh= =3Dyes Tested-by: Philippe Mathieu-Daud=C3=A9 Reviewed-by: Philippe Mathieu-Daud=C3=A9 Signed-off-by: Daniel P. Berrang=C3=A9 Reviewed-by: Marc-Andr=C3=A9 Lureau --- authz/Makefile.objs | 1 + authz/listfile.c | 283 ++++++++++++++++++++++++++++++++++++ authz/trace-events | 4 + include/authz/listfile.h | 111 ++++++++++++++ qemu-options.hx | 46 ++++++ tests/Makefile.include | 2 + tests/test-authz-listfile.c | 195 +++++++++++++++++++++++++ 7 files changed, 642 insertions(+) create mode 100644 authz/listfile.c create mode 100644 include/authz/listfile.h create mode 100644 tests/test-authz-listfile.c diff --git a/authz/Makefile.objs b/authz/Makefile.objs index 921fa624d7..8351bf181d 100644 --- a/authz/Makefile.objs +++ b/authz/Makefile.objs @@ -1,3 +1,4 @@ authz-obj-y +=3D base.o authz-obj-y +=3D simple.o authz-obj-y +=3D list.o +authz-obj-y +=3D listfile.o diff --git a/authz/listfile.c b/authz/listfile.c new file mode 100644 index 0000000000..d4579767e7 --- /dev/null +++ b/authz/listfile.c @@ -0,0 +1,283 @@ +/* + * QEMU access control list file authorization driver + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#include "qemu/osdep.h" +#include "authz/listfile.h" +#include "authz/trace.h" +#include "qemu/error-report.h" +#include "qemu/main-loop.h" +#include "qemu/sockets.h" +#include "qemu/filemonitor.h" +#include "qom/object_interfaces.h" +#include "qapi/qapi-visit-authz.h" +#include "qapi/qmp/qjson.h" +#include "qapi/qmp/qobject.h" +#include "qapi/qmp/qerror.h" +#include "qapi/qobject-input-visitor.h" + + +static bool +qauthz_list_file_is_allowed(QAuthZ *authz, + const char *identity, + Error **errp) +{ + QAuthZListFile *fauthz =3D QAUTHZ_LIST_FILE(authz); + if (fauthz->list) { + return qauthz_is_allowed(fauthz->list, identity, errp); + } + + return false; +} + + +static QAuthZ * +qauthz_list_file_load(QAuthZListFile *fauthz, Error **errp) +{ + GError *err =3D NULL; + gchar *content =3D NULL; + gsize len; + QObject *obj =3D NULL; + QDict *pdict; + Visitor *v =3D NULL; + QAuthZ *ret =3D NULL; + + trace_qauthz_list_file_load(fauthz, fauthz->filename); + if (!g_file_get_contents(fauthz->filename, &content, &len, &err)) { + error_setg(errp, "Unable to read '%s': %s", + fauthz->filename, err->message); + goto cleanup; + } + + obj =3D qobject_from_json(content, errp); + if (!obj) { + goto cleanup; + } + + pdict =3D qobject_to(QDict, obj); + if (!pdict) { + error_setg(errp, QERR_INVALID_PARAMETER_TYPE, "obj", "dict"); + goto cleanup; + } + + v =3D qobject_input_visitor_new(obj); + + ret =3D (QAuthZ *)user_creatable_add_type(TYPE_QAUTHZ_LIST, + NULL, pdict, v, errp); + + cleanup: + visit_free(v); + qobject_unref(obj); + if (err) { + g_error_free(err); + } + g_free(content); + return ret; +} + + +static void +qauthz_list_file_event(int wd G_GNUC_UNUSED, + QFileMonitorEvent ev G_GNUC_UNUSED, + const char *name G_GNUC_UNUSED, + void *opaque) +{ + QAuthZListFile *fauthz =3D opaque; + Error *err =3D NULL; + + if (ev !=3D QFILE_MONITOR_EVENT_MODIFIED && + ev !=3D QFILE_MONITOR_EVENT_CREATED) { + return; + } + + object_unref(OBJECT(fauthz->list)); + fauthz->list =3D qauthz_list_file_load(fauthz, &err); + trace_qauthz_list_file_refresh(fauthz, + fauthz->filename, fauthz->list ? 1 : 0); + if (!fauthz->list) { + error_report_err(err); + } +} + +static void +qauthz_list_file_complete(UserCreatable *uc, Error **errp) +{ + QAuthZListFile *fauthz =3D QAUTHZ_LIST_FILE(uc); + gchar *dir =3D NULL, *file =3D NULL; + + fauthz->list =3D qauthz_list_file_load(fauthz, errp); + + if (!fauthz->refresh) { + return; + } + + fauthz->file_monitor =3D qemu_file_monitor_new(errp); + if (!fauthz->file_monitor) { + return; + } + + dir =3D g_path_get_dirname(fauthz->filename); + if (g_str_equal(dir, ".")) { + error_setg(errp, "Filename must be an absolute path"); + goto cleanup; + } + file =3D g_path_get_basename(fauthz->filename); + if (g_str_equal(file, ".")) { + error_setg(errp, "Path has no trailing filename component"); + goto cleanup; + } + + fauthz->file_watch =3D qemu_file_monitor_add_watch( + fauthz->file_monitor, dir, file, + qauthz_list_file_event, fauthz, errp); + if (fauthz->file_watch < 0) { + goto cleanup; + } + + cleanup: + g_free(file); + g_free(dir); +} + + +static void +qauthz_list_file_prop_set_filename(Object *obj, + const char *value, + Error **errp G_GNUC_UNUSED) +{ + QAuthZListFile *fauthz =3D QAUTHZ_LIST_FILE(obj); + + g_free(fauthz->filename); + fauthz->filename =3D g_strdup(value); +} + + +static char * +qauthz_list_file_prop_get_filename(Object *obj, + Error **errp G_GNUC_UNUSED) +{ + QAuthZListFile *fauthz =3D QAUTHZ_LIST_FILE(obj); + + return g_strdup(fauthz->filename); +} + + +static void +qauthz_list_file_prop_set_refresh(Object *obj, + bool value, + Error **errp G_GNUC_UNUSED) +{ + QAuthZListFile *fauthz =3D QAUTHZ_LIST_FILE(obj); + + fauthz->refresh =3D value; +} + + +static bool +qauthz_list_file_prop_get_refresh(Object *obj, + Error **errp G_GNUC_UNUSED) +{ + QAuthZListFile *fauthz =3D QAUTHZ_LIST_FILE(obj); + + return fauthz->refresh; +} + + +static void +qauthz_list_file_finalize(Object *obj) +{ + QAuthZListFile *fauthz =3D QAUTHZ_LIST_FILE(obj); + + object_unref(OBJECT(fauthz->list)); + g_free(fauthz->filename); + qemu_file_monitor_free(fauthz->file_monitor); +} + + +static void +qauthz_list_file_class_init(ObjectClass *oc, void *data) +{ + UserCreatableClass *ucc =3D USER_CREATABLE_CLASS(oc); + QAuthZClass *authz =3D QAUTHZ_CLASS(oc); + + ucc->complete =3D qauthz_list_file_complete; + + object_class_property_add_str(oc, "filename", + qauthz_list_file_prop_get_filename, + qauthz_list_file_prop_set_filename, + NULL); + object_class_property_add_bool(oc, "refresh", + qauthz_list_file_prop_get_refresh, + qauthz_list_file_prop_set_refresh, + NULL); + + authz->is_allowed =3D qauthz_list_file_is_allowed; +} + + +static void +qauthz_list_file_init(Object *obj) +{ + QAuthZListFile *authz =3D QAUTHZ_LIST_FILE(obj); + + authz->file_watch =3D -1; +#ifdef CONFIG_INOTIFY1 + authz->refresh =3D TRUE; +#endif +} + + +QAuthZListFile *qauthz_list_file_new(const char *id, + const char *filename, + bool refresh, + Error **errp) +{ + return QAUTHZ_LIST_FILE( + object_new_with_props(TYPE_QAUTHZ_LIST_FILE, + object_get_objects_root(), + id, errp, + "filename", filename, + "refresh", refresh ? "yes" : "no", + NULL)); +} + + +static const TypeInfo qauthz_list_file_info =3D { + .parent =3D TYPE_QAUTHZ, + .name =3D TYPE_QAUTHZ_LIST_FILE, + .instance_init =3D qauthz_list_file_init, + .instance_size =3D sizeof(QAuthZListFile), + .instance_finalize =3D qauthz_list_file_finalize, + .class_size =3D sizeof(QAuthZListFileClass), + .class_init =3D qauthz_list_file_class_init, + .interfaces =3D (InterfaceInfo[]) { + { TYPE_USER_CREATABLE }, + { } + } +}; + + +static void +qauthz_list_file_register_types(void) +{ + type_register_static(&qauthz_list_file_info); +} + + +type_init(qauthz_list_file_register_types); diff --git a/authz/trace-events b/authz/trace-events index a896d876e8..fb65349a90 100644 --- a/authz/trace-events +++ b/authz/trace-events @@ -9,3 +9,7 @@ qauthz_simple_is_allowed(void *authz, const char *wantident= ity, const char *goti # auth/list.c qauthz_list_check_rule(void *authz, const char *identity, const char *rule= , int format, int policy) "AuthZ list %p check rule=3D%s identity=3D%s form= at=3D%d policy=3D%d" qauthz_list_default_policy(void *authz, const char *identity, int policy) = "AuthZ list %p default identity=3D%s policy=3D%d" + +# auth/listfile.c +qauthz_list_file_load(void *authz, const char *filename) "AuthZ file %p lo= ad filename=3D%s" +qauthz_list_file_refresh(void *authz, const char *filename, int success) "= AuthZ file %p load filename=3D%s success=3D%d" diff --git a/include/authz/listfile.h b/include/authz/listfile.h new file mode 100644 index 0000000000..bcc8d80743 --- /dev/null +++ b/include/authz/listfile.h @@ -0,0 +1,111 @@ +/* + * QEMU list file authorization driver + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#ifndef QAUTHZ_LIST_FILE_H__ +#define QAUTHZ_LIST_FILE_H__ + +#include "authz/list.h" +#include "qapi/qapi-types-authz.h" +#include "qemu/filemonitor.h" + +#define TYPE_QAUTHZ_LIST_FILE "authz-list-file" + +#define QAUTHZ_LIST_FILE_CLASS(klass) \ + OBJECT_CLASS_CHECK(QAuthZListFileClass, (klass), \ + TYPE_QAUTHZ_LIST_FILE) +#define QAUTHZ_LIST_FILE_GET_CLASS(obj) \ + OBJECT_GET_CLASS(QAuthZListFileClass, (obj), \ + TYPE_QAUTHZ_LIST_FILE) +#define QAUTHZ_LIST_FILE(obj) \ + INTERFACE_CHECK(QAuthZListFile, (obj), \ + TYPE_QAUTHZ_LIST_FILE) + +typedef struct QAuthZListFile QAuthZListFile; +typedef struct QAuthZListFileClass QAuthZListFileClass; + + +/** + * QAuthZListFile: + * + * This authorization driver provides a file mechanism + * for granting access by matching user names against a + * file of globs. Each match rule has an associated policy + * and a catch all policy applies if no rule matches + * + * To create an instance of this class via QMP: + * + * { + * "execute": "object-add", + * "arguments": { + * "qom-type": "authz-list-file", + * "id": "authz0", + * "props": { + * "filename": "/etc/qemu/myvm-vnc.acl", + * "refresh": true + * } + * } + * } + * + * If 'refresh' is 'yes', inotify is used to monitor for changes + * to the file and auto-reload the rules. + * + * The myvm-vnc.acl file should contain the parameters for + * the QAuthZList object in JSON format: + * + * { + * "rules": [ + * { "match": "fred", "policy": "allow", "format": "exact" }, + * { "match": "bob", "policy": "allow", "format": "exact" }, + * { "match": "danb", "policy": "deny", "format": "exact" }, + * { "match": "dan*", "policy": "allow", "format": "glob" } + * ], + * "policy": "deny" + * } + * + * The object can be created on the command line using + * + * -object authz-list-file,id=3Dauthz0,\ + * filename=3D/etc/qemu/myvm-vnc.acl,refresh=3Dyes + * + */ +struct QAuthZListFile { + QAuthZ parent_obj; + + QAuthZ *list; + char *filename; + bool refresh; + QFileMonitor *file_monitor; + int file_watch; +}; + + +struct QAuthZListFileClass { + QAuthZClass parent_class; +}; + + +QAuthZListFile *qauthz_list_file_new(const char *id, + const char *filename, + bool refresh, + Error **errp); + + +#endif /* QAUTHZ_LIST_FILE_H__ */ + diff --git a/qemu-options.hx b/qemu-options.hx index a948cacc07..e34d30a013 100644 --- a/qemu-options.hx +++ b/qemu-options.hx @@ -4384,6 +4384,52 @@ would look like: Note the use of quotes due to the x509 distinguished name containing whitespace, and escaping of ','. =20 +@item -object authz-listfile,id=3D@var{id},filename=3D@var{path},refresh= =3D@var{yes|no} + +Create an authorization object that will control access to network service= s. + +The @option{filename} parameter is the fully qualified path to a file +containing the access control list rules in JSON format. + +An example set of rules that match against SASL usernames might look +like: + +@example + @{ + "rules": [ + @{ "match": "fred", "policy": "allow", "format": "exact" @}, + @{ "match": "bob", "policy": "allow", "format": "exact" @}, + @{ "match": "danb", "policy": "deny", "format": "glob" @}, + @{ "match": "dan*", "policy": "allow", "format": "exact" @}, + ], + "policy": "deny" + @} +@end example + +When checking access the object will iterate over all the rules and +the first rule to match will have its @option{policy} value returned +as the result. If no rules match, then the default @option{policy} +value is returned. + +The rules can either be an exact string match, or they can use the +simple UNIX glob pattern matching to allow wildcards to be used. + +If @option{refresh} is set to true the file will be monitored +and automatically reloaded whenever its content changes. + +As with the @code{authz-simple} object, the format of the identity +strings being matched depends on the network service, but is usually +a TLS x509 distinguished name, or a SASL username. + +An example authorization object to validate a SASL username +would look like: +@example + # $QEMU \ + ... + -object authz-simple,id=3Dauth0,filename=3D/etc/qemu/vnc-sasl.acl,ref= resh=3Dyes + ... +@end example + @end table =20 ETEXI diff --git a/tests/Makefile.include b/tests/Makefile.include index c007968805..199e74d670 100644 --- a/tests/Makefile.include +++ b/tests/Makefile.include @@ -118,6 +118,7 @@ check-unit-$(CONFIG_INOTIFY1) +=3D tests/test-util-file= monitor$(EXESUF) check-unit-y +=3D tests/test-util-sockets$(EXESUF) check-unit-y +=3D tests/test-authz-simple$(EXESUF) check-unit-y +=3D tests/test-authz-list$(EXESUF) +check-unit-y +=3D tests/test-authz-listfile$(EXESUF) check-unit-y +=3D tests/test-io-task$(EXESUF) check-unit-y +=3D tests/test-io-channel-socket$(EXESUF) check-unit-y +=3D tests/test-io-channel-file$(EXESUF) @@ -667,6 +668,7 @@ tests/test-util-sockets$(EXESUF): tests/test-util-socke= ts.o \ tests/socket-helpers.o $(test-util-obj-y) tests/test-authz-simple$(EXESUF): tests/test-authz-simple.o $(test-authz-o= bj-y) tests/test-authz-list$(EXESUF): tests/test-authz-list.o $(test-authz-obj-y) +tests/test-authz-listfile$(EXESUF): tests/test-authz-listfile.o $(test-aut= hz-obj-y) tests/test-io-task$(EXESUF): tests/test-io-task.o $(test-io-obj-y) tests/test-io-channel-socket$(EXESUF): tests/test-io-channel-socket.o \ tests/io-channel-helpers.o tests/socket-helpers.o $(test-io-obj-y) diff --git a/tests/test-authz-listfile.c b/tests/test-authz-listfile.c new file mode 100644 index 0000000000..1e452fef6d --- /dev/null +++ b/tests/test-authz-listfile.c @@ -0,0 +1,195 @@ +/* + * QEMU list authorization object tests + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#include "qemu/osdep.h" +#include "qemu/main-loop.h" +#include "authz/listfile.h" + +static char *workdir; + +static gchar *qemu_authz_listfile_test_save(const gchar *name, + const gchar *cfg) +{ + gchar *path =3D g_strdup_printf("%s/default-deny.cfg", workdir); + GError *gerr =3D NULL; + + if (!g_file_set_contents(path, cfg, -1, &gerr)) { + g_printerr("Unable to save config %s: %s\n", + path, gerr->message); + g_error_free(gerr); + g_free(path); + rmdir(workdir); + abort(); + } + + return path; +} + +static void test_authz_default_deny(void) +{ + gchar *file =3D qemu_authz_listfile_test_save( + "default-deny.cfg", + "{ \"policy\": \"deny\" }"); + Error *local_err =3D NULL; + + QAuthZListFile *auth =3D qauthz_list_file_new("auth0", + file, false, + &local_err); + unlink(file); + g_free(file); + g_assert(local_err =3D=3D NULL); + g_assert(!qauthz_is_allowed(QAUTHZ(auth), "fred", &error_abort)); + + object_unparent(OBJECT(auth)); +} + +static void test_authz_default_allow(void) +{ + gchar *file =3D qemu_authz_listfile_test_save( + "default-allow.cfg", + "{ \"policy\": \"allow\" }"); + Error *local_err =3D NULL; + + QAuthZListFile *auth =3D qauthz_list_file_new("auth0", + file, false, + &local_err); + unlink(file); + g_free(file); + g_assert(local_err =3D=3D NULL); + g_assert(qauthz_is_allowed(QAUTHZ(auth), "fred", &error_abort)); + + object_unparent(OBJECT(auth)); +} + +static void test_authz_explicit_deny(void) +{ + gchar *file =3D qemu_authz_listfile_test_save( + "explicit-deny.cfg", + "{ \"rules\": [ " + " { \"match\": \"fred\"," + " \"policy\": \"deny\"," + " \"format\": \"exact\" } ]," + " \"policy\": \"allow\" }"); + Error *local_err =3D NULL; + + QAuthZListFile *auth =3D qauthz_list_file_new("auth0", + file, false, + &local_err); + unlink(file); + g_free(file); + g_assert(local_err =3D=3D NULL); + + g_assert(!qauthz_is_allowed(QAUTHZ(auth), "fred", &error_abort)); + + object_unparent(OBJECT(auth)); +} + +static void test_authz_explicit_allow(void) +{ + gchar *file =3D qemu_authz_listfile_test_save( + "explicit-allow.cfg", + "{ \"rules\": [ " + " { \"match\": \"fred\"," + " \"policy\": \"allow\"," + " \"format\": \"exact\" } ]," + " \"policy\": \"deny\" }"); + Error *local_err =3D NULL; + + QAuthZListFile *auth =3D qauthz_list_file_new("auth0", + file, false, + &local_err); + unlink(file); + g_free(file); + g_assert(local_err =3D=3D NULL); + + g_assert(qauthz_is_allowed(QAUTHZ(auth), "fred", &error_abort)); + + object_unparent(OBJECT(auth)); +} + + +static void test_authz_complex(void) +{ + gchar *file =3D qemu_authz_listfile_test_save( + "complex.cfg", + "{ \"rules\": [ " + " { \"match\": \"fred\"," + " \"policy\": \"allow\"," + " \"format\": \"exact\" }," + " { \"match\": \"bob\"," + " \"policy\": \"allow\"," + " \"format\": \"exact\" }," + " { \"match\": \"dan\"," + " \"policy\": \"deny\"," + " \"format\": \"exact\" }," + " { \"match\": \"dan*\"," + " \"policy\": \"allow\"," + " \"format\": \"glob\" } ]," + " \"policy\": \"deny\" }"); + + Error *local_err =3D NULL; + + QAuthZListFile *auth =3D qauthz_list_file_new("auth0", + file, false, + &local_err); + unlink(file); + g_free(file); + g_assert(local_err =3D=3D NULL); + + g_assert(qauthz_is_allowed(QAUTHZ(auth), "fred", &error_abort)); + g_assert(qauthz_is_allowed(QAUTHZ(auth), "bob", &error_abort)); + g_assert(!qauthz_is_allowed(QAUTHZ(auth), "dan", &error_abort)); + g_assert(qauthz_is_allowed(QAUTHZ(auth), "danb", &error_abort)); + + object_unparent(OBJECT(auth)); +} + + +int main(int argc, char **argv) +{ + int ret; + GError *gerr =3D NULL; + + g_test_init(&argc, &argv, NULL); + + module_call_init(MODULE_INIT_QOM); + + workdir =3D g_dir_make_tmp("qemu-test-authz-listfile-XXXXXX", + &gerr); + if (!workdir) { + g_printerr("Unable to create temporary dir: %s\n", + gerr->message); + g_error_free(gerr); + abort(); + } + + g_test_add_func("/auth/list/default/deny", test_authz_default_deny); + g_test_add_func("/auth/list/default/allow", test_authz_default_allow); + g_test_add_func("/auth/list/explicit/deny", test_authz_explicit_deny); + g_test_add_func("/auth/list/explicit/allow", test_authz_explicit_allow= ); + g_test_add_func("/auth/list/complex", test_authz_complex); + + ret =3D g_test_run(); + + rmdir(workdir); + g_free(workdir); + + return ret; +} --=20 2.20.1 From nobody Sun May 5 13:38:15 2024 Delivered-To: importer@patchew.org Received-SPF: temperror (zoho.com: Error in retrieving data from DNS) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Authentication-Results: mx.zohomail.com; spf=temperror (zoho.com: Error in retrieving data from DNS) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.gnu.org (209.51.188.17 [209.51.188.17]) by mx.zohomail.com with SMTPS id 1550246705823416.5074784092403; Fri, 15 Feb 2019 08:05:05 -0800 (PST) Received: from localhost ([127.0.0.1]:42075 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufyr-0001jM-Cg for importer@patchew.org; Fri, 15 Feb 2019 11:04:49 -0500 Received: from eggs.gnu.org ([209.51.188.92]:47049) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufso-0005Yt-Rk for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:37 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1gufsm-0003OD-JJ for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:34 -0500 Received: from mx1.redhat.com ([209.132.183.28]:45616) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1gufsj-0003Hb-Dg for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:32 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id D7A352F947B; Fri, 15 Feb 2019 15:58:18 +0000 (UTC) Received: from localhost.localdomain.com (ovpn-112-65.ams2.redhat.com [10.36.112.65]) by smtp.corp.redhat.com (Postfix) with ESMTP id D0D5C101E848; Fri, 15 Feb 2019 15:58:16 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Date: Fri, 15 Feb 2019 15:57:08 +0000 Message-Id: <20190215155709.15777-11-berrange@redhat.com> In-Reply-To: <20190215155709.15777-1-berrange@redhat.com> References: <20190215155709.15777-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.84 on 10.5.11.22 X-Greylist: Sender IP whitelisted, not delayed by milter-greylist-4.5.16 (mx1.redhat.com [10.5.110.29]); Fri, 15 Feb 2019 15:58:18 +0000 (UTC) Content-Transfer-Encoding: quoted-printable X-detected-operating-system: by eggs.gnu.org: GNU/Linux 2.2.x-3.x [generic] X-Received-From: 209.132.183.28 Subject: [Qemu-devel] [PATCH v8 10/11] authz: add QAuthZPAM object type for authorizing using PAM X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Markus Armbruster , "Dr. David Alan Gilbert" , Gerd Hoffmann , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , =?UTF-8?q?Andreas=20F=C3=A4rber?= Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Content-Type: text/plain; charset="utf-8" From: "Daniel P. Berrange" Add an authorization backend that talks to PAM to check whether the user identity is allowed. This only uses the PAM account validation facility, which is essentially just a check to see if the provided username is permit= ted access. It doesn't use the authentication or session parts of PAM, since that's dealt with by the relevant part of QEMU (eg VNC server). Consider starting QEMU with a VNC server and telling it to use TLS with x509 client certificates and configuring it to use an PAM to validate the x509 distinguished name. In this example we're telling it to use PAM for the QAuthZ impl with a service name of "qemu-vnc" $ qemu-system-x86_64 \ -object tls-creds-x509,id=3Dtls0,dir=3D/home/berrange/security/qemutls= ,\ endpoint=3Dserver,verify-peer=3Dyes \ -object authz-pam,id=3Dauthz0,service=3Dqemu-vnc \ -vnc :1,tls-creds=3Dtls0,tls-authz=3Dauthz0 This requires an /etc/pam/qemu-vnc file to be created with the auth rules. A very simple file based whitelist can be setup using $ cat > /etc/pam/qemu-vnc < /etc/qemu/vnc.allow < Reviewed-by: Philippe Mathieu-Daud=C3=A9 Tested-by: Philippe Mathieu-Daud=C3=A9 --- authz/Makefile.objs | 3 + authz/pamacct.c | 149 ++++++++++++++++++++++++++++++++++++++++ authz/trace-events | 3 + configure | 37 ++++++++++ include/authz/pamacct.h | 100 +++++++++++++++++++++++++++ qemu-options.hx | 35 ++++++++++ tests/Makefile.include | 2 + tests/test-authz-pam.c | 124 +++++++++++++++++++++++++++++++++ 8 files changed, 453 insertions(+) create mode 100644 authz/pamacct.c create mode 100644 include/authz/pamacct.h create mode 100644 tests/test-authz-pam.c diff --git a/authz/Makefile.objs b/authz/Makefile.objs index 8351bf181d..ed7b273596 100644 --- a/authz/Makefile.objs +++ b/authz/Makefile.objs @@ -2,3 +2,6 @@ authz-obj-y +=3D base.o authz-obj-y +=3D simple.o authz-obj-y +=3D list.o authz-obj-y +=3D listfile.o +authz-obj-$(CONFIG_AUTH_PAM) +=3D pamacct.o + +pamacct.o-libs =3D -lpam diff --git a/authz/pamacct.c b/authz/pamacct.c new file mode 100644 index 0000000000..8fe4c8ee11 --- /dev/null +++ b/authz/pamacct.c @@ -0,0 +1,149 @@ +/* + * QEMU PAM authorization driver + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#include "qemu/osdep.h" +#include "authz/pamacct.h" +#include "authz/trace.h" +#include "qom/object_interfaces.h" + +#include + + +static bool qauthz_pam_is_allowed(QAuthZ *authz, + const char *identity, + Error **errp) +{ + QAuthZPAM *pauthz =3D QAUTHZ_PAM(authz); + const struct pam_conv pam_conversation =3D { 0 }; + pam_handle_t *pamh =3D NULL; + int ret; + + trace_qauthz_pam_check(authz, identity, pauthz->service); + ret =3D pam_start(pauthz->service, + identity, + &pam_conversation, + &pamh); + if (ret !=3D PAM_SUCCESS) { + error_setg(errp, "Unable to start PAM transaction: %s", + pam_strerror(NULL, ret)); + return false; + } + + ret =3D pam_acct_mgmt(pamh, PAM_SILENT); + if (ret !=3D PAM_SUCCESS) { + error_setg(errp, "Unable to authorize user '%s': %s", + identity, pam_strerror(pamh, ret)); + goto cleanup; + } + + cleanup: + pam_end(pamh, ret); + return ret =3D=3D PAM_SUCCESS; +} + + +static void +qauthz_pam_prop_set_service(Object *obj, + const char *service, + Error **errp G_GNUC_UNUSED) +{ + QAuthZPAM *pauthz =3D QAUTHZ_PAM(obj); + + g_free(pauthz->service); + pauthz->service =3D g_strdup(service); +} + + +static char * +qauthz_pam_prop_get_service(Object *obj, + Error **errp G_GNUC_UNUSED) +{ + QAuthZPAM *pauthz =3D QAUTHZ_PAM(obj); + + return g_strdup(pauthz->service); +} + + +static void +qauthz_pam_complete(UserCreatable *uc, Error **errp) +{ +} + + +static void +qauthz_pam_finalize(Object *obj) +{ + QAuthZPAM *pauthz =3D QAUTHZ_PAM(obj); + + g_free(pauthz->service); +} + + +static void +qauthz_pam_class_init(ObjectClass *oc, void *data) +{ + UserCreatableClass *ucc =3D USER_CREATABLE_CLASS(oc); + QAuthZClass *authz =3D QAUTHZ_CLASS(oc); + + ucc->complete =3D qauthz_pam_complete; + authz->is_allowed =3D qauthz_pam_is_allowed; + + object_class_property_add_str(oc, "service", + qauthz_pam_prop_get_service, + qauthz_pam_prop_set_service, + NULL); +} + + +QAuthZPAM *qauthz_pam_new(const char *id, + const char *service, + Error **errp) +{ + return QAUTHZ_PAM( + object_new_with_props(TYPE_QAUTHZ_PAM, + object_get_objects_root(), + id, errp, + "service", service, + NULL)); +} + + +static const TypeInfo qauthz_pam_info =3D { + .parent =3D TYPE_QAUTHZ, + .name =3D TYPE_QAUTHZ_PAM, + .instance_size =3D sizeof(QAuthZPAM), + .instance_finalize =3D qauthz_pam_finalize, + .class_size =3D sizeof(QAuthZPAMClass), + .class_init =3D qauthz_pam_class_init, + .interfaces =3D (InterfaceInfo[]) { + { TYPE_USER_CREATABLE }, + { } + } +}; + + +static void +qauthz_pam_register_types(void) +{ + type_register_static(&qauthz_pam_info); +} + + +type_init(qauthz_pam_register_types); diff --git a/authz/trace-events b/authz/trace-events index fb65349a90..72c411927d 100644 --- a/authz/trace-events +++ b/authz/trace-events @@ -13,3 +13,6 @@ qauthz_list_default_policy(void *authz, const char *ident= ity, int policy) "AuthZ # auth/listfile.c qauthz_list_file_load(void *authz, const char *filename) "AuthZ file %p lo= ad filename=3D%s" qauthz_list_file_refresh(void *authz, const char *filename, int success) "= AuthZ file %p load filename=3D%s success=3D%d" + +# auth/pam.c +qauthz_pam_check(void *authz, const char *identity, const char *service) "= AuthZ PAM %p identity=3D%s service=3D%s" diff --git a/configure b/configure index a61682c3c7..4fe916e31f 100755 --- a/configure +++ b/configure @@ -463,6 +463,7 @@ gnutls=3D"" nettle=3D"" gcrypt=3D"" gcrypt_hmac=3D"no" +auth_pam=3D"" vte=3D"" virglrenderer=3D"" tpm=3D"yes" @@ -1381,6 +1382,10 @@ for opt do ;; --enable-gcrypt) gcrypt=3D"yes" ;; + --disable-auth-pam) auth_pam=3D"no" + ;; + --enable-auth-pam) auth_pam=3D"yes" + ;; --enable-rdma) rdma=3D"yes" ;; --disable-rdma) rdma=3D"no" @@ -1707,6 +1712,7 @@ disabled with --disable-FEATURE, default is enabled i= f available: gnutls GNUTLS cryptography support nettle nettle cryptography support gcrypt libgcrypt cryptography support + auth-pam PAM access control sdl SDL UI sdl_image SDL Image support for icons gtk gtk UI @@ -2864,6 +2870,33 @@ else fi =20 =20 +########################################## +# PAM probe + +if test "x$auth_pam" !=3D "no"; then + cat > $TMPC < +#include +int main(void) { + const char *service_name =3D "qemu"; + const char *user =3D "frank"; + const struct pam_conv *pam_conv =3D NULL; + pam_handle_t *pamh =3D NULL; + pam_start(service_name, user, pam_conv, &pamh); + return 0; +} +EOF + if compile_prog "" "-lpam" ; then + auth_pam=3Dyes + else + if test "$auth_pam" =3D "yes"; then + feature_not_found "PAM" "Install PAM development package" + else + auth_pam=3Dno + fi + fi +fi + ########################################## # getifaddrs (for tests/test-io-channel-socket ) =20 @@ -6083,6 +6116,7 @@ echo "GNUTLS support $gnutls" echo "libgcrypt $gcrypt" echo "nettle $nettle $(echo_version $nettle $nettle_version)" echo "libtasn1 $tasn1" +echo "PAM $auth_pam" echo "curses support $curses" echo "virgl support $virglrenderer $(echo_version $virglrenderer $virg= l_version)" echo "curl support $curl" @@ -6537,6 +6571,9 @@ fi if test "$tasn1" =3D "yes" ; then echo "CONFIG_TASN1=3Dy" >> $config_host_mak fi +if test "$auth_pam" =3D "yes" ; then + echo "CONFIG_AUTH_PAM=3Dy" >> $config_host_mak +fi if test "$have_ifaddrs_h" =3D "yes" ; then echo "HAVE_IFADDRS_H=3Dy" >> $config_host_mak fi diff --git a/include/authz/pamacct.h b/include/authz/pamacct.h new file mode 100644 index 0000000000..6e3046e528 --- /dev/null +++ b/include/authz/pamacct.h @@ -0,0 +1,100 @@ +/* + * QEMU PAM authorization driver + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#ifndef QAUTHZ_PAM_H__ +#define QAUTHZ_PAM_H__ + +#include "authz/base.h" + + +#define TYPE_QAUTHZ_PAM "authz-pam" + +#define QAUTHZ_PAM_CLASS(klass) \ + OBJECT_CLASS_CHECK(QAuthZPAMClass, (klass), \ + TYPE_QAUTHZ_PAM) +#define QAUTHZ_PAM_GET_CLASS(obj) \ + OBJECT_GET_CLASS(QAuthZPAMClass, (obj), \ + TYPE_QAUTHZ_PAM) +#define QAUTHZ_PAM(obj) \ + INTERFACE_CHECK(QAuthZPAM, (obj), \ + TYPE_QAUTHZ_PAM) + +typedef struct QAuthZPAM QAuthZPAM; +typedef struct QAuthZPAMClass QAuthZPAMClass; + + +/** + * QAuthZPAM: + * + * This authorization driver provides a PAM mechanism + * for granting access by matching user names against a + * list of globs. Each match rule has an associated policy + * and a catch all policy applies if no rule matches + * + * To create an instance of this class via QMP: + * + * { + * "execute": "object-add", + * "arguments": { + * "qom-type": "authz-pam", + * "id": "authz0", + * "parameters": { + * "service": "qemu-vnc-tls" + * } + * } + * } + * + * The driver only uses the PAM "account" verification + * subsystem. The above config would require a config + * file /etc/pam.d/qemu-vnc-tls. For a simple file + * lookup it would contain + * + * account requisite pam_listfile.so item=3Duser sense=3Dallow \ + * file=3D/etc/qemu/vnc.allow + * + * The external file would then contain a list of usernames. + * If x509 cert was being used as the username, a suitable + * entry would match the distinguish name: + * + * CN=3Dlaptop.berrange.com,O=3DBerrange Home,L=3DLondon,ST=3DLondon,C=3D= GB + * + * On the command line it can be created using + * + * -object authz-pam,id=3Dauthz0,service=3Dqemu-vnc-tls + * + */ +struct QAuthZPAM { + QAuthZ parent_obj; + + char *service; +}; + + +struct QAuthZPAMClass { + QAuthZClass parent_class; +}; + + +QAuthZPAM *qauthz_pam_new(const char *id, + const char *service, + Error **errp); + + +#endif /* QAUTHZ_PAM_H__ */ diff --git a/qemu-options.hx b/qemu-options.hx index e34d30a013..22cfb32489 100644 --- a/qemu-options.hx +++ b/qemu-options.hx @@ -4430,6 +4430,41 @@ would look like: ... @end example =20 +@item -object authz-pam,id=3D@var{id},service=3D@var{string} + +Create an authorization object that will control access to network service= s. + +The @option{service} parameter provides the name of a PAM service to use +for authorization. It requires that a file @code{/etc/pam.d/@var{service}} +exist to provide the configuration for the @code{account} subsystem. + +An example authorization object to validate a TLS x509 distinguished +name would look like: + +@example + # $QEMU \ + ... + -object authz-pam,id=3Dauth0,service=3Dqemu-vnc + ... +@end example + +There would then be a corresponding config file for PAM at +@code{/etc/pam.d/qemu-vnc} that contains: + +@example +account requisite pam_listfile.so item=3Duser sense=3Dallow \ + file=3D/etc/qemu/vnc.allow +@end example + +Finally the @code{/etc/qemu/vnc.allow} file would contain +the list of x509 distingished names that are permitted +access + +@example +CN=3Dlaptop.example.com,O=3DExample Home,L=3DLondon,ST=3DLondon,C=3DGB +@end example + + @end table =20 ETEXI diff --git a/tests/Makefile.include b/tests/Makefile.include index 199e74d670..bc11d565a6 100644 --- a/tests/Makefile.include +++ b/tests/Makefile.include @@ -119,6 +119,7 @@ check-unit-y +=3D tests/test-util-sockets$(EXESUF) check-unit-y +=3D tests/test-authz-simple$(EXESUF) check-unit-y +=3D tests/test-authz-list$(EXESUF) check-unit-y +=3D tests/test-authz-listfile$(EXESUF) +check-unit-$(CONFIG_AUTH_PAM) +=3D tests/test-authz-pam$(EXESUF) check-unit-y +=3D tests/test-io-task$(EXESUF) check-unit-y +=3D tests/test-io-channel-socket$(EXESUF) check-unit-y +=3D tests/test-io-channel-file$(EXESUF) @@ -669,6 +670,7 @@ tests/test-util-sockets$(EXESUF): tests/test-util-socke= ts.o \ tests/test-authz-simple$(EXESUF): tests/test-authz-simple.o $(test-authz-o= bj-y) tests/test-authz-list$(EXESUF): tests/test-authz-list.o $(test-authz-obj-y) tests/test-authz-listfile$(EXESUF): tests/test-authz-listfile.o $(test-aut= hz-obj-y) +tests/test-authz-pam$(EXESUF): tests/test-authz-pam.o $(test-authz-obj-y) tests/test-io-task$(EXESUF): tests/test-io-task.o $(test-io-obj-y) tests/test-io-channel-socket$(EXESUF): tests/test-io-channel-socket.o \ tests/io-channel-helpers.o tests/socket-helpers.o $(test-io-obj-y) diff --git a/tests/test-authz-pam.c b/tests/test-authz-pam.c new file mode 100644 index 0000000000..93d5ac8bbf --- /dev/null +++ b/tests/test-authz-pam.c @@ -0,0 +1,124 @@ +/* + * QEMU PAM authorization object tests + * + * Copyright (c) 2018 Red Hat, Inc. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + */ + +#include "qemu/osdep.h" +#include "qapi/error.h" +#include "authz/pamacct.h" + +#include + +static bool failauth; + +/* + * These two functions are exported by libpam.so. + * + * By defining them again here, our impls are resolved + * by the linker instead of those in libpam.so + * + * The test suite is thus isolated from the host system + * PAM setup, so we can do predictable test scenarios + */ +int +pam_start(const char *service_name, const char *user, + const struct pam_conv *pam_conversation, + pam_handle_t **pamh) +{ + failauth =3D true; + if (!g_str_equal(service_name, "qemu-vnc")) { + return PAM_AUTH_ERR; + } + + if (g_str_equal(user, "fred")) { + failauth =3D false; + } + + return PAM_SUCCESS; +} + + +int +pam_acct_mgmt(pam_handle_t *pamh, int flags) +{ + if (failauth) { + return PAM_AUTH_ERR; + } + + return PAM_SUCCESS; +} + + +static void test_authz_unknown_service(void) +{ + Error *local_err =3D NULL; + QAuthZPAM *auth =3D qauthz_pam_new("auth0", + "qemu-does-not-exist", + &error_abort); + + g_assert_nonnull(auth); + + g_assert_false(qauthz_is_allowed(QAUTHZ(auth), "fred", &local_err)); + + error_free_or_abort(&local_err); + object_unparent(OBJECT(auth)); +} + + +static void test_authz_good_user(void) +{ + QAuthZPAM *auth =3D qauthz_pam_new("auth0", + "qemu-vnc", + &error_abort); + + g_assert_nonnull(auth); + + g_assert_true(qauthz_is_allowed(QAUTHZ(auth), "fred", &error_abort)); + + object_unparent(OBJECT(auth)); +} + + +static void test_authz_bad_user(void) +{ + Error *local_err =3D NULL; + QAuthZPAM *auth =3D qauthz_pam_new("auth0", + "qemu-vnc", + &error_abort); + + g_assert_nonnull(auth); + + g_assert_false(qauthz_is_allowed(QAUTHZ(auth), "bob", &local_err)); + + error_free_or_abort(&local_err); + object_unparent(OBJECT(auth)); +} + + +int main(int argc, char **argv) +{ + g_test_init(&argc, &argv, NULL); + + module_call_init(MODULE_INIT_QOM); + + g_test_add_func("/auth/pam/unknown-service", test_authz_unknown_servic= e); + g_test_add_func("/auth/pam/good-user", test_authz_good_user); + g_test_add_func("/auth/pam/bad-user", test_authz_bad_user); + + return g_test_run(); +} --=20 2.20.1 From nobody Sun May 5 13:38:15 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) client-ip=209.51.188.17; envelope-from=qemu-devel-bounces+importer=patchew.org@nongnu.org; helo=lists.gnu.org; Authentication-Results: mx.zohomail.com; spf=pass (zoho.com: domain of gnu.org designates 209.51.188.17 as permitted sender) smtp.mailfrom=qemu-devel-bounces+importer=patchew.org@nongnu.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) by mx.zohomail.com with SMTPS id 1550246793074475.9645765122332; Fri, 15 Feb 2019 08:06:33 -0800 (PST) Received: from localhost ([127.0.0.1]:42110 helo=lists.gnu.org) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gug0T-00034D-Ri for importer@patchew.org; Fri, 15 Feb 2019 11:06:29 -0500 Received: from eggs.gnu.org ([209.51.188.92]:47061) by lists.gnu.org with esmtp (Exim 4.71) (envelope-from ) id 1gufsp-0005Yz-JT for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:39 -0500 Received: from Debian-exim by eggs.gnu.org with spam-scanned (Exim 4.71) (envelope-from ) id 1gufsm-0003OJ-Jx for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:35 -0500 Received: from mx1.redhat.com ([209.132.183.28]:51394) by eggs.gnu.org with esmtps (TLS1.0:DHE_RSA_AES_256_CBC_SHA1:32) (Exim 4.71) (envelope-from ) id 1gufsj-0003L0-Da for qemu-devel@nongnu.org; Fri, 15 Feb 2019 10:58:32 -0500 Received: from smtp.corp.redhat.com (int-mx07.intmail.prod.int.phx2.redhat.com [10.5.11.22]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mx1.redhat.com (Postfix) with ESMTPS id 621603F156; Fri, 15 Feb 2019 15:58:26 +0000 (UTC) Received: from localhost.localdomain.com (ovpn-112-65.ams2.redhat.com [10.36.112.65]) by smtp.corp.redhat.com (Postfix) with ESMTP id 39B6E10018FB; Fri, 15 Feb 2019 15:58:19 +0000 (UTC) From: =?UTF-8?q?Daniel=20P=2E=20Berrang=C3=A9?= To: qemu-devel@nongnu.org Date: Fri, 15 Feb 2019 15:57:09 +0000 Message-Id: <20190215155709.15777-12-berrange@redhat.com> In-Reply-To: <20190215155709.15777-1-berrange@redhat.com> References: <20190215155709.15777-1-berrange@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.84 on 10.5.11.22 X-Greylist: Sender IP whitelisted, not delayed by milter-greylist-4.5.16 (mx1.redhat.com [10.5.110.27]); Fri, 15 Feb 2019 15:58:26 +0000 (UTC) Content-Transfer-Encoding: quoted-printable X-detected-operating-system: by eggs.gnu.org: GNU/Linux 2.2.x-3.x [generic] X-Received-From: 209.132.183.28 Subject: [Qemu-devel] [PATCH v8 11/11] authz: delete existing ACL implementation X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.21 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: =?UTF-8?q?Philippe=20Mathieu-Daud=C3=A9?= , Markus Armbruster , "Dr. David Alan Gilbert" , Gerd Hoffmann , =?UTF-8?q?Marc-Andr=C3=A9=20Lureau?= , =?UTF-8?q?Andreas=20F=C3=A4rber?= Errors-To: qemu-devel-bounces+importer=patchew.org@nongnu.org Sender: "Qemu-devel" Content-Type: text/plain; charset="utf-8" From: "Daniel P. Berrange" The 'qemu_acl' type was a previous non-QOM based attempt to provide an authorization facility in QEMU. Because it is non-QOM based it cannot be created via the command line and requires special monitor commands to manipulate it. The new QAuthZ subclasses provide a superset of the functionality in qemu_acl, so the latter can now be deleted. The HMP 'acl_*' monitor commands are converted to use the new QAuthZSimple data type instead in order to provide temporary backwards compatibility. Reviewed-by: Philippe Mathieu-Daud=C3=A9 Tested-by: Philippe Mathieu-Daud=C3=A9 Signed-off-by: Daniel P. Berrange --- configure | 17 ---- crypto/tlssession.c | 35 ++++--- crypto/trace-events | 2 +- include/qemu/acl.h | 66 ------------ monitor.c | 179 ++++++++++++++++++++++----------- tests/Makefile.include | 4 +- tests/test-crypto-tlssession.c | 15 ++- tests/test-io-channel-tls.c | 16 ++- ui/vnc-auth-sasl.c | 23 +++-- ui/vnc-auth-sasl.h | 5 +- ui/vnc-auth-vencrypt.c | 2 +- ui/vnc-ws.c | 2 +- ui/vnc.c | 37 ++++--- ui/vnc.h | 4 +- util/Makefile.objs | 1 - util/acl.c | 179 --------------------------------- 16 files changed, 209 insertions(+), 378 deletions(-) delete mode 100644 include/qemu/acl.h delete mode 100644 util/acl.c diff --git a/configure b/configure index 4fe916e31f..65a8c8c1db 100755 --- a/configure +++ b/configure @@ -3205,20 +3205,6 @@ if test "$xkbcommon" !=3D "no" ; then fi fi =20 -########################################## -# fnmatch() probe, used for ACL routines -fnmatch=3D"no" -cat > $TMPC << EOF -#include -int main(void) -{ - fnmatch("foo", "foo", 0); - return 0; -} -EOF -if compile_prog "" "" ; then - fnmatch=3D"yes" -fi =20 ########################################## # xfsctl() probe, used for file-posix.c @@ -6408,9 +6394,6 @@ if test "$xkbcommon" =3D "yes" ; then echo "XKBCOMMON_CFLAGS=3D$xkbcommon_cflags" >> $config_host_mak echo "XKBCOMMON_LIBS=3D$xkbcommon_libs" >> $config_host_mak fi -if test "$fnmatch" =3D "yes" ; then - echo "CONFIG_FNMATCH=3Dy" >> $config_host_mak -fi if test "$xfs" =3D "yes" ; then echo "CONFIG_XFS=3Dy" >> $config_host_mak fi diff --git a/crypto/tlssession.c b/crypto/tlssession.c index 0dedd4af52..c3a920dfe8 100644 --- a/crypto/tlssession.c +++ b/crypto/tlssession.c @@ -24,7 +24,7 @@ #include "crypto/tlscredspsk.h" #include "crypto/tlscredsx509.h" #include "qapi/error.h" -#include "qemu/acl.h" +#include "authz/base.h" #include "trace.h" =20 #ifdef CONFIG_GNUTLS @@ -37,7 +37,7 @@ struct QCryptoTLSSession { QCryptoTLSCreds *creds; gnutls_session_t handle; char *hostname; - char *aclname; + char *authzid; bool handshakeComplete; QCryptoTLSSessionWriteFunc writeFunc; QCryptoTLSSessionReadFunc readFunc; @@ -56,7 +56,7 @@ qcrypto_tls_session_free(QCryptoTLSSession *session) gnutls_deinit(session->handle); g_free(session->hostname); g_free(session->peername); - g_free(session->aclname); + g_free(session->authzid); object_unref(OBJECT(session->creds)); g_free(session); } @@ -95,7 +95,7 @@ qcrypto_tls_session_pull(void *opaque, void *buf, size_t = len) QCryptoTLSSession * qcrypto_tls_session_new(QCryptoTLSCreds *creds, const char *hostname, - const char *aclname, + const char *authzid, QCryptoTLSCredsEndpoint endpoint, Error **errp) { @@ -105,13 +105,13 @@ qcrypto_tls_session_new(QCryptoTLSCreds *creds, session =3D g_new0(QCryptoTLSSession, 1); trace_qcrypto_tls_session_new( session, creds, hostname ? hostname : "", - aclname ? aclname : "", endpoint); + authzid ? authzid : "", endpoint); =20 if (hostname) { session->hostname =3D g_strdup(hostname); } - if (aclname) { - session->aclname =3D g_strdup(aclname); + if (authzid) { + session->authzid =3D g_strdup(authzid); } session->creds =3D creds; object_ref(OBJECT(creds)); @@ -262,6 +262,7 @@ qcrypto_tls_session_check_certificate(QCryptoTLSSession= *session, unsigned int nCerts, i; time_t now; gnutls_x509_crt_t cert =3D NULL; + Error *err =3D NULL; =20 now =3D time(NULL); if (now =3D=3D ((time_t)-1)) { @@ -349,19 +350,17 @@ qcrypto_tls_session_check_certificate(QCryptoTLSSessi= on *session, gnutls_strerror(ret)); goto error; } - if (session->aclname) { - qemu_acl *acl =3D qemu_acl_find(session->aclname); - int allow; - if (!acl) { - error_setg(errp, "Cannot find ACL %s", - session->aclname); + if (session->authzid) { + bool allow; + + allow =3D qauthz_is_allowed_by_id(session->authzid, + session->peername, &err); + if (err) { + error_propagate(errp, err); goto error; } - - allow =3D qemu_acl_party_is_allowed(acl, session->peername= ); - if (!allow) { - error_setg(errp, "TLS x509 ACL check for %s is denied", + error_setg(errp, "TLS x509 authz check for %s is denie= d", session->peername); goto error; } @@ -555,7 +554,7 @@ qcrypto_tls_session_get_peer_name(QCryptoTLSSession *se= ssion) QCryptoTLSSession * qcrypto_tls_session_new(QCryptoTLSCreds *creds G_GNUC_UNUSED, const char *hostname G_GNUC_UNUSED, - const char *aclname G_GNUC_UNUSED, + const char *authzid G_GNUC_UNUSED, QCryptoTLSCredsEndpoint endpoint G_GNUC_UNUSED, Error **errp) { diff --git a/crypto/trace-events b/crypto/trace-events index 597389b73c..a38ad7b787 100644 --- a/crypto/trace-events +++ b/crypto/trace-events @@ -19,5 +19,5 @@ qcrypto_tls_creds_x509_load_cert(void *creds, int isServe= r, const char *file) "T qcrypto_tls_creds_x509_load_cert_list(void *creds, const char *file) "TLS = creds x509 load cert list creds=3D%p file=3D%s" =20 # crypto/tlssession.c -qcrypto_tls_session_new(void *session, void *creds, const char *hostname, = const char *aclname, int endpoint) "TLS session new session=3D%p creds=3D%p= hostname=3D%s aclname=3D%s endpoint=3D%d" +qcrypto_tls_session_new(void *session, void *creds, const char *hostname, = const char *authzid, int endpoint) "TLS session new session=3D%p creds=3D%p= hostname=3D%s authzid=3D%s endpoint=3D%d" qcrypto_tls_session_check_creds(void *session, const char *status) "TLS se= ssion check creds session=3D%p status=3D%s" diff --git a/include/qemu/acl.h b/include/qemu/acl.h deleted file mode 100644 index 73d2a71c8d..0000000000 --- a/include/qemu/acl.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * QEMU access control list management - * - * Copyright (C) 2009 Red Hat, Inc - * - * Permission is hereby granted, free of charge, to any person obtaining a= copy - * of this software and associated documentation files (the "Software"), t= o deal - * in the Software without restriction, including without limitation the r= ights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or se= ll - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included= in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS= OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OT= HER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING= FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS = IN - * THE SOFTWARE. - */ - -#ifndef QEMU_ACL_H -#define QEMU_ACL_H - -#include "qemu/queue.h" - -typedef struct qemu_acl_entry qemu_acl_entry; -typedef struct qemu_acl qemu_acl; - -struct qemu_acl_entry { - char *match; - int deny; - - QTAILQ_ENTRY(qemu_acl_entry) next; -}; - -struct qemu_acl { - char *aclname; - unsigned int nentries; - QTAILQ_HEAD(,qemu_acl_entry) entries; - int defaultDeny; -}; - -qemu_acl *qemu_acl_init(const char *aclname); - -qemu_acl *qemu_acl_find(const char *aclname); - -int qemu_acl_party_is_allowed(qemu_acl *acl, - const char *party); - -void qemu_acl_reset(qemu_acl *acl); - -int qemu_acl_append(qemu_acl *acl, - int deny, - const char *match); -int qemu_acl_insert(qemu_acl *acl, - int deny, - const char *match, - int index); -int qemu_acl_remove(qemu_acl *acl, - const char *match); - -#endif /* QEMU_ACL_H */ diff --git a/monitor.c b/monitor.c index e5de5765b8..b2a5ae5374 100644 --- a/monitor.c +++ b/monitor.c @@ -51,7 +51,8 @@ #include "sysemu/balloon.h" #include "qemu/timer.h" #include "sysemu/hw_accel.h" -#include "qemu/acl.h" +#include "authz/list.h" +#include "qapi/util.h" #include "sysemu/tpm.h" #include "qapi/qmp/qdict.h" #include "qapi/qmp/qerror.h" @@ -2052,93 +2053,148 @@ static void hmp_wavcapture(Monitor *mon, const QDi= ct *qdict) QLIST_INSERT_HEAD (&capture_head, s, entries); } =20 -static qemu_acl *find_acl(Monitor *mon, const char *name) +static QAuthZList *find_auth(Monitor *mon, const char *name) { - qemu_acl *acl =3D qemu_acl_find(name); + Object *obj; + Object *container; =20 - if (!acl) { + container =3D object_get_objects_root(); + obj =3D object_resolve_path_component(container, name); + if (!obj) { monitor_printf(mon, "acl: unknown list '%s'\n", name); + return NULL; } - return acl; + + return QAUTHZ_LIST(obj); } =20 static void hmp_acl_show(Monitor *mon, const QDict *qdict) { const char *aclname =3D qdict_get_str(qdict, "aclname"); - qemu_acl *acl =3D find_acl(mon, aclname); - qemu_acl_entry *entry; - int i =3D 0; - - if (acl) { - monitor_printf(mon, "policy: %s\n", - acl->defaultDeny ? "deny" : "allow"); - QTAILQ_FOREACH(entry, &acl->entries, next) { - i++; - monitor_printf(mon, "%d: %s %s\n", i, - entry->deny ? "deny" : "allow", entry->match); - } + QAuthZList *auth =3D find_auth(mon, aclname); + QAuthZListRuleList *rules; + size_t i =3D 0; + + if (!auth) { + return; + } + + monitor_printf(mon, "policy: %s\n", + QAuthZListPolicy_str(auth->policy)); + + rules =3D auth->rules; + while (rules) { + QAuthZListRule *rule =3D rules->value; + i++; + monitor_printf(mon, "%zu: %s %s\n", i, + QAuthZListPolicy_str(rule->policy), + rule->match); + rules =3D rules->next; } } =20 static void hmp_acl_reset(Monitor *mon, const QDict *qdict) { const char *aclname =3D qdict_get_str(qdict, "aclname"); - qemu_acl *acl =3D find_acl(mon, aclname); + QAuthZList *auth =3D find_auth(mon, aclname); =20 - if (acl) { - qemu_acl_reset(acl); - monitor_printf(mon, "acl: removed all rules\n"); + if (!auth) { + return; } + + auth->policy =3D QAUTHZ_LIST_POLICY_DENY; + qapi_free_QAuthZListRuleList(auth->rules); + auth->rules =3D NULL; + monitor_printf(mon, "acl: removed all rules\n"); } =20 static void hmp_acl_policy(Monitor *mon, const QDict *qdict) { const char *aclname =3D qdict_get_str(qdict, "aclname"); const char *policy =3D qdict_get_str(qdict, "policy"); - qemu_acl *acl =3D find_acl(mon, aclname); + QAuthZList *auth =3D find_auth(mon, aclname); + int val; + Error *err =3D NULL; =20 - if (acl) { - if (strcmp(policy, "allow") =3D=3D 0) { - acl->defaultDeny =3D 0; + if (!auth) { + return; + } + + val =3D qapi_enum_parse(&QAuthZListPolicy_lookup, + policy, + QAUTHZ_LIST_POLICY_DENY, + &err); + if (err) { + error_free(err); + monitor_printf(mon, "acl: unknown policy '%s', " + "expected 'deny' or 'allow'\n", policy); + } else { + auth->policy =3D val; + if (auth->policy =3D=3D QAUTHZ_LIST_POLICY_ALLOW) { monitor_printf(mon, "acl: policy set to 'allow'\n"); - } else if (strcmp(policy, "deny") =3D=3D 0) { - acl->defaultDeny =3D 1; - monitor_printf(mon, "acl: policy set to 'deny'\n"); } else { - monitor_printf(mon, "acl: unknown policy '%s', " - "expected 'deny' or 'allow'\n", policy); + monitor_printf(mon, "acl: policy set to 'deny'\n"); } } } =20 +static QAuthZListFormat hmp_acl_get_format(const char *match) +{ + if (strchr(match, '*')) { + return QAUTHZ_LIST_FORMAT_GLOB; + } else { + return QAUTHZ_LIST_FORMAT_EXACT; + } +} + static void hmp_acl_add(Monitor *mon, const QDict *qdict) { const char *aclname =3D qdict_get_str(qdict, "aclname"); const char *match =3D qdict_get_str(qdict, "match"); - const char *policy =3D qdict_get_str(qdict, "policy"); + const char *policystr =3D qdict_get_str(qdict, "policy"); int has_index =3D qdict_haskey(qdict, "index"); int index =3D qdict_get_try_int(qdict, "index", -1); - qemu_acl *acl =3D find_acl(mon, aclname); - int deny, ret; - - if (acl) { - if (strcmp(policy, "allow") =3D=3D 0) { - deny =3D 0; - } else if (strcmp(policy, "deny") =3D=3D 0) { - deny =3D 1; - } else { - monitor_printf(mon, "acl: unknown policy '%s', " - "expected 'deny' or 'allow'\n", policy); - return; - } - if (has_index) - ret =3D qemu_acl_insert(acl, deny, match, index); - else - ret =3D qemu_acl_append(acl, deny, match); - if (ret < 0) - monitor_printf(mon, "acl: unable to add acl entry\n"); - else - monitor_printf(mon, "acl: added rule at position %d\n", ret); + QAuthZList *auth =3D find_auth(mon, aclname); + Error *err =3D NULL; + QAuthZListPolicy policy; + QAuthZListFormat format; + size_t i =3D 0; + + if (!auth) { + return; + } + + policy =3D qapi_enum_parse(&QAuthZListPolicy_lookup, + policystr, + QAUTHZ_LIST_POLICY_DENY, + &err); + if (err) { + error_free(err); + monitor_printf(mon, "acl: unknown policy '%s', " + "expected 'deny' or 'allow'\n", policystr); + return; + } + + format =3D hmp_acl_get_format(match); + + if (has_index && index =3D=3D 0) { + monitor_printf(mon, "acl: unable to add acl entry\n"); + return; + } + + if (has_index) { + i =3D qauthz_list_insert_rule(auth, match, policy, + format, index - 1, &err); + } else { + i =3D qauthz_list_append_rule(auth, match, policy, + format, &err); + } + if (err) { + monitor_printf(mon, "acl: unable to add rule: %s", + error_get_pretty(err)); + error_free(err); + } else { + monitor_printf(mon, "acl: added rule at position %zu\n", i + 1); } } =20 @@ -2146,15 +2202,18 @@ static void hmp_acl_remove(Monitor *mon, const QDic= t *qdict) { const char *aclname =3D qdict_get_str(qdict, "aclname"); const char *match =3D qdict_get_str(qdict, "match"); - qemu_acl *acl =3D find_acl(mon, aclname); - int ret; + QAuthZList *auth =3D find_auth(mon, aclname); + ssize_t i =3D 0; =20 - if (acl) { - ret =3D qemu_acl_remove(acl, match); - if (ret < 0) - monitor_printf(mon, "acl: no matching acl entry\n"); - else - monitor_printf(mon, "acl: removed rule at position %d\n", ret); + if (!auth) { + return; + } + + i =3D qauthz_list_delete_rule(auth, match); + if (i >=3D 0) { + monitor_printf(mon, "acl: removed rule at position %zu\n", i + 1); + } else { + monitor_printf(mon, "acl: no matching acl entry\n"); } } =20 diff --git a/tests/Makefile.include b/tests/Makefile.include index bc11d565a6..1792b1115a 100644 --- a/tests/Makefile.include +++ b/tests/Makefile.include @@ -537,8 +537,8 @@ test-qom-obj-y =3D $(qom-obj-y) $(test-util-obj-y) test-qapi-obj-y =3D tests/test-qapi-visit.o tests/test-qapi-types.o \ tests/test-qapi-introspect.o \ $(test-qom-obj-y) -benchmark-crypto-obj-y =3D $(crypto-obj-y) $(test-qom-obj-y) -test-crypto-obj-y =3D $(crypto-obj-y) $(test-qom-obj-y) +benchmark-crypto-obj-y =3D $(authz-obj-y) $(crypto-obj-y) $(test-qom-obj-y) +test-crypto-obj-y =3D $(authz-obj-y) $(crypto-obj-y) $(test-qom-obj-y) test-io-obj-y =3D $(io-obj-y) $(test-crypto-obj-y) test-authz-obj-y =3D $(test-qom-obj-y) $(authz-obj-y) test-block-obj-y =3D $(block-obj-y) $(test-io-obj-y) tests/iothread.o diff --git a/tests/test-crypto-tlssession.c b/tests/test-crypto-tlssession.c index 6fa9950afb..15212ec276 100644 --- a/tests/test-crypto-tlssession.c +++ b/tests/test-crypto-tlssession.c @@ -28,7 +28,7 @@ #include "qom/object_interfaces.h" #include "qapi/error.h" #include "qemu/sockets.h" -#include "qemu/acl.h" +#include "authz/list.h" =20 #ifdef QCRYPTO_HAVE_TLS_TEST_SUPPORT =20 @@ -229,7 +229,7 @@ static void test_crypto_tls_session_x509(const void *op= aque) QCryptoTLSCreds *serverCreds; QCryptoTLSSession *clientSess =3D NULL; QCryptoTLSSession *serverSess =3D NULL; - qemu_acl *acl; + QAuthZList *auth; const char * const *wildcards; int channel[2]; bool clientShake =3D false; @@ -285,11 +285,15 @@ static void test_crypto_tls_session_x509(const void *= opaque) SERVER_CERT_DIR); g_assert(serverCreds !=3D NULL); =20 - acl =3D qemu_acl_init("tlssessionacl"); - qemu_acl_reset(acl); + auth =3D qauthz_list_new("tlssessionacl", + QAUTHZ_LIST_POLICY_DENY, + &error_abort); wildcards =3D data->wildcards; while (wildcards && *wildcards) { - qemu_acl_append(acl, 0, *wildcards); + qauthz_list_append_rule(auth, *wildcards, + QAUTHZ_LIST_POLICY_ALLOW, + QAUTHZ_LIST_FORMAT_GLOB, + &error_abort); wildcards++; } =20 @@ -377,6 +381,7 @@ static void test_crypto_tls_session_x509(const void *op= aque) =20 object_unparent(OBJECT(serverCreds)); object_unparent(OBJECT(clientCreds)); + object_unparent(OBJECT(auth)); =20 qcrypto_tls_session_free(serverSess); qcrypto_tls_session_free(clientSess); diff --git a/tests/test-io-channel-tls.c b/tests/test-io-channel-tls.c index 4900c6d433..43b707eba7 100644 --- a/tests/test-io-channel-tls.c +++ b/tests/test-io-channel-tls.c @@ -29,8 +29,8 @@ #include "io-channel-helpers.h" #include "crypto/init.h" #include "crypto/tlscredsx509.h" -#include "qemu/acl.h" #include "qapi/error.h" +#include "authz/list.h" #include "qom/object_interfaces.h" =20 #ifdef QCRYPTO_HAVE_TLS_TEST_SUPPORT @@ -113,7 +113,7 @@ static void test_io_channel_tls(const void *opaque) QIOChannelTLS *serverChanTLS; QIOChannelSocket *clientChanSock; QIOChannelSocket *serverChanSock; - qemu_acl *acl; + QAuthZList *auth; const char * const *wildcards; int channel[2]; struct QIOChannelTLSHandshakeData clientHandshake =3D { false, false }; @@ -161,11 +161,15 @@ static void test_io_channel_tls(const void *opaque) SERVER_CERT_DIR); g_assert(serverCreds !=3D NULL); =20 - acl =3D qemu_acl_init("channeltlsacl"); - qemu_acl_reset(acl); + auth =3D qauthz_list_new("channeltlsacl", + QAUTHZ_LIST_POLICY_DENY, + &error_abort); wildcards =3D data->wildcards; while (wildcards && *wildcards) { - qemu_acl_append(acl, 0, *wildcards); + qauthz_list_append_rule(auth, *wildcards, + QAUTHZ_LIST_POLICY_ALLOW, + QAUTHZ_LIST_FORMAT_GLOB, + &error_abort); wildcards++; } =20 @@ -253,6 +257,8 @@ static void test_io_channel_tls(const void *opaque) object_unref(OBJECT(serverChanSock)); object_unref(OBJECT(clientChanSock)); =20 + object_unparent(OBJECT(auth)); + close(channel[0]); close(channel[1]); } diff --git a/ui/vnc-auth-sasl.c b/ui/vnc-auth-sasl.c index 3751a777a4..7b2b09f242 100644 --- a/ui/vnc-auth-sasl.c +++ b/ui/vnc-auth-sasl.c @@ -24,6 +24,7 @@ =20 #include "qemu/osdep.h" #include "qapi/error.h" +#include "authz/base.h" #include "vnc.h" #include "trace.h" =20 @@ -146,13 +147,14 @@ size_t vnc_client_read_sasl(VncState *vs) static int vnc_auth_sasl_check_access(VncState *vs) { const void *val; - int err; - int allow; + int rv; + Error *err =3D NULL; + bool allow; =20 - err =3D sasl_getprop(vs->sasl.conn, SASL_USERNAME, &val); - if (err !=3D SASL_OK) { + rv =3D sasl_getprop(vs->sasl.conn, SASL_USERNAME, &val); + if (rv !=3D SASL_OK) { trace_vnc_auth_fail(vs, vs->auth, "Cannot fetch SASL username", - sasl_errstring(err, NULL, NULL)); + sasl_errstring(rv, NULL, NULL)); return -1; } if (val =3D=3D NULL) { @@ -163,12 +165,19 @@ static int vnc_auth_sasl_check_access(VncState *vs) vs->sasl.username =3D g_strdup((const char*)val); trace_vnc_auth_sasl_username(vs, vs->sasl.username); =20 - if (vs->vd->sasl.acl =3D=3D NULL) { + if (vs->vd->sasl.authzid =3D=3D NULL) { trace_vnc_auth_sasl_acl(vs, 1); return 0; } =20 - allow =3D qemu_acl_party_is_allowed(vs->vd->sasl.acl, vs->sasl.usernam= e); + allow =3D qauthz_is_allowed_by_id(vs->vd->sasl.authzid, + vs->sasl.username, &err); + if (err) { + trace_vnc_auth_fail(vs, vs->auth, "Error from authz", + error_get_pretty(err)); + error_free(err); + return -1; + } =20 trace_vnc_auth_sasl_acl(vs, allow); return allow ? 0 : -1; diff --git a/ui/vnc-auth-sasl.h b/ui/vnc-auth-sasl.h index 2ae224ee3a..fb55fe04ca 100644 --- a/ui/vnc-auth-sasl.h +++ b/ui/vnc-auth-sasl.h @@ -30,8 +30,8 @@ typedef struct VncStateSASL VncStateSASL; typedef struct VncDisplaySASL VncDisplaySASL; =20 -#include "qemu/acl.h" #include "qemu/main-loop.h" +#include "authz/base.h" =20 struct VncStateSASL { sasl_conn_t *conn; @@ -60,7 +60,8 @@ struct VncStateSASL { }; =20 struct VncDisplaySASL { - qemu_acl *acl; + QAuthZ *authz; + char *authzid; }; =20 void vnc_sasl_client_cleanup(VncState *vs); diff --git a/ui/vnc-auth-vencrypt.c b/ui/vnc-auth-vencrypt.c index d99ea362c1..f072e16ace 100644 --- a/ui/vnc-auth-vencrypt.c +++ b/ui/vnc-auth-vencrypt.c @@ -109,7 +109,7 @@ static int protocol_client_vencrypt_auth(VncState *vs, = uint8_t *data, size_t len tls =3D qio_channel_tls_new_server( vs->ioc, vs->vd->tlscreds, - vs->vd->tlsaclname, + vs->vd->tlsauthzid, &err); if (!tls) { trace_vnc_auth_fail(vs, vs->auth, "TLS setup failed", diff --git a/ui/vnc-ws.c b/ui/vnc-ws.c index 950f1cd2ac..95c9703c72 100644 --- a/ui/vnc-ws.c +++ b/ui/vnc-ws.c @@ -62,7 +62,7 @@ gboolean vncws_tls_handshake_io(QIOChannel *ioc G_GNUC_UN= USED, tls =3D qio_channel_tls_new_server( vs->ioc, vs->vd->tlscreds, - vs->vd->tlsaclname, + vs->vd->tlsauthzid, &err); if (!tls) { VNC_DEBUG("Failed to setup TLS %s\n", error_get_pretty(err)); diff --git a/ui/vnc.c b/ui/vnc.c index 0fef646fc4..f4b335eb5f 100644 --- a/ui/vnc.c +++ b/ui/vnc.c @@ -33,7 +33,7 @@ #include "qemu/option.h" #include "qemu/sockets.h" #include "qemu/timer.h" -#include "qemu/acl.h" +#include "authz/list.h" #include "qemu/config-file.h" #include "qapi/qapi-events.h" #include "qapi/error.h" @@ -3228,12 +3228,24 @@ static void vnc_display_close(VncDisplay *vd) object_unparent(OBJECT(vd->tlscreds)); vd->tlscreds =3D NULL; } - g_free(vd->tlsaclname); - vd->tlsaclname =3D NULL; + if (vd->tlsauthz) { + object_unparent(OBJECT(vd->tlsauthz)); + vd->tlsauthz =3D NULL; + } + g_free(vd->tlsauthzid); + vd->tlsauthzid =3D NULL; if (vd->lock_key_sync) { qemu_remove_led_event_handler(vd->led); vd->led =3D NULL; } +#ifdef CONFIG_VNC_SASL + if (vd->sasl.authz) { + object_unparent(OBJECT(vd->sasl.authz)); + vd->sasl.authz =3D NULL; + } + g_free(vd->sasl.authzid); + vd->sasl.authzid =3D NULL; +#endif } =20 int vnc_display_password(const char *id, const char *password) @@ -3886,23 +3898,24 @@ void vnc_display_open(const char *id, Error **errp) =20 if (acl) { if (strcmp(vd->id, "default") =3D=3D 0) { - vd->tlsaclname =3D g_strdup("vnc.x509dname"); + vd->tlsauthzid =3D g_strdup("vnc.x509dname"); } else { - vd->tlsaclname =3D g_strdup_printf("vnc.%s.x509dname", vd->id); + vd->tlsauthzid =3D g_strdup_printf("vnc.%s.x509dname", vd->id); } - qemu_acl_init(vd->tlsaclname); + vd->tlsauthz =3D QAUTHZ(qauthz_list_new(vd->tlsauthzid, + QAUTHZ_LIST_POLICY_DENY, + &error_abort)); } #ifdef CONFIG_VNC_SASL if (acl && sasl) { - char *aclname; - if (strcmp(vd->id, "default") =3D=3D 0) { - aclname =3D g_strdup("vnc.username"); + vd->sasl.authzid =3D g_strdup("vnc.username"); } else { - aclname =3D g_strdup_printf("vnc.%s.username", vd->id); + vd->sasl.authzid =3D g_strdup_printf("vnc.%s.username", vd->id= ); } - vd->sasl.acl =3D qemu_acl_init(aclname); - g_free(aclname); + vd->sasl.authz =3D QAUTHZ(qauthz_list_new(vd->sasl.authzid, + QAUTHZ_LIST_POLICY_DENY, + &error_abort)); } #endif =20 diff --git a/ui/vnc.h b/ui/vnc.h index 81daa7a0eb..ee3da08f4a 100644 --- a/ui/vnc.h +++ b/ui/vnc.h @@ -39,6 +39,7 @@ #include "io/channel-socket.h" #include "io/channel-tls.h" #include "io/net-listener.h" +#include "authz/base.h" #include =20 #include "keymaps.h" @@ -178,7 +179,8 @@ struct VncDisplay bool lossy; bool non_adaptive; QCryptoTLSCreds *tlscreds; - char *tlsaclname; + QAuthZ *tlsauthz; + char *tlsauthzid; #ifdef CONFIG_VNC_SASL VncDisplaySASL sasl; #endif diff --git a/util/Makefile.objs b/util/Makefile.objs index c1dd746902..0808575e3e 100644 --- a/util/Makefile.objs +++ b/util/Makefile.objs @@ -20,7 +20,6 @@ util-obj-y +=3D envlist.o path.o module.o util-obj-y +=3D host-utils.o util-obj-y +=3D bitmap.o bitops.o hbitmap.o util-obj-y +=3D fifo8.o -util-obj-y +=3D acl.o util-obj-y +=3D cacheinfo.o util-obj-y +=3D error.o qemu-error.o util-obj-y +=3D id.o diff --git a/util/acl.c b/util/acl.c deleted file mode 100644 index c105addadc..0000000000 --- a/util/acl.c +++ /dev/null @@ -1,179 +0,0 @@ -/* - * QEMU access control list management - * - * Copyright (C) 2009 Red Hat, Inc - * - * Permission is hereby granted, free of charge, to any person obtaining a= copy - * of this software and associated documentation files (the "Software"), t= o deal - * in the Software without restriction, including without limitation the r= ights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or se= ll - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included= in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS= OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OT= HER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING= FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS = IN - * THE SOFTWARE. - */ - - -#include "qemu/osdep.h" -#include "qemu-common.h" -#include "qemu/acl.h" - -#ifdef CONFIG_FNMATCH -#include -#endif - - -static unsigned int nacls =3D 0; -static qemu_acl **acls =3D NULL; - - - -qemu_acl *qemu_acl_find(const char *aclname) -{ - int i; - for (i =3D 0 ; i < nacls ; i++) { - if (strcmp(acls[i]->aclname, aclname) =3D=3D 0) - return acls[i]; - } - - return NULL; -} - -qemu_acl *qemu_acl_init(const char *aclname) -{ - qemu_acl *acl; - - acl =3D qemu_acl_find(aclname); - if (acl) - return acl; - - acl =3D g_malloc(sizeof(*acl)); - acl->aclname =3D g_strdup(aclname); - /* Deny by default, so there is no window of "open - * access" between QEMU starting, and the user setting - * up ACLs in the monitor */ - acl->defaultDeny =3D 1; - - acl->nentries =3D 0; - QTAILQ_INIT(&acl->entries); - - acls =3D g_realloc(acls, sizeof(*acls) * (nacls +1)); - acls[nacls] =3D acl; - nacls++; - - return acl; -} - -int qemu_acl_party_is_allowed(qemu_acl *acl, - const char *party) -{ - qemu_acl_entry *entry; - - QTAILQ_FOREACH(entry, &acl->entries, next) { -#ifdef CONFIG_FNMATCH - if (fnmatch(entry->match, party, 0) =3D=3D 0) - return entry->deny ? 0 : 1; -#else - /* No fnmatch, so fallback to exact string matching - * instead of allowing wildcards */ - if (strcmp(entry->match, party) =3D=3D 0) - return entry->deny ? 0 : 1; -#endif - } - - return acl->defaultDeny ? 0 : 1; -} - - -void qemu_acl_reset(qemu_acl *acl) -{ - qemu_acl_entry *entry, *next_entry; - - /* Put back to deny by default, so there is no window - * of "open access" while the user re-initializes the - * access control list */ - acl->defaultDeny =3D 1; - QTAILQ_FOREACH_SAFE(entry, &acl->entries, next, next_entry) { - QTAILQ_REMOVE(&acl->entries, entry, next); - g_free(entry->match); - g_free(entry); - } - acl->nentries =3D 0; -} - - -int qemu_acl_append(qemu_acl *acl, - int deny, - const char *match) -{ - qemu_acl_entry *entry; - - entry =3D g_malloc(sizeof(*entry)); - entry->match =3D g_strdup(match); - entry->deny =3D deny; - - QTAILQ_INSERT_TAIL(&acl->entries, entry, next); - acl->nentries++; - - return acl->nentries; -} - - -int qemu_acl_insert(qemu_acl *acl, - int deny, - const char *match, - int index) -{ - qemu_acl_entry *tmp; - int i =3D 0; - - if (index <=3D 0) - return -1; - if (index > acl->nentries) { - return qemu_acl_append(acl, deny, match); - } - - QTAILQ_FOREACH(tmp, &acl->entries, next) { - i++; - if (i =3D=3D index) { - qemu_acl_entry *entry; - entry =3D g_malloc(sizeof(*entry)); - entry->match =3D g_strdup(match); - entry->deny =3D deny; - - QTAILQ_INSERT_BEFORE(tmp, entry, next); - acl->nentries++; - break; - } - } - - return i; -} - -int qemu_acl_remove(qemu_acl *acl, - const char *match) -{ - qemu_acl_entry *entry; - int i =3D 0; - - QTAILQ_FOREACH(entry, &acl->entries, next) { - i++; - if (strcmp(entry->match, match) =3D=3D 0) { - QTAILQ_REMOVE(&acl->entries, entry, next); - acl->nentries--; - g_free(entry->match); - g_free(entry); - return i; - } - } - return -1; -} --=20 2.20.1