Migrating a Magento Installation from Apache2 to NGINX on Ubuntu 18.04 LTS

Magento is one of the worlds leading e-commerce CMS solutions and is used by over 200K websites. What makes Magento such an appealing e-commerce CMS is that Magento offers a free, community edition of their platform. Anyone with some Linux knowledge and access to a modest virtual machine can get their online store up and running in no time. Magento runs on a Linux stack giving wide flexibility on the open source components that are used to power the store. The typical first choice for a Linux web server is usually Apache which makes for a stable and dependable choice. However, there are other options that can offer greater performance with lower system resource usage. One popular such alternative is NGINX.

In this guide, we will walk through the process of migrating an existing Magento installation from Apache to NGINX on Ubuntu 18.04 LTS.

Prerequisites

In order to follow this guide you will need the following:

  • An Ubuntu 18.04 server.
  • A Magento installation.
  • A non-root sudo user account on the Magento server.

In order to begin this guide you need to log into your server as a non-root sudo enabled user.

Put Magento in Maintenance Mode

During this guide, we will be stopping and starting the web servers which will make your Magento store appear and disappear for any user accessing it. This is not a great experience for your clients we will avoid this issue by putting Magento into maintenance mode. When Magento is in maintenance mode any visitor will see a holding page and will not be able to interact with your store.

You put Magento into maintenance mode by running the following command:

sudo php /path/to/magento2/bin/magento maintenance:enable --ip=

The --ip= option will allow you to access your store from your IP whilst all other IP’s will see the maintenance page. This will allow you to view and check that the store is working whilst still maintaining maintenance mode for visitors.

Now that Magento is in maintenance mode we can install NGINX.

Step 2 – Installation

In this step, we will install NGINX and the PHP-FPM packages. NGINX uses PHP-FPM which is a performant re-implementation of standard PHP. If you are already using PHP-FPM with Apache you can remove it from the apt-get install command but leaving it in place will not cause a problem.

We should stop Apache here or the installation will encounter an error when APT attempts to start NGINX while Apache is running. The following commands will stop Apache running and disable it from stating on boot:

sudo systemctl stop apache2.service
sudo systemctl disable apache2.service

Run the following command to install NGINX and PHP-FPM:

sudo apt-get install nginx php-fpm

NGINX is now installed and ready for configuration.

Installation NGINX and PHP-FPM

In this step, we will configure NGINX to serve only an HTTP Magento instance. If your Magento instance uses HTTPS then skip ahead to the next section which covers migrating an HTTPS Magento instance.

NGINX works like Apache in that it has two directories /etc/nginx/sites-available and /etc/nginx/sites-enabled that contain the web server configuration to serve your store. We will first place the configuration file into /etc/nginx/sites-available and then create a symlink to that file in /etc/nginx/sites-enabled which will allow NGINX to start serving your site.

We will create and edit the site configuration file using a text editor. I will use nano throughout this guide but you can use whichever you are most comfortable with:

sudo nano /etc/nginx/sites-available/magento.conf

The contents of this file should look like the following basic example (remember you need to change exmaple.com and /var/www/magento2 to match your setup):

server {
   listen 80;
   server_name ;
   set $MAGE_ROOT /path/to/magento2;
   include /path/to/magento2/nginx.conf.sample;
}

upstream fastcgi_backend {
   server  unix:/var/run/php/php7.1-fpm.sock;
}

The above configuration assumes that you are using PHP 7.1 (the default) on your server. If you are using a different version then you will need to edit the line server unix:/var/run/php/php7.1-fpm.sock; to match the version of PHP and PHP-FPM you are using. If you run:

ls /var/run/php/

You will be able to see the name of the PHP-FPM socket that you need to use.

The following line:

include /path/to/magento2/nginx.conf.sample;

causes NGINX to load additional configuration contained in the file /path/to/magento2/nginx.conf.sample. This file is supplied by Magento and contains very important additional configuration such as blocking access to confidential files, setting compression etc. If you don’t have a copy of this file you can download one from these locations:

You will need to include this file for this NGINX configuration file to serve your store.

Now that the configuration file is in place we need to enable it by creating a symlink from sites-enabled with the following command:

sudo ln -s /etc/nginx/sites-available/magento.conf /etc/nginx/sites-enabled/

Then reload NGINX:

sudo systemctl reload nginx.service

NGINX should now be serving your store. You should visit your store in a browser to check that it is working normally. If your site does not render correctly after the migration it is quite likely because of stale cache and indexed data. Flushing the cache and re-indexing the site with these two commands will resolve this issue:

sudo php /path/to/magento2/bin/magento cache:flush
sudo php /path/to/magento2/bin/magento indexer:reindex

The site should now be working normally. You should visit both the home page and the admin pages to ensure they are working as expected. The following command will disable maintenance mode and resume normal site operation:

sudo php /path/to/magento2/bin/magento maintenance:disable

Your Magento instance is now migrated to using NGINX as its webserver.

Migrating An HTTPS Magento Instance

In this step, we will configure NGINX to serve an HTTPS enabled Magento instance. NGINX works like Apache in that it has two directories /etc/nginx/sites-available and /etc/nginx/sites-enabled that contain the website configuration. We will first place the configuration file into /etc/nginx/sites-available and then create a symlink to that file in /etc/nginx/sites-enabled which will enable NGINX to start serving your store.

We will create and edit the site configuration file using a text editor. I will use nano throughout this guide but you can use whichever you are most comfortable with:

sudo nano /etc/nginx/sites-available/magento.conf

The following file will serve an HTTPS site. The first server block will automatically redirect any visitors arriving on HTTP to the HTTPS site:

server {
    listen 80;
    server_name ;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl;
    server_name ;

    ssl on;
    ssl_certificate /path/to/fullchain.pem;
    ssl_certificate_key /path/to/privkey.pem;

    set $MAGE_ROOT /path/to/magento2;
    include /path/to/magento2/nginx.conf.sample;
}

upstream fastcgi_backend {
        server  unix:/run/php/php7.1-fpm.sock;
}

The above configuration assumes that you are using PHP 7.1 (the default) on your server. If you are using a different version then you will need to edit the line server unix:/var/run/php/php7.1-fpm.sock; to match the version of PHP and PHP-FPM you are using. If you run:

ls /var/run/php/

You will be able to see the name of the PHP-FPM socket that you need to use.

The following line:

include /path/to/magento2/nginx.conf.sample;

causes NGINX to load additional configuration contained in the file /path/to/magento2/nginx.conf.sample. This file is supplied by Magento and contains very important additional configuration such as blocking access to confidential files, setting compression, etc. If you don’t have a copy of this file you can download one from these locations:

You will need to include this file for this NGINX configuration file to serve your store.

Now that the configuration file is in place we need to enable it by creating a symlink from sites-enabled with the following command:

sudo ln -s /etc/nginx/sites-available/magento.conf /etc/nginx/sites-enabled/

Then reload NGINX:

sudo systemctl reload nginx.service

NGINX should now be serving your store. You should visit your store in a browser to check that it is working normally. If your site does not render correctly after the migration it is quite likely because of stale cache and indexed data. Flushing the cache and re-indexing the site with these two commands will resolve this issue:

sudo php /path/to/magento2/bin/magento cache:flush
sudo php /path/to/magento2/bin/magento indexer:reindex

The site should now be working normally. You should visit both the home page and the admin pages to ensure they are working as expected. The following command will disable maintenance mode and resume normal site operation:

sudo php /path/to/magento2/bin/magento maintenance:disable

Conclusion

Your site should now be running normally and taking advantage of the increased performance and reduced resource requirements of NGINX. If you need additional information on configuration and tuning NGINX their documentation can be found on their website here.

The post Migrating a Magento Installation from Apache2 to NGINX on Ubuntu 18.04 LTS appeared first on Low End Box.

How to Set Up a Minecraft Server on Your VPS

This tutorial will show you how to set up and configure your own Minecraft server on a VPS.

We will be installing SpigotMC, a highly optimized Minecraft server, written in Java, with integrated support for plugins. In the end, you will have a Minecraft server always ready for you and your friends to play on.

What We Are Going to Cover

  • How to install Java runtime and Git for Ubuntu/Debian and CentOS,
  • How to compile Spigot,
  • Connecting to the server and verifying that everything works correctly
  • An overview of some must-have plugins

Prerequisites

  • A clean Linux VPS running Ubuntu 16.04 and up, Debian, or CentOS 7
  • root user access
  • 1Gb of RAM memory for the Minecraft server itself, to support up to 4 players
  • Add 1Gb of RAM per additional 5 players
  • CentOS uses a lot of memory for itself, so plan on adding even more RAM on that operating system.
  • At least 2 CPU cores (for up to 4 players). More powerful CPUs with more cores will be required in case of higher loads.

Step 1: Installing Java Runtime and Git

Once you are logged in as root, you can create a new user account that you’ll use from now on for running Spigot. The root user is not needed for running a Minecraft server.

We’ll call the new user spigotuser. On both Ubuntu / Debian and CentoOS the first step is the same:

adduser spigotuser

Further instructions differ:

Setting Up Java and Git on Ubuntu / Debian

On Debian and Ubuntu, you need to add spigotuser to the sudo group, so that you can run commands as sudo:

usermod -aG sudo spigotuser

You will be immediately asked to enter a password for the new user, so provide it.

Log in as the new user:

su spigotuser

Run the following commands to refresh apt cache and install Git, Java and wget:

sudo apt update
sudo apt install -y git openjdk-8-jdk wget

Setting Up Java and Git on CentOS

On CentOS, to be able to run commands as sudo, you’ll need to add spigotuser to the wheel group:

usermod -aG wheel spigotuser

In contrast to Ubuntu, CentOS will not ask you to enter a password, so you’ll need to set it up manually with the following command:

passwd spigotuser

Then, log in as the new user:

su spigotuser

Use yum to install Java and wget:

sudo yum install -y java-1.8.0-openjdk-devel wget

You’ll need to install Git separately, because CentOS comes with an outdated version that practically won’t work. Add repository which maintains the latest Git to yum:

sudo yum -y install https://centos7.iuscommunity.org/ius-release.rpm

Then, install it:

sudo yum -y install git2u-all

Now you have all the reqired dependencies installed. Next, you’ll build Spigot.

Step 2: Building Spigot

Create a folder to house the binaries which we will soon generate:

mkdir ~/spigot-binaries

Navigate to it:

cd ~/spigot-binaries

Because of legal concerns, Spigot does not distribute binaries directly. Instead, you’ll have to download and run Build Tools, a specialized program that generates the final Spigot server binary.

Download the latest Build Tools version by running:

wget https://hub.spigotmc.org/jenkins/job/BuildTools/lastSuccessfulBuild/artifact/target/BuildTools.jar

Before actually running Build Tools, you’ll need to configure Git so that it does not automatically convert line endings:

git config --global --unset core.autocrlf

You can now run Build Tools to get fresh server binaries for the latest available server version:

java -jar BuildTools.jar --rev latest

Instead of latest, which may be unsuitable for production use, you can also pass in a specific Minecraft version. At the time of this writing, the latest stable Spigot version was 1.13.2. If you wanted this specific version, run this command:

java -jar BuildTools.jar --rev 1.13.2

The compilation will take a long time, especially on slower machines, so be patient. You’ll need to have at least 512Mb RAM free for Build Tools to use.

When it finishes compiling, you’ll have a JAR file in the directory, called spigot-rev.jar, where rev is the version of Minecraft. For the command above, it will be spigot-1.13.2.jar.

Step 3: Starting Up the Server

You should separate compilation files from server files, so create a new directory for the server:

mkdir ~/spigot-server

Copy the JAR file to the new directory:

cp spigot-1.13.2.jar ~/spigot-server/spigot.jar

Navigate to the directory:

cd ~/spigot-server

Before running the server for the first time, you’ll need to create a file called eula.txt to signify that you agree with the Mojang Account EULA. Create it using nano:

nano eula.txt

Add the following line:

eula=true

Save and close the file. You’ll now create a script that will be used for starting your Spigot Minecraft server. Create a file called start.sh:

nano start.sh

Add the following lines:

#!/bin/sh

java -Xms1G -Xmx1G -XX:+UseConcMarkSweepGC -jar spigot.jar

The command runs Spigot with 1Gb allocated (as denoted by 1G in the command). You must change this in both places to the amount of RAM you can give Spigot on your server – otherwise, it won’t run.

When you are done, save and close the file.

Make it executable:

chmod +x start.sh

Now, run Spigot server for the first time, which will generate configuration files and folders you can later customize:

./start.sh

Allow it some time to initialize the worlds: the Overworld, the Nether and the End.

When it says Done!, type

stop

into the console to shut the server down. If you now run ‘ls’, you’ll see that Spigot has generated its data structures and written them to the disk:

Internal Configuration

Spigot uses .yml and .json files to store its internal configuration. The folders are used for storing the following:

  • logs – Spigot runtime logs
  • plugins – initially empty. This is the folder where you’ll place compatible plugins
  • world – Minecraft world Overworld
  • world_nether – Minecraft world Nether
  • world_the_end – Minecraft world End

server.properties configures gameplay-related settings. Here is what its default version looks like:

A complete list of parameters can be found here, along with their explanations. These are the most important ones:

  • gamemode – sets the game mode: 0 is survival, 1 is hardcore, and 2 is creative mode
  • spawn-monsters – true by default; controls whether monsters spawn
  • pvp – true by default; enables Player vs Player fights
  • max-players – sets the maximum numbers of players who can play on your server at the same time. Set to 20 by default; you should edit this according to system resources allocated to Spigot
  • server-port – the port of the server. You should leave the default value (25565)
  • spawn-npcs – true by default; controls whether villagers spawn
  • allow-flight – set this to true to allow players to fly
  • level-name – set to world, which is the default world Spigot automatically generates. It is located in a folder with the same name. You can put your custom world in a folder and enter its name here to play on it
  • spawn-animals – true by default; controls whether animals spawn
  • white-list – false by default; set this to true to enforce the whitelist. Allowed UUIDs (usernames) can be set in the file white-list.txt, one per line
  • generate-structures – true by default; controls whether the world generator spawns structures in biomes
  • online-mode – if true, only paid Minecraft accounts can connect to the server
  • motd – the text that will be shown underneath the server name in Minecraft. Supports Unicode characters, but they must first be escaped

You can edit server.properties with the following command:

nano server.properties

When you are done, start the server again:

./start.sh

Keeping the Server Turned On

When you close you current SSH connection, your server will shut down. To prevent this, you can run it in a separate terminal using screen. Create a new file, called start-screen.sh, for editing:

nano start-screen.sh

Add the following line:

screen -S "mc-server" -U -m -d sh start.sh

Save and close the file.

This command starts a screen with the name mc-server in detached mode, which means that it will run in the background on the VPS. When it launches, it runs the command sh start.sh, which in turn starts the server. This way, even after you close your SSH connection, your Minecraft server will always be available for you and your friends to play on.

Step 4: Connecting to Your Server

When the server loads, open Minecraft on your local machine. Click on Multiplayer, then press on Add Server. Enter a name of your choice and for the server address, enter :. You can omit the part if you left the port setting intact (25565).

Press on Done and double click on your server in the list.

Wait a while for it to connect, and then you and your friends will be able to play on your own Minecraft server!

If you get the following error when connecting to your server:

that means that you have tried to connect with online-mode set to true in server.properties. Set it to false and try again.

Step 5: Learning About Spigot Plugins

Right now, your server will offer a vanilla experience. You can install plugins from the Spigot’s website by downloading the JAR files and then uploading them into the plugins directory. The easiest way to upload files to your server is via FTP, but setting that up is out of scope of this tutorial.

The server will load plugins on every start, and report any errors (most likely arising from version incompatibilities) immediately. When you add new plugins, restart your Minecraft server by joining it from the game and issuing the /restart command.

Here are some must-have plugins that will greatly enhance your player’s experience:

  • Vault – a plugin that all others depend on. It greatly simplifies plugin development
  • EssentialsX – this plugin adds over 100 convenience commands that your players will expect to find
  • WorldEdit – an in-game world editor. It allows for massive & easy block manipulation
  • WorldGuard – depends on WorldEdit. It allows you to define in-game access rules, for example to prevent players from griefing your property
  • LuckPerms – every server should have a permissions plugin, and LuckPerms is fast, reliable and maintained. It also offers a web editor, and is very easy to use

Dusko Savic is a technical writer and Flutter developer.

DuskoSavic.com

The post How to Set Up a Minecraft Server on Your VPS appeared first on Low End Box.

How to Install ISPConfig 3 on Ubuntu 18.04

ISPConfig is arguably the most complete open source server administration control panel in existence. Developed by Till Brehm of projektfarm in 2005, it has stood the test of time and endured as the de facto favorite among serious self-hosters and hosting agencies alike.

Not only does ISPConfig offer a full-featured control panel for managing multiple servers, but it also includes support for a customer billing system, available as a paid module. That means you can use your server to run your own reseller hosting business at very little cost. The two other paid modules are the Migration Toolkit for moving your ISPConfig around, and the ISPProtect Malware Scanner module.

Hosting control panels like ISPConfig are designed to make managing a server easy by abstracting away the gnarly technical bits behind middle-man automation. That said, some people may be turned away from ISPConfig because it has an air of complexity about it, which is somewhat true.

ISPConfig gives you extremely fine-grained control over your server from its web-based control panel interface. Through this central interface, you can manage everything from per-website web server environments, email accounts, databases, FTP users, jailed SSH users, cron jobs, to DNS zone settings and more. The control panel supports four built-in user roles: administrator, reseller, client, and email user.

In this tutorial, you’ll learn how to install and configure the latest ISPConfig 3.1 on Ubuntu 18.04.

Requirements

  • A VPS or dedicated server with Ubuntu 18.04 freshly installed. The recommended OS is Debian, but Ubuntu comes in at a close second since it’s based on Debian, just with newer package releases. 1GB+ of RAM is best.

Step 1: Add a sudo user

We’re going to use the root user to install ISPConfig, but you’ll want to create a non-root user for later down the road, in case you ever need to SSH into the server for some reason. Log in to your server as root and add a new user (replace “myuser” with your own username):

adduser myuser

Next, add “myuser” to the sudo group:

usermod -aG sudo myuser

Step 2: Use the install script

One of the perks of ISPConfig is that you have complete control over the server setup process, and thankfully the developers happen to provide detailed tutorials on how to prepare a new server for ISPConfig.

We’re going to skip all that and use the automated installation script instead. Note that the script is not guaranteed to work on every OS image, even though the distribution (e.g. 18.04) may be correct. If you have trouble with the installer, consult the HowToForge Perfect Server tutorials to install ISPConfig step-by-step. Be warned, it’s quite a slog, but worth it if you want to understand what’s running under the hood.

Copy and paste this into your terminal:

cd /tmp; wget –no-check-certificate -O installer.tgz “https://github.com/servisys/ispconfig_setup/tarball/master”; tar zxvf installer.tgz; cd *ispconfig*; bash install.sh

Now complete the Standard Mode installation by following the prompts in the console.

Troubleshooting: If the installer script freezes on this line:

“Updating apt package database and upgrading currently installed packages…”

… Then you will need to reinstall the server and run apt-get update and apt-get upgrade manually like this:

apt-get update && apt-get upgrade

Once done, you can try running the install script again.

Step 3: Check your server config

When ISPConfig is installed, you can log in to your control panel by entering https://Your_IP_Address:8080 in your browser. The admin area is secured with a self-signed SSL certificate, so you can safely add an exception when the security warning pops up.

Go to the System tab, click CP Users, and then change the admin password.

From the System tab, you can manage:

  • System services
  • General server config
  • Server networking and firewall
  • App packages and repositories

Feel free to take a look at System > Server Config and explore all the different configuration options.  Since there are so many options, it can be tricky to know what to configure here. Try to stick with what you know (and need), and leave the advanced configuration settings as default.

Step 4: Add a new website

The Sites tab lets you manage:

  • Websites
  • Databases
  • FTP and Shell users
  • Cron jobs
  • Apps
  • Stats

To add a new website, go to Websites > Website and fill out the form after clicking “Add new website”.

ISPConfig’s forms are designed so that you can assign websites, databases, and users to different client accounts. This allows you to limit hard disk space and traffic bandwidth on a per-client basis. Of course, if you’re only running ISPConfig for yourself, then you ignore the “Client” field and leave most of the other fields as default (e.g. unlimited).

At a minimum, you will have to enter these fields: Server IP, Domain, and PHP type (PHP-FPM is recommended for HTTP/2 support).

Next, make sure you’ve set your DNS host records for your domain to the server IP that you set for your website on ISPConfig. Then, you can test your website by typing its URL into a browser. You will see the default Apache2 index page:

Excellent. Now, to install something actually worth running (like WordPress or another PHP app) you must create a new database user and database, and then set up an FTP user so that you can upload the files onto your website.  All this can be done easily under the Sites tab as well.

Step 5: Set up email

What good is a website without email? To set up mailboxes for your domain, go to the Email tab and add a new email domain. Remember to set your spam filter sensitivity.

Once you’ve added your domain, go to Email Mailbox and create a new mailbox – e.g. admin@yourdomain.com.

You can then access your mailbox with Roundcube by navigating to http://yourdomain.com/webmail and logging in.

Step 6: Going further

ISPConfig is extremely powerful and includes way more than we could reasonably cover in this brief tutorial. Don’t be afraid to explore its capabilities. Once you have a handle on the basic control panel features, consider purchasing the ISPConfig User Manual. For free software as amazing as this, it’s the least you can do to support it (while supporting yourself at the same time).

The post How to Install ISPConfig 3 on Ubuntu 18.04 appeared first on Low End Box.

How to Set Up a Node.js Application On Ubuntu 16.04 VPS

How to Set Up a Node.js Application On Ubuntu 16.04 VPS

Node.js is an open source, cross platform, server side environment for building fast and scalable network applications. Node.js applications are written in JavaScript and executed by Google’s V8 JS engine. It effectively allows you to run JavaScript code on the server. Here are some of its main features:

  • Completely Asynchronous: all calls in Node.js are asynchronous, and thus do not block execution. This is achieved using Events and Promises, patterns native to the JavaScript language.
  • Single threaded: Node.js works only on a single thread, which fits well into its event driven architecture. Node.js applications are fast and scalable because they never buffer data.
  • Freely licensed: Node.js is released under the MIT license, so you can do almost anything with its source code.

If you need CPU intensive computations, Node.js may not be the right choice for you. It is severely limited by its use of only one thread, and you should probably use C++ or Python instead. Here is what kind of apps Node.js is the right fit for:

  • Web applications
  • I/O bound apps
  • API services

The list of companies that use it speaks volumes about its usefulness: PayPal, Netflix, Ebay, Walmart, Medium.com, Mozilla, NASA, Linkedin, Trello… You will also find thousands of individual projects written in Node.js as well.

What we are going to cover

  • installation of latest Node.js,
  • what is REPL and how to use it,
  • what are NPM packages and how to benefit from them,
  • creation of an example web app in Node.js

Prerequisites

  • A clean VPS with root access,
  • running Ubuntu 16.04 with
  • at least 512MB RAM, 1GHz CPU and 20Gb disk space.
  • Understanding of JavaScript.

Step 1: Install the Latest Node.js

First, login to your VPS as root via SSH. Navigate to the /tmp directory by running the following command:

cd /tmp

Install curl:

apt install curl -y

Download the installation script for the latest NodeJS version:

curl -sLO https://deb.nodesource.com/setup_12.x

At the time of writing of this article, the latest Node.js version was v12. New versions are being released in April and October. To install a newer version, substitute the new version number in the command above.

Run it with:

bash setup_12.x

The script will set up the proper Ubuntu package repositories. It will take a while to run. When it finishes, install Node JS and compilation tools by running:

apt install -y nodejs gcc g++ make

You have also installed gcc, g++ and make. They may be required by some Node.js packages during their installation to compile their parts written in C or C++. You’ll learn about Node.js packages later in the tutorial.

When the installation finishes, run the following command to inspect Node.js version:

nodejs -v

If it shows a version (which was, at the time of writing, v12.2.0), you have installed Node.js correctly. If it shows an error, double check the commands you entered against the ones shown above.

Step 2: Learning About Node.js REPL

REPL stands for Read-Eval-Process-Loop and is an interactive environment for Node.js. You execute a single expression and the result is printed back immediately. It is a great way to experiment with the language.

Run the integrated Node.js REPL with the following command:

nodejs

You’ll see the following:

Welcome to Node.js v12.2.0.
Type ".help" for more information.
>

The REPL now waits for you to enter an expression. Try some simple math by typing in:

1+2

The result will be 3. Parentheses are also obeyed:

(1+2)*5

You can now try executing some of Node’s built-in functions, such as printing to console:

console.log('hello!')

The output will be:

hello!
undefined

The REPL executed the console.log() call, which returned ‘hello!’. undefined, shown in gray in the next line, means that the call did not return anything.

Variables are also supported:

a=5
b=6

You can try adding them:

a+b

The result will be 11, shown in yellow, which denotes a number. (Green denotes a string.)

You can use the up and down arrows to traverse through command history. To list all the available commands, press Tab twice.

To exit the Node.js REPL, press CTRL + C twice.

Step 3: Learning About NPM Packages

NPM (Node Package Manager) is the world’s largest JavaScript library registry with package manager capabilities. Both open source developers and big companies use it to make software development easier. NPM is free to use and is included with Node.js since version 0.6.3.

The biggest benefit of NPM is its package manager. You specify all your project dependencies in a file named package.json, and all you need to do to start developing is run npm install. It is also possible to specify specific versions of packages that your project will work with.

Confirm that npm is installed and check its version by running:

npm -v

Local and Global Package Installations

With NPM, installing packages is easy. To install a package locally, just run:

npm install 

and NPM will take care of all the dependencies for you. Installing a package locally means that NPM will download and store the files in a directory named nodemodules_ in the current directory.

For example, if you wish to locally install cheerio (a version of jQuery optimized for server side), you’ll need to run:

npm install cheerio

When cheerio finishes installing, you can import it from your code with this line:

const cheerio = require('cheerio');

The cheerio object will provide access to the library’s functionality.

By passing ‘-g’ to npm install, you can install packages globally. You can access them from the CLI, but can’t import them from the code. To list all the globally installed packages, run:

npm ls -g

Updating, Uninstalling, Searching

To update a package, use npm update:

npm update 

To uninstall a package, use npm uninstall:

npm uninstall 

You can also search for a package by its name using npm search:

npm search 

You will get a tabulated list of packages whose name matches the one you passed in.

Creating a New Package

File package.json stores information about the package. Creating a package.json makes sense only when you want to publish your library to the npm package registry.

From the working directory of your package, run the following command to create one interactively:

npm init

It will ask you for your package name, current version, description, entry point file, command for running tests, Git repository, keywords, your name as the author and code license. NPM will then ask you if you are content with the generated JSON – if you are, type in ‘y’ or press Enter.

NPM will then save the newly generated package.json into the current directory.

Publishing a Package

To publish a package to the NPM package registry, first sign up for an account at npmjs.org.

If you haven’t logged in before already, NPM will have you log in before you publish a package. You can add a new user to npm with the following command:

npm adduser

NPM will then ask you for your username, password and email address (which will be shown publicly). When you are done, you can publish your package by running the following command from the working directory of your package:

npm publish

Step 4: Creating an Example Web Server App

We’ll now create a simple web server app which will return the requested URL in upper case. To create an HTTP server, we’ll use the built-in http package, and to convert characters to their upper case variants, we’ll use the upper-case package from NPM. Install the latter using this command:

npm install upper-case

Navigate to the home directory:

cd ~

Open a file named uppercase-http.js for editing:

nano uppercase-http.js

Add the following lines:

var http = require('http');
var uc = require('upper-case');
console.log('starting...');
http.createServer(function (req, res) {
  console.log('received request for url: ' + req.url);
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(uc(req.url + 'n'));
  res.end();
}).listen(8080);

Save and close the file.

First, we require two packages (http and upper-case) and store them in separate variables (http and uc, respectively). Then we call the createServer method of the http package and pass it a function which will be executed whenever the server receives a request; the request itself will be stored in variable req.

The function will write the Content-Type header of type text/html to the response variable res, telling the client that the response will be in HTML. In line starting with res.write(), we call uc (the upper-case package), which will return the uppercase variant of the requested URL and append a new line to it.

The last two lines end the response by calling end() and order the HTTP server to listen to port 8080. You can specify any other port that you like, provided that it will be free when the app runs.

Run the app:

node uppercase-http.js

You will see the following message:

starting...

To test it, fire up another terminal, connect to your VPS as root via SSH and curl localhost:8080:

curl localhost:8080

The output will be a slash (/), because you haven’t requested a more specific path. Try curl-ing /hello:

curl localhost:8080/hello

You’ll get the following response:

/HELLO

The program correctly converted the path to uppercase. If you look at the server app itself, it showed a status message for both requests:

received request for url: /
received request for url: /hello

If you’d like to access this app from your web browser, you’d need to configure a reverse proxy (probably using Nginx), which is out of scope of this tutorial.

Conclusion

Now that you know how to install Node.js and use NPM, you’ll be able to craft hobby projects over the weekend, or try building the next Netflix! Node.js is flexible enough to run on even the cheapest servers, and you’ll still be able to build a professional web app with it.

Dusko Savic is a technical writer and Flutter programmer.

DuskoSavic.com

The post How to Set Up a Node.js Application On Ubuntu 16.04 VPS appeared first on Low End Box.

How To Set Up A Laravel Application on Ubuntu 16.04 VPS

How To Set Up A Laravel Application on Ubuntu 16.04 VPS

Let us presume that you have already set up an Ubuntu 16.04 VPS server with Apache and that you have installed a bare bones Laravel app. In this tutorial we shall install and create a MySQL database and connect the app to it. The final step is to fully configure the application via the .env file and artisan.

;

What we are going to cover

  • Creation of MySQL database for the app,
  • Connecting Laravel app to the database
  • Creating the .env file for Laravel environment variables
  • Using artisan to generate the app key
  • Additional configuration for timezone and locale

PRE-REQUISITES

We shall install and deploy Laravel 5 on Ubuntu 16.04:

  • Starting with a clean VPS with
  • At least 512Mb of RAM and
  • 15Gb of free disk space.
  • You will need root user access
  • You have already installed Laravel on your VPS and it is running properly

Step 1: Install MySQL Database

First use SSH to access the VPS server. To install MySQL database, run the following command from Ubuntu command line:

sudo apt install mysql-server -y

This will install the MariaDB database server (an enhanced fork of MySQL). You will be asked to enter password for the MySQL root user. (Use Tab key from the keyboard to switch to the OK button and press Enter on the keyboard.)

Then secure MySQL installation by running:

sudo /usr/bin/mysql_secure_installation

Depending on the level of security you wish to achieve, you will have the option to adjust the minimum password complexity. Press 2 to select the highest level. Answer y to every prompt you get afterwards.

So you enter one password first, to enable access to MySQL, then ener another password to secure the installation. Store that second password as you will need it in Step 9 of this article.

To make it run on every system boot, enable it via systemctl:

sudo systemctl enable mysql

Step 2 Creating a Database

Launch MySQL shell:

sudo mysql -u root -p

When asked, enter the second password from Step 1 of this tutorial.

Once in MySQL prompt, copy and paste the following code as a whole, then press Enter on the keyboard:

CREATE DATABASE blogdb;
USE blogdb;
CREATE TABLE posts (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(50),
    body TEXT,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);
    INSERT INTO posts (title, body, created)
    VALUES ('Sample title', 'This is the article body.', NOW());
    GRANT ALL PRIVILEGES ON blogdb.* TO 'post_user'@'localhost' IDENTIFIED BY 'password9I%';
    FLUSH PRIVILEGES;
    EXIT;

That will execute everything at once. Here is what it will look like in the terninal:

The first line will create a database blogdb and from the second line on, will start using it. Then we create table called posts with two visible fields, title and body. Column idis necessary but will be used by only internally.

Then we populate table posts by inserting one sample value.

Command GRANT ALL PRIVILEGES creates a new user called postuser_ and grants it all privileges on database blogdb. Currently there is only one table in this database, posts.

Command IDENTIFIED BY defines the password. It must contain lower and uppercase letters, as well as digits and special characters. Be sure to always change and invent new passwords for database users.

Command FLUSH PRIVILEGES; reloads the database with the changes made. The last command is EXIT, to leave the MySQL prompt and go back to the command line in Ubuntu itself.

Step 3 The .env File

Navigate to the app folder and execute the ls -a command:

cd /var/www/html/blog/
ls -a

The following image shows the contents of the blog folder. Note that there are files starting with dot, such as .end, which is not visible with the usual ls command. Using ls -a will, however, show the dot files as well.

The fact that the dot files are “invisible” will not stop us from reading these files into an editor and changing them to finish the installation. The .env file contains debugging options, parameters to connect to the database and so on. So let us open it for editing:

sudo nano /var/www/html/blog/.env

Step 4 Connect the App To the Database

Put the following into the .env file to enable access to the database you have created in previous steps:

DB_DATABASE=blogdb
DB_USERNAME=post_user
DB_PASSWORD=assword9I%

Save and close the file.

The .env File May Be Missing

In some installations and scenarios, the .env file may be missing. You can download it from here, then create the missing .env file by opening it in an editor such as nano and copying the contents there.

With every installation there will be a file called .env.example so the other way to recreate the .env file is to use .env.example as a template, and create the .env files by copying:

cd /var/www/html/blog
cp .env.example .env

Step 5 Creating the Key for the Application

With each change of the the .env file, there will be several artisan commands to execute. As a minimum, you will need to run php artisan key:generate. If you don’t, you will get a warning screen like this:

So execute the following commands in a row:

php artisan key:generate
php artisan config:cache
composer dump-autoload

If you are changing the database, run the migration commands as well:

php artisan migrate

Step 6 Additional Configuration

In file config/app.php you can set up timezone and locale parameters. They look like this:

The command to access the file is:

sudo nano /var/www/html/blog/config/app.php

What To Do Next

Now you have a rudimentary Laravel app on your server, running smoothly.Once you develop your app and test it, you may aim for a production level of system. See article “How To Set Up Laravel For Production: Ubuntu 16.04” to improve your site before going to production phase.

Dusko Savic is a technical writer and Flutter programmer.
duskosavic.com

The post How To Set Up A Laravel Application on Ubuntu 16.04 VPS appeared first on Low End Box.

How To Install Laravel on Ubuntu 16.04 VPS

How To Install Laravel on Ubuntu 16.04 VPS

With this tutorial, you will start from a clean Ubuntu 16.04 install, set it up to run Laravel, and end up with a demo Laravel application installed. Other articles in this series will show you how to set up the database and Laravel environment, and then how to strenghten the Laravel setup for production.

;

What we are going to cover

  • installation of Apache and PHP 7.2,
  • creation of user which will have access to the app,
  • installation of Laravel itself,
  • setting up Apache to execute the app.

PRE-REQUISITES

We shall install and deploy Laravel 5 on Ubuntu 16.04:

  • Starting with a clean VPS with
  • At least 512Mb of RAM and
  • 15Gb of free disk space.
  • You will need root user access

Step 1: Creating a Non Root User

Once you are logged in as root, you can create a new user account that you’ll use to access the app once it is installed. We’ll call the new user laraveluser. To create it, run:

adduser laraveluser

Then, add it to the sudo group, so that you can run commands as sudo:

usermod -aG sudo laraveluser

Step 2: Install Apache

First, update your package manager’s cache:

sudo apt update -y

Install the Apache web server:

sudo apt install apache2 -y

Enable its service to make it run on every system boot:

sudo systemctl enable apache2

Finally, start it:

sudo systemctl start apache2

To verify that Apache was installed successfully, access it from your local browser by navigating to http://SERVER_IP/. If that does not work, try adding :80 in the end, like this:

http://SERVER_IP:80

You should see a welcome page for Apache, which means that you now have Apache running.

Step 3: Install PHP 7.2

We are installing version 5.8 of Laravel, which requires a version of PHP greater than 7.1.3. We shall install PHP 7.2. First install the prerequisite packages:

sudo apt-get install software-properties-common python-software-properties

Then, add the ondrej PPA:

sudo add-apt-repository -y ppa:ondrej/php
sudo apt-get update

and update your sources by running:

sudo apt install php -y

Install PHP 7.2 using the following command:

sudo apt-get install php7.2 php7.2-cli php7.2-common

Step 4 Install the Extensions For Laravel

These are the PHP extensions that Laravel 5.8 requires:

  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension
  • Ctype PHP Extension
  • JSON PHP Extension
  • BCMath PHP Extension

First install the most popular PHP extensions:

sudo apt-get install php7.2-curl php7.2-gd php7.2-json  php7.2-mbstring php7.2-intl php7.2-mysql php7.2-xml php7.2-zip

Then add the extensions specific to Laravel:

sudo apt install -y php7.2-bcmath  php7.2-ctype

Restart to activate changes:

sudo systemctl restart apache2

Linux uses tar to decompress files while some of the files for PHP come in zip format, so here is the command to install zip and unzip extensions as well:

sudo apt -y install zip

Step 6 Install git

We shall use git to install Laravel apps from github.com.

sudo apt install -y git

Step 5 Install redis

Redis is a database, cache and message in-memory broker. We are not going to use it in this tutorial, though, but we can install it now.

sudo apt install -y redis-server

Step 6: Install Composer

Laravel uses Composer to manage all of its dependencies.

Install curl to download the install script for Composer:

sudo apt install curl -y

Then, download the installer:

cd ~
sudo curl -s https://getcomposer.org/installer | php

To make it available globally, move it to /usr/bin:

sudo mv composer.phar /usr/local/bin/composer

You are installing Composer as root user and it will show a warning about it. Once we have the app installed, we shall give access to its folder to user laraveluser.

Step 7: Create an Example Laravel App

Apache stores the data it serves under /var/www/html. To create a new Laravel app, run:

composer create-project --prefer-dist laravel/laravel /var/www/html/blog

Here “blog” will be the name of the app.

When Composer asks if you want it to set up folder permissions, answer with y.

Run these two commands to enable access to folders storage and bootstrap/cache as without that access, Laravel will not run:

sudo chmod -R a+rw /var/www/html/blog/storage
sudo chmod -R a+rw /var/www/html/blog/bootstrap/cache

We can now give user laraveluser access to the app folder:

sudo chown -R laraveluser /var/www/html/blog

Ubuntu will ask you for passwords whenever you change or access something in the system so be sure to have them nearby.

Step 8: Configuring Apache

Edit Apache configuration file so that it will serve Laravel app by default. It is called 000-default.conf and is stored in directory /etc/apache/sites-enabled. Open it for editing:

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

Find line which starts with DocumentRoot and replace it with this:

DocumentRoot /var/www/html/blog/public

Save and close the file.

Laravel requires Apache modulerewrite_ to also be enabled; do so by running:

sudo a2enmod rewrite

Finally, instruct Apache to use .htaccess files, with which Laravel configures Apache on the fly. Open Apache global configuration file for editing:

sudo nano /etc/apache2/apache2.conf

Under the block, you’ll find the following line:

AllowOverride None

Change it to

AllowOverride All

When you are done, save the file.

Again restart Apache so that it takes new configuration into account:

sudo systemctl restart apache2

You can now navigate to your domain in your browser. You should see the following:

Laravel is now installed properly.

What To Do Next

Now you have a Laravel app on your server. The server is set up but Laravel itself is not. Follow the article “How To Set Up a Laravel Application on Ubuntu 16.04” which will show you how to create a database, connect it to the app and set up environment for a Laravel app properly. This will enable you to further develop and test your app on this server.

When your app becomes ready for deployment and production, read the next article in the series, on “How To Set Up Laravel For Production: Ubuntu 16.04”.

Dusko Savic is a technical writer and Flutter programmer.

duskosavic.com

The post How To Install Laravel on Ubuntu 16.04 VPS appeared first on Low End Box.

Setup SSH Keys on Ubuntu 18.04

Who should read this?

This tutorial is for novice to intermediate linux users who want to go beyond basic password security.  Security professionals recommend using ssh keys to make authentication into ssh sessions faster, easier and more secure.   As passwords become longer and more complex they become more difficult to use and manage.

Key based access is more secure and easier to manage for individuals.  For teams and organizations key based access has some challenges around rotation and user hygiene that are outside of the scope of this tutorial.

What are we talking about ?

This tutorial will walk you through the basic procedures on setting up and utilizing SSH keys on your servers and how to use those keys with common windows ssh tools like putty or on OSX, or Linux.

SSH is a client server protocol originally developed to replace the insecure and unencrypted telnet protocol.  SSh1 was originally developed in 1995 by Tatu Ylonen, a researcher at the Helsinki University of Technology.   Tatu went on to found ssh.com.  SSH went on to become one of the most widely used security and administration tools in modern technology.

OpenSSH was a derivative work forked (by the OpenBSD project) from earlier versions of the SSH server application that had less restrictive licensing.

Why

Using SSH keys makes system access fast, easy, secure and scalable.   It’s pretty much the only way to fly if you’re serious about being a linux administrator.

What are SSH Keys?

SSH keys are a public and private key pair used for authenticating users whom are trying to remotely login to systems to perform administrative tasks and actions.  The public key is placed on the remote server and the private key is held as a secret on the  user’s local machine.

Pre-requisites

This tutorial is based on Ubuntu 18.04 running the latest

$ sudo apt-get update && apt-get upgrade

If you are using windows you’ll need:
Putty https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html    ### You need at least putty v0.70 to use ED25519

WinSCP https://winscp.net/eng/download.php

Puttygen https://winscp.net/eng/download.php  This is included in the WinSCP installer

Step 1

$ mkdir -p ~/.ssh
$ chmod 0700 ~/.ssh
$ ssh-keygen -t ed25519 -C "VPS server #101"    ### https://ed25519.cr.yp.to/ if you are wondering what ED25519 is 
Generating public/private ed25519 key pair.
Enter file in which to save the key (/root/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):   #haha I can't type 
Enter same passphrase again:
Passphrases do not match.  Try again.
Enter passphrase (empty for no passphrase):  #still can't type
DEnter same passphrase again:
Your identification has been saved in /root/.ssh/id_ed25519.
Your public key has been saved in /root/.ssh/id_ed25519.pub.
The key fingerprint is:
SHA256:+EgRgp7QUWicc/vjjYfl8iW/HW1E5PkzOYY7TmCMlYU VPS server #101
The key's randomart image is:  
+--[ED25519 256]--+
| o.*o .     ...  |
|. O ..     Eoo . |
| + + ...   o  +  |
|  o .  O  +  .+..|
|     .o S. + ..*.|
|     .oo. . .oo +|
|     ..Bo . .+o  |
|      = ++ .oo.  |
|       +. o...   |
+----[SHA256]-----+
$ ls -al ~/.ssh
total 16
drwx------ 2 root root 4096 Apr 30 04:12 .            ### Agree to pretend that I didn't run this as root
drwx------ 7 root root 4096 Apr 30 04:11 ..
-rw------- 1 root root  411 Apr 30 04:12 id_ed25519    ### THIS IS YOUR PRIVATE KEY DO NOT SHARE
-rw-r--r-- 1 root root   97 Apr 30 04:12 id_ed25519.pub ### THIS IS YOUR PUBLIC KEY - GOES ON REMOTE DEVICES 

Step 2

You need to add your public key to the ~/.ssh/authorized_keys file on any server you want to login to.

$ cat id_ed25519.pub >> ~/.ssh/authorized_keys   #APPENDS THE CONTENTS OF FILE_1 to FILE_2

Use WinSCP or SCP to download your private key to your workstation.

On Windows

Open PuttyGen and load the private key that you downloaded from the VPS.  Make sure you select the ED25519 parameter if that is the key type that you generated!

Then hit Save Private Key, save the id_ed25519.ppk key file somewhere smart.

Open Putty and navigate to SSH > Auth in the left hand menu, browse to and load your private key file

Go back to Session and save the session so that you don’t have to specify the key file over and over again like a robot.

If your session throws an error “Unable to load private key file .ppk (file format error)” your version of putty probably is too old and doesn’t support ED25519.

On Linux / OSX

Downloading your keys on your linux workstation is pretty simple.

user@workstation:~$ scp user@192.168.1.101~/.ssh/id_ed25519 ~/.ssh/
user@192.168.1.101’s password:
id_ed25519 100% 411 15.4KB/s 00:00
user@workstation:~$ ssh root@192.168.1.101    #type your passphrase and boom you are in
Welcome to Ubuntu 18.04.2 LTS (GNU/Linux 4.15.0-38-generic x86_64)

References

  • https://www.openssh.com/history.html
  • https://www.ssh.com/ssh/
  • https://ed25519.cr.yp.to/ if you are wondering what ED25519 is

About the Author

Sean Richards, CISSP,  is a 20 year  Technology enthusiast and security practitioner.   Loves family, animals, BBQ, and bicycles.
https://www.linkedin.com/in/seangrichards/
https://github.com/seangrichards/
https://twitter.com/seangrichards

The post Setup SSH Keys on Ubuntu 18.04 appeared first on Low End Box.

How To Set Up CakePHP For Production: Ubuntu 16.04

How To Set Up CakePHP For Production: Ubuntu 16.04

We shall assume that you have developed a CakePHP app on the server and that you are going to launch it as a product. To bring your app to the production level, you’ll need to

  • Clean up the code,
  • Increase security by enabling Security and CSRF components, and
  • Set up the app on the server correctly.

Cleaning Up the Code

Disable Debug Mode

Every installation of CakePHP comes with the Debug mode enabled and virtually all programmers use it. Debug mode set to false is the way to go in production, to prevent leaking of sensitive info.

To disable Debug mode, open the config file for editing:

sudo nano config/app.php

and find the line where the debug variable is mentioned, at the top of the file. Set its value to false, like this:

'debug' => filter_var(env('DEBUG', false), FILTER_VALIDATE_BOOLEAN),

Save the file and refresh the site in your browser. In case you have a brand new app, this is the screen you are going to see:

This page, located under src/Template/Pages/home.ctp, is the homepage. This is the place to introduce the site or redirect the user to another page. The following code will save the existing home.ctp file, in case you want to bring it back later, and will create an empty file so that you can put the appropriate code into it.

Execute this from command line:

cd /var/www/html/cakeapp/src/Template/Pages/
mv home.ctp home_old.ctp
touch home.ctp
sudo nano /var/www/html/cakeapp/src/Template/Pages/home.ctp

Command mv renames the existing file, touch creates a new file with the same name, only empty. It then opens the editor so you can put the following code into it:

window.location='https://google.com';
?>

That will redirect the app to Google.com but in real life, you will redirect it to one of the pages on your own site.

Setting Up Passwords in SetEnv Variables

Environment variables on Apache HTTP Server store information in named variables that are available in PHP and CakePHP code. Normal usage of environment variables would be to control logging or access to certain pages on the site. You can also set a value for Debug as SetEnv and dynamically check it in the app. The following goes to the Apache configuration file:

SetEnv CAKEPHP_DEBUG 1

and then you can check it out in the app.php file:

$debug = (bool)getenv('CAKEPHP_DEBUG');
return [
    'debug' => $debug,
    .....
];

SetEnv can also store sensitive data such as passwords. Then, the passwords would be available in code, but not through text in source code of the app, which adds another level of security.

Clear the Cache Before You Begin

Cached files in CakePHP may reach hundreds of MB and will slow the app down. Before you go to production, be sure to execute this command from your app directory:

bin/cake schema_cache clear

You should also issue this command whenever you change any data structure in any of the databases and tables, otherwise CakePHP will not take them into account.

NOTE: Once in production, use the Migration tool to change database schemas.

Models Should Have the Correct Validation Rules Enabled

Model classes in directory /Model/Table contain code for logic validation of input in forms. There will be two functions in those files, validationDefault and buildRules and here is what they do.

validationDefault will have an entry like this:

$validator
            ->requirePresence('username', 'create')
            ->notEmpty('username');

which means that for input field called username, when you press Save on the Form, the field must not be empty. If it is empty, an error will be shown and the data will not be saved to the database, but will instead be presented to the user again.

buildRules may look like this:

        $rules->add($rules->isUnique(['email']));
        $rules->add($rules->existsIn(['user_id'], 'Users'));

isUnique means that the email address entered must be unique in the database and if there is a match, a message will be shown to the user and the form data will not be saved.

existsIn means that the value entered must be present in table Users and if it is not there, an error message will be shown and the form will not be saved.

You can turn off all these validators, by just commenting them out. Do it at your own risk, because it opens up the possibility of entering data in inappropriate formats.

Learn more about Validators from the official documenation page.

Improve Security of Your CakePHP App

Activate the Cross Site Request Forgery Component

Once in the wild, your app can become an object of attack, mostly by automated software. Cross Site Request Forgery is a common attack performed on web apps and if successful, can lead to the equivalent of online robbery.

The protection mechanism consists of adding a randomly generated token as a hidden field to every form, which the server knows. This way, the potential attacker has no means of knowing what the token might be, and the attack will fail.

As of version 3.5, CakePHP also implements CSRF protection as middleware.
You should either use CSRF as a component or as middleware, but not both at the same time.

Activate the Security Component

The Security component will enable you to:

  • Restrict which HTTP methods your application accepts
  • Prevent Form tampering
  • Require that SSL be used
  • Limit cross controller communication

Use it in your controller’s beforeFilter() call. Since Security can be used with other callbacks from there, it should be executed before them in the initialize() method.

The Security Component will automatically give you the means to fight form tampering protection. It inserts and then checks on hidden token fields that are automatically inserted into forms.

It will also work in conjunction with the SCRF component.

Where To Put Code to Activate Security Components

You may put all of your security components into the file AppController.php, as all other controllers will import that file automatically. Access it via

sudo nano /var/www/html/cakeapp/src/Controller/AppController.php

This is the beginning of the file and it may have additional lines of code in it.

Setting Up the App on the Server Correctly

Set Up DocumentRoot

If you have followed advice on installing and setting up your first CakePHP app, you will have set up this properly already. If not, open Apache default site config file for editing:

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

and change the DocumentRoot like this:

DocumentRoot /var/www/html/cakeapp/webroot

If you are on shared hosting, it is not likely that you will be able to change DocumentRoot directly. Your only option may be to use basic html folder as the root of the app and for the details have a look here.

Take Care of the webroot Folder

Files and directories in webroot folder of your app are accessible to the rest of the Internet. If you want to store public images on the site, that’s where you can put them.

If you have old PHP code that is important to execute without change, you may put it in webroot subfolder as well. It will be executed outside of CakePHP, which means that someone can destroy your site without you ever noticing. If you must put a PHP file there, be sure never to execute it in the browser, or – even better – rewrite the old code to be compatible with CakePHP and then execute it in a normal Cake way.

Dusko Savic is a technical writer and Flutter programmer.

DuskoSavic.com

Dusko on LinkedIn

The post How To Set Up CakePHP For Production: Ubuntu 16.04 appeared first on Low End Box.

How To Install CakePHP On Ubuntu 16.04 VPS

How To Install CakePHP On a Ubuntu 16.04 VPS

With this tutorial, you will be able to create a CakePHP environment from scratch, define a database, and automatically generate a working web app.

You will start with an empty black screen and within an hour have a small web site on a VPS.

What are we going to cover

  • installation of LAMP stack (Linux, Apache, MySQL, PHP),
  • creation of user which will have access to the app,
  • installation of CakePHP itself,
  • creation of the database for the app,
  • creation of the app itself, through the process known as baking.

PRE-REQUISITES

We shall install and deploy CakePHP on Ubuntu 16.04:

  • Starting with a clean VPS with
  • At least 512Mb of RAM and
  • 15Gb of free disk space.
  • You will need root user access

Step 1: Creating a Non Root User

Once you are logged in as root, you can create a new user account that you’ll use from now on. Root is useful for performing system administration tasks, but using it for ordinary tasks is error prone and risky.

We’ll call the new user cakeuser. To create it, run:

adduser cakeuser

Then, add it to the sudo group, so that you can run commands as sudo:

usermod -aG sudo cakeuser

Step 2: Install Apache

First, update your package manager’s cache:

sudo apt update -y

Install the Apache web server:

sudo apt install apache2 -y

Next, enable its service to make it run on every system boot:

sudo systemctl enable apache2

Finally, start it:

sudo systemctl start apache2

To verify that Apache was installed successfully, access it from your local browser by navigating to http://SERVER_IP/. If that does not work, try adding :80 in the end, like this:

http://SERVER_IP:80

You should see a welcome page for Apache, which means that you now have Apache running.

Step 3: Install MySQL Database

To install MySQL database, run the following command:

sudo apt install mysql-server -y

This will install the MariaDB database server (an enhanced fork of MySQL). You will be asked to enter a password for the MySQL root user. (Use Tab key from the keyboard to switch to the OK button and press Enter on the keyboard.)

Then secure MySQL installation by running:

sudo /usr/bin/mysql_secure_installation

Depending on the level of security you wish to achieve, you’ll have the option to adjust the minimum password complexity. Press 2 to select the highest level. Answer y to every prompt you get afterwards.

So you enter one password first, to enable access to MySQL, then ener another password to secure the installation. Store that second password as you will need it in Step 9 of this article.

To make it run on every system boot, enable it via systemctl:

sudo systemctl enable mysql

Step 4: Install PHP

Finally, install PHP by running:

sudo apt install php -y

This will install PHP 7.0, which will here serve just fine.

You’ll then need to install common PHP extensions that CakePHP requires:

sudo apt install php-{bcmath,bz2,intl,gd,mbstring,mcrypt,mysql,zip,intl,xml} libapache2-mod-php unzip -y

Linux uses tar to decompress files while some of the files for PHP come in zip format, so the above line will install zip and unzip programs as well.

Step 5: Install Composer

Composer is a flexible PHP package manager, which CakePHP uses to manage all of its dependencies.

Install curl to download the install script for Composer:

sudo apt install curl -y

Then, download the installer:

cd ~
sudo curl -s https://getcomposer.org/installer | php

To make it available globally, move it to /usr/bin:

sudo mv composer.phar /usr/local/bin/composer

You are installing Composer as root user and it will show a warning about it. Once we have the app installed, we shall give access to its folder to user cakeuser.

Step 6: Create an Example CakePHP App

Apache stores the data it serves under /var/www/html. To create a new app, run:

composer create-project --prefer-dist cakephp/app /var/www/html/cakeapp

Here “cakeapp” will be the name of the app. You may install several CakePHP apps in this way on the same server, just change “cakeapp” for the new name.

When Composer asks if you want it to set up folder permissions, answer with y.

If for some reason you later get a warning that these folders are not accessible, you may run these two commands:

sudo chmod -R a+rw /var/www/html/cakeapp/logs
sudo chmod -R a+rw /var/www/html/cakeapp/tmp

In Step 11 of this tutorial we shall use bake command in CakePHP to create a ready made app. For now, let us create a permission to access it:

cd /var/www/html/cakeapp
chmod +x bin/cake

We can now give user cakeuser access to the app folder:

sudo chown -R cakeuser /var/www/html/cakeapp

Have your passwords always easily accessible as Ubuntu will ask you for them whenever you change or access something in the system.

Step 8: Configuring Apache

Edit Apache configuration file so that it will serve CakePHP app by default. It is called 000-default.conf and is stored in directory /etc/apache/sites-enabled. Open it for editing:

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

Find line which starts with DocumentRoot and replace it with this:

DocumentRoot /var/www/html/cakeapp/webroot

Save and close the file.

CakePHP requires Apache module_rewrite to also be enabled; do so by running:

sudo a2enmod rewrite

Finally, instruct Apache to use .htaccess files, with which CakePHP configures Apache on the fly. Open Apache global configuration file for editing:

sudo nano /etc/apache2/apache2.conf

Under the block, you’ll find the following line:

AllowOverride None

Change it to

AllowOverride All

When you are done, save the file.

Again restart Apache so that it takes new configuration into account:

sudo systemctl restart apache2

You can now navigate to your domain in your browser. You should see the following:

CakePHP is now installed properly, save for the fact that there is no database to connect to. We shall first create the database and then connect it to CakePHP in the next step.

Step 9 – Creating a Database

Launch MySQL shell:

sudo mysql -u root -p

When asked, enter the second password from Step 3 of this tutorial.

Once in MySQL prompt, copy and paste the following code as a whole, then press Enter on the keyboard:

CREATE DATABASE blogdb;
USE blogdb;
CREATE TABLE posts (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(50),
    body TEXT,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);
    INSERT INTO posts (title, body, created)
    VALUES ('Sample title', 'This is the article body.', NOW());
    GRANT ALL PRIVILEGES ON blogdb.* TO 'post_user'@'localhost' IDENTIFIED BY 'password9I%';
    FLUSH PRIVILEGES;
    EXIT;

That will execute everything at once. Here is what it will look like in the terninal:

The first line will create a database blogdb and from the second line on, will start using it. Then we create table called posts with two visible fields, title and body. Columns id, created, and modified are necessary but will be used by CakePHP only internally.

Then we populate table posts by inserting one sample value.

The next line, starting with GRANT ALL PRIVILEGES is crucial. It creates a new user called _postuser and grants it all privileges on database blogdb. Currently there is only one table in this database, posts.

The third part, starting with IDENTIFIED BY, defines the password. It must contain lower and uppercase letters, as well as digits and special characters. Be sure to always change and invent new passwords for database users.

Command FLUSH PRIVILEGES; reloads the database with the changes made. The last command is EXIT, to leave the MySQL prompt and go back to the command line in Ubuntu itself.

Step 10: Connecting App to the Database

Navigate to the app folder:

cd /var/www/html/cakeapp/

CakePHP stores database credentials in a file named app.php, stored under the config folder. Open it for editing:

sudo nano /var/www/html/cakeapp/config/app.php

Find the Datasources block:

    'Datasources' => [
        'default' => [
            'className' => 'CakeDatabaseConnection',
            'driver' => 'CakeDatabaseDriverMysql',
            'persistent' => false,
            'host' => 'localhost',
            ...
            //'port' => 'non_standard_port_number',
            'username' => 'post_user',
            'password' => 'password9I%',
            'database' => 'blogdb',

In your terminal it may look like this:

For ‘username’ put your database user’s user name (post_user), for ‘password’ put your database user’s password (password9I%), and for database name it is obvious what to put (blogdb).

Save and close the file.

Refresh app in your browser and observe the success message under the Database section.

Step 11: Creating Your First CakePHP App

Under normal circumstances, you would have to now learn programming in PHP, then learn CakePHP, and within a couple of days, weeks or months, you would have your first “Hello World” app on the server.

There is a much faster way – using the bake command. Execute this:

./bin/cake bake all posts

It will create CakePHP code in various folders and produce an app that can read, save, update and delete entries in table posts of database blogdb.

Part of the bake output is shown here:

Visit the address in the browser:

http://SERVER_IP/posts

That’s it, we now have a CakePHP app installed, connected to the database and running for real.

What To Do Next

Now you have a rudimentary CakePHP app on your server. The rest depends on your original intentions. For example, if you are a developer selling sites to the clients, at this point you can upload your CakePHP app and be sure that it will run properly.

Once you finish your app, see article “How To Set Up CakePHP For Production: Ubuntu 16.04” how to improve your site before going to production phase.

Dusko Savic is a technical writer and Flutter programmer.
duskosavic.com

The post How To Install CakePHP On Ubuntu 16.04 VPS appeared first on Low End Box.

How to setup OpenVPN on your VPS: Ubuntu 18.04

Who should read this tutorial:

This tutorial is written for novice level Linux users and DevOps folks who need to add encryption to their internet traffic.  A virtual private network (an encrypted network over the public internet) to access specific networks or services from the outside is the way to go.

What are we going to cover

  1. Walk through the installation of OpenVPN on Ubuntu 18.04
  2. How to install the OpenVPN client on a windows workstation
  3. Generate a certificate and connect to the VPN server

Why Would You Want to Do This?

The key benefit of a VPN is to access resources that are otherwise inaccessible from external networks while maintaining a minimum level of network security at the time.

Generally adding an encrypted virtual private network connection to your infrastructure is a good idea if:

  • you are not confident of the security of the network you are connecting from (public wifi anyone?)
  • the resources that you want to utilize lack inherent security (such as network communications that don’t support strong levels of encryption.)
  • attempting accessing resources that are protected by multiple levels of network security and should never be publicly accessible such as systems holding payment card, healthcare, or security data.

My personal use case is to access my home security system (MotionEye) while traveling on my laptop or on my mobile device so that I can keep an eye on my cats, dogs and fend off porch pirates.


Random internet cat

PRE-REQUISITES

We recommend:

  • Starting with a clean VPS
  • At least 512Mb of Ram
  • 15GB of free disk space
  • This tutorial is written for Ubuntu 18.04

Skills and Tools

  • You need to know how to SSH and get around the command line
  • An SSH client like Putty
  • An SFTP client like WinSCP
  • The ability to work with files and transfering files

First Step – Make Sure You Are at the Latest and Greatest

Connect to your VPS via SSH

Upgrade your repositories to make sure they are up to date.  We are installing git because this is about 500% faster if we use the fantastic script from Angristan.

$ sudo apt-get update && sudo apt-get upgrade

$ sudo apt-get install git

Do you know your public IP address and your private IP address if you are behind a NAT device (like a router?)

Get the IP from your server

$ ifconfig
eth0: flags=4163  mtu 1500
        inet 192.168.1.166  netmask 255.255.255.0  broadcast 192.168.1.255
        inet6 fe80::216:3cff:fe43:ba41  prefixlen 64 scopeid 0x20
        ether 00:16:3c:43:ba:41  txqueuelen 1000 (Ethernet)
        RX packets 11672693  bytes 1049010192 (1.0 GB)
        RX errors 0  dropped 0 overruns 0  frame 0
        TX packets 347581  bytes 57193541 (57.1 MB)
        TX errors 0  dropped 0 overruns 0  carrier 0 collisions 0

--

If you are behind a device like a firewall or router I visit http://www.whatismyip.com to find my public IP since it is easier than logging into the router directly.

Make a note of these IP addresses on your scratch pad. You might need them later

The Actual Install starts here

The process with the openvpn-install.sh script is dead simple. We are going to clone the script from github.  Then, change into the directory that was created and make sure the script is executable and then bang, run that baby as root or with sudo!  That will kick off the installation dialogues and away you go.

$ cd ~ 
$ git clone https://github.com/angristan/openvpn-install openvpn-install
$ cd openvpn-install/
$ ls -l 
$ chmod +x openvpn-install.sh
$ sudo ./openvpn-install.sh

Welcome to the OpenVPN installer!
The git repository is available at: https://github.com/angristan/openvpn-install
I need to ask you a few questions before starting the setup.

You can leave the default options and just press enter if you are ok with them.

I need to know the IPv4 address of the network interface you want OpenVPN listening to.
Unless your server is behind NAT, it should be your public IPv4 address.

IP address: 192.168.1.111

Checking for IPv6 connectivity...

Your host does not appear to have IPv6 connectivity.

Do you want to enable IPv6 support (NAT)? [y/n]: n

What port do you want OpenVPN to listen to?

   1) Default: 1194
   2) Custom
   3) Random [49152-65535]

Port choice [1-3]: 2

Custom port [1-65535]: 7777     #YOU MIGHT WANT 80 or 443 if your local network is filtering things

What protocol do you want OpenVPN to use?

UDP is faster. Unless it is not available, you shouldn't use TCP.

   1) UDP
   2) TCP

Protocol [1-2]: 1

What DNS resolvers do you want to use with the VPN?

   1) Current system resolvers (from /etc/resolv.conf)
   2) Self-hosted DNS Resolver (Unbound)
   3) Cloudflare (Anycast: worldwide)
   4) Quad9 (Anycast: worldwide)
   5) Quad9 uncensored (Anycast: worldwide)
   6) FDN (France)
   7) DNS.WATCH (Germany)
   8) OpenDNS (Anycast: worldwide)
   9) Google (Anycast: worldwide)
   10) Yandex Basic (Russia)
   11) AdGuard DNS (Russia)

DNS [1-10]: 9

Do you want to use compression? It is not recommended since the VORACLE attack make use of it.

Enable compression? [y/n]: n

Do you want to customize encryption settings?

Unless you know what you're doing, you should stick with the default parameters provided by the script.

Note that whatever you choose, all the choices presented in the script are safe. (Unlike OpenVPN's defaults)
See https://github.com/angristan/openvpn-install#security-and-encryption to learn more.

Customize encryption settings? [y/n]: n

Okay, that was all I needed. We are ready to setup your OpenVPN server now.
You will be able to generate a client at the end of the installation.

Press any key to continue...

Tell me a name for the client.
Use one word only, no special characters.

Client name: chad

Do you want to protect the configuration file with a password?

(e.g. encrypt the private key with a password)
   1) Add a passwordless client
   2) Use a password for the client

Select an option [1-2]: 2

⚠ You will be asked for the client password below ⚠

Note: using Easy-RSA configuration from: ./vars
Using SSL: openssl OpenSSL 1.1.0g  2 Nov 2017
Generating an EC private key
writing new private key to '/etc/openvpn/easy-rsa/pki/private/chad.key.hYBMPyHfHV'
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:
-----
Using configuration from /etc/openvpn/easy-rsa/pki/safessl-easyrsa.cnf
Check that the request matches the signature

Signature ok

The Subject's Distinguished Name is as follows
commonName            :ASN.1 12:'chad'
Certificate is to be certified until Apr  9 03:48:48 2022 GMT (1080 days)

Write out database with 1 new entries
Data Base Updated
Client chad added, the configuration file is available at /root/chad.ovpn.

Download the .ovpn file and import it in your OpenVPN client.

Checking Our Work

I like to hit https://www.whatismyip.com while I’m connected and make sure that I see the remote network in the returned page rather than the external IP of my local network.

Then I like to visit https://speedtest.net and see what kind of throughput I get out of the system.  I got 28.75Mbps down and 73.31 Mbps. Not bad at all!

User Management

To manage OpenVPN users on the system we just re-visit the installer and it will detect that OpenVPN has already been installed and proceed to give us 4 management options.

  1. Add a new user
  2. Revoke an existing user
  3. Remove OpenVPN
  4. Exit
-- 
$ ./openvpn-install.sh 
Looks like OpenVPN is already installed.

What do you want to do?
   1) Add a new user
   2) Revoke an existing user
   3) Remove OpenVPN
   4) Exit 

Select an option [1-4]: 1

Tell me a name for the client certificate.
Please, use one word only, no special characters.

Client name: chad

Using SSL: openssl OpenSSL 1.1.0g  2 Nov 2017
Generating a 2048 bit RSA private key
............+++
.........................+++
writing new private key to '/etc/openvpn/easy-rsa/pki/private/chad.key.YjDIHqlesv'
-----
Using configuration from /etc/openvpn/easy-rsa/pki/safessl-easyrsa.cnf
Check that the request matches the signature
Signature ok
The Subject's Distinguished Name is as follows

commonName            :ASN.1 12:'chad'
Certificate is to be certified until Apr 22 02:45:13 2029 GMT (3650 days)
Write out database with 1 new entries
Data Base Updated
Client chad added, configuration is available at: /root/chad.ovpn
root@ubuntu:~/openvpn-install#
--

Grab your SFTP client and download the username.ovpn certificate file to the workstation that is going to run the OpenVPN client.

Installing the Client on a Windows 10 Workstation

On the workstation download the appropriate client from OpenVPN  at https://openvpn.net/community-downloads/

Assuming Windows 10 download and run the installer and then in your system tray right click the little monitor with a lock on it  and Import your chad.ovpn file! Then Chad > Connect and you should be good to go.  I like to hit https://whatismyip.com while connected and verify that I’m showing the IP address of the OpenVPN server that I’m connected to and not the public IP address of my local network.

Installing the OpenVPN client on your iPhone

https://itunes.apple.com/us/app/openvpn-connect/id590379981 grab that thing from the App Store and then use a cloud file utility like google drive to get the chad.ovpn file or do something really insecure and email it to yourself…

References & Other Options

Alternatives to OpenVPN

About the Author

Sean Richards, CISSP,  is a 20 year linux enthusiast and security practitioner.  He loves family, animals, BBQ, and bicycles.
https://www.linkedin.com/in/seangrichards/
https://github.com/seangrichards/
https://twitter.com/seangrichards

The post How to setup OpenVPN on your VPS: Ubuntu 18.04 appeared first on Low End Box.