Início

porplague70

Google reCAPTCHA V2 tutorial with Example Demo in PHP

Google has announced new service to prevent spams and attacks to your website. They name it “NO CAPTCHA reCAPTCHA” . Google reCAPTCHA is designed to protect your website from spams and abuse.

In this tutorial i am going to show you how to integrate it into your website. For demo purpose i made one simple script. Please look at the demo.LIVE DEMODOWNLOAD

Google has deprecated the reCAPTCHA V1. We have updated the article to meet the changes of Google reCAPTCHA V2.

Table of Contents

Register your website and get Secret Key.

Very first thing you need to do is register your website on Google recaptcha to do that click here.

Login to your Google account and create the app by filling the form. Select the reCAPTCHA v2 and in that select “I am not a robot” checkbox option.

google recaptcha v2 create app

Once submit, Google will provide you following two information.

  • Site key
  • Secret key
Google recaptcha v2 credentials

Integrate Google reCAPTCHA in your website.

To integrate it into your website you need to put it in client side as well as in Server side. In client HTML page you need to integrate this line before <HEAD> tag.<script src=’https://www.google.com/recaptcha/api.js’ async defer></script>

And to show the widget into your form you need to put this below contact form, comment form etc.<div class=”g-recaptcha” data-sitekey=”== Your site Key ==”></div>

When the form get submit to Server, this script will send ‘g-recaptcha-response’ as a POST data. You need to verify it in order to see whether user has checked the Captcha or not.

Sample project

Here is the HTML code for the simple form with comment box and submit button. On submit of this form we will use PHP in back-end to do the Google reCAPTCHA validation.Index.html<html>
  <head>
    <title>Google recapcha demo – Codeforgeek</title>
    <script src=’https://www.google.com/recaptcha/api.js’ async defer></script>
  </head>
  <body>
    <h1>Google reCAPTHA Demo</h1>
    <form id=”comment_form” action=”form.php” method=”post”>
      <input type=”email” placeholder=”Type your email” size=”40″><br><br>
      <textarea name=”comment” rows=”8″ cols=”39″></textarea><br><br>
      <input type=”submit” name=”submit” value=”Post comment”><br><br>
      <div class=”g-recaptcha” data-sitekey=”=== Your site key ===”></div>
    </form>
  </body>
</html>

google recaptcha form

This will generate this form.

On server side i am using PHP for now. So on Form submit request we will check the POST variable.form.php<?php
        $email;$comment;$captcha;
        if(isset($_POST[‘email’])){
          $email=$_POST[‘email’];
        }
        if(isset($_POST[‘comment’])){
          $comment=$_POST[‘comment’];
        }
        if(isset($_POST[‘g-recaptcha-response’])){
          $captcha=$_POST[‘g-recaptcha-response’];
        }
        if(!$captcha){
          echo ‘<h2>Please check the the captcha form.</h2>’;
exit;
        }
        $secretKey = “Put your secret key here”;
        $ip = $_SERVER[‘REMOTE_ADDR’];
// post request to server
        $url = ‘https://www.google.com/recaptcha/api/siteverify?secret=’ .urlencode($secretKey) .  ‘&response=’ . urlencode($captcha);
        $response = file_get_contents($url);
        $responseKeys = json_decode($response,true);
// should return JSON with success as true
        if($responseKeys[“success”]) {
                echo ‘<h2>Thanks for posting comment</h2>’;
        } else {
                echo ‘<h2>You are spammer ! Get the @$%K out</h2>’;
        }
?>

try out the demo to see how it works.

porplague70

Comando ifconfig não funciona no Debian 9 “Stretch”

Comando ifconfig não funciona no Debian 9 “Stretch”

O comando ifconfig não funciona no Debian 9 “Stretch” porquê precisamos instalar primeiramente o pacote net-tools. vamos entender quem é o net-tools:

Debian.org (net-tools)

Pacote net-tools

Este pacote inclui as importantes ferramentas para controlar o sub-sistema de rede do kernel do Linux. exemplos:

  • arp
  • ifconfig
  • netstat
  • rarp
  • nameif
  • route

Além das ferramentas, o net-tools de forma adicional contém utilitários relacionados a tipos particulares de hardware de rede como:

  • plipconfig
  • slattach
  • mii-tool

Além dos tipos particulares de hardware de rede, o pacote possui aspectos avançados de configuração IP, exemplos:

  • iptunnel
  • ipmaddr

As listas acima são apenas exemplificativas, ou seja, existem mais ferramentas que também fazem parte do pacote net-tools.

Instalação do pacote net-tools

Antes de realizar qualquer instalação de pacotes via apt (gerenciador de pacotes), é necessário realizar a atualização dos repositórios de pacotes com o comando: sudo apt-get update, após a atualização realize a instalação.

Para instalar o pacote net-tools no Debian 9 (Stretch) você precisa executar os seguintes comandos no terminal:

sudo apt-get update -y
sudo apt-get install net-tools -y

Nota: o parâmetro -y é para que o comando seja executado sem a interação com o usuário, ou seja, será executado sem a necessidade de pressionar a tecla y (yes) para dar continuidade a instalação dos pacotes.

porplague70

Liberar uso do Skype atrás de um Firewall

Para resolver o problema fiz uma regra tendo a LAN como origem e destino um grupo de IPs (Alias) com a porta 443.

IPs:

157.55.135.130
157.55.135.134
157.55.134.136
13.107.3.128
13.90.95.57
65.55.163.82
65.55.163.78
52.114.128.10
65.55.163.76
23.101.156.198
104.46.97.118
104.215.101.245
104.208.165.109
52.179.199.114
52.187.36.169
52.114.142.67
52.114.32.8
65.52.108.76
40.84.51.249
13.94.112.175

 

Segue links:
config.edge.skype.com
edge.skype.com
options.skype.com
api.asm.skype.com
avatar.skype.com
wsapi.skype.com
people.skype.com

porplague70

Ip´s skype

188.129.195.0/24
5.64.136.0/24
187.170.24.0/24
78.134.9.0/24
64.4.23.0/24
212.187.172.0/24
213.199.179.0/24
64.94.18.0/24
184.25.203.0/24
65.55.64.0/24
204.9.163.0/24
91.190.216.0/24
65.55.71.0/24
65.55.223.0/24
157.56.52.0/24
111.221.77.0/24
157.55.130.0/24
91.190.218.0/24
149.13.32.0/24
65.54.165.0/24
65.55.223.0/24
91.190.216.0/24
184.25.203.0/24
64.94.18.0/24
212.161.8.0/24
78.141.177.0/24
157.55.56.0/24
193.95.154.0/24
157.55.235.0/24
111.221.74.0/24
193.95.154.0/24
157.55.130.0/24
71.58.242.0/24
204.9.163.0/24
184.25.201.0/24
78.141.179.0/24
71.92.79.0/24
65.55.223.0/24
76.89.177.0/24
204.9.163.0/24
212.187.172.0/24
184.25.203.0/24
193.120.199.0/24
91.190.216.0/24
157.55.130.0/24
184.25.203.0/24
157.55.235.0/24
65.55.223.0/24
84.250.183.0/24
66.171.55.0/24
78.141.179.0/24
157.55.130.0/24
184.25.201.0/24
65.54.187.0/24
199.7.71.0/24
184.30.37.0/24
65.54.186.0/24
79.86.239.0/24
212.8.166.0/24
64.4.23.0/24
111.221.77.0/24
91.190.218.0/24
65.55.158.0/24
157.56.52.0/24
157.55.130.0/24
157.56.149.0/24
189.86.41.0/24
239.255.255.0/24
239.255.255.0/24

porplague70

O arquivo está bloqueado – como desbloquear.

Você não pode acessar os arquivos porque eles estão bloqueados e você encontra esses erros no seu arquivo de log:

{"reqId":"0DijSqEkfOg2iyh9VD8J","remoteAddr":"xx.xx.xx.xx","app":"webdav","message":"Exception: {\"Message\":\"HTTP\\\/1.1 423 \\\"path\\\/file.extension\\\" is locked\",\"Exception\":\"OCA\\\\DAV\\\\Connector\\\\Sabre\\\\Exception\\\\FileLocked\",\"Code\":0,\"Trace\":\"#0

Se você estiver executando a ramificação ownCloud 8.2.x, certifique-se de estar usando pelo menos 8.2.2 (as versões anteriores tinham um bug causando esse problema).

Desativar manualmente o estado de bloqueio:

  • coloque o ownCloud no modo de manutenção: edite config/config.phpe altere esta linha:
    'maintenance' => true,
  • Mesa vazia oc_file_locks: use ferramentas como o phpmyadmin ou conecte-se diretamente ao seu banco de dados e execute:
    DELETE FROM oc_file_locks WHERE 1
  • desativar o modo de manutenção (desfazer a primeira etapa).

Redefinir automaticamente o estado de bloqueio:
Normalmente ownCloud deve redefinir o estado bloqueado por conta própria através de trabalhos em segundo plano. Portanto, certifique-se de que seus cron-jobs sejam executados corretamente (a página de administração informa quando o cron foi executado pela última vez): https://doc.owncloud.org/server/9.0/admin_manual/configuration_server/background_jobs_configuration.html 3.4k 

Solução permanente (se acontecer regularmente)

porplague70

Criando partição maior que 2 TB no Linux

Descobri somente na pratica que o MBR está limitado para partições de até 2 TB, mas para maiores temos uma solução o GPT!

Para mais informações olhe as fontes!

Aqui vai como fazer:

Vendo dados do Disco

# fdisk -l /dev/sdb

Saida:

Disk /dev/sdb: 3000.6 GB, 3000592982016 bytes
255 heads, 63 sectors/track, 364801 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x00000000
Disk /dev/sdb doesn't contain a valid partition table

Criar um partição de 3 TB

# parted /dev/sdb

Saída:

GNU Parted 2.3
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted)

Criando um novo rotulo do tipo GPT:

(parted) mklabel gpt

saída:

Warning: The existing disk label on /dev/sdb will be destroyed and all data on this disk will be lost. Do you want to continue?
Yes/No? yes
(parted)

Setar para TB a unidade de medida:

(parted) unit TB

Criando a partição com 3TB:

(parted) mkpart primary 0.00TB 3.00TB

Imprimindo o resultado:

(parted) print

Sample outputs:

Model: ATA ST33000651AS (scsi)
Disk /dev/sdb: 3.00TB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Number  Start   End     Size    File system  Name     Flags
 1      0.00TB  3.00TB  3.00TB  ext4         primary

Saindo e salvando as mudanças:

(parted) quit

Agora utilize o mkfs.ext4 para formatar a partição criada!

# mkfs.ext4 /dev/sdb1

porplague70

Tagging obvious Spam

Left Menu > Domain Templates > RBL Templates

Add: spamhaus-zen, spamcop.net, sorbs-dnsrbl

Left Menu > Domain Templates > Process Policy

Modify: Spam Lists to Be Spam = 1
(or 2 to be less aggressive)

Modify: Spam Lists to Reach High Score = 2
(or 3 to be less aggressive)

Left Menu > Mailborder Servers > MTA > Edit Postfix

Scroll down to “smtpd_recipient_restrictions” and add this above the “permit” statement:

reject_rbl_client zen.spamhaus.org,
reject_rbl_client bl.spamcop.net,
reject_rbl_client cbl.abuseat.org,
reject_rbl_client b.barracudacentral.org,

This will stop spam from being accepted by the server if the remote MTA is on any of the blacklists.

porplague70

pf2ad Script para aplicação de configuração do Samba para autenticação AD no Squid para o pfSense®

pf2ad

Script para aplicação de configuração do Samba para autenticação AD no Squid para o pfSense®

 

https://pf2ad.mundounix.com.br/pt/index.html

porplague70

How To Install and Secure phpMyAdmin with Apache on a CentOS 7 Server

Introduction

Relational database management systems like MySQL and MariaDB are needed for a significant portion of web sites and applications. However, not all users feel comfortable administering their data from the command line.

To solve this problem, a project called phpMyAdmin was created in order to offer an alternative in the form of a web-based management interface. In this guide, we will demonstrate how to install and secure a phpMyAdmin configuration on a CentOS 7 server. We will build this setup on top of the Apache web server, the most popular web server in the world.

Prerequisites

Before we begin, there are a few requirements that need to be settled.

To ensure that you have a solid base to build this system upon, you should run through our initial server setup guide for CentOS 7. Among other things, this will walk you through setting up a non-root user with sudo access for administrative commands.

The second prerequisite that must be fulfilled in order to start on this guide is to install a LAMP (Linux, Apache, MariaDB, and PHP) stack on your CentOS 7 server. This is the platform that we will use to serve our phpMyAdmin interface (MariaDB is also the database management software that we are wishing to manage). If you do not yet have a LAMP installation on your server, follow our tutorial on installing LAMP on CentOS 7.

When your server is in a properly functioning state after following these guides, you can continue on with the rest of this page.

Step One — Install phpMyAdmin

With our LAMP platform already in place, we can begin right away with installing the phpMyAdmin software. Unfortunately, phpMyAdmin is not available in CentOS 7’s default repository.

To get the packages we need, we’ll have to add an additional repo to our system. The EPEL repo (Extra Packages for Enterprise Linux) contains many additional packages, including the phpMyAdmin package we are looking for.

The EPEL repository can be made available to your server by installing a special package called epel-release. This will reconfigure your repository list and give you access to the EPEL packages.

To install, just type:

sudo yum install epel-release

Now that the EPEL repo is configured, you can install the phpMyAdmin package using the yum packaging system by typing:

sudo yum install phpmyadmin

The installation will now complete. The installation included an Apache configuration file that has already been put into place. We will need to modify this a bit to get it to work correctly for our installation.

Open the file in your text editor now so that we can make a few changes:

sudo nano /etc/httpd/conf.d/phpMyAdmin.conf

Inside, we see some directory blocks with some conditional logic to explain the access policy for our directory. There are two distinct directories that are defined, and within these, configurations that will be valid for both Apache 2.2 and Apache 2.4 (which we are running).

Currently, this setup is configured to deny access to any connection not being made from the server itself. Since we are working on our server remotely, we need to modify some lines to specify the IP address of your home connection.

Change any lines that read Require ip 127.0.0.1 or Allow from 127.0.0.1 to refer to your home connection’s IP address. If you need help finding the IP address of your home connection, check out the next section. There should be four locations in the file that must be changed:

. . .
Require ip your_workstation_IP_address
. . .
Allow from your_workstation_IP_address
. . .
Require ip your_workstation_IP_address
. . .
Allow from your_workstation_IP_address
. . .

When you are finished, restart the Apache web server to implement your modifications by typing:

sudo systemctl restart httpd.service

With that, our phpMyAdmin installation is now operational. To access the interface, go to your server’s domain name or public IP address followed by /phpMyAdmin, in your web browser:

http://server_domain_or_IP/phpMyAdmin

phpMyAdmin login screen

To sign in, use a username/password pair of a valid MariaDB user. The root user and the MariaDB administrative password is a good choice to get started. You will then be able to access the administrative interface:

phpMyAdmin admin interface

Find Your IP Address

You will need to know the IP address of the computer you are using to access your databases in order to complete the step above. This is a security precaution so that unauthorized people cannot connect to your server.

Note: This is not the IP address of your VPS, it is the IP address of your home or work computer.

You can find out how the greater web sees your IP address by visiting one of these sites in your web browser:

Compare a few different sites and make sure they all give you the same value. Use this value in the configuration file above.

Step Two — Secure your phpMyAdmin Instance

The phpMyAdmin instance installed on our server should be completely usable at this point. However, by installing a web interface, we have exposed our MySQL system to the outside world.

Even with the included authentication screen, this is quite a problem. Because of phpMyAdmin’s popularity combined with the large amount of data it provides access to, installations like these are common targets for attackers.

We will implement two simple strategies to lessen the chances of our installation being targeted and compromised. We will change the location of the interface from /phpMyAdmin to something else to sidestep some of the automated bot brute-force attempts. We will also create an additional, web server-level authentication gateway that must be passed before even getting to the phpMyAdmin login screen.

Changing the Application’s Access Location

In order for our Apache web server to work with phpMyAdmin, our phpMyAdmin Apache configuration file uses an alias to point to the directory location of the files.

To change the URL where our phpMyAdmin interface can be accessed, we simply need to rename the alias. Open the phpMyAdmin Apache configuration file now:

sudo nano /etc/httpd/conf.d/phpMyAdmin.conf

Toward the top of the file, you will see two lines that look like this:

Alias /phpMyAdmin /usr/share/phpMyAdmin
Alias /phpmyadmin /usr/share/phpMyAdmin

These two lines are our aliases, which means that if we access our site’s domain name or IP address, followed by either /phpMyAdmin or /phpmyadmin, we will be served the content at /usr/share/phpMyAdmin.

We want to disable these specific aliases since they are heavily targeted by bots and malicious users. Instead, we should decide on our own alias. It should be easy to remember, but not easy to guess. It shouldn’t indicate the purpose of the URL location. In our case, we’ll go with /nothingtosee.

To apply our intended changes, we should remove or comment out the existing lines and add our own:

# Alias /phpMyAdmin /usr/share/phpMyAdmin
# Alias /phpmyadmin /usr/share/phpMyAdmin
Alias /nothingtosee /usr/share/phpMyAdmin

When you are finished, save and close the file.

To implement the changes, restart the web service:

sudo systemctl restart httpd.service

Now, if you go to the previous location of your phpMyAdmin installation, you will get a 404 error:

http://server_domain_or_IP/phpMyAdmin

phpMyAdmin 404 error

However, your phpMyAdmin interface will be available at the new location we selected:

http://server_domain_or_IP/nothingtosee

phpMyAdmin login screen

Setting up a Web Server Authentication Gate

The next feature we wanted for our installation was an authentication prompt that a user would be required to pass before ever seeing the phpMyAdmin login screen.

Fortunately, most web servers, including Apache, provide this capability natively. We will just need to modify our Apache configuration file to use an authorization file.

Open the phpMyAdmin Apache configuration file in your text editor again:

sudo nano /etc/httpd/conf.d/phpMyAdmin.conf

Within the /usr/share/phpMyAdmin directory block, but outside of any of the blocks inside, we need to add an override directive. It will look like this:

. . .
<Directory /usr/share/phpMyAdmin/>
   AllowOverride All
   <IfModule mod_authz_core.c>
   . . .
</Directory>
. . .

This will allow us to specify additional configuration details in a file called .htaccess located within the phpMyAdmin directory itself. We will use this file to set up our password authentication.

Save and close the file when you are finished.

Restart the web service to implement this change:

sudo systemctl restart httpd.service

Create an .htaccess File

Now that we have the override directive in our configuration, Apache will look for a file called .htaccesswithin the /usr/share/phpMyAdmin directory. If it finds one, it will use the directives contained within to supplement its previous configuration data.

Our next step is to create the .htaccess file within that directory. Use your text editor to do so now:

sudo nano /usr/share/phpMyAdmin/.htaccess

Within this file, we need to enter the following information:

AuthType Basic
AuthName "Admin Login"
AuthUserFile /etc/httpd/pma_pass
Require valid-user

Let’s go over what each of these lines mean:

  • AuthType Basic: This line specifies the authentication type that we are implementing. This type will implement password authentication using a password file.
  • AuthName: This sets the message for the authentication dialog box. You should keep this generic so that unauthorized users won’t gain knowledge about what is being protected.
  • AuthUserFile: This sets the location of the actual password file that will be used for authentication. This should be outside of the directories that are being served. We will create this file in a moment.
  • Require valid-user: This specifies that only authenticated users should be given access to this resource. This is what actually stops unauthorized users from entering.

When you are finished entering this information, save and close the file.

Create the Password File for Authentication

Now that we have specified the location for our password file through the use of the AuthUserFiledirective in our .htaccess file, we need to create and populate the password file.

This can be accomplished through the use of an Apache utility called htpasswd. We invoke the command by passing it the location where we would like to create the file and the username we would like to enter authentication details for:

sudo htpasswd -c /etc/httpd/pma_pass username

The -c flag indicates that this will create an initial file. The directory location is the path and filename that will be used for the file. The username is the first user we would like to add. You will be prompted to enter and confirm a password for the user.

If you want to add additional users to authenticate, you can call the same command again without the -cflag, and with a new username:

sudo htpasswd /etc/httpd/pma_pass seconduser

With our password file created, an authentication gateway has been implemented and we should now see a password prompt the next time we visit our site:

http://server_domain_or_IP/nothingtosee

Apache authentication page

Once you enter your credentials, you will be taken to the normal phpMyAdmin login page. This added layer of protection will help keep your MySQL logs clean of authentication attempts in addition to the added security benefit.

Conclusion

You can now manage your MySQL databases from a reasonably secure web interface. This UI exposes most of the functionality that is available from the MySQL command prompt. You can view databases and schema, execute queries, and create new data sets and structures.

porplague70

How To Install Apache Tomcat 8 on CentOS 7

Introduction

Apache Tomcat is a web server and servlet container that is used to serve Java applications. Tomcat is an open source implementation of the Java Servlet and JavaServer Pages technologies, released by the Apache Software Foundation. This tutorial covers the basic installation and some configuration of the latest release of Tomcat 8 on your CentOS 7 server.

Prerequisites

Before you begin with this guide, you should have a separate, non-root user account set up on your server. You can learn how to do this by completing steps 1-3 in the initial server setup for CentOS 7. We will be using the demo user created here for the rest of this tutorial.

Install Java

Tomcat requires that Java is installed on the server, so any Java web application code can be executed. Let’s satisfy that requirement by installing OpenJDK 7 with yum.

To install OpenJDK 7 JDK using yum, run this command:

  • sudo yum install java-1.7.0-openjdk-devel

Answer y at the prompt to continue installing OpenJDK 7.

Note that a shortcut to the JAVA_HOME directory, which we will need to configure Tomcat later, can be found at /usr/lib/jvm/jre.

Now that Java is installed, let’s create a tomcat user, which will be used to run the Tomcat service.

Create Tomcat User

For security purposes, Tomcat should be run as an unprivileged user (i.e. not root). We will create a new user and group that will run the Tomcat service.

First, create a new tomcat group:

  • sudo groupadd tomcat

Then create a new tomcat user. We’ll make this user a member of the tomcat group, with a home directory of /opt/tomcat (where we will install Tomcat), and with a shell of /bin/false (so nobody can log into the account):

  • sudo useradd -M -s /bin/nologin -g tomcat -d /opt/tomcat tomcat

Now that our tomcat user is set up, let’s download and install Tomcat.

Install Tomcat

The easiest way to install Tomcat 8 at this time is to download the latest binary release then configure it manually.

Download Tomcat Binary

Find the latest version of Tomcat 8 at the Tomcat 8 Downloads page. At the time of writing, the latest version is 8.5.9. Under the Binary Distributions section, then under the Core list, copy the link to the “tar.gz”.

Let’s download the latest binary distribution to our home directory.

First, change to your home directory:

  • cd ~

Then use wget and paste in the link to download the Tomcat 8 archive, like this (your mirror link will probably differ from the example):

  • wget http://apache.mirrors.ionfish.org/tomcat/tomcat-8/v8.5.9/bin/apache-tomcat-8.5.9.tar.gz

We’re going to install Tomcat to the /opt/tomcat directory. Create the directory, then extract the the archive to it with these commands:

  • sudo mkdir /opt/tomcat
  • sudo tar xvf apache-tomcat-8*tar.gz -C /opt/tomcat –strip-components=1

Now we’re ready to set up the proper user permissions.

Update Permissions

The tomcat user that we set up needs to have the proper access to the Tomcat installation. We’ll set that up now.

Change to the Tomcat installation path:

  • cd /opt/tomcat

Give the tomcat group ownership over the entire installation directory:

  • sudo chgrp -R tomcat /opt/tomcat

Next, give the tomcat group read access to the conf directory and all of its contents, and execute access to the directory itself:

  • sudo chmod -R g+r conf
  • sudo chmod g+x conf

Then make the tomcat user the owner of the webappsworktemp, and logs directories:

  • sudo chown -R tomcat webapps/ work/ temp/ logs/

Now that the proper permissions are set up, let’s set up a Systemd unit file.

Install Systemd Unit File

Because we want to be able to run Tomcat as a service, we will set up a Tomcat Systemd unit file .

Create and open the unit file by running this command:

  • sudo vi /etc/systemd/system/tomcat.service

Paste in the following script. You may also want to modify the memory allocation settings that are specified in CATALINA_OPTS:

/etc/systemd/system/tomcat.service
# Systemd unit file for tomcat
[Unit]
Description=Apache Tomcat Web Application Container
After=syslog.target network.target

[Service]
Type=forking

Environment=JAVA_HOME=/usr/lib/jvm/jre
Environment=CATALINA_PID=/opt/tomcat/temp/tomcat.pid
Environment=CATALINA_HOME=/opt/tomcat
Environment=CATALINA_BASE=/opt/tomcat
Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'
Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'

ExecStart=/opt/tomcat/bin/startup.sh
ExecStop=/bin/kill -15 $MAINPID

User=tomcat
Group=tomcat
UMask=0007
RestartSec=10
Restart=always

[Install]
WantedBy=multi-user.target

Save and exit. This script tells the server to run the Tomcat service as the tomcat user, with the settings specified.

Now reload Systemd to load the Tomcat unit file:

  • sudo systemctl daemon-reload

Now you can start the Tomcat service with this systemctl command:

  • sudo systemctl start tomcat

Check that the service successfully started by typing:

  • sudo systemctl status tomcat

If you want to enable the Tomcat service, so it starts on server boot, run this command:

  • sudo systemctl enable tomcat

Tomcat is not completely set up yet, but you can access the default splash page by going to your domain or IP address followed by :8080 in a web browser:

Open in web browser:
http://server_IP_address:8080

You will see the default Tomcat splash page, in addition to other information. Now we will go deeper into the installation of Tomcat.

Configure Tomcat Web Management Interface

In order to use the manager webapp that comes with Tomcat, we must add a login to our Tomcat server. We will do this by editing the tomcat-users.xml file:

  • sudo vi /opt/tomcat/conf/tomcat-users.xml

This file is filled with comments which describe how to configure the file. You may want to delete all the comments between the following two lines, or you may leave them if you want to reference the examples:

tomcat-users.xml excerpt
<tomcat-users>
...
</tomcat-users>

You will want to add a user who can access the manager-gui and admin-gui (webapps that come with Tomcat). You can do so by defining a user similar to the example below. Be sure to change the username and password to something secure:

tomcat-users.xml — Admin User
<tomcat-users>
    <user username="admin" password="password" roles="manager-gui,admin-gui"/>
</tomcat-users>

Save and quit the tomcat-users.xml file.

By default, newer versions of Tomcat restrict access to the Manager and Host Manager apps to connections coming from the server itself. Since we are installing on a remote machine, you will probably want to remove or alter this restriction. To change the IP address restrictions on these, open the appropriate context.xml files.

For the Manager app, type:

  • sudo vi /opt/tomcat/webapps/manager/META-INF/context.xml

For the Host Manager app, type:

  • sudo vi /opt/tomcat/webapps/host-manager/META-INF/context.xml

Inside, comment out the IP address restriction to allow connections from anywhere. Alternatively, if you would like to allow access only to connections coming from your own IP address, you can add your public IP address to the list:

context.xml files for Tomcat webapps
<Context antiResourceLocking="false" privileged="true" >
  <!--<Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />-->
</Context>

Save and close the files when you are finished.

To put our changes into effect, restart the Tomcat service:

  • sudo systemctl restart tomcat

Access the Web Interface

Now that Tomcat is up and running, let’s access the web management interface in a web browser. You can do this by accessing the public IP address of the server, on port 8080:

Open in web browser:
http://server_IP_address:8080

You will see something like the following image:

Tomcat root

As you can see, there are links to the admin webapps that we configured an admin user for.

Let’s take a look at the Manager App, accessible via the link or http://server_IP_address:8080/manager/html:

Tomcat Web Application Manager

The Web Application Manager is used to manage your Java applications. You can Start, Stop, Reload, Deploy, and Undeploy here. You can also run some diagnostics on your apps (i.e. find memory leaks). Lastly, information about your server is available at the very bottom of this page.

Now let’s take a look at the Host Manager, accessible via the link or http://server_IP_address:8080/host-manager/html/:

Tomcat Virtual Host Manager

From the Virtual Host Manager page, you can add virtual hosts to serve your applications from.

Conclusion

Your installation of Tomcat is complete! Your are now free to deploy your own Java web applications!