Skip to contentSkip to conversation

random: introduce getrandom(2) system call

RFC PATCH In review Theodore Ts'o 16 participants 35 messages Jul 17, 2014 – Jul 23, 2014 5 messages not in the archive

Subsystems (5)
lore
Share & tools
lore

Theodore Ts'o

author maintainer
#0 lore raw

RFC PATCH 1/1 random: introduce getrandom(2) system call

The getrandom(2) system call was requested by the LibreSSL Portable developers. It is analoguous to the getentropy(2) system call in OpenBSD.

The rationale of this system call is to provide resiliance against file descriptor exhaustion attacks, where the attacker consumes all available file descriptors, forcing the use of the fallback code where /dev/[u]random is not available. Since the fallback code is often not well-tested, it is better to eliminate this potential failure mode entirely.

The other feature provided by this new system call is the ability to request randomness from the /dev/urandom entropy pool, but to block until at least 128 bits of entropy has been accumulated in the /dev/urandom entropy pool. Historically, the emphasis in the /dev/urandom development has been to ensure that urandom pool is initialized as quickly as possible after system boot, and preferably before the init scripts start execution. This is because changing /dev/urandom reads to block represents an interface change that could potentially break userspace which is not acceptable. In practice, on most x86 desktop and server systems, in general the entropy pool can be initialized before it is needed (and in modern kernels, we will printk a warning message if not). However, on an embedded system, this may not be hte case. And so with a new interface, we can provide this requested functionality of blocking until the urandom pool has been initialized. Any userspace program which uses this new functionality must make sure that if it is used in early boot, that it will not cause the boot up scripts or other portions of the system startup to hang indefinitely.

SYNOPSIS

	#include <linux/random.h>

	int getrandom(void *buf, size_t buflen, unsigned int flags);

DESCRIPTION

The system call getrandom() fills the buffer pointed to by buf with up to buflen random bytes which can be used to seed user space random number generators (i.e., DRBG's) or for other cryptographic processes. It should not be used Monte Carlo simulations or for other probabilistic sampling applications.

If the GRND_RANDOM flags bit is set, then draw from the /dev/random pool instead of /dev/urandom pool. The /dev/random pool is limited based on the entropy that can be obtained from environmental noise, so if there is insufficient entropy, the requested number of bytes may not be returned. If there is no entropy available at all, getrandom(2) will either return an error with errno set to EAGAIN, or block if the GRND_BLOCK flags bit is set.

If the GRND_RANDOM flags bit is not set, then the /dev/raundom pool will be used. Unlike reading from the /dev/urandom, if the urandom pool has not been sufficiently initialized, getrandom(2) will either return an error with errno set to EGAIN, or block if the GRND_BLOCK flags bit is set.

RETURN VALUE
On success, the number of bytes that was returned is returned.

On error, -1 is returned, and errno is set appropriately

ERRORS
EINVAL The buflen value was invalid.

EFAULT buf is outside your accessible address space.

EAGAIN The requested entropy was not available, and the
getentropy(2) would have blocked if GRND_BLOCK flag was set.

---
 arch/x86/syscalls/syscall_32.tbl  |  1 +
 arch/x86/syscalls/syscall_64.tbl  |  1 +
 drivers/char/random.c             | 35 +++++++++++++++++++++++++++++++++--
 include/linux/syscalls.h          |  3 +++
 include/uapi/asm-generic/unistd.h |  4 +++-
 include/uapi/linux/random.h       |  9 +++++++++
 6 files changed, 50 insertions(+), 3 deletions(-)
arch/x86/syscalls/syscall_32.tbl +1 -0
index d6b8679..f484e39 100644
@@ -360,3 +360,4 @@
 351	i386	sched_setattr		sys_sched_setattr
 352	i386	sched_getattr		sys_sched_getattr
 353	i386	renameat2		sys_renameat2
+354	i386	getrandom		sys_getrandom
arch/x86/syscalls/syscall_64.tbl +1 -0
index ec255a1..6705032 100644
@@ -323,6 +323,7 @@
 314	common	sched_setattr		sys_sched_setattr
 315	common	sched_getattr		sys_sched_getattr
 316	common	renameat2		sys_renameat2
+317	common	getrandom		sys_getrandom
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
drivers/char/random.c +33 -2
index aa22fe5..76a56f6 100644
@@ -258,6 +258,8 @@
 #include <linux/kmemcheck.h>
 #include <linux/workqueue.h>
 #include <linux/irq.h>
+#include <linux/syscalls.h>
+#include <linux/completion.h>
 
 #include <asm/processor.h>
 #include <asm/uaccess.h>
@@ -469,6 +471,8 @@ static struct entropy_store nonblocking_pool = {
 					push_to_pool),
 };
 
+DECLARE_COMPLETION(urandom_initialized);
+
 static __u32 const twist_table[8] = {
 	0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
 	0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
@@ -657,6 +661,7 @@ retry:
 		r->entropy_total = 0;
 		if (r == &nonblocking_pool) {
 			prandom_reseed_late();
+			complete_all(&urandom_initialized);
 			pr_notice("random: %s pool is initialized\n", r->name);
 		}
 	}
@@ -1355,7 +1360,7 @@ static int arch_random_refill(void)
 }
 
 static ssize_t
-random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
+_random_read(int nonblock, char __user *buf, size_t nbytes)
 {
 	ssize_t n;
 
@@ -1379,7 +1384,7 @@ random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
 		if (arch_random_refill())
 			continue;
 
-		if (file->f_flags & O_NONBLOCK)
+		if (nonblock)
 			return -EAGAIN;
 
 		wait_event_interruptible(random_read_wait,
@@ -1391,6 +1396,12 @@ random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
 }
 
 static ssize_t
+random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
+{
+	return _random_read(file->f_flags & O_NONBLOCK, buf, nbytes);
+}
+
+static ssize_t
 urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
 {
 	int ret;
@@ -1533,6 +1544,26 @@ const struct file_operations urandom_fops = {
 	.llseek = noop_llseek,
 };
 
+SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
+		unsigned int, flags)
+{
+	int r;
+
+	if (count > 256)
+		return -EINVAL;
+
+	if (flags & GRND_RANDOM) {
+		return _random_read(!(flags & GRND_BLOCK), buf, count);
+	}
+	if (flags & GRND_BLOCK) {
+		r = wait_for_completion_interruptible(&urandom_initialized);
+		if (r)
+			return r;
+	} else if (!completion_done(&urandom_initialized))
+		return -EAGAIN;
+	return urandom_read(NULL, buf, count, NULL);
+}
+
 /***************************************************************
  * Random UUID interface
  *
include/linux/syscalls.h +3 -0
index b0881a0..cd82f72f 100644
@@ -866,4 +866,7 @@ asmlinkage long sys_process_vm_writev(pid_t pid,
 asmlinkage long sys_kcmp(pid_t pid1, pid_t pid2, int type,
 			 unsigned long idx1, unsigned long idx2);
 asmlinkage long sys_finit_module(int fd, const char __user *uargs, int flags);
+asmlinkage long sys_getrandom(char __user * buf, size_t count,
+			      unsigned int flags);
+
 #endif
include/uapi/asm-generic/unistd.h +3 -1
index 3336406..2926b1d 100644
@@ -699,9 +699,11 @@ __SYSCALL(__NR_sched_setattr, sys_sched_setattr)
 __SYSCALL(__NR_sched_getattr, sys_sched_getattr)
 #define __NR_renameat2 276
 __SYSCALL(__NR_renameat2, sys_renameat2)
+#define __NR_getrandom 277
+__SYSCALL(__NR_getrandom, sys_getrandom)
 
 #undef __NR_syscalls
-#define __NR_syscalls 277
+#define __NR_syscalls 278
 
 /*
  * All syscalls below here should go away really,
include/uapi/linux/random.h +9 -0
index fff3528..6c13442 100644
@@ -40,4 +40,13 @@ struct rand_pool_info {
 	__u32	buf[0];
 };
 
+/*
+ * Flags for getrandom(2)
+ *
+ * GAND_BLOCK 		Allow getrandom(2) to block
+ * GAND_RANDOM		Use the /dev/random pool instead of /dev/urandom
+ */
+#define GRND_BLOCK	0x0001
+#define GRND_RANDOM	0x0002
+
 #endif /* _UAPI_LINUX_RANDOM_H */
Signature · 1 line
2.0.0
#1 lore raw
Quoted 4 lines · Theodore Ts'o

SYNOPSIS

	#include <linux/random.h>

	int getrandom(void *buf, size_t buflen, unsigned int flags);

Cool, I think the interface is sane.

Btw. couldn't libressl etc. fall back to binary_sysctl kernel.random.uuid and seed with that as a last resort? We have it available for few more years.

drivers/char/random.c const struct file_operations urandom_fops = { · line 1554

Quoted 8 lines
drivers/char/random.c +8 -0
+SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
+		unsigned int, flags)
+{
+	int r;
+
+	if (count > 256)
+		return -EINVAL;
+

Why this "arbitrary" limitation? Couldn't we just check for > SSIZE_MAX or to be more conservative to INT_MAX?

drivers/char/random.c const struct file_operations urandom_fops = { · line 1566

Quoted 12 lines
drivers/char/random.c +12 -0
+	if (flags & GRND_RANDOM) {
+		return _random_read(!(flags & GRND_BLOCK), buf, count);
+	}
+	if (flags & GRND_BLOCK) {
+		r = wait_for_completion_interruptible(&urandom_initialized);
+		if (r)
+			return r;
+	} else if (!completion_done(&urandom_initialized))
+		return -EAGAIN;
+	return urandom_read(NULL, buf, count, NULL);
+}
+

Great, thanks Ted,
Hannes

author maintainer
#2 lore raw
Quoted 4 lines · Hannes Frederic Sowa

Btw. couldn't libressl etc. fall back to binary_sysctl kernel.random.uuid and seed with that as a last resort? We have it available for few more years.

Yes, they could. But trying to avoid more uses of binary_sysctl seems to be a good thing, I think. The other thing is that is that this interface provides is the ability to block until the entropy pool is initialized, which isn't a big deal for x86 systems, but might be useful as a gentle forcing function to force ARM systems to figure out good ways of making sure the entropy pools are initialized (i.e., by actually providing !@#!@ cycle counter) without breaking userspace compatibility --- since this is a new interface.

Quoted 6 lines

drivers/char/random.c const struct file_operations urandom_fops = { · line 1554

Quoted 3 lines
drivers/char/random.c +3 -0
+	if (count > 256)
+		return -EINVAL;
+

Why this "arbitrary" limitation? Couldn't we just check for > SSIZE_MAX or to be more conservative to INT_MAX?

I'm not wedded to this limitation. OpenBSD's getentropy(2) has an architected arbitrary limit of 128 bytes. I haven't made a final decision if the right answer is to hard code some value, or make this limit be configurable, or remote the limit entirely (which in practice would be SSIZE_MAX or INT_MAX).

The main argument I can see for putting in a limit is to encourage the "proper" use of the interface. In practice, anything larger than 128 probably means the interface is getting misused, either due to a bug or some other kind of oversight.

For example, when I started instrumenting /dev/urandom, I caught Google Chrome pulling 4k out of /dev/urandom --- twice --- at startup time. It turns out it was the fault of the NSS library, which was using fopen() to access /dev/urandom. (Sigh.)

- Ted

#3 lore raw
Quoted 6 lines · Theodore Ts'o
Quoted 4 lines · Hannes Frederic Sowa

Btw. couldn't libressl etc. fall back to binary_sysctl kernel.random.uuid and seed with that as a last resort? We have it available for few more years.

Quoted 8 lines

Yes, they could. But trying to avoid more uses of binary_sysctl seems to be a good thing, I think. The other thing is that is that this interface provides is the ability to block until the entropy pool is initialized, which isn't a big deal for x86 systems, but might be useful as a gentle forcing function to force ARM systems to figure out good ways of making sure the entropy pools are initialized (i.e., by actually providing !@#!@ cycle counter) without breaking userspace compatibility --- since this is a new interface.

I am not questioning this new interface - I like it - just wanted to mention there is already a safe fallback for LibreSSL in the way they already seem to do it in OpenBSD (via sysctl).

Quoted 19 lines
Quoted 7 lines

drivers/char/random.c const struct file_operations urandom_fops = { · line 1554

Quoted 4 lines
drivers/char/random.c +3 -0
+	if (count > 256)
+		return -EINVAL;
+

Why this "arbitrary" limitation? Couldn't we just check for > SSIZE_MAX or to be more conservative to INT_MAX?

I'm not wedded to this limitation. OpenBSD's getentropy(2) has an architected arbitrary limit of 128 bytes. I haven't made a final decision if the right answer is to hard code some value, or make this limit be configurable, or remote the limit entirely (which in practice would be SSIZE_MAX or INT_MAX).

The main argument I can see for putting in a limit is to encourage the "proper" use of the interface. In practice, anything larger than 128 probably means the interface is getting misused, either due to a bug or some other kind of oversight.

Quoted 4 lines

For example, when I started instrumenting /dev/urandom, I caught Google Chrome pulling 4k out of /dev/urandom --- twice --- at startup time. It turns out it was the fault of the NSS library, which was using fopen() to access /dev/urandom. (Sigh.)

In the end people would just recall getentropy in a loop and fetch 256 bytes each time. I don't think the artificial limit does make any sense. I agree that this allows a potential misuse of the interface, but doesn't a warning in dmesg suffice?

It also makes it easier to port applications from open("/dev/*random"), read(...) to getentropy() by reusing the same limits.

I would vote for warning (at about 256 bytes) + no limit.

Thanks,
Hannes

#4 lore raw
In reply to Theodore Ts'o

On 2014-07-17 at 11:18:15 +0200, Theodore Ts'o <[email protected]> wrote:

[...]

Quoted 6 lines

+/*
+ * Flags for getrandom(2)
+ *
+ * GAND_BLOCK Allow getrandom(2) to block
+ * GAND_RANDOM Use the /dev/random pool instead of /dev/urandom
+ */

Very minor nitpick: These should probably read GRND_BLOCK/GRND_RANDOM as well, no?

Quoted 13 lines
include/uapi/linux/random.h +3 -0
+#define GRND_BLOCK	0x0001
+#define GRND_RANDOM	0x0002
+
 #endif /* _UAPI_LINUX_RANDOM_H */
Signature · 7 lines
2.0.0

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to [email protected]
More majordomo info at  http://vger.kernel.org/majordomo-info.html
Please read the FAQ at  http://www.tux.org/lkml/
author maintainer
#5 lore raw
Quoted 10 lines · Tobias Klauser
Quoted 7 lines

+/*
+ * Flags for getrandom(2)
+ *
+ * GAND_BLOCK Allow getrandom(2) to block
+ * GAND_RANDOM Use the /dev/random pool instead of /dev/urandom
+ */

Very minor nitpick: These should probably read GRND_BLOCK/GRND_RANDOM as well, no?

Thanks, typo. I'll get this fixed up.

- Ted

#6 lore raw
In reply to Theodore Ts'o
Quoted 3 lines · Theodore Ts'o

The getrandom(2) system call was requested by the LibreSSL Portable developers. It is analoguous to the getentropy(2) system call in OpenBSD.

What's the reason to not implement exactly the same system call OpenBSD does? Having slightly different names and semantics for the same functionality is highly annoying.

author maintainer
#7 lore raw
Quoted 8 lines · Christoph Hellwig
Quoted 3 lines · Theodore Ts'o

The getrandom(2) system call was requested by the LibreSSL Portable developers. It is analoguous to the getentropy(2) system call in OpenBSD.

What's the reason to not implement exactly the same system call OpenBSD does? Having slightly different names and semantics for the same functionality is highly annoying.

The getrandom(2) system call is a superset of getentropy(2). When we add the support for this into glibc, it won't be terribly difficult nor annoying to drop the following in alongside the standard support needed for any new system call:

int getentropy(void *buf, size_t buflen)

{
	int	ret;

	ret = getentropy(buf, buflen, 0);
	return (ret > 0) ? 0 : ret;
}

The reason for the additional flags is that I'm trying to solve more problems than just getentropy()'s raison d'etre. The discussion of this is in the commit description; let me know if there bits that I could make clearer.

Cheers,

- Ted

#8 lore raw

Hi Ted, yeah I understand the reasoning, it would be good if there was a way to influence the various libc people to
ensure they manage to provide a getentropy().

Quoted 31 lines · Theodore Ts'o
Quoted 8 lines · Christoph Hellwig
Quoted 3 lines · Theodore Ts'o

The getrandom(2) system call was requested by the LibreSSL Portable developers. It is analoguous to the getentropy(2) system call in OpenBSD.

What's the reason to not implement exactly the same system call OpenBSD does? Having slightly different names and semantics for the same functionality is highly annoying.

The getrandom(2) system call is a superset of getentropy(2). When we add the support for this into glibc, it won't be terribly difficult nor annoying to drop the following in alongside the standard support needed for any new system call:

int getentropy(void *buf, size_t buflen)

{
        int     ret;

        ret = getentropy(buf, buflen, 0);
        return (ret > 0) ? 0 : ret;
}

The reason for the additional flags is that I'm trying to solve more problems than just getentropy()'s raison d'etre. The discussion of this is in the commit description; let me know if there bits that I could make clearer.

Cheers,

- Ted

author maintainer
#9 lore raw
Quoted 3 lines · Bob Beck

Hi Ted, yeah I understand the reasoning, it would be good if there was a way to influence the various libc people to
ensure they manage to provide a getentropy().

I don't anticipate that to be a problem. And before they do, and/or if you are dealing with a system where the kernel has been upgraded, but not libc, you have your choice of either sticking with the binary_sysctl approach, or calling getrandom directly using the syscall method; and in that case, whether we use getrandom() or provide an exact getentropy() replacement system call isn't that much difference, since you'd have to have Linux-specific workaround code anyway....

- Ted

#10 lore raw

we have diffs pending that will do the syscall method until we start to see it in libc :)

So basically we're going to put that in right away :)

Quoted 15 lines · Theodore Ts'o
Quoted 3 lines · Bob Beck

Hi Ted, yeah I understand the reasoning, it would be good if there was a way to influence the various libc people to
ensure they manage to provide a getentropy().

I don't anticipate that to be a problem. And before they do, and/or if you are dealing with a system where the kernel has been upgraded, but not libc, you have your choice of either sticking with the binary_sysctl approach, or calling getrandom directly using the syscall method; and in that case, whether we use getrandom() or provide an exact getentropy() replacement system call isn't that much difference, since you'd have to have Linux-specific workaround code anyway....

- Ted

#11 lore raw

And thanks btw.

I don't suppose you guys know who we should talk to about possibly getting MAP_INHERIT_ZERO minherit() support?

Quoted 21 lines · Bob Beck

we have diffs pending that will do the syscall method until we start to see it in libc :)

So basically we're going to put that in right away :)

Quoted 15 lines · Theodore Ts'o
Quoted 3 lines · Bob Beck

Hi Ted, yeah I understand the reasoning, it would be good if there was a way to influence the various libc people to
ensure they manage to provide a getentropy().

I don't anticipate that to be a problem. And before they do, and/or if you are dealing with a system where the kernel has been upgraded, but not libc, you have your choice of either sticking with the binary_sysctl approach, or calling getrandom directly using the syscall method; and in that case, whether we use getrandom() or provide an exact getentropy() replacement system call isn't that much difference, since you'd have to have Linux-specific workaround code anyway....

- Ted

#12 lore raw

Or perhaps to put that another way, since you don't do minherit - maybe a FORK_ZERO for madvise? or a similar way
to do that?

Quoted 27 lines · Bob Beck

And thanks btw.

I don't suppose you guys know who we should talk to about possibly getting MAP_INHERIT_ZERO minherit() support?

Quoted 21 lines · Bob Beck

we have diffs pending that will do the syscall method until we start to see it in libc :)

So basically we're going to put that in right away :)

Quoted 15 lines · Theodore Ts'o
Quoted 3 lines · Bob Beck

Hi Ted, yeah I understand the reasoning, it would be good if there was a way to influence the various libc people to
ensure they manage to provide a getentropy().

I don't anticipate that to be a problem. And before they do, and/or if you are dealing with a system where the kernel has been upgraded, but not libc, you have your choice of either sticking with the binary_sysctl approach, or calling getrandom directly using the syscall method; and in that case, whether we use getrandom() or provide an exact getentropy() replacement system call isn't that much difference, since you'd have to have Linux-specific workaround code anyway....

- Ted

author maintainer
#13 lore raw
In reply to Bob Beck
Quoted 2 lines · Bob Beck

we have diffs pending that will do the syscall method until we start to see it in libc :)

One warning --- please don't check in the syscall number until it actually hits mainline. Kees has another patch outstanding for seccomp(2) that is using the same syscall numbers I have in my patch. Please treat the numbers in my patch as placeholders until it has been accepted and we see what numbers we actually get assigned.

Thanks,

- Ted

#14 lore raw
In reply to Theodore Ts'o

Hey Ted, one more nit. Yes, I have a bicycle too..

I see here we add a flag to make it block - whereas it seems most other system calls that can block the flag is
added to make it not block (I.E. O_NONBLOCK, etc. etc.) Would it make more sense to invert this so it was more
like the typical convention in other system calls?

Quoted 15 lines · Theodore Ts'o
Quoted 3 lines · Bob Beck

Hi Ted, yeah I understand the reasoning, it would be good if there was a way to influence the various libc people to
ensure they manage to provide a getentropy().

I don't anticipate that to be a problem. And before they do, and/or if you are dealing with a system where the kernel has been upgraded, but not libc, you have your choice of either sticking with the binary_sysctl approach, or calling getrandom directly using the syscall method; and in that case, whether we use getrandom() or provide an exact getentropy() replacement system call isn't that much difference, since you'd have to have Linux-specific workaround code anyway....

- Ted

A message that is not in the archive (sent off-list or not yet received): CAComcpObt4y--GEuAZgzkaDWnrJYBKhwsvqjOkdiXU_yGnV2Tg@mail.gmail.com

A message that is not in the archive (sent off-list or not yet received): CAComcpObt4y--GEuAZgzkaDWnrJYBKhwsvqjOkdiXU_yGnV2Tg-JsoAwUIsXosN+BqQ9rBEUg@public.gmane.org

#17 lore raw
Quoted 9 lines · Bob Beck
Quoted 9 lines

int getentropy(void *buf, size_t buflen)

{
        int     ret;

        ret = getentropy(buf, buflen, 0);
        return (ret > 0) ? 0 : ret;
}
Quoted 6 lines
Quoted 4 lines

The reason for the additional flags is that I'm trying to solve more problems than just getentropy()'s raison d'etre. The discussion of this is in the commit description; let me know if there bits that I could make clearer.

Ted is that the right flags with the new call so it doesn't block?

Yes, it's currently the correct flags. There are some people who are arguing for GRND_NONBLOCK instead of GRND_BLOCK. The original idea was that default should always be non-blocking, and you want 0 to be the default.

Quoted 2 lines · Zach Brown

Do we want it to block by default and have the flag be _NONBLOCK? Feels more.. familiar.

Yes, I'm starting to think so. In the default case where we are using the urandom pool, we *do* want the default to block until the pool is initialized. At least, the FreeBSD people have been whining forever that Linux is horribly insecure because we don't block until we are sure that we know that we have good entropy in the pool.

The git description explains why I haven't changed this to date; I didn't want to break userspace. In addition, I've been working awfully hard to make sure that least on x86 systems, that we gather enough system noise that despite the fact that we are being very conservative in our entropy estimation/accounting), the pool gets initialized very quickly.

My goal was that on x86 laptops and severs, that the pool would be fully initialized before the openssh scripts has a chance to run. We have a printk that triggers if something tries to read from /dev/urandom before it is fully initialized, and we seem to be doing pretty well. Systemd seems to want to read from /dev/urandom in very early boot:

Jul 11 21:14:10 closure kernel: [    2.941902] random: systemd urandom read with 109 bits of entropy available

.... but if you use the old-fashioned System V init scripts, it seems to work fairly well. :-)

So in practice, the fact that we block at system init time shouldn't be a hardship for LibreSSL in most cases --- and in the case where you are running on an embedded system where there are barely any devices, no cycle counter, and nothing that produces enough interrupts to initialize the pool, what would you prefer that we do? Return data that might not be fully "seed grade entropy"?

If you are determined to get data from a not a fully initialized entropy pool, then you can open /dev/urandom and get it via the old interface. In actual practice, this shouldn't happen except in very early boot, when any sane system wouldn't be trying to create long-term public keys anyway. (The fact that most systems try to create OpenSSH's host keys as the first thing after an out-of-the-Box first boot situation is something I've always considered Crazy-Eddie Bat-Shit Insane....) And that early in the boot sequence, it's highly unlikely that an attacker would be carrying out a fd exhaustion attack, since the network won't have been started. And if you are determined to get data even from an potentially insecure pool, and you can't open /dev/urandom due to a fd exhaustion attack, the right answer is to SIGKILL yourself anyway....

- Ted

A message that is not in the archive (sent off-list or not yet received): [email protected]

#19 lore raw
Quoted 10 lines · Theodore Ts'o

So in practice, the fact that we block at system init time shouldn't be a hardship for LibreSSL in most cases --- and in the case where you are running on an embedded system where there are barely any devices, no cycle counter, and nothing that produces enough interrupts to initialize the pool, what would you prefer that we do? Return data that might not be fully "seed grade entropy"?

If you are determined to get data from a not a fully initialized entropy pool, then you can open /dev/urandom and get it via the old interface.

That sounds reasonable. Maybe a slightly edited version of this writeup could be dropped in the man page to give people context?

Quoted 3 lines

(The fact that most systems try to create OpenSSH's host keys as the first thing after an out-of-the-Box first boot situation is something I've always considered Crazy-Eddie Bat-Shit Insane....)

(Seriously. My atrophied sysadmin muscles still still cringe at that.)

- z

A message that is not in the archive (sent off-list or not yet received): 20140717214450.GE24196-fypN+1c5dIyjpB87vu3CluTW4wlIGRCZ@public.gmane.org

#21 lore raw
Quoted 9 lines · Zach Brown
Quoted 7 lines · Theodore Ts'o

So in practice, the fact that we block at system init time shouldn't be a hardship for LibreSSL in most cases --- and in the case where you are running on an embedded system where there are barely any devices, no cycle counter, and nothing that produces enough interrupts to initialize the pool, what would you prefer that we do? Return data that might not be fully "seed grade entropy"?

Quoted 6 lines
Quoted 3 lines

If you are determined to get data from a not a fully initialized entropy pool, then you can open /dev/urandom and get it via the old interface.

That sounds reasonable. Maybe a slightly edited version of this writeup could be dropped in the man page to give people context?

And we'll be in a sad state in which we have a getrandom(2) syscall but there's no decent way to use srand without either opening /dev/urandom or mucking with AT_RANDOM. And the latter barely works because I think that most (all?) glibc versions clear it after using it to initialize their stack canaries.

This isn't a regression, and it isn't a reason to object to getrandom(2), but if getrandom(2) goes in as is, I'll submit a patch adding the new flag immediately.

--Andy

A message that is not in the archive (sent off-list or not yet received): CALCETrVC2SVC2BwintZ7P5MvwDO4z0VBe0svpWhVhx7Xgfoeag-JsoAwUIsXosN+BqQ9rBEUg@public.gmane.org

#23 lore raw
Quoted 6 lines · Andy Lutomirski

And we'll be in a sad state in which we have a getrandom(2) syscall but there's no decent way to use srand without either opening /dev/urandom or mucking with AT_RANDOM. And the latter barely works because I think that most (all?) glibc versions clear it after using it to initialize their stack canaries.

Sorry, I really don't think that supporting srand() is a good use of getrandom(2). If it's for non-crypto purposes, using getpid() and time() is *just* *fine*.

If we add such a flag, my big fear is that it gets misused. Sometimes it does make sense to create interfaces that a strong point of view. The primary use of getrandom(2) should be for cryptographic purposes, and trying to avoid misuse should be the primary objective.

- Ted

#24 lore raw
In reply to Theodore Ts'o
Quoted 13 lines · Theodore Ts'o

The getrandom(2) system call is a superset of getentropy(2). When we add the support for this into glibc, it won't be terribly difficult nor annoying to drop the following in alongside the standard support needed for any new system call:

int getentropy(void *buf, size_t buflen)

{
	int	ret;

	ret = getentropy(buf, buflen, 0);
	return (ret > 0) ? 0 : ret;
}
Quoted 4 lines

The reason for the additional flags is that I'm trying to solve more problems than just getentropy()'s raison d'etre. The discussion of this is in the commit description; let me know if there bits that I could make clearer.

This could still return predictable bytes during early boot, though, right?

Signature · 2 lines
Dwayne C. Litzenberger <[email protected]>
OpenPGP: 19E1 1FE8 B3CF F273 ED17  4A24 928C EC13 39C2 5CF7
#25 lore raw
In reply to Theodore Ts'o

On Thu, Jul 17, 2014 at 05:18:15AM -0400, Theodore Ts'o wrote:

Minor nit:

drivers/char/random.c static struct entropy_store nonblocking_pool = { · line 475

Quoted 6 lines
drivers/char/random.c +2 -0
@@ -469,6 +471,8 @@ static struct entropy_store nonblocking_pool = {
 					push_to_pool),
 };
 
+DECLARE_COMPLETION(urandom_initialized);
+

static DECLARE_COMPLETION(urandom_initialized);

instead?

thanks,

greg k-h

#26 lore raw
In reply to Theodore Ts'o
Quoted 9 lines · Theodore Ts'o
drivers/char/random.c +9 -0
+SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
+		unsigned int, flags)
+{
+	int r;
+
+	if (count > 256)
+		return -EINVAL;
+
+	if (flags & GRND_RANDOM) {

drivers/char/random.c const struct file_operations urandom_fops = { · line 1565

Quoted 10 lines
drivers/char/random.c +10 -0
+		return _random_read(!(flags & GRND_BLOCK), buf, count);
+	}
+	if (flags & GRND_BLOCK) {
+		r = wait_for_completion_interruptible(&urandom_initialized);
+		if (r)
+			return r;
+	} else if (!completion_done(&urandom_initialized))
+		return -EAGAIN;
+	return urandom_read(NULL, buf, count, NULL);
+}

You should fail if any other bits are set that you don't understand in the flags value, to make it easier for newer kernels with more flags to fail properly on old kernel releases.

thanks,

greg k-h

#27 lore raw
In reply to Theodore Ts'o
Quoted 4 lines

SYNOPSIS

	#include <linux/random.h>

	int getrandom(void *buf, size_t buflen, unsigned int flags);

I certainly like the idea of getting entropy without having to worry about fds.

Quoted 1 line

If the GRND_RANDOM flags bit is not set, then the /dev/raundom

(raundom typo)

Quoted 2 lines

RETURN VALUE
On success, the number of bytes that was returned is returned.

The description talks about filling the buffer, maybe say 'the number of bytes filled is returned'?

Quoted 1 line

+DECLARE_COMPLETION(urandom_initialized);

static?

drivers/char/random.c const struct file_operations urandom_fops = { · line 1551

Quoted 5 lines
drivers/char/random.c +5 -0
+SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
+		unsigned int, flags)
+{
+	int r;
+

Michael Kerrisk wants you to return -EINVAL on unknown flags :)

http://lwn.net/Articles/588444/

drivers/char/random.c const struct file_operations urandom_fops = { · line 1553

Quoted 2 lines
drivers/char/random.c +2 -0
+	if (count > 256)
+		return -EINVAL;

I'd vote for not having the limit. It seems easy enough to iterate over the buffer. We'd need to clamp the count to ssize_t, though.

drivers/char/random.c const struct file_operations urandom_fops = { · line 1557

Quoted 3 lines
drivers/char/random.c +3 -0
+	if (flags & GRND_RANDOM) {
+		return _random_read(!(flags & GRND_BLOCK), buf, count);
+	}

Do we want it to block by default and have the flag be _NONBLOCK? Feels more.. familiar.

drivers/char/random.c const struct file_operations urandom_fops = { · line 1561

Quoted 4 lines
drivers/char/random.c +4 -0
+	if (flags & GRND_BLOCK) {
+		r = wait_for_completion_interruptible(&urandom_initialized);
+		if (r)
+			return r;

I can *never* remember the rules for -ERESTARTSYS. The syscall callers take care of this?

drivers/char/random.c const struct file_operations urandom_fops = { · line 1564

Quoted 1 line
drivers/char/random.c +1 -0
+	return urandom_read(NULL, buf, count, NULL);

I wonder if we want to refactor the entry points a bit more instead of directly calling the device read functions. get_random_bytes() and urandom_read() both have their own uninitialied use warning message and tracing. Does the syscall want its own little extraction function as well?

- z

author maintainer
#28 lore raw
Quoted 8 lines · Zach Brown

drivers/char/random.c const struct file_operations urandom_fops = { · line 1564

Quoted 2 lines
drivers/char/random.c +1 -0
+	return urandom_read(NULL, buf, count, NULL);

I wonder if we want to refactor the entry points a bit more instead of directly calling the device read functions. get_random_bytes() and urandom_read() both have their own uninitialied use warning message and tracing. Does the syscall want its own little extraction function as well?

I'm not sure what warning you are worried about? urandom_read() never uses file or ppos, so passing in NULL works just fine as near as I can tell.

I could refactor the entropy point, but it probably wouldn't add any extra bloat, since the compiler would hopefully compile it away, but adding the extra static function would seem to make things less readable at least in my opinion.

- Ted

#29 lore raw
Quoted 11 lines · Theodore Ts'o
Quoted 5 lines · Zach Brown

drivers/char/random.c const struct file_operations urandom_fops = { · line 1564

Quoted 2 lines
drivers/char/random.c +1 -0
+	return urandom_read(NULL, buf, count, NULL);

I wonder if we want to refactor the entry points a bit more instead of directly calling the device read functions.

I could refactor the entropy point, but it probably wouldn't add any extra bloat, since the compiler would hopefully compile it away, but adding the extra static function would seem to make things less readable at least in my opinion.

Fair enough, I don't have a strong preference either way. It was just something I noticed when leafing through the (unfamiliar) code.

- z

#30 lore raw
In reply to Theodore Ts'o
Quoted 165 lines · Theodore Ts'o

The getrandom(2) system call was requested by the LibreSSL Portable developers. It is analoguous to the getentropy(2) system call in OpenBSD.

The rationale of this system call is to provide resiliance against file descriptor exhaustion attacks, where the attacker consumes all available file descriptors, forcing the use of the fallback code where /dev/[u]random is not available. Since the fallback code is often not well-tested, it is better to eliminate this potential failure mode entirely.

The other feature provided by this new system call is the ability to request randomness from the /dev/urandom entropy pool, but to block until at least 128 bits of entropy has been accumulated in the /dev/urandom entropy pool. Historically, the emphasis in the /dev/urandom development has been to ensure that urandom pool is initialized as quickly as possible after system boot, and preferably before the init scripts start execution. This is because changing /dev/urandom reads to block represents an interface change that could potentially break userspace which is not acceptable. In practice, on most x86 desktop and server systems, in general the entropy pool can be initialized before it is needed (and in modern kernels, we will printk a warning message if not). However, on an embedded system, this may not be hte case. And so with a new interface, we can provide this requested functionality of blocking until the urandom pool has been initialized. Any userspace program which uses this new functionality must make sure that if it is used in early boot, that it will not cause the boot up scripts or other portions of the system startup to hang indefinitely.

SYNOPSIS

	#include <linux/random.h>

	int getrandom(void *buf, size_t buflen, unsigned int flags);

DESCRIPTION

The system call getrandom() fills the buffer pointed to by buf with up to buflen random bytes which can be used to seed user space random number generators (i.e., DRBG's) or for other cryptographic processes. It should not be used Monte Carlo simulations or for other probabilistic sampling applications.

If the GRND_RANDOM flags bit is set, then draw from the /dev/random pool instead of /dev/urandom pool. The /dev/random pool is limited based on the entropy that can be obtained from environmental noise, so if there is insufficient entropy, the requested number of bytes may not be returned. If there is no entropy available at all, getrandom(2) will either return an error with errno set to EAGAIN, or block if the GRND_BLOCK flags bit is set.

If the GRND_RANDOM flags bit is not set, then the /dev/raundom pool will be used. Unlike reading from the /dev/urandom, if the urandom pool has not been sufficiently initialized, getrandom(2) will either return an error with errno set to EGAIN, or block if the GRND_BLOCK flags bit is set.

RETURN VALUE
On success, the number of bytes that was returned is returned.

On error, -1 is returned, and errno is set appropriately

ERRORS
EINVAL The buflen value was invalid.

EFAULT buf is outside your accessible address space.

EAGAIN The requested entropy was not available, and the
getentropy(2) would have blocked if GRND_BLOCK flag was set.

---
 arch/x86/syscalls/syscall_32.tbl  |  1 +
 arch/x86/syscalls/syscall_64.tbl  |  1 +
 drivers/char/random.c             | 35 +++++++++++++++++++++++++++++++++--
 include/linux/syscalls.h          |  3 +++
 include/uapi/asm-generic/unistd.h |  4 +++-
 include/uapi/linux/random.h       |  9 +++++++++
 6 files changed, 50 insertions(+), 3 deletions(-)
arch/x86/syscalls/syscall_32.tbl +1 -0
index d6b8679..f484e39 100644
@@ -360,3 +360,4 @@
 351	i386	sched_setattr		sys_sched_setattr
 352	i386	sched_getattr		sys_sched_getattr
 353	i386	renameat2		sys_renameat2
+354	i386	getrandom		sys_getrandom
arch/x86/syscalls/syscall_64.tbl +1 -0
index ec255a1..6705032 100644
@@ -323,6 +323,7 @@
 314	common	sched_setattr		sys_sched_setattr
 315	common	sched_getattr		sys_sched_getattr
 316	common	renameat2		sys_renameat2
+317	common	getrandom		sys_getrandom
 
 #
 # x32-specific system call numbers start at 512 to avoid cache impact
drivers/char/random.c +13 -2
index aa22fe5..76a56f6 100644
@@ -258,6 +258,8 @@
 #include <linux/kmemcheck.h>
 #include <linux/workqueue.h>
 #include <linux/irq.h>
+#include <linux/syscalls.h>
+#include <linux/completion.h>
 
 #include <asm/processor.h>
 #include <asm/uaccess.h>
@@ -469,6 +471,8 @@ static struct entropy_store nonblocking_pool = {
 					push_to_pool),
 };
 
+DECLARE_COMPLETION(urandom_initialized);
+
 static __u32 const twist_table[8] = {
 	0x00000000, 0x3b6e20c8, 0x76dc4190, 0x4db26158,
 	0xedb88320, 0xd6d6a3e8, 0x9b64c2b0, 0xa00ae278 };
@@ -657,6 +661,7 @@ retry:
 		r->entropy_total = 0;
 		if (r == &nonblocking_pool) {
 			prandom_reseed_late();
+			complete_all(&urandom_initialized);
 			pr_notice("random: %s pool is initialized\n", r->name);
 		}
 	}
@@ -1355,7 +1360,7 @@ static int arch_random_refill(void)
 }
 
 static ssize_t
-random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
+_random_read(int nonblock, char __user *buf, size_t nbytes)
 {
 	ssize_t n;
 
@@ -1379,7 +1384,7 @@ random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
 		if (arch_random_refill())
 			continue;
 
-		if (file->f_flags & O_NONBLOCK)
+		if (nonblock)
 			return -EAGAIN;
 
 		wait_event_interruptible(random_read_wait,
@@ -1391,6 +1396,12 @@ random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
 }
 
 static ssize_t
+random_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
+{
+	return _random_read(file->f_flags & O_NONBLOCK, buf, nbytes);
+}
+
+static ssize_t
 urandom_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos)
 {
 	int ret;

drivers/char/random.c const struct file_operations urandom_fops = { · line 1551

Quoted 8 lines
drivers/char/random.c +5 -0
@@ -1533,6 +1544,26 @@ const struct file_operations urandom_fops = {
 	.llseek = noop_llseek,
 };
 
+SYSCALL_DEFINE3(getrandom, char __user *, buf, size_t, count,
+		unsigned int, flags)
+{
+	int r;
+

As previously noted, this needs to validate flags.

drivers/char/random.c const struct file_operations urandom_fops = { · line 1553

Quoted 2 lines
drivers/char/random.c +2 -0
+	if (count > 256)
+		return -EINVAL;

I think I'd rather see this allow any length, at least when using urandom.

drivers/char/random.c const struct file_operations urandom_fops = { · line 1564

Quoted 11 lines
drivers/char/random.c +11 -0
+
+	if (flags & GRND_RANDOM) {
+		return _random_read(!(flags & GRND_BLOCK), buf, count);
+	}
+	if (flags & GRND_BLOCK) {
+		r = wait_for_completion_interruptible(&urandom_initialized);
+		if (r)
+			return r;
+	} else if (!completion_done(&urandom_initialized))
+		return -EAGAIN;
+	return urandom_read(NULL, buf, count, NULL);

This can return -ERESTARTSYS. Does it need any logic to restart correctly?

I don't think it's possible for the urandom case to succeed without filling the buffer. If that's true, can we document it and add a corresponding BUG_ON/WARN_ON in the syscall implementation?

--Andy

drivers/char/random.c const struct file_operations urandom_fops = { · line 1569

Quoted 5 lines
drivers/char/random.c +5 -0
+/*
+ * Flags for getrandom(2)
+ *
+ * GAND_BLOCK 		Allow getrandom(2) to block
+ * GAND_RANDOM		Use the /dev/random pool instead of /dev/urandom

GRND?

Quoted 6 lines
drivers/char/random.c +4 -0
+ */
+#define GRND_BLOCK	0x0001
+#define GRND_RANDOM	0x0002
+
 #endif /* _UAPI_LINUX_RANDOM_H */
author maintainer
#31 lore raw
Quoted 3 lines · Andy Lutomirski

drivers/char/random.c const struct file_operations urandom_fops = { · line 1564

Quoted 1 line
drivers/char/random.c +1 -0
+	return urandom_read(NULL, buf, count, NULL);

This can return -ERESTARTSYS. Does it need any logic to restart correctly?

Nope; because we only return -ERESTARTSYS when we haven't generated any randomness yet. The way /dev/urandom and /dev/random devices work is that if we get interrupted, we return a short read. We do *not* resume generation of random bytes from where we got interrupted from the signal handler.

This is consistent with the definition in the signal(7) man page:

If a blocked call to one of the following interfaces is interrupted by a signal handler, then the call will be automatically restarted after the signal handler returns if the SA_RESTART flag was used; otherwise the call will fail with the error EINTR:

* read(2), readv(2), write(2), writev(2), and ioctl(2) calls on "slow" devices. A "slow" device is one where the I/O call may block for an indefinite time, for example, a terminal, pipe, or socket. (A disk is not a slow device according to this definition.) If an I/O call on a slow device has already transferred some data by the time it is interrupted by a signal handler, then the call will return a success status (normally, the number of bytes transferred).

And in answer to Zach's question along these lines, ERESTARTSYS gets restarted or transformed into EINTR by the system call layer, so long as you only set ERESTARTSYS when signal_pending(current) is true. If you accidentally set the return value to ERESTARTSYS when a signal is not pending, this error code can escape out to user space, which is considered a bug. But we're using this correctly in drivers/char/random.c.

- Ted

#32 lore raw
In reply to Theodore Ts'o
Quoted 7 lines · Theodore Ts'o

DESCRIPTION

The system call getrandom() fills the buffer pointed to by buf with up to buflen random bytes which can be used to seed user space random number generators (i.e., DRBG's) or for other cryptographic processes. It should not be used Monte Carlo simulations or for other probabilistic sampling applications.

The "for" looks misplaced, shouldn't this be "for Monte Carlo simulations or other ..."?

Greetings,

Eike

#33 lore raw
In reply to Theodore Ts'o

include/uapi/asm-generic/unistd.h __SYSCALL(__NR_sched_setattr, sys_sched_setattr) · line 706

Quoted 4 lines · Theodore Ts'o

#undef __NR_syscalls

include/uapi/asm-generic/unistd.h +1 -1
-#define __NR_syscalls 277
+#define __NR_syscalls 278

You need to add the syscall to kernel/sys_ni.c too, otherwise it will be impossible to build without random device.

-Andi

Signature · 1 line
[email protected] -- Speaking for myself only
author maintainer
#34 lore raw
Quoted 8 lines · Andi Kleen

include/uapi/asm-generic/unistd.h __SYSCALL(__NR_sched_setattr, sys_sched_setattr) · line 706

Quoted 4 lines · Theodore Ts'o

#undef __NR_syscalls

include/uapi/asm-generic/unistd.h +1 -1
-#define __NR_syscalls 277
+#define __NR_syscalls 278

You need to add the syscall to kernel/sys_ni.c too, otherwise it will be impossible to build without random device.

The random device is not optional; it is alaways guaranteed to be present. From drivers/char/Makefile:

obj-y += mem.o random.o

Cheers,

- Ted

#35 lore raw
In reply to Theodore Ts'o
Quoted 2 lines · Theodore Ts'o

ERRORS
EINVAL The buflen value was invalid.

Also on unknown flags? Without that it would be impossible to probe for implemented flags.

Andreas.

Signature · 3 lines
Andreas Schwab, [email protected]
GPG Key fingerprint = 58CA 54C7 6D53 942B 1756  01D3 44D5 214B 8276 4ED5
"And now for something completely different."
author maintainer
#36 lore raw
Quoted 7 lines · Andreas Schwab
Quoted 2 lines · Theodore Ts'o

ERRORS
EINVAL The buflen value was invalid.

Also on unknown flags? Without that it would be impossible to probe for implemented flags.

We removed the cap on the buflen size (although if someone gives something insanely large, it can get capped), so EINVAL will only happen for unknown flags. I'll fix the suggested man page.

- Ted

P.S. The reason why OpenBSD had a very strong opinion about returning EIO for buflen greater than 256 bytes was they really wanted to pound it into application writers than if they were trying to fetch more than 256 bytes, they were probably Doing Something Wrong, and they decided EIO was less subtle that EINVAL....

#37 lore raw
In reply to Theodore Ts'o
Quoted 5 lines · Theodore Ts'o

SYNOPSIS

	#include <linux/random.h>

	int getrandom(void *buf, size_t buflen, unsigned int flags);
Quoted 7 lines

DESCRIPTION

The system call getrandom() fills the buffer pointed to by buf with up to buflen random bytes which can be used to seed user space random number generators (i.e., DRBG's) or for other cryptographic processes. It should not be used Monte Carlo simulations or for other probabilistic sampling applications.

Aside from poor performance for the offending application, will anything actually break if an application ignores this warning and makes heavy use of getrandom(2)? It would be helpful if the documentation made this clearer, rather than just saying, "don't do that".

As the developer of a userspace crypto library, I can't always prevent downstream developers from doing silly things, and many developers simply don't understand different "kinds" of random numbers, so I prefer to tell them to just use the kernel CSPRNG by default, and to ask for help once they run into performance problems. It's not ideal, but it's safer than the alternative.[1]

Quoted 15 lines

If the GRND_RANDOM flags bit is set, then draw from the /dev/random pool instead of /dev/urandom pool. The /dev/random pool is limited based on the entropy that can be obtained from environmental noise, so if there is insufficient entropy, the requested number of bytes may not be returned. If there is no entropy available at all, getrandom(2) will either return an error with errno set to EAGAIN, or block if the GRND_BLOCK flags bit is set.

If the GRND_RANDOM flags bit is not set, then the /dev/raundom pool will be used. Unlike reading from the /dev/urandom, if the urandom pool has not been sufficiently initialized, getrandom(2) will either return an error with errno set to EGAIN, or block if the GRND_BLOCK flags bit is set.

Quoted 4 lines

RETURN VALUE
On success, the number of bytes that was returned is returned.

On error, -1 is returned, and errno is set appropriately

Hm. Is it correct that, in blocking mode, the call is guaranteed either to return -EINVAL immediately, or to block until the buffer is *completely* populated with buflen bytes? If so, I think a few small changes could make this a really nice interface to work with:

* Use blocking mode by default.

* Add a new flag called GRND_PARTIAL (replacing GRND_BLOCK), which indicates that the caller is prepared to handle a partial/incomplete result.

* On success with GRND_PARTIAL, return the number of bytes that were written into buf. (Or -EAGAIN, as is currently done.)

* If GRND_PARTIAL is *not* set, just return 0 on success. (This avoids all signed-unsigned confusion when buflen > INT_MAX.)

With those changes, it would be trivial for a userspace library to implement a reliable RNG interface as recommended in [2] or [3]:

/*
* memzap(3)
*
* Fills the buffer pointed to by buf with exactly buflen random bytes
* suitable for cryptographic purposes. Nothing is returned. *
* This function is thread-safe, and is safe to call from inside a
* signal handler.
*
* It blocks if the kernel random number generator is not yet fully
* initialized (e.g. early in the boot process), and it may trigger
* abort(3) if invoked on an old kernel version that does not support
* the getrandom(2) system call.
*/
void memzap(void *buf, size_t buflen)

{
       int     ret;

       ret = getrandom(buf, buflen, 0);
       if (ret != 0) {
               perror("getrandom(2) failed");
               abort();
       }
}

Best,
- Dwayne

P.S. If I had my way, I would also drop GRND_RANDOM. Most software won't use it, there's no legacy installed base, and no developer who still wants that behavior can legitimately claim to care about RNG availability guarantees, IMHO. Anyone who really wants the old /dev/random behavior can always just continue to use the existing character device. I don't really care enough to put up a fight about it, though, as long as it doesn't affect the quality of the non-GRND_RANDOM interface.

[1] On more than one occasion, I've seen developers use Python's
standard "random" module to generate IVs. I mean, why not? IVs are public, right?
[2] http://cr.yp.to/highspeed/coolnacl-20120725.pdf
[3] https://groups.google.com/forum/#!msg/randomness-generation/4opmDHA6_3w/__TyKhbnNWsJ

Signature · 2 lines
Dwayne C. Litzenberger <[email protected]>
OpenPGP: 19E1 1FE8 B3CF F273 ED17  4A24 928C EC13 39C2 5CF7
author maintainer
#38 lore raw
Quoted 2 lines · Dwayne Litzenberger

This could still return predictable bytes during early boot, though, right?

Read the suggetsed man page; especially, the version of the man page in the commit description -v4 version of the patch.

getrandom(2) is a new interface, so I can afford do things differently from redaing from /dev/urandom. Specifically, it will block until it is fully initialized, and in GRND_NONBLOCK mode, it will return EAGAIN.

There have been some people kvetching and whining that this is less convenient for seeding srand(3), but for non-crypto uses, using getpid() and time() to seed random(3) or rand(3) is just fine, and if they really want, they can open /dev/urandom.

Quoted 9 lines
Quoted 5 lines

The system call getrandom() fills the buffer pointed to by buf with up to buflen random bytes which can be used to seed user space random number generators (i.e., DRBG's) or for other cryptographic processes. It should not be used Monte Carlo simulations or for other probabilistic sampling applications.

Aside from poor performance for the offending application, will anything actually break if an application ignores this warning and makes heavy use of getrandom(2)?

It will be slow, and then the graduate student will whine and complain and send a bug report. It will cause urandom to pull more heavily on entropy, and if that means that you are using some kind of hardware random generator on a laptop, such as tpm-rng, you will burn more battery, but no, it will not break. This is why the man page says
SHOULD not, and not MUST not. :-)

Quoted 6 lines

As the developer of a userspace crypto library, I can't always prevent downstream developers from doing silly things, and many developers simply don't understand different "kinds" of random numbers, so I prefer to tell them to just use the kernel CSPRNG by default, and to ask for help once they run into performance problems. It's not ideal, but it's safer than the alternative.[1]

Yes, but the point is that Monte Carlo simulations don't need any kind crypto guarantees.

Quoted 6 lines

Hm. Is it correct that, in blocking mode, the call is guaranteed either to return -EINVAL immediately, or to block until the buffer is *completely* populated with buflen bytes? If so, I think a few small changes could make this a really nice interface to work with:

* Use blocking mode by default.

Read the -v4 version of the patch. Blocking is now the default.

Quoted 3 lines

* Add a new flag called GRND_PARTIAL (replacing GRND_BLOCK), which indicates that the caller is prepared to handle a partial/incomplete result.

This is not needed if you are using the preferred use of flags == 0, and are extracting a sane amount of entropy. For values of buflen < 256 bytes, once urandom pool is initialized, getrandom(buf, buflen, 0) will not block and will always return the amount of entropy that you asked for.

But if the user asks for INT_MAX bytes, getrandom(2) must be interruptible, or else you will end up burning CPU time for a long, LONG, LONG time. The choice was to either pick some arbitrarily limit, such as 256, and then return EIO, which is what OpenBSD did. I decided to simply allow getrandom(2) to be interruptible if buflen > 256.

Similarly, if you use GRND_RANDOM, you are also implicitly agreeing for what you are calling GRND_PARTIAL semantics, because otherwise, you could end up blocking for a very long time, with no way to interrupt a buggy program.

I'd much rather keep things simple, and not add too many extra flags, especially when certain combination of flags result in a really unfriendly / insane result.

Quoted 2 lines

* If GRND_PARTIAL is *not* set, just return 0 on success. (This avoids all signed-unsigned confusion when buflen > INT_MAX.)

We simply cap any requests for buflen > INT_MAX, and in practice, it would take so long to generate the requested number of bytes that the user would want to interrupt the process anyway.

I considered adding a printk to shame any application writer that tried to ask for more than 256 bytes, but ultimately decided that was a bit over the top. But in any case, any request anywhere near INT_MAX bytes is really not anything I'm concerned about. If we do start seeing evidence for that, I might reconsider and add some kind of "Warning! The author of [current->comm] is asking for insane amounts of entropy" printk.

Quoted 2 lines

With those changes, it would be trivial for a userspace library to implement a reliable RNG interface as recommended in [2] or [3]:

The userspace library should ideally be integrted into glibc, so it is fork- and thread- aware, and it should use a proper CRNG, much like OpenBSD's arcrandom(3). There's been a proposal submitted to the Austin Group for future standardization in Posix, and I'm all in favor of something like that.

Quoted 4 lines

P.S. If I had my way, I would also drop GRND_RANDOM. Most software won't use it, there's no legacy installed base, and no developer who still wants that behavior can legitimately claim to care about RNG availability guarantees, IMHO.

GnuPG uses /dev/random when generating long term public keys. So there are some use cases where I think GRND_RANDOM makes sense. I agree they are not the normal ones, but they do exist.

Quoted 3 lines

[1] On more than one occasion, I've seen developers use Python's standard "random" module to generate IVs. I mean, why not? IVs are public, right?

Why are they writing code that needs raw IV's in the first place? Sounds like a misdesigned crypto library for me, or they were using low-level crypto when they should have been using a more higher-level abstraction.

The fundamental problem is that it's impossible to make an interface be moron-proof because morons are so ingenious. :-) If they are so misinformed that they are using random(3) to generate IV's, they are extremely likely to be making other, much more fundamentally wrong mistakes. The only real solution is to not let them anywhere near that level of crypto programming, which means you need to have high level libraries which are so appealing and easy to use that they aren't tempted to go low level on you...

Originally I thought that the answer was to have a userspace library interface where you would ask the user to tell you whether they needed the interface for Monte Carlo simulations, IV's, padding, session keys, long-term keys, etc. However, the counter argument was that the morons that would be helped by this explicit statement of need would likely be making other crypto-implementation mistakes anyway, so it's not worth it.

The one reamining reason why specifying the usage of the random values might be useful is if you are in a world where various NIST standards or some Military- or credit-card-processing imposed standards might require you to say, using a certified hardware RNG for long-term keys, but allowed the use of a crypto-based DRBG for session keys (for example), that's something that could be configured or controlled in a single location.

Cheers,

- Ted

#39 lore raw
In reply to Theodore Ts'o

Hi,

I am wondering if we could improve the design of the system call a bit to prevent programming errors.
Right now, EINVAL is returned in case of invalid flags (or in the older version of getrandom() also if buflen is too large), EFAULT if buf is an invalid address and EAGAIN if there is not enough entropy.

However, of course no programmer is save against programming errors. Everybody *should* check the return value of syscalls, but sometimes it is forgotten, and theoretically you must be stoned to death for that.

Still, we should think about how we could prevent these errors. Here is a list of possible modifications of getrandom() and pros and cons:

1. memset(buf, 0x0, buflen) in case of an error
pros:
- it is more obvious to the userspace programmer that the content of
buffer does *not* contain random bytes
cons:
- in case even the zero-ed buf is not noticed by the programmer, she/he
might end up using a 100% predictable string of "random bytes". In contrast if zero-ing the buf is ommitted, you would at least end up using some (not-cryptographically) random bytes from somewhere in RAM.

I am aware that this memset() call should theoretically be superfluous but it would only be executed in very rare cases where the programmer misuses getrandom().

2. int getrandom(void **buf, size_t buflen, unsigned int flags)

                      ^^

If flags, are fine, return a pointer to a buffer of random bytes, otherwise return a pointer to NULL.

pros:
- it would ensure that an error in a getrandom() call cannot be
ignored.
cons:
- not sure if a syscall should allocate memory in the name of a
userspace program
- not a very unix-like syscall signature
- anytime getrandom() is called, it will allocate a new buffer which
might end up in decreased performance (however, getrandom() should not be called multiple times)

3. send a signal to the userland process that (by default) leads to an abnormal termination of the process
Essentially an error in getrandom() could be seen as critical as a division by 0.

pros:
- the userspace programmer is forced to handle this error (otherwise
the signal would terminate the program)
cons:
- adds more complexity to the userspace program that might lead to new
programming errors

These are three possibilities. Maybe one of you is more creative and can come up with a much better idea. At the moment, I like option 2 the best, because it forces the programmer to deal with these errors, but probably one of you has a good point why this is not a good idea. Handling the NULL pointer would be much easier than using signals (option 3). However, it lead to a syscall signature that is different from, let's say read(), because the syscall itself would allocate its buffer.

Again, I am aware that you must always check return values, but programming errors happen. E.g. everybody knows that you cannot trust data that you received via network, yet heartbleed happened. Here we have the chance to eradicate a critical programming error by improving the syscall design and I think we should spend some time thinking about that.

Best,

Manuel