Preventing other applications from binding to port 80 and 443

Solution 1:

You can't prevent a port from being bound by the wrong service. In your case, just remove apache from autostart and you should be good.

For 16.04 and newer:

sudo systemctl disable apache2

For older Ubuntu versions:

sudo update-rc.d apache2 disable

Solution 2:

If you really aren't using apache2, and it's PHP 7.0 that's requiring it, then it looks like you have libapache2-mod-php7.0 installed. That package is useless without Apache. Since you're using nginx, you likely also have php7.0-fpm or php7.0-cgi installed, either of which is sufficient for satisfying php7.0's dependency requirements:

$ apt-cache depends php7.0
php7.0
 |Depends: php7.0-fpm
 |Depends: libapache2-mod-php7.0
  Depends: php7.0-cgi
  Depends: php7.0-common
  Conflicts: <php5>

If you do have either of php7.0-{fpm,cgi} installed, you can go ahead and uninstall Apache.


Solution 3:

To answer your question, you can probably restrict a port to a specific application by using SElinux. I haven't used it myself and have only superficial knowledge of its capabilities, but here is a pointer I found in this site:

https://serverfault.com/a/257056/392230

In that answer, wzzrd seems to show how to give a specific application (foo) permission to bind to a specific port (803). You'd just have to have the policy set-up so that only your application (nginx) is allowed the ports you specify (80 and 443).

Basing myself on wzzrd's answer, it might be as simple as adding this to the policy

allow nginx_t nginx_port_t:tcp_socket name_bind;

and running this

semanage port -a -t nginx_port_t -p tcp 80
semanage port -a -t nginx_port_t -p tcp 443

Though, I imagine you'll also need a line in the policy that specifies that no other program may bind to those ports.

In the end, I'm just guessing what the appropriate configuration is.

Anyway, I don't think there's been an Ubuntu that has SElinux installed and enabled by default. Because I believe it requires applying certain patches to various utilities and a kernel option, it might be easier to simply use Centos which does have SElinux installed and enabled from the get-go.

Sorry, I'm not of more help. Maybe some other time, I'll download an image of Centos and try this; it'll be a good learning step. I'll update this answer if I do.


Solution 4:

Something that I haven't seen in the answers yet, but is still a possibility:

Change the Apache config to listen to another port, just in case. You can do that by opening the Apache config file, and changing the lines that have Listen 80 to another port.