Hack 54. Run Asterisk Without Root, for Security's Sake
Running a critical service as root makes a security-minded sysadmin squirm. But it doesn't have to be that way. Asterisk doesn't need to run as the all-powerful root user.
By default, Asterisk runs as rootthe user account with total, unrestricted power. This is generally considered a bad idea, as an exploit to Asterisk can lead to someone taking over your entire machine. To avoid this, the Apache Web Server doesn't usually run as root. This hack shows you how to run Asterisk as a less-godly user.
To do so, create a user called asterisk. In the following command, I use the Red Hat adduser command:
# adduser -c "Asterisk PBX" -d /var/lib/asterisk asterisk
Next, you'll need to alter Asterisk's Makefile, located at /usr/src/asterisk/Makefile. Using your favorite text editor, find the ASTVARRUNDIR constant in the file, and alter its definition to match what follows:
The directory referenced here needs to be writeable by the user running Asterisk, just as the directory normally used should be writeable only by root. By changing the setting, you're allowing Asterisk to use a directory that can be written by its own nonroot user account. Now, recompile Asterisk using this sequence of commands:
# cd /usr/src/asterisk # make clean ; make install
Once the recompile and install are done, you'll need to make sure the new user account has appropriate permission to several Asterisk-related directories, including the one you referenced in the altered Makefile:
# chown -R asterisk:asterisk /var/lib/asterisk # chown -R asterisk:asterisk /var/log/asterisk # chown -R asterisk:asterisk /var/run/asterisk # chown -R asterisk:asterisk /var/spool/asterisk # chown -R asterisk:asterisk /dev/zap # chmod -R u=rwX,g=rX,o= /var/lib/asterisk # chmod -R u=rwX,g=rX,o= /var/log/asterisk # chmod -R u=rwX,g=rX,o= /var/run/asterisk # chmod -R u=rwX,g=rX,o= /var/spool/asterisk # chmod -R u=rwX,g=rX,o= /dev/zap # chown R root:asterisk /etc/asterisk # chmod -R u=rwX,g=rX,o= /etc/asterisk
You can now launch the Asterisk server from the new user account, or from root using the su command:
# su asterisk -c /usr/sbin/safe_asterisk
Finally, you'll need to adjust the safe_asterisk script so that it uses the new user account to launch Asterisk, rather than root. To do so, open /usr/sbin/safe_asterisk in your favorite text editor, and add su asterisk -c before each instance of an asterisk command. Be sure to leave the commands unchanged, aside from prefixing them with the su command.
Once these steps are taken, Asterisk will have only as much power as you grant the asterisk user. Would-be attackers might be able to crash Asterisk, but in so doing, they won't be able to gain access to root's credentials.