Bypass dev / urandom | random for testing

I want to write a functional test case that tests a program with a known value for random numbers. I've already tested it with mocks during unit testing. But I would like this for functional testing too (not all of them, of course :)

What's the simplest way to override /dev/urandom

for just one process? Is there a way to do something like chroot

for one file and let all the others pass'?

+3


source to share


1 answer


If your system is new enough (e.g. RHEL 7) and supports syscall setns

, this can be done using the mount namespaces. Root access required.

The idea is to create a separate mount namespace for the process, and within that namespace, bind the mount of another file or FIFO over /dev/random

so that processes from that mount namespace will read the data from this bind-related file, Other processes will see regular ones /dev/random

.

Here's how to do it.

Preparation: Run the following command to get all this staff working (as it might not work by default, see this question ).

# mount --make-rprivate /

      

Now create a shell running inside the new mount namespace.

# unshare -m /bin/bash

      

You have a new bash

one that has its own mount namespace. You can compare the output of the following command from within this shell and from some other shell:

This shell:

# ls -l /proc/self/ns/mnt
lrwxrwxrwx. 1 root root 0 Sep 26 16:06 /proc/self/ns/mnt -> mnt:[4026532148]

      

Another shell:



$ ls -l /proc/self/ns/mnt
lrwxrwxrwx. 1 ec2-user ec2-user 0 Sep 26 16:06 /proc/self/ns/mnt -> mnt:[4026531840]

      

Note that the numbers are different, so the two shells are in different monster namespaces, and mounts made from the first shell will not be visible to other processes on the system (except for all children of that shell).

Now in this shell, we can link-mount something on top of the existing one /dev/random

.

# echo 'some large text' > /tmp/fakerandom
# mount --bind /tmp/fakerandom /dev/random

      

Other processes don't see what /dev/random

works for them as usual:

$ ls -l /dev/random
crw-rw-rw-. 1 root root 1, 8 Sep 26 15:45 /dev/random
$ cat /dev/random
 Znp7 v c  Ω^C

      

But in our shell, this is a feature:

# ls -l /dev/random
-rw-r--r--. 1 root root 16 Sep 26 16:18 /dev/random
# cat /dev/random
some large text

      

For functional testing, you can substitute /dev/random

some FIFOs and write some known data to that FIFO in some other process (see mkfifo(1)

for more information on this if needed).

More information on monster namespaces can be found in this excellent article.

+3


source







All Articles