Fill buf with len random bytes. Prefers /dev/urandom for cryptographic * quality; falls back to rand() if /dev/urandom cannot be opened or read * (e.g. inside a chroot or container without /dev populated). */
| 1995 | * quality; falls back to rand() if /dev/urandom cannot be opened or read |
| 1996 | * (e.g. inside a chroot or container without /dev populated). */ |
| 1997 | static void rand_bytes(unsigned char *buf, size_t len) |
| 1998 | { |
| 1999 | #ifndef O_CLOEXEC |
| 2000 | #define O_CLOEXEC 0 |
| 2001 | #endif |
| 2002 | int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC); |
| 2003 | if (fd >= 0) { |
| 2004 | ssize_t n = read(fd, buf, len); |
| 2005 | close(fd); |
| 2006 | if (n == (ssize_t)len) { |
| 2007 | return; |
| 2008 | } |
| 2009 | } |
| 2010 | for (size_t i = 0; i < len; i++) { |
| 2011 | buf[i] = (unsigned char)rand(); |
| 2012 | } |
| 2013 | } |
| 2014 | |
| 2015 | /* |
| 2016 | Secure version of mkstemp that prevents symlink attacks on parent directories. |