Title: Sending emails with php inside a chroot
Date: 2016-10-07 13:00

For [websec.fr](https://websec.fr), we're running each level into a *harneded*
chroot, under a different user, likely because we trust the players as much as
we trust php. Our last level, [level19](https://websec.fr/level19/index.php) may
send some emails, but unfortunately, with our setup, this is non-trivial,
because the [mail](https://secure.php.net/manual/en/function.mail.php) function of php
is directly using the [sendmail](https://en.wikipedia.org/wiki/Sendmail#Security) binary.

So I thought about compiling it statically.

- **But** since sendmail is bloated (and painful to compile), I gave a try to
  [mini_sendmail](https://github.com/mattrude/mini_sendmail), which had a broken
  makefile.
- **But** it's using `gethostbyname`, so it can't be compiled in a static
  way, because this function is implemented in glibc's [NSS wrapper](
  https://www.gnu.org/software/libc/manual/html_node/Name-Service-Switch.html ),
  so I went with [musl](https://www.musl-libc.org/) instead. 
- **But** since we didn't want to host our own smtp server, we're using a free
  mail provider, than only accept [opportunistic
  TLS](https://en.wikipedia.org/wiki/Opportunistic_TLS), and musl doesn't
  provide enough crypto for that. So we implemented a `smtp` client in pure
  PHP.
- **But** since PHP is, well, PHP, it failed to [switch to
  crypto](https://secure.php.net/manual/en/function.stream-socket-enable-crypto.php)
  inside the chroot.

The solution is simply to type `mknod dev/random c 1 8` (and not `urandom`,
because apparently there are still people that don't get the
[difference](http://www.2uo.de/myths-about-urandom/)), to provide a source of
entropy _inside_ the chroot. It doesn't make much sense, since php should already have
access to a PRNG, even inside a chroot.

You can now use `stream_socket_enable_crypto` inside your chroot (and send `STARTTLS` powered emails)!

(many thanks to [nurfed](https://twitter.com/nurfed1) for <s>wasting time with me</s> helping me.)
