How To Install and Configure SNMP on CentOS

Introduction

SNMP, or Simple Network Management Protocol, is widely used to communicate with and monitor network devices, servers, and more, all via IP. In this case, we’ll be installing an SNMP agent on a CentOS 6.5 server, which will allow for collection of data from our server, and make the information available to a remote SNMP manager.

Pre-Flight Check

  • These instructions are intended for installing SNMP and doing a very basic configuration.
  • I’ll be working from a Liquid Web Core Managed CentOS 6.5 server, and I’ll be logged in as root.

Install SNMP and SNMP Utilities

Installing SNMP and some optional SNMP utilities is as simple as running one command:

yum -y install net-snmp net-snmp-utils

Add a Basic Configuration for SNMP

Now, let’s take the default SNMP configuration file, /etc/snmp/snmpd.conf and move it to an alternate location, /etc/snmp/snmpd.conf.orig.

mv /etc/snmp/snmpd.conf /etc/snmp/snmpd.conf.orig

And now we’ll create a new /etc/snmp/snmpd.conf:

vim /etc/snmp/snmpd.conf

For a refresher on editing files with vim see: New User Tutorial: Overview of the Vim Text Editor

Insert the following text into the new /etc/snmp/snmpd.conf

# Map 'idv90we3rnov90wer' community to the 'ConfigUser'
# Map '209ijvfwer0df92jd' community to the 'AllUser'
#       sec.name        source          community
com2sec ConfigUser      default         idv90we3rnov90wer
com2sec AllUser         default         209ijvfwer0df92jd
# Map 'ConfigUser' to 'ConfigGroup' for SNMP Version 2c
# Map 'AllUser' to 'AllGroup' for SNMP Version 2c
#                       sec.model       sec.name
group   ConfigGroup     v2c             ConfigUser
group   AllGroup        v2c             AllUser
# Define 'SystemView', which includes everything under .1.3.6.1.2.1.1 (or .1.3.6.1.2.1.25.1)
# Define 'AllView', which includes everything under .1
#                       incl/excl       subtree
view    SystemView      included        .1.3.6.1.2.1.1
view    SystemView      included        .1.3.6.1.2.1.25.1.1
view    AllView         included        .1
# Give 'ConfigGroup' read access to objects in the view 'SystemView'
# Give 'AllGroup' read access to objects in the view 'AllView'
#                       context model   level   prefix  read            write   notify
access  ConfigGroup     ""      any     noauth  exact   SystemView      none    none
access  AllGroup        ""      any     noauth  exact   AllView         none    none

The above text is noted with basic information on the function of each configuration line. In short, we’re creating two scenarios for polling information from SNMP version 2c.

Note: SNMPv2c contains some security enhancements over SNMPv1 but uses the existing SNMPv1 administration structure, which is “community” based. Areas of improvement include: transport mappings, protocol packet types, and MIB structure elements.

In the first scenario: ConfigUser is assigned to ConfigGroup and may only use SNMP security model 2c,ConfigGroup can use the SystemView, SystemView is assigned to two OID sub-trees, and all of this is referenced in an SNMP poll by the secret, and unique community string idv90we3rnov90wer.

In the second scenario: AllUser is assigned to AllGroup and may only use SNMP security model 2c,AllGroup can use the AllView, AllView is assigned to the entire OID tree, and all of this is referenced in an SNMP poll by the secret, and unique community string 209ijvfwer0df92jd.

Important Tip: Be ABSOLUTELY SURE that you choose a unique community string and replace the community strings in the above examples. Keep each secret, and keep each safe.

Exit vim, and restart the SNMP service to reload the new configuration file:

service snmpd restart

Configure SNMP to start when the server boots:

chkconfig snmpd on

Test the SNMP Configuration

Now let’s test the SNMP configuration… try running the following two commands:

snmpwalk -v 2c -c idv90we3rnov90wer -O e 127.0.0.1
snmpwalk -v 2c -c 209ijvfwer0df92jd -O e 127.0.0.1

Note: The default port for SNMP is 161 and 162. If you’re going to connect to SNMP from a remote server, be sure your server’s firewall has the appropriate ports open.

The result for your first command should be about 33 lines, and contain some basic system information. The result for the second command should contain a lot more information about your system, and will likely be thousands of lines.

How To Configure Nginx as a Web Server and Reverse Proxy for Apache on One Ubuntu 14.04 Droplet

Introduction

Apache and Nginx are two popular open source web servers often used with PHP. It can be useful to run both of them on the same virtual machine when hosting multiple websites which have varied requirements. The general solution for running two web servers on a single system is to either use multiple IP addresses or different port numbers.

Droplets which have both IPv4 and IPv6 addresses can be configured to serve Apache sites on one protocol and Nginx sites on the other, but this isn’t currently practical, as IPv6 adoption by ISPs is still not widespread. Having a different port number like 81 or 8080 for the second web server is another solution, but sharing URLs with port numbers (such as http://example.com:81) isn’t always reasonable or ideal.

This tutorial will show you how to configure Nginx as both a web server and as a reverse proxy for Apache – all on one Droplet. Depending on the web application, code changes might be required to keep Apache reverse-proxy-aware, especially when SSL sites are configured. To ensure this, we will install an Apache module named mod_rpaf which rewrites certain environment variables so it appears that Apache is directly handling requests from web clients.

We will host four domain names on one Droplet. Two will be served by Nginx: example.com (the default virtual host) and sample.org. The remaining two, foobar.net and test.io, will be served by Apache.

Prerequisites

  • A new Ubuntu 14.04 Droplet.
  • A standard user account with sudo privileges. You can set up a standard account by following Steps 2 and 3 of the Initial Server Setup with Ubuntu 14.04.
  • The desired domain names should point to your Droplet’s IP address in the DigitalOcean control panel. See Step 3 of How To Set Up a Host Name with DigitalOcean for an example of how to do this. If you host your domains’ DNS elsewhere, you should create appropriate A records there instead.

Optional References

This tutorial requires basic knowledge of virtual hosts in Apache and Nginx, and SSL certificate creation and configuration. For more information on these topics, see the following articles.

Step 1 — Installing Apache and PHP5-FPM

In addition to Apache and PHP-FPM, we must also install the PHP FastCGI Apache module. This islibapache2-mod-fastcgi, available in Ubuntu’s multiverse repository, which must first be enabled in the sources.list file.

sudo nano /etc/apt/sources.list

Find the following lines and uncomment them by removing the hash symbol (#) at the beginning.

# deb http://mirrors.digitalocean.com/ubuntu trusty multiverse

 . . .

# deb http://mirrors.digitalocean.com/ubuntu trusty-updates multiverse

That should leave you with what’s shown below.

 deb http://mirrors.digitalocean.com/ubuntu trusty multiverse

 . . .

 deb http://mirrors.digitalocean.com/ubuntu trusty-updates multiverse

Save the file and update the apt repository.

sudo apt-get update

Then install the necessary packages.

sudo apt-get install apache2 libapache2-mod-fastcgi php5-fpm

Step 2 — Configuring Apache and PHP5-FPM

In this step we will change Apache’s port number to 8080 and configure it to work with PHP5-FPM using the mod_fastcgi module. Edit the Apache configuration file and change the port number of Apache.

sudo nano /etc/apache2/ports.conf

Find the following line:

Listen 80

Change it to:

Listen 8080

Save and exit ports.conf.

Note: Web servers are generally set to listen on 127.0.0.1:8080 when configuring a reverse proxy but doing so would set the value of PHP’s environment variable SERVER_ADDR to the loopback IP address instead of the server’s public IP. Our aim is to set up Apache in such a way that its websites do not see a reverse proxy in front of it. So, we will configure it to listen on 8080 on all IP addresses.

Next we’ll edit the default virtual host file of Apache. The <VirtualHost> directive in this file is set to serve sites only on port 80.

sudo nano /etc/apache2/sites-available/000-default.conf

The first line should be:

<VirtualHost *:80>

Change it to:

<VirtualHost *:8080>

Save the file and reload Apache.

sudo service apache2 reload

Verify that Apache is now listening on 8080.

sudo netstat -tlpn

The output should look like below, with apache2 listening on :::8080.

Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address     Foreign Address      State    PID/Program name
tcp        0      0 0.0.0.0:22        0.0.0.0:*            LISTEN   1086/sshd
tcp6       0      0 :::8080           :::*                 LISTEN   4678/apache2
tcp6       0      0 :::22             :::*                 LISTEN   1086/sshd

Step 3 — Configuring Apache to Use mod_fastcgi

Apache works with mod_php by default, but it requires additional configuration to work with PHP5-FPM.

Note: If you are trying this tutorial on an existing installation of LAMP with mod_php, disable it first with:

sudo a2dismod php5

We will be adding a configuration block for mod_fastcgi which depends on mod_action. mod-actionis disabled by default, so we first need to enable it.

sudo a2enmod actions

Find out which version of Apache is installed on your Droplet with:

sudo apache2 -v

Edit the fastcgi configuration file accordingly. These configuration directives pass requests for .phpfiles to the PHP5-FPM UNIX socket.

sudo nano /etc/apache2/mods-enabled/fastcgi.conf

Add the following lines to the bottom of the <IfModule mod_fastcgi.c> . . . </IfModule> block for Apache 2.4:

 AddType application/x-httpd-fastphp5 .php
 Action application/x-httpd-fastphp5 /php5-fcgi
 Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
 FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization
 <Directory /usr/lib/cgi-bin>
  Require all granted
 </Directory>

Apache 2.2 does not require the <Directory> section so add the following:

 AddType application/x-httpd-fastphp5 .php
 Action application/x-httpd-fastphp5 /php5-fcgi
 Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
 FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization

When finished in fastcgi.conf, do a configuration test.

sudo apachectl -t

Reload Apache if Syntax OK is displayed. If you see the warning Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message., that’s fine. It doesn’t affect us now.

sudo service apache2 reload

Step 4 — Verifying PHP Functionality

Check if PHP works by creating a phpinfo() file and accessing it from your web browser.

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

To see the file in a browser, go to http://111.111.111.111:8080/info.php but using your Droplet’s IP address. This will give you a list of configuration specifications PHP is using.

phpinfo Server API

phpinfo PHP Variables

At the top of the page, check that Server API says FPM/FastCGI. About two-thirds of the way down the page, the PHP Variables section will tell you the SERVER_SOFTWARE is Apache on Ubuntu. These confirm that mod_fastcgi is active and Apache is using PHP5-FPM to process PHP files.

Step 5 — Creating Virtual Hosts for Apache

We will create two Apache virtual host files for the domains foobar.net and test.io. This begins with creating document root directories for both sites.

sudo mkdir -v /var/www/{foobar.net,test.io}

Now we will add two files to each directory for testing after setup is complete.

First we’ll create an index file for each site.

echo "<h1 style='color: green;'>Foo Bar</h1>" | sudo tee /var/www/foobar.net/index.html
echo "<h1 style='color: red;'>Test IO</h1>" | sudo tee /var/www/test.io/index.html

Then, a phpinfo() file.

echo "<?php phpinfo(); ?>" | sudo tee /var/www/foobar.net/info.php
echo "<?php phpinfo(); ?>" | sudo tee /var/www/test.io/info.php

Create the virtual host file for the foobar.net domain.

sudo nano /etc/apache2/sites-available/foobar.net.conf

Place the following directive in it:

<VirtualHost *:*>
    ServerName foobar.net
    ServerAlias www.foobar.net
    DocumentRoot /var/www/foobar.net
    <Directory /var/www/foobar.net>
        AllowOverride All
    </Directory>
</VirtualHost>

Save and close the file. Then do the same for test.io.

sudo nano /etc/apache2/sites-available/test.io.conf
<VirtualHost *:*>
    ServerName test.io
    ServerAlias www.test.io
    DocumentRoot /var/www/test.io
    <Directory /var/www/test.io>
        AllowOverride All
    </Directory>
</VirtualHost>

Note 1: AllowOverride All enables .htaccess support.

Note 2: These are only the most basic directives. For a complete guide on setting up virtual hosts in Apache, see How To Set Up Apache Virtual Hosts on Ubuntu 14.04 LTS.

Now that both Apache virtual hosts are set up, enable the sites using the a2ensite command. This creates a symbolic link to the virtual host file in the sites-enabled directory.

sudo a2ensite foobar.net
sudo a2ensite test.io

Check Apache for configuration errors again.

sudo apachectl -t

Reload it if Syntax OK is displayed.

sudo service apache2 reload

To confirm the sites are working, open http://foobar.net:8080 and http://test.io:8080 in your browser and verify they’re displaying their index.html files.

You should see:

foobar.net index page

test.io index page

Also, check if PHP is working by accessing the info.php files: http://foobar.net:8080/info.php andhttp://test.io:8080/info.php.

You should see the same PHP configuration spec list on each site as you saw in Step 1. We now have two websites hosted on Apache at port 8080.

Step 6 — Installing and Configuring Nginx

In this step we will install Nginx and configure the domains example.com and sample.org as Nginx’s virtual hosts. For a complete guide on setting up virtual hosts in Nginx, see How To Set Up Nginx Server Blocks (Virtual Hosts) on Ubuntu 14.04 LTS.

Install Nginx.

sudo apt-get install nginx

Then remove the default virtual host’s symlink.

sudo rm /etc/nginx/sites-enabled/default

Now we’ll create virtual hosts for Nginx. First make document root directories for both the websites:

sudo mkdir -v /usr/share/nginx/{example.com,sample.org}

As we did with Apache’s virtual hosts, we’ll again create index and phpinfo() files for testing after setup is complete.

echo "<h1 style='color: green;'>Example.com</h1>" | sudo tee /usr/share/nginx/example.com/index.html
echo "<h1 style='color: red;'>Sample.org</h1>" | sudo tee /usr/share/nginx/sample.org/index.html
echo "<?php phpinfo(); ?>" | sudo tee /usr/share/nginx/example.com/info.php
echo "<?php phpinfo(); ?>" | sudo tee /usr/share/nginx/sample.org/info.php

Now create a virtual host file for the domain example.com.

sudo nano /etc/nginx/sites-available/example.com

Nginx calls server {. . .} areas of a configuration file server blocks. Create a server block for the primary virtual host, example.com. The default_server configuration directive makes this the default virtual host which processes HTTP requests that do not match any other virtual host.

Paste the following into the file for example.com:

server {
    listen 80 default_server;

    root /usr/share/nginx/example.com;
    index index.php index.html index.htm;

    server_name example.com www.example.com;
    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

Save and close the file. Now create a virtual host file for Nginx’s second domain, sample.org.

sudo nano /etc/nginx/sites-available/sample.org

The server block for sample.org should look like this:

server {
    root /usr/share/nginx/sample.org;
    index index.php index.html index.htm;

    server_name sample.org www.sample.org;
    location / {
        try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

Save and close the file. Then enable both the sites by creating symbolic links to the sites-enableddirectory.

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.com
sudo ln -s /etc/nginx/sites-available/sample.org /etc/nginx/sites-enabled/sample.org

Do an Nginx configuration test:

sudo service nginx configtest

Then reload Nginx if OK is displayed.

sudo service nginx reload

Now acccess the phpinfo() file of your Nginx virtual hosts in a web browser byhttp://example.com/info.php and http://sample.org/info.php. Look under the PHP Variablessection again.

Nginx PHP Variables

[“SERVER_SOFTWARE”] should say nginx, indicating that the files were directly served by Nginx.[“DOCUMENT_ROOT”] should point to the directory you created earlier in this step for each Nginx site.

At this point, we have installed Nginx and created two virtual hosts. Next we will set up an additional virtual host to proxy requests meant for domains hosted on Apache.

Step 7 — Configuring Nginx for Apache’s Virtual Hosts

In this section we will create an additional Nginx virtual host with multiple domain names in theserver_name directives. Requests for these domain names will be proxied to Apache.

Create a new Nginx virtual host file:

sudo nano /etc/nginx/sites-available/apache

Add the code block below. This specifies the names of both Apache virtual host domains, and proxies their requests to Apache. Remember to use the public IP address in proxy_pass.

server {
    listen 80;
    server_name foobar.net www.foobar.net test.io www.test.io;

    location / {
        proxy_pass http://111.111.111.111:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Save the file and enable this new virtual host by creating a symbolic link.

sudo ln -s /etc/nginx/sites-available/apache /etc/nginx/sites-enabled/apache

Do a configuration test:

sudo service nginx configtest

Reload Nginx if OK is displayed.

sudo service nginx reload

Open the browser and access the http://foobar.net/info.php on one of Apache’s domain names. Scroll down to the PHP Variables section and check the values displayed.

phpinfo of Apache via Nginx

The variables SERVER_SOFTWARE and DOCUMENT_ROOT should confirm that this request was handled by Apache. The variables HTTP_X_REAL_IP and HTTP_X_FORWARDED_FOR were added by Nginx and should show the public IP address of the computer you’re accessing the URL from in your browser.

We have successfully setup Nginx to proxy requests for specific domains to Apache. The next step is to configure Apache to set variables REMOTE_ADDR as if it were handling these requests directly.

Step 8 — Installing and Configuring mod_rpaf

In this step we will install an Apache module named mod_rpaf which rewrites the values ofREMOTE_ADDR, HTTPS and HTTP_PORT based on the values provided by a reverse proxy. Without this module, some PHP applications would require code changes to work seamlessly from behind a proxy. This module is present in Ubuntu’s repository as libapache2-mod-rpaf but is outdated and doesn’t support certain configuration directives. Instead, we will install it from source.

Install the packages needed to compile and build the module:

sudo apt-get install unzip build-essential apache2-threaded-dev

Download the latest stable release from GitHub.

wget https://github.com/gnif/mod_rpaf/archive/stable.zip

Extract it with:

unzip stable.zip

Change into the working directory.

cd mod_rpaf-stable

Then compile and install the module.

sudo make
sudo make install

Create a file in the mods-available directory which loads the rpaf module.

sudo nano /etc/apache2/mods-available/rpaf.load

Add the following line to the file:

LoadModule rpaf_module /usr/lib/apache2/modules/mod_rpaf.so

Create another file in this directory. This will contain the configuration directives.

sudo nano /etc/apache2/mods-available/rpaf.conf

Add the following code block, making sure to add the IP address of your Droplet.

<IfModule mod_rpaf.c>
        RPAF_Enable             On
        RPAF_Header             X-Real-Ip
        RPAF_ProxyIPs           111.111.111.111
        RPAF_SetHostName        On
        RPAF_SetHTTPS           On
        RPAF_SetPort            On
</IfModule>

Here’s a brief description of each directive. See the mod_rpaf README file for more information.

  • RPAF_Header – The header to use for the client’s real IP address.
  • RPAF_ProxyIPs – The proxy IP to adjust HTTP requests for.
  • RPAF_SetHostName – Updates the vhost name so ServerName and ServerAlias work.
  • RPAF_SetHTTPS – Sets the HTTPS environment variable based on the value contained in X-Forwarded-Proto.
  • RPAF_SetPort – Sets the SERVER_PORT environment variable. Useful for when Apache is behind a SSL proxy.

Save rpaf.conf and enable the module.

sudo a2enmod rpaf

This creates symbolic links of the files rpaf.load and rpaf.conf in the mods-enabled directory. Now do a configuration test.

sudo apachectl -t

Reload Apache if Syntax OK is returned.

sudo service apache2 reload

Access one of Apache’s websites’ phpinfo() page on your browser and check the PHP Variablessection. The REMOTE_ADDR variable will now also be that of your local computer’s public IP address.

Step 9 — Setting Up HTTPS Websites (Optional)

In this step we will configure SSL certificates for both the domains hosted on Apache. Nginx supports SSL termination so we can set up SSL without modifying Apache’s configuration files. The mod_rpaf module ensures the required environment variables are set on Apache to make applications work seamlessly behind a SSL reverse proxy.

Create a directory for the SSL certificates and their private keys.

sudo mkdir /etc/nginx/ssl

For this article we will use self-signed SSL certificates with a validity of 10 years. Generate self-signed certificates for both foobar.net and test.io.

sudo openssl req -x509 -sha256 -newkey rsa:2048 -keyout /etc/nginx/ssl/foobar.net-key.pem -out /etc/nginx/ssl/foobar.net-cert.pem -days 3650 -nodes
sudo openssl req -x509 -sha256 -newkey rsa:2048 -keyout /etc/nginx/ssl/test.io-key.pem -out /etc/nginx/ssl/test.io-cert.pem -days 3650 -nodes

Each time, you will be prompted for certificate identification details.

Country Name (2 letter code) [AU]:US
State or Province Name (full name) [Some-State]:New York
Locality Name (eg, city) []:New York City
Organization Name (eg, company) [Internet Widgits Pty Ltd]:DigitalOcean Inc
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:example.com
Email Address []:

Now open the apache virtual host file that proxies requests from Nginx to Apache.

sudo nano /etc/nginx/sites-available/apache

Since we have separate certificates and keys for each domain we need to have separate server { . . . } blocks for each domain. You should delete it’s current contents and when finished, your apachevhost file should look similar to below.

server {
    listen 80;
    listen 443 ssl;
    server_name test.io www.test.io;

    ssl on;
    ssl_certificate /etc/nginx/ssl/test.io-cert.pem;
    ssl_certificate_key /etc/nginx/ssl/test.io-key.pem;

    location / {
        proxy_pass http://111.111.111.111:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

server {
    listen 80;
    listen 443 ssl;
    server_name foobar.net www.foobar.net;

    ssl on;
    ssl_certificate /etc/nginx/ssl/foobar.net-cert.pem;
    ssl_certificate_key /etc/nginx/ssl/foobar.net-key.pem;

    location / {
        proxy_pass http://111.111.111.111:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Save the file and perform a configuration test.

sudo service nginx configtest

Reload Nginx if the test succeeds.

sudo service nginx reload

Access one of Apache’s domains over the browser with the https:// prefix:https://foobar.net/info.php

phpinfo ssl

Look in the PHP Variables section. The variable SERVER_PORT has been set to 443 and HTTPS set to on, as though Apache was directly accessed over HTTPS. With these variables set, PHP applications do not have to be specially configured to work behind a reverse proxy.

Step 10 — Blocking Direct Access to Apache (Optional)

Since Apache is listening on port 8080 on the public IP address, it is accessible by everyone. It can be blocked by working the following IPtables command into your firewall rule set.

sudo iptables -I INPUT -p tcp --dport 8080 ! -s 111.111.111.111 -j REJECT --reject-with tcp-reset

Be sure to use your Droplet’s IP address in place of the example in red. Once port 8080 is blocked in your firewall, test that Apache is unreachable on it. Open your web browser and try accessing one of Apache’s domain names on port 8080. For example: http://example.com:8080

The browser should display an “Unable to connect” or “Webpage is not available” error message. With the IPtables tcp-reset option in place, an outsider would see no difference between port 8080 and a port that doesn’t have any service on it.

Note: IPtables rules do not survive a system reboot by default. There are multiple ways to preserve IPtables rules, but the easiest is to use iptables-persistent in Ubuntu’s repository.

Step 11 — Serving Static Files Using Nginx (Optional)

When Nginx proxies requests for Apache’s domains, it sends every file request to domain to Apache. Nginx is faster than Apache in serving static files like images, JavaScript and style sheets. So in this section we will configure Nginx’s apache virtual host file to directly serve static files and just send PHP requests to Apache.

Open the apache virtual host file.

sudo nano /etc/nginx/sites-available/apache

Add two additional location blocks to each server block as shown in red in the code block below.

server {
    listen 80;
    server_name test.io www.test.io;
    root /var/www/test.io;
    index index.php index.htm index.html;

    location / {
     try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        proxy_pass http://111.111.111.111:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location ~ /\. {
     deny all;
    }
}

server {
    listen 80;
    server_name foobar.net www.foobar.net;
    root /var/www/foobar.net;
    index index.php index.htm index.html;

    location / {
     try_files $uri $uri/ /index.php;
    }

    location ~ \.php$ {
        proxy_pass http://111.111.111.111:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location ~ /\. {
     deny all;
    }
}

The try_files directive makes Nginx to look for files in the document root and directly serve them. If the file has a .php extension, the request is passed to Apache. Even if the file is not found in thedocument root, the request is passed on to Apache so that application features like permalinks work without problems.

Safe the file and perform a configuration test.

sudo service nginx configtest

Reload Nginx if the test succeeds.

sudo service nginx reload

To verify this is working, you can examine Apache’s log files in /var/log/apache2 and see the GET requests for the index.php files of test.io and foobar.net. The only caveat of this setup is that Apache will not be able to restrict access to static files. Access control for static files would need to be configured in Nginx’s apache virtual host file.

Warning: The location ~ /\. directive is very important to include. This prevents Nginx from printing the contents of files like .htaccess and .htpasswd.

Conclusion

Having completed this tutorial, you should now have one Ubuntu Droplet with Nginx servingexample.com and sample.org, along with Apache serving foobar.net and test.io. Though Nginx is acting as a reverse-proxy for Apache, Nginx’s proxy service is transparent and connections to Apache’s domains appear be served directly from Apache itself.

Source : https://www.digitalocean.com/community/tutorials/how-to-configure-nginx-as-a-web-server-and-reverse-proxy-for-apache-on-one-ubuntu-14-04-droplet

 

รับ-ส่ง SMS ง่ายๆ ด้วย AirCard บน Raspberry Pi

ปัจจุบันมีโครงงานทางระบบสมองกลจำนวนมากที่ต้องการใช้ SMS ไม่ว่าจะเป็นเพื่อส่งข้อมูลจากเซ็นเซอร์ต่างๆ ไปเก็บที่ศูนย์กลาง  หรือเพื่อส่งข้อความแจ้งเตือนผู้ใช้ถึงเหตุการณ์ต่างๆ ที่ระบบตรวจสอบได้ ซึ่งเดิมการส่ง SMS นั้นต้องใช้อุปกรณ์เฉพาะที่ราคาแพง และต้องอาศัยความรู้เรื่องการต่อวงจร และเขียนโปรแกรมควบคุมพอสมควร แต่การรับ-ส่ง SMS โดยใช้ Raspberry Pi นั้นเป็นสิ่งที่ทำได้ง่ายมากๆ เพราะสามารถใช้ USB AirCard ที่มีจำหน่ายทั่วไป ซึ่งราคาคุ้มค่า และมีแนวโน้มถูกลงเรื่อยๆ ตามความนิยม ประกอบกับคำสั่งที่ใช้รับ-ส่ง SMS บน Linux นั้นง่ายมากๆ บทความนี้จะแนะนำและแสดงตัวอย่างการรับส่งข้อความอย่างง่าย เพื่อเป็นต้นแบบให้กับโครงงานที่ต้องการใช้ความสามารถนี้

อุปกรณ์ที่ต้องใช้

  1. Raspberry Pi (หรือคอมพิวเตอร์ที่ใช้ Linux และมี port USB ว่าง 1 พอร์ท)
  2. USB AirCard ที่เข้ากันได้กับระบบปฏิบัติการ Raspbian ของ Raspberry Pi (ดูรายชื่ออุปกรณ์ได้จากที่นี่) บทความนี้เลือกใช้ 3G AirCard ของ TrueMove-H ซึ่งภายในเป็นอุปกรณ์ของ Huawei รุ่น E303 ราคา 790 บาท (ซิมและโปรโมชันที่ใช้ต้องซื้อต่างหาก)
  3. โทรศัพท์มือถือเอาไว้ทดสอบการรับ-ส่งข้อความ

IMG_1921

การเตรียมระบบ

  • ติดตั้งโปรแกรม gammu และส่วนเสริมที่จำเป็น ให้เรียกใช้โปรแกรม Terminal แล้วพิมพ์คำสั่งต่อไปนี้ เครื่อง Raspberry Pi จะต้องเชื่อมต่อกับอินเทอร์เน็ต
sudo apt-get install gammu usb-modeswitch python-gammu
  • ลองเสียบ SIM ในโทรศัพท์มือถือทั่วไปและทดลองดูว่าสามารถรับส่งข้อความได้หรือไม่ เมื่อแน่ใจว่า SIM ใช้งานได้ ก็ให้ย้ายไปใส่ใน AirCard แล้วเสียบ AirCard เข้ากับช่อง USB ของ Raspberry Pi
  • ตรวจสอบว่า Raspberry Pi มองเห็น AirCard หรือไม่

ใช้คำสั่ง

lsusb

เนื่องจาก AirCard รุ่นที่ใช้ในตัวอย่างนี้จะทำตัวเป็น USB Drive ได้ด้วย ซึ่งบางครั้งจะทำให้ Raspberry Pi สับสน นึกว่าอุปกรณ์นี้ไม่ใช่ AirCard แต่เป็น USB Drive แทน ดังนั้นคำสั่ง lsusb จะให้ผลลัพท์ได้สองแบบ

เห็น AirCard (ถูกต้อง)

Bus 001 Device 010: ID 12d1:1506 Huawei Technologies Co., Ltd. E398 LTE/UMTS/GSM Modem/Networkcard

ไม่เห็น AirCard แต่เห็น USB Drive แทน (ผิด)

Bus 001 Device 010: ID 12d1:14d1 Huawei Technologies Co., Ltd.

แม้หากว่าลองแล้วได้ผลถูกต้อง แต่ก็เป็นไปได้ว่าบางครั้งเมื่อ reboot ระบบอาจกลับไปเห็นอุปกรณ์ที่ไม่ถูกต้องก็ได้ ดังนั้นถ้าให้แน่ใจจริงๆ ควรใช้โปรกรม usb-modeswitch เพื่อตั้งค่าอุปกรณ์ให้ถูกต้องตามขั้นตอนต่อไปนี้

  • ตั้งค่าโปรแกรม usb-modeswitch

โปรแกรมนี้ทำหน้าที่เปลี่ยนโหมดของอุปกรณ์ USB ที่มีหลากอุปกรณ์ในตัว และตั้งค่าเลือกอุปกรณ์ตัวที่เราต้องการใช้ การจะเลือกอุปกรณ์ จะต้องรู้รหัส Vendor ID กับ Product ID ซึ่งรหัสนี้จะต่างกันไปแล้วแต่ยี่ห้อและรุ่นของ AirCard ที่ใช้ ดังนั้นจะต้องไปค้นข้อมูลนี้จาก internet มาเองให้ตรงรุ่น แล้วนำค่านี้ไปเขียนต่อท้ายในไฟล์ /etc/usb_modeswitch.conf โดยใช้คำสั่งต่อไปนี้จาก Terminal

sudo nano /etc/usb_modeswitch.conf

เช่น AirCard Huawei E303 ที่ใช้ในบทความนี้จะมีค่ารหัสดังนี้ (หาพบจากการค้นหา “Huawei E303 USB vendor product Id” ใน Google)

DefaultVendor = 0x12d1
DefaultProduct = 0x1506

เมื่อเพิ่มสองบรรทัดนี้เข้าไปในไฟล์แล้วก็ให้ save ไฟล์ (กด Ctrl-X และ Y) แล้วลอง reboot เครื่อง และเรียก lsusb อีกครั้ง ซึ่งคราวนี้น่าจะเห็นอุปกรณ์ที่ถูกต้อง

  • ตรวจสอบชื่ออุปกรณ์ของ AirCard โดยใช้คำสั่ง
dmesg | grep ttyUSB*

สังเกตุบรรทัดที่มีคำว่า GSM modem และดูว่าอุปกรณ์ชื่ออะไร เช่น ttyUSB0, ttyUSB1, ฯลฯ จำชื่อนี้ไว้

  • ตั้งค่าโปรแกรม gammu

โปรแกรม gammu จะทำหน้าที่รับส่ง SMS ซึ่งจะต้องตั้งค่าให้โปรแกรมรู้จัก AirCard ที่ใช้ก่อน โดยพิมพ์คำสั่งต่อไปนี้

sudo gammu-config

ซึ่งจะแสดงหน้าต่างการตั้งค่าขึ้นมา ให้เราตั้งค่าดังนี้

Port: /dev/ttyUSB0 << แล้วแต่เสียบ port ไหน
 Connection: at19200 
 Model: ปล่อยว่างๆ 
 Synchronize time: yes 
 Log file: ปล่อยว่างๆ 
 Log format: nothing 
 Use locking: ปล่อยว่างๆ 
 Gammu localisation: ปล่อยว่างๆ

เมื่อเสร็จก็ให้ save แล้วออกจากโปรแกรม

 การส่ง SMS

เมื่อติดตั้งทุกอย่างเสร็จสิ้นแล้ว ต่อไปก็ให้ทดลองส่ง SMS โดยพิมพ์คำสั่งต่อไปนี้ใน Terminal โดยจะต้องเปลี่ยนหมายเลขโทรศัพท์ผู้รับให้ตรงกับโทรศัพท์ที่ใช้ทดสอบด้วย

 sudo gammu sendsms TEXT +66819876543 -textutf8 "Hello from Raspberry Pi"

คำสั่งนี้จะส่งข้อความ “Hello from Raspberry Pi” ไปยังหมายเลขโทรศัพท์ 081-987-6543 ซึ่งรูปแบบการเขียนเบอร์โทรศัพท์ที่เป็น +66819876543 นี้เป็นมาตรฐานนานาชาติ คือขึ้นต้นด้วย “+” ตามด้วยรหัสประเทศ (66 = ประเทศไทย) และตามด้วยเบอร์โทร โดยตัด 0 ตัวแรกทิ้งไป ต่อไปนี้เป็นตัวอย่างการส่ง SMS ข้างต้นโดยใช้ภาษา Python

1
2
3
4
5
import commands
commandString = 'sudo gammu sendsms TEXT +66819876543 -textutf8 "Hello from Raspberry Pi" '
print commands.getoutput(commandString)

การใช้ภาษา Python มีความยืนหยุ่นสูงกว่าเพราะทำให้เราสามารถสร้างข้อความที่รับค่าจากผู้ใช้ได้เช่น

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import commands
# Ask for your name
name = raw_input('What is your name? ')
# Ask for a phone number. Use the international format. +country-code phone-number,
# I.e. +66819876543
phoneNumber = raw_input('What is your phone number? ')
commandString = 'sudo gammu sendsms TEXT ' + phoneNumber + ' -textutf8 "Hello ' + name + '. This is Raspberry Pi"'
print 'Sending text "Hello ' + name + '. This is Raspberry Pi" to phone number ' + phoneNumber
# send the command to the AirCard
print commands.getoutput(commandString)

โปรแกรมข้างต้นจะถามชื่อ และหมายเลขโทรศัพท์จากผู้ใช้ แล้วทำการส่ง SMS ข้อความทักทายไปยังหมายเลขโทรศัพท์นั้น โปรแกรมนี้สามารถนำไปประยุกต์เพื่อใช้ส่งค่าอื่นๆ ได้เช่น ค่าที่อ่านจากเซ็นเซอร์ หรือเงื่อนไขที่ต้องการตรวจสอบ หรือกำหนดให้ส่งข้อความตามระยะเวลาที่กำหนด

การรับ SMS

ปกติหาก AirCard ทำงานอยู่เมื่อมี SMS ส่งเข้ามามันจะเก็บข้อความเหล่านั้นไว้ในหน่วยความจำภายใน SIM Card โดยอัตโนมัติ ซึ่งเราสามารถใช้ API ชื่อ python-gammu การอ่านและจัดการข้อความเหล่านี้ได้ โปรแกรมตัวอย่างต่อไปนี้จะทำการพิมพ์ข้อความ SMS ทั้งหมดที่มีใน SIM Card ออกมาพร้อมกับ หมายเลขโทรศัพท์ผู้ส่ง, วันเวลาที่ได้รับ, และสถานะ (อ่าน หรือ ยังไม่ได้อ่าน)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import gammu
def readAllSMS():
    sm = gammu.StateMachine()
    sm.ReadConfig()
    sm.Init()
    status = sm.GetSMSStatus()
    smsCount = status['SIMUsed']
    print "SMS count = " + str(smsCount)
    for i in range(0,smsCount):
         if i==0:
            sms = sm.GetNextSMS(Folder=0, Start=True)
         else:
            sms = sm.GetNextSMS(Folder=0, Location=i-1)
         print sms[0]['Number']     # Sender's phone number
         print sms[0]['DateTime']   # Receive date and time
         print sms[0]['State']      # message state (unread/read)
         print sms[0]['Text']       # SMS content
         print "=================================="
    print "Done"
readAllSMS()

โปรแกรมตัวอย่างถัดไปจะคอยตรวจสอบว่ามี SMS ใหม่เข้ามาหรือไม่ และทำงานตามคำสั่งที่ได้รับในข้อความนั้นๆ ซึ่งในที่นี้คือทำการเปิดปิดมอเตอร์ที่ต่อกับบอร์ด PiTopping

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import gammu
import time
from pibot import *
smsCount = 0
def executeCommand(command):
    if command=='on':
        talkTo('a')
        on()
    elif command == 'off':
        talkTo('a')
        off()
def checkSMS():
    global smsCount
    status = sm.GetSMSStatus()
    # check amount of SMS in the SIM card
    newSmsCount = status['SIMUsed']
    print "SMS count = " + str(newSmsCount)
    # if new SMS
    if (newSmsCount > 0) and (newSmsCount != smsCount) :
    smsCount = newSmsCount
       # read the SMS
       sms = sm.GetNextSMS(Folder=0, Location=smsCount-1)
       # only use 'unread' SMS
       if sms[0]['State'].lower() == 'unread':
           # copy the SMS content
           command = sms[0]['Text'].lower()
           print "New command: " + command
           # execute the SMS command
           executeCommand(command)   
    print "Done"
sm = gammu.StateMachine()
sm.ReadConfig()
sm.Init()
while True:
    print "Checking SMS"
    checkSMS()
    time.sleep(4)

การทำงานของโปรแกรมข้างต้นเป็นดังนี้

  • โปรแกรมจะคอยเรียกฟังก์ชัน checkSMS() ทุกๆ 4 วินาที
  • ในฟังก์ชัน checkSMS() จะทำงานดังนี้
    • จะคอยอ่านจำนวน SMS ที่มีอยู่ใน SIM และเอาไปเทียบกับจำนวนที่เก็บไว้ในตัวแปร smsCount หากมีค่าไม่เท่ากันก็แสดงว่ามีข้อความใหม่เข้ามา
    • เมื่อมีข้อความใหม่โปรแกรมก็จะตรวจสอบเพื่อความแน่ใจว่าสถานะของข้อความนั้นคือยังไม่ได้อ่าน (UnRead)  ถ้าเป็นจริงก็จะส่งข้อความนั้นให้ฟังก์ชัน executeCommand() นำไปประมวลผลต่อไป (ว่าควรเปิด หรือปิดมอเตอร์)

วิดีโอสาธิตการทำงานของโปรแกรม

คำแนะนำ

  • ในการรับ SMS ควรทำการลบข้อความที่ไม่ได้ใช้เป็นพักๆ เพื่อป้องกันไม่ให้หน่วยความจำของ SIM Card เต็ม ซึ่งอาจทำให้ไม่สามารถรับข้อความใหม่ๆ ได้ โดยคำสั่งที่ใช้ลบข้อความทั้งหมดใน SIM คือ
gammu deleteallsms 1

โดยจะเรียกใช้จาก Command Prompt หรือในภาษา Python ผ่านทาง คำสั่ง commands.getoutput() ก็ได้

  • จากการทดลองใช้งาน พบว่าบริษัทผู้ให้บริการมักมีการส่งข้อความ SMS โฆษณาประชาสัมพันธ์ต่างๆ เข้ามาบ่อยๆ ดังนั้นหากจะใช้การรับ SMS เพื่อสั่งงาน ควรตรวจสอบเนื้อหาให้แน่ใจเสมอว่าใช่คำสั่งที่ส่งมาจริงๆ หรือไม่

อ้างอิง

รายละเอียดและคำสั่งเพิ่มเติมเกี่ยวกับการควบคุมระบบ SMS สามารถศึกษาได้จาก

 สรุป

การรับและส่ง SMS นั้นทำได้ง่ายขึ้นมากเมื่อใช้ Raspberry Pi คู่กับ USB AirCard เทียบกับวิธีการเดิมของระบบสมองกลฝังตัวทั่วไป บทความนี้ได้แนะนำวิธีการเบื้องต้นในการใช้งาน SMS ซึ่งน่าจะครอบคลุมความต้องการพื้นฐานของโครงงานทั่วไปที่ต้องการใช้ความสามารถนี้

MYSQL Create databases

Pre-Flight Check
  • These instructions are intended for creating a MySQL database on Linux via the command line.
  • I’ll be working from a Liquid Web Core Managed CentOS 6.5 server, and I’ll be logged in as root.
Create a MySQL Database

First we’ll login to the MySQL server from the command line with the following command:

mysql -u root -p

In this case, I’ve specified the user root with the -u flag, and then used the -p flag so MySQL prompts for a password. Enter your current password to complete the login.

If you need to change your root (or any other) password in the database, then follow this tutorial on changing a password for MySQL via the command line.

You should now be at a MySQL prompt that looks very similar to this:

mysql>

To create a database with the name tutorial_database type the following command:

CREATE DATABASE tutorial_database;

If a database of the same name already exists, then a new database will not be created and you’ll receive this error:

ERROR 1007 (HY000): Can't create database 'tutorial_database'; database exists

To avoid seeing this error use the following command instead:

CREATE DATABASE IF NOT EXISTS tutorial_database;

The above command will only create the database tutorial_database if a database of that name does not already exist.

View All MySQL Databases

To view the database you’ve created simply issue the following command:

SHOW DATABASES;

Your result should be similar to this:

mysql> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| test               |
| tutorial_database  |
+--------------------+
4 rows in set (0.00 sec)

FreeBSD 10 FAMP

FAMP – Installing Apache2.4, MySQL, PHP on FreeBSD 10

Here is a procedure to install a FAMP(FreeBSD with Apache, MySQL and PHP) server. The following setup runs Apache 2.4, MySQL 5.6, and PHP 5.5 on FreeBSD 10. If any version of the packages needs to be changed, replace the versions in the commands accordingly.

Pre-Installation Tasks

Before installation of the components, Download the compressed snapshot of the ports collection, using the following command

# portsnap fetch

Now extract the snapshot into /usr/ports using the following command

# portsnap extract

Apache 2.4 – Installation and Configuration

# cd /usr/ports/www/apache24
# make install

(While running “make install” the installer asks to check the boxes to install various libraries and support packages. Check the appropriate boxes as per requirements.

# make clean

Edit the apache configuration file i.e. /usr/local/etc/apache24/httpd.conf and make the following changes

ServerRoot "/usr/local"
ServerAdmin you@your.address
ServerName www.example.com:80
DocumentRoot "/usr/local/www/apache24/data"
Listen :80

Edit the /etc/hosts file and add the following line:

<ip-address>                  <hostname>.<domain>

eg:

192.168.1.1               hostname.example.org

Create a file named /boot/loader.conf or edit it if it is already present and add the following line:

accf_http_load="YES"

Add the following line to /etc/rc.conf

 apache24_enable="YES"

Test the apache server installation using the following command:

# /usr/local/sbin/apachectl start

MySQL – Installation and Configuration

# cd /usr/ports/databases/mysql56-server/
# make install
# make clean

Start MySQL

 # /usr/local/etc/rc.d/mysql-server onestart

Add the following line to the file /etc/rc.conf

 mysql_enable="YES"

Set password for my sql using the following command

# rehash
# mysqladmin -uroot password ''

Configuring mysql

Use the following command

 # cp /usr/local/share/mysql/my-default.cnf /etc/my.cnf

Restart mysql using the following commands

# /usr/local/etc/rc.d/mysql-server restart

PHP – Installation and Configuration

Use the following commands to install PHP5.5 and other supporting packages

# cd /usr/ports/lang/php55
# make install
# make clean

Check the option ‘Build Apache Module’ as shown in the image and continue

PHP_apache module

Edit /usr/local/etc/apache24/httpd.conf file and add the following lines under /AddType

AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps

And add the following line under LoadModule section

LoadModule php5_module        libexec/apache24/libphp5.so

Modify the line ‘DirectoryIndex index.html’ to the following

 DirectoryIndex index.php index.html

Now restart the apache server by using the following command

# /usr/local/sbin/apachectl restart

Setup 2 NIC BSD

/etc/rc.conf

ifconfig_bge0=”inet 192.168.10.100 netmask 255.255.255.0″

defaultrouter=”192.168.10.1″
ifconfig_bge1=”inet 192.168.20.100 netmask 255.255.255.0″

IPFW Firewall BSD

IPF=”ipfw -q add”
ipfw -q -f flush
#loopback
$IPF 10 allow all from any to any via lo0
$IPF 20 deny all from any to 127.0.0.0/8
$IPF 30 deny all from 127.0.0.0/8 to any
$IPF 40 deny tcp from any to any frag
# statefull
$IPF 50 check-state
$IPF 60 allow tcp from any to any established
$IPF 70 allow all from any to any out keep-state
$IPF 80 allow icmp from any to any
# open port ftp (20,21), ssh (22), mail (25)
# http (80), dns (53) etc
$IPF 110 allow tcp from any to any 21 in via bge1
$IPF 120 allow tcp from any to any 21 out via bge1
$IPF 130 allow tcp from any to any 22 in via bge1
$IPF 140 allow tcp from any to any 22 out via bge1
$IPF 150 allow tcp from any to any 80 in
$IPF 160 allow tcp from any to any 80 out
$IPF 200 allow tcp from any to any 443 in
$IPF 210 allow tcp from any to any 443 out
# deny and log everything
$IPF 500 deny log all from any to any

FreeBSD Setting up Firewall using IPFW

FreeBSD compile kernel for IPFW

This step is optional. You do not need to compile IPFW into the FreeBSD kernel unless you want NAT function enabled. However some old version may not have IPFW compiled. Here is a quick guide to compile kernel with IPFW.

Make sure IPFW support not compiled into the kernel:
#ipfw list
If you get an error that read as follows, you must now compile the source code for the kernel.
ipfw: getsockopt(IP_FW_GET): Protocol not available

Another option is open default kernel config file /usr/src/sys/i386/conf and look for IPFIREWALL option:
# grep IPFIREWALL /usr/src/sys/i386/conf

Building and Installing a Custom Kernel with IPFW

Copy default kernel file:
# cd /usr/src/sys/i386/conf
# cp GENERIC IPFWKERNEL

Add IPFW support:
# vi IPFWKERNEL
Append following directives:
options IPFIREWALL # required for IPFW
options IPFIREWALL_VERBOSE # optional; logging
options IPFIREWALL_VERBOSE_LIMIT=10 # optional; don't get too many log entries
options IPDIVERT # needed for natd

Save and close the file. Building a Kernel, type following commnds:
# cd /usr/src
# make buildkernel KERNCONF=IPFWKERNEL

Install the new kernel:
# make installkernel KERNCONF=IPFWKERNEL
Now reboot the system:
# reboot

Step # 1: Enabling IPFW

Open /etc/rc.conf file
# vi /etc/rc.conf
Append following settings:
firewall_enable="YES"
firewall_script="/usr/local/etc/ipfw.rules"

Save and close the file..

Step # 2 Write a Firewall Rule Script

You need to place a firewall rules in a script called /usr/local/etc/ipfw.rule:
# vi /usr/local/etc/ipfw.rules
Append following code:

IPF="ipfw -q add"
ipfw -q -f flush
#loopback
$IPF 10 allow all from any to any via lo0
$IPF 20 deny all from any to 127.0.0.0/8
$IPF 30 deny all from 127.0.0.0/8 to any
$IPF 40 deny tcp from any to any frag
# statefull
$IPF 50 check-state
$IPF 60 allow tcp from any to any established
$IPF 70 allow all from any to any out keep-state
$IPF 80 allow icmp from any to any
# open port ftp (20,21), ssh (22), mail (25)
# http (80), dns (53) etc
$IPF 110 allow tcp from any to any 21 in via bge1
$IPF 120 allow tcp from any to any 21 out via bge1
$IPF 130 allow tcp from any to any 22 in via bge1
$IPF 140 allow tcp from any to any 22 out via bge1
$IPF 150 allow tcp from any to any 80 in
$IPF 160 allow tcp from any to any 80 out
$IPF 200 allow tcp from any to any 443 in
$IPF 210 allow tcp from any to any 443 out
# deny and log everything
$IPF 500 deny log all from any to any

Save and close the file.

Step # 3: Start a firewall

You can reboot the box or you could reload these rules by entering on the command line.
# sh /usr/local/etc/ipfw.rules

Task: List all the rules in sequence

Type the following command:
# ipfw list