• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Create a VM ($25 Credit)
  • Buy a Domain
  • 1 Month free Back Blaze Backup
  • Other Deals
    • Domain Email
    • Nixstats Server Monitoring
    • ewww.io Auto WordPress Image Resizing and Acceleration
  • About
  • Links

IoT, Code, Security, Server Stuff etc

Views are my own and not my employer's.

Personal Development Blog...

Coding for fun since 1996, Learn by doing and sharing.

Buy a domain name, then create your own server (get $25 free credit)

View all of my posts.

  • Cloud
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • How to buy a new domain and SSL cert from NameCheap, a Server from Digital Ocean and configure it.
    • Setting up a Vultr VM and configuring it
    • All Cloud Articles
  • Dev
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • How to setup pooled MySQL connections in Node JS that don’t disconnect
    • NodeJS code to handle App logins via API (using MySQL connection pools (1000 connections) and query parameters)
    • Infographic: So you have an idea for an app
    • All Development Articles
  • MySQL
    • Using the free Adminer GUI for MySQL on your website
    • All MySQL Articles
  • Perf
    • PHP 7 code to send object oriented sanitised input data via bound parameters to a MYSQL database
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • Measuring VM performance (CPU, Disk, Latency, Concurrent Users etc) on Ubuntu and comparing Vultr, Digital Ocean and UpCloud – Part 1 of 4
    • Speeding up WordPress with the ewww.io ExactDN CDN and Image Compression Plugin
    • Setting up a website to use Cloudflare on a VM hosted on Vultr and Namecheap
    • All Performance Articles
  • Sec
    • Using the Qualys FreeScan Scanner to test your website for online vulnerabilities
    • Using OWASP ZAP GUI to scan your Applications for security issues
    • Setting up the Debian Kali Linux distro to perform penetration testing of your systems
    • Enabling TLS 1.3 SSL on a NGINX Website (Ubuntu 16.04 server) that is using Cloudflare
    • PHP implementation to check a password exposure level with Troy Hunt’s pwnedpasswords API
    • Setting strong SSL cryptographic protocols and ciphers on Ubuntu and NGINX
    • Securing Google G Suite email by setting up SPF, DKIM and DMARC with Cloudflare
    • All Security Articles
  • Server
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • All Server Articles
  • Ubuntu
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • Useful Linux Terminal Commands
    • All Ubuntu Articles
  • VM
    • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
    • All VM Articles
  • WordPress
    • Speeding up WordPress with the ewww.io ExactDN CDN and Image Compression Plugin
    • Installing and managing WordPress with WP-CLI from the command line on Ubuntu
    • How to backup WordPress on a host that has CPanel
    • Moving WordPress to a new self managed server away from CPanel
    • Moving a CPanel domain with email to a self managed VPS and Gmail
    • All WordPress Articles
  • All

Terminal

How to send email via G Suite from Ubuntu in the cloud

August 20, 2017 by Zach Meissner

Here is how I send emails from the command line in Ubuntu servers in the cloud via G SUote connect emails

Jan 2018 Update

Post on adding a second domain to G Suite

Post on adding email aliases to G Suite

Main

If you use ufw for your Ubuntu firewall then allow port 587 out traffic (read more in securing Ubuntu in the cloud here).

sudo ufw allow out 587

Ensure your port is open on IPV4 and IPV6.

sudo ufw status

If you have a GUI managed firewall with your server host then configure it to allow port 587 (out).

Read more on useful terminal commands here or setting up a Digital Ocean Ubuntu server here for as low as $5 a month here, Vultr server for as low as $2.5 here ($10 free credit). Read more about setting up an AWS Ubuntu server here.

Install sendmail and other pre requisites

apt-get install libio-socket-ssl-perl libnet-ssleay-perl sendemail

Now you are ready to send an email with 1 line in the terminal (use your Gmail email unless you have diverted your email to G Suite (then use that email, guide here). Create a G Suite account here.

FYI: I have setup my email for my domain to redirect via G Suite (see my guide here and older guide here)

Send an email from the command line

sendemail -f [email protected] -t [email protected] -u "test email" -m "test message" -s smtp.gmail.com:587 -o tls=yes -xu [email protected] -xp [email protected][email protected]

This is not a drop-in replacement for Outlook or Thunderbird email clients but it is perfect for command-line alerts to con-jobs or start-up notifications.

Sending an email with an attachment

sendemail -f [email protected] -t [email protected] -u "test email" -m "test message" -s smtp.gmail.com:587 -o tls=yes -xu [email protected] -xp [email protected]&[email protected] -a /folder/file.zip

Coming soon: A guide on backing up Ubuntu with Rsync etc.

More

Post on adding a second domain to G Suite

Post on adding email aliases to G Suite

Donate and make this blog better




Ask a question or recommend an article
[contact-form-7 id=”30″ title=”Ask a Question”]

v1.2 added other links

v1.1 added links to two G Suite guides.

Filed Under: AWS, Cloud, Digital Ocean, Server, Terminal, Ubuntu, VM, Vultr Tagged With: command line, email, senemail, sent

Useful Linux Terminal Commands

August 13, 2017 by Simon

Below are Ubuntu Linux commands I use often to setup, debug maintain servers.

Read this guide for Useful OSX Commands (for setting up Apache, PHP, MySQL, Adminer etc on OSX)

I recently moved my domain from a C-Panel hosted domain (and Email to Google G Suite (my guide here)) to a self-managed Digital Ocean domain (my LetsEncrypt Guide here, my Digital Ocean guide here, my AWS setup guide here, my Vultr setup guide here) and needed to transfer my WordPress site. Setup your own Digital Ocean Ubuntu server form $5  a month (get the first 2 months free by clicking here) or setup your own Vultr Ubuntu server for as low as $2.5/month by clicking here.

How to Reboot (from time to time when prompted with *** system restart required ***” messages appear).

sudo shutdown -r now

How to set up a  bash file (*.sh) as Executable.

chmod +X filename.sh

The file will now be executable.

Viewing your crontab (Windows Task Scheduler equiv)

crontab -e

Ping a port

nmap -p 80 google.com

Rename a folder

mv /www/oldname /www/newname

Set the owner of a folder

sudo chown -R www-data:www-data /wwwfolder/wp-content/uploads/2017/11/

Check the rsync port

nmap -p 873 theserver.com

Starting Nmap 7.01 ( https://nmap.org ) at 2017-08-19 10:34 AEST
Nmap scan report for theserver.com (xxx.xxx.xxx.xxx)
Host is up (0.00012s latency).
Other addresses for theserver.com (not scanned): xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
rDNS record for xxx.xxx.xxx.xxx: theserver.com
PORT    STATE SERVICE
873/tcp open  rsync

Run a file every 1 minute

*/1 * * * * /scripts/script1.sh

Show server name

hostname

How to verify patch status for Meltdown and Spectre

Read my guide here to install the patch here.

Verify Spectre and Meltdown patch status

dmesg | grep isolation && echo "patched :)" || echo "unpatched :("
[ 0.000000] Kernel/User page tables isolation: enabled
patched :)

or

sudo grep "cpu_insecure\|cpu_meltdown\|kaiser" /proc/cpuinfo && echo "patched :)" || echo "unpatched :("
flags           : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 syscall nx rdtscp lm constant_tsc rep_good nopl xtopology eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm invpcid_single kaiser fsgsbase bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat
patched :)

Restart network

sudo /etc/init.d/networking restart

More here.

Show Operating System Name

hostnamectl ! grep "Operating System"
 Operating System: Ubuntu 10.04.3 LTS

Show installed Packages

sudo apt-get install apt-show-versions

Show all packages with “PHP” in the name.

sudo apt-show-versions | grep php | more
 
libapache2-mod-php7.0:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
libapache2-mod-php7.0:i386 not installed
php-common:all/xenial 1:55+ubuntu16.04.1+deb.sury.org+1 uptodate
php-xdebug:amd64/xenial 2.5.5-3+ubuntu16.04.1+deb.sury.org+1 uptodate
php-xdebug:i386 not installed
php7.0:all/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-cli:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-cli:i386 not installed
php7.0-common:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-common:i386 not installed
php7.0-curl:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-curl:i386 not installed
php7.0-dev:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-dev:i386 not installed
php7.0-fpm:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-fpm:i386 not installed
php7.0-gd:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-gd:i386 not installed
php7.0-imap:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-imap:i386 not installed
php7.0-intl:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-intl:i386 not installed
php7.0-json:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-json:i386 not installed
php7.0-ldap:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-ldap:i386 not installed
php7.0-mbstring:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-mbstring:i386 not installed
php7.0-mysql:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-mysql:i386 not installed
php7.0-opcache:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-opcache:i386 not installed
php7.0-pgsql:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-pgsql:i386 not installed
php7.0-phpdbg:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-phpdbg:i386 not installed
php7.0-pspell:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-pspell:i386 not installed
php7.0-readline:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-readline:i386 not installed
php7.0-recode:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-recode:i386 not installed
php7.0-snmp:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-snmp:i386 not installed
php7.0-tidy:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-tidy:i386 not installed
php7.0-xml:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-xml:i386 not installed
php7.0-zip:amd64/xenial 7.0.25-1+ubuntu16.04.1+deb.sury.org+1 uptodate
php7.0-zip:i386 not installed

Send Messages Other Logged In Users (CLI)

Show all user logged in

w
 20:11:51 up 1 day, 10:25,  2 users,  load average: 0.00, 0.04, 0.01
USER     TTY      FROM             [email protected]   IDLE   JCPU   PCPU WHAT
root     tty1                      20:03   31.00s  0.24s  0.20s -bash
user1    pts/0    123.123.123.123  20:09    0.00s  0.08s  0.01s w

Sent a message to usr1

echo "Hello User1" > /dev/pts/0

Sent a message to the root console

echo "Hello Admin" > /dev/tty1

Messages will appear at the bottom of the user’s console.

Processor

List processes in a tree view (… = removed)

ps -e --forest
  PID TTY          TIME CMD
    2 ?        00:00:00 kthreadd
    3 ?        00:00:00  \_ ksoftirqd/0
    5 ?        00:00:00  \_ kworker/0:0H
    7 ?        00:01:56  \_ rcu_sched
    8 ?        00:00:00  \_ rcu_bh
    9 ?        00:00:00  \_ migration/0
   35 ?        00:00:00  \_ vmstat
   37 ?        00:00:00  \_ ecryptfs-kthrea
   54 ?        00:00:00  \_ acpi_thermal_pm
   55 ?        00:00:00  \_ vballoon
   65 ?        00:00:00  \_ scsi_eh_0
   66 ?        00:00:00  \_ scsi_tmf_0
   67 ?        00:00:00  \_ scsi_eh_1
   68 ?        00:00:00  \_ scsi_tmf_1
   74 ?        00:00:00  \_ ipv6_addrconf
   36 ?        00:00:00  \_ kpsmoused
  456 ?        00:00:00  \_ iscsi_eh
...
    1 ?        00:00:02 init
...
  452 ?        00:00:00 upstart-file-br
  453 ?        00:00:00 dbus-daemon
...
 1489 ?        00:00:00 cron
 1514 ?        00:00:06 irqbalance
 1518 ?        00:00:00 sshd
11855 ?        00:00:00  \_ sshd
11914 pts/4    00:00:00      \_ bash
12008 pts/4    00:00:00          \_ ps
 1523 ?        00:00:09 php-fpm7.0
 1785 ?        00:00:03  \_ php-fpm7.0
 1786 ?        00:00:02  \_ php-fpm7.0
...
 1692 ?        00:01:52 mysqld
 ...
 1891 ?        00:00:53 fail2ban-server
...
 1956 ?        00:00:00 nginx
 1957 ?        00:00:02  \_ nginx
 1958 ?        00:00:03  \_ nginx
 1959 ?        00:00:01  \_ nginx
 1978 ?        00:00:24 ntpd
 2000 ?        00:00:00 systemd-logind
 2011 ?        00:03:24 redis-server
 ...

View major processes by usage/memory

ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head                                    Sat Sep 16 18:51:17 2017

  PID  PPID CMD                         %MEM %CPU
 1692     1 /usr/sbin/mysqld             5.0  0.0
 1523     1 php-fpm: master process (/e  1.0  0.0
 1662     1 /usr/bin/lxd --group lxd --  0.4  0.0
 1785  1523 php-fpm: pool www            0.4  0.0
 1786  1523 php-fpm: pool www            0.3  0.0
 1891     1 /usr/bin/python3 /usr/bin/f  0.3  0.0
 1957  1956 nginx: worker process        0.2  0.0
 1958  1956 nginx: worker process        0.2  0.0
11855  1518 sshd: [email protected]/4             0.1  0.0

Read more on ps here.

How big is a folder

du -hs ./foldername
412MB    ./foldername

Change FIle Create/Modify time’s

Change File Creation Date

SetFile -d '11/25/2019 23:00:00' ./file.doc

Change file modify/accessed time

touch -mt 201911282300 ./filename.doc

Tree

Tree needs to be installed first

sudo apt-get install tree

Show an ASCII representation of a folder structure

tree

Show files in a  structure

tree -a -h -v
.
├── [4.0K]  folder
├── [3.0K]  logfile.log
└── [1.7M]  zipfile.tgz

Show directories

tree -d
.
└── [4.0K]  subfolder

List all files and folders in a structure

tree -a -f -p -h  -l -R

Backup a  www folder

cp -rTv /www/ /backup/www

Common (Digital Ocean) Debugging commands

cat /etc/network/interfaces.d/50-cloud-init.cfg
cat /etc/network/interfaces
ip addr
ip route
uname -a
iptables -nvL --line-numbers
ls -l /lib/modules
cat /etc/udev/rules.d/70-persistent-net.rules

Networking

Display all TCP connections

netstat -at

Display all UDP connections

netstat -au

List all Listening Connections

netstat -l

Show all Network stats

netstat -s

Show all UDP Network stats

netstat -st

Show all TCP Network stats

netstat -su

Show network packets

netstat -i

Displaying raw info

netstat --statistics --raw

Show open ports

netstat -a | grep "LISTEN "

Upload a file to a remote server over ssh

scp /local/folder/local-file.zip [email protected]:/remote/server/destination-folder/

Zip files

Install zip

sudo apt-get install zip

Zip a  whole directory (with high compression)

zip -r -9 /folder/zipfile.zip /directory-to-zip

Zip a  whole directory (excluding *.tmp, *temp, *.bak and *.zip file types)

zip -r -9 /folder/zipfile.zip /directory-to-zip -x "*.tmp" -x "*.temp" -x"./backup/*.bak"-x "./backup/*.zip" -x "*promo*.mp4""

Zip Help

zip
Copyright (c) 1990-2008 Info-ZIP - Type 'zip "-L"' for software license.
Zip 3.0 (July 5th 2008). Usage:
zip [-options] [-b path] [-t mmddyyyy] [-n suffixes] [zipfile list] [-xi list]
  The default action is to add or replace zipfile entries from list, which
  can include the special name - to compress standard input.
  If zipfile and list are omitted, zip compresses stdin to stdout.
  -f   freshen: only changed files  -u   update: only changed or new files
  -d   delete entries in zipfile    -m   move into zipfile (delete OS files)
  -r   recurse into directories     -j   junk (don't record) directory names
  -0   store only                   -l   convert LF to CR LF (-ll CR LF to LF)
  -1   compress faster              -9   compress better
  -q   quiet operation              -v   verbose operation/print version info
  -c   add one-line comments        -z   add zipfile comment
  [email protected]   read names from stdin        -o   make zipfile as old as latest entry
  -x   exclude the following names  -i   include only the following names
  -F   fix zipfile (-FF try harder) -D   do not add directory entries
  -A   adjust self-extracting exe   -J   junk zipfile prefix (unzipsfx)
  -T   test zipfile integrity       -X   eXclude eXtra file attributes
  -y   store symbolic links as the link instead of the referenced file
  -e   encrypt                      -n   don't compress these suffixes
  -h2  show more help

Backup NGINX

zip -r -9 /backup/nginx.zip /etc/nginx/ -x "*.tmp" -x "*.temp" -x"./backup/*.bak" -x "./backup/*.zip"

Unzip

Installing Unzip

sudo apt-get install unzip

Unzip a  file

unzip filename.zip

Updates

Setup Unattended Ubuntu Security updates

sudo apt-get install unattended-upgrades
sudo unattended-upgrades -d

At login, you should receive

0 updates are security updates.

Show Configured NGINX server names

grep "server_name" /etc/nginx/sites-available/default
server_name www.servername.com myservername.com localhost;

Services

Reload daemon services

systemctl daemon-reload

Verify the MongoDB service file exists

ls /etc/systemd/system | grep servivename

View the status of services

systemctl list-unit-files --type=service
UNIT FILE                                  STATE
accounts-daemon.service                    enabled
acpid.service                              disabled
[email protected]                    static
apt-daily-upgrade.service                  static
apt-daily.service                          static
...

Local Dump

locale -a
C
C.UTF-8
en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IN
en_IN.utf8
en_NG
en_NG.utf8
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US
en_US.iso88591
en_US.utf8
en_ZA.utf8
en_ZM
en_ZM.utf8
en_ZW.utf8
POSIX

Show All Defined Ports

cat /etc/services

Show defined rsync ports

cat /etc/services | grep rsync

Show listening ports (active connections)

netstat -plntu
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      1707/mysqld
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      2023/redis-server 1
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1968/nginx
tcp        0      0 0.0.0.0:21              0.0.0.0:*               LISTEN      2097/pure-ftpd (SER
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1525/sshd
tcp        0      0 0.0.0.0:443             0.0.0.0:*               LISTEN      1968/nginx
tcp6       0      0 fe80::1:13128           :::*                    LISTEN      1708/lxd-bridge-pro
tcp6       0      0 :::80                   :::*                    LISTEN      1968/nginx
tcp6       0      0 :::21                   :::*                    LISTEN      2097/pure-ftpd (SER
tcp6       0      0 :::22                   :::*                    LISTEN      1525/sshd
udp        0      0 10.99.0.10:123          0.0.0.0:*                           1990/ntpd
udp        0      0 45.77.48.141:123        0.0.0.0:*                           1990/ntpd
udp        0      0 127.0.0.1:123           0.0.0.0:*                           1990/ntpd
udp        0      0 0.0.0.0:123             0.0.0.0:*                           1990/ntpd
udp6       0      0 fe80::1:123             :::*                                1990/ntpd
udp6       0      0 ::1:123                 :::*                                1990/ntpd
udp6       0      0 :::123                  :::*                                1990/ntpd

Show service status

service --status-all

View your bash history for a past command (e.g “openssl”).

grep "openssl" ~/.bash_history
openssl req -new -newkey rsa:4096 -nodes -keyout fearby.key -out fearby.csr

View last 1 line of a file.

tail -n 1 index.html
</body></html>

Ping a server

ping -c 2 fearby.com

How to check system uptime (and load average)

uptime
> 12:18:48 up 1 min,  1 user,  load average: 0.30, 0.18, 0.17

Uptime in friendly format

uptime -p
up 23 hours, 42 minutes

The load averages at the end are the last 1, 5 min and 15 minutes.

The w command is handy for showing uptime information as-well as logged in users (The ‘w -i’  parameter -i is handy for seeing what IP people are logged in from).

w -i
> 12:22:41 up 5 min,  1 user,  load average: 0.00, 0.07, 0.05
USER     TTY      FROM             [email protected]   IDLE   JCPU   PCPU WHAT
root     pts/0    123.123.123.123    12:18    1.00s  0.07s  0.00s w

How to download a file

curl -o localfile.zip http://www.serverwhereiuploadedthefile.com/remotefile.zip

How to edit NGINX configuration

sudo nano /etc/nginx/nginx.conf

and

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

How to find a file

find / -name filename.ext

also

locate php.ini

Find contents in files (recursive)

grep -r "ahref" *

Find files by name and run a command on each

find -iname "index.html" -exec md5sum {} \;

Show differences in files

diff index.html index2.html
< <body>Loading <a href="http://simon.fearby.com/blog/">http://simon.fearby.com/blog/</a></body></html>
---
> <body>Loading <a href="https://www.fearby.com/blog/">https://www.fearby.com/blog/</a></body></html>

Show contents of file (e.g urls.txt)

cat urls.txt
http://www.server1.com
http://www.server2.com
http://www.server3.com
http://www.server4.com
http://www.server5.com

Download all files mentioned in a text file.

cat urls.txt | xargs wget –c
.. download 4 files ...
cat urls.txt | xargs wget –c

View all packages with updates

sudo /usr/lib/update-notifier/apt-check -p

Output:

cryptsetup-bin
libdns-export162
libisccfg140
mongodb-org-mongos
linux-libc-dev
libgdk-pixbuf2.0-0
tcpdump
bind9-host
dnsutils
nodejs
libpython3.5
python3.5
python3.5-minimal
libisc160
grub-legacy-ec2
libapparmor1
libplymouth4
mongodb-org-shell
ntp
libtidy5
libapparmor-perl
libisc-export160
liblwres141
libcryptsetup4
libgdk-pixbuf2.0-common
libdns162
apache2-bin
apparmor
libisccc140
mongodb-org
libpython3.5-stdlib
libbind9-140
libpython3.5-minimal
cryptsetup
mongodb-org-server

or (on ubuntu 16.04)

apt list --upgradable

Updates

Always backup your server’s configuration before updating.

Backup MySQL

mysqldump --all-databases > /backup/dump-$( date '+%Y-%m-%d_%H-%M-%S' ).sql -u root -p

Crontab

Add this to crontab -e to backup at 1 am every day

0 1 * * * /usr/bin/mysqldump --all-databases > /backup/mysql/dump-$( date '+%Y-%m-%d_%H-%M-%S' ).sql -u root -pmysqlpassword

/scripts/shrinkmysql.sh  script to shrink SQL files

sudo nano /scripts/shrinkmysql.sh
#!/bin/bash

tar -zcf /backup/mysql-$( date '+%Y-%m-%d_%H-%M-%S' ).tgz /backup/mysql/
rm /backup/mysql/*.sql

I had to add this to crontab

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin/:/sbin:/usr/sbin:/scripts/:

Cron job to shrink SQL dumps at 2am every day

0 2 * * * /bin/bash /scripts/shrinkmysql.sh > /dev/null 2>&1

Write to a single log file from the crontab at 2 am every day.

todo

Query a package (e.g. siege package)

sudo dpkg-query -l | grep siege *

How to set up a free SSL certificate (see my guide here).

How to set your timezone.

dpkg-reconfigure tzdata

How to restart PHP

sudo systemctl restart php7.0-fpm

How to show the time on the server

sudo hwclock --show

Reload and restart the NGINX configuration and web server.

sudo nginx -t
sudo nginx -s reload
sudo /etc/init.d/nginx restart

JSON viewing program

Installing

sudo apt-get install jq

Using

wget wget https://downloads.wordpress.org/plugin/genesis-enews-extended.2.0.2.zip

or

curl 'https://api.github.com/repos/stedolan/jq/commits?per_page=5' | jq .

output from json tool

Below are utilities I use a lot.

ncdu file size utility

Installing

sudo apt-get install ncdu

Using

sudo ncdu /

pydf disk checking utility

Installing

sudo apt-get install pydf

Using

pydf

output from pydf tool

ntp timezone service

Installing

sudo apt-get install ntp

Using

ntp

Displaying startup processes

Installing

sudo apt-get install rcconf

Using

sudo rcconf

htop process manager.

Installing

sudo apt-get install htop

Using

htop

output from htop tool

Network Benchmarking (between two servers)

I use iperf to measure total bandwidth between two servers. You will need to allow port 5001 (TCP IPV4 and TCP IPV6 in and out) in any local firewalls and hosts GUIs.

Allow port 5001 on an ufw firewall (IN and OUT)

sudo ufw allow 5001

#I Set port 5001 firewall on my hosts (Digital  Ocean and Vultr GUI)

Deny IP

sudo ufw deny from 123.123.123.123

Allow port 22 access to known IP

sudo ufw allow from 123.123.123.123/24  to any port 22

Deny Outgoing Port

sudo ufw deny out 22

Allow out on port to known IP

sudo ufw allow out from 123.123.123.123 to any port 22

More securing Ubuntu in the cloud here.

Install iperf on the target and source Ubuntu server.

sudo apt-get install iperf

Run this on the listening server.

iperf -s

Run this on benchmarking server (and add the IP of the listening server).

iperf -c 123.123.123.123

Results

Screen dump of ipref -c ip
iperf benchmarking output

Testing concurrent connections to a web server with siege.

Install siege

sudo apt-get install siege

Benchmarking a HTTP server

./siege -t1m c10 'https://fearby.com'

#10 Concurent users

Benchmarking HTTPS sites

Install siege 4.0.2 ( steps here ).

Verify siege 4.0.2 is installed by running

siege -v

Now can benchmark https sites

./siege -t1m c10 'https:/thedomain.com'

View incoming connections on the target server

sudo netstat -tupn

I always increase my history size and tell it not to store duplicates.

Viewing your typed terminal history

history

Increasing your history size

HISTSIZE=10000
HISTCONTROL=ignoredups

How to Update Ubuntu

sudo apt-get update
sudo apt-get dist-upgrade

or

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

Edit SSH authorized keys

sudo nano ~/.ssh/authorized_keys

Search file and show lines where text matches

grep -i "href" index.html
> <body>Loading <a href="http://simon.fearby.com/blog/">http://simon.fearby.com/blog/</a></body></html>

View packages with updates

/usr/lib/update-notifier/apt-check --human-readable
35 packages can be updated.
15 updates are security updates.

View Boot Text

dmesg

Automatic Monitoring (ever 1 second)

Active network connections

watch -n 1 'netstat -at'

Network Packets

watch -n 1 'netstat -i'

Free memory

watch -n 1 'free -m'

Memory breakdown

watch -n 1 'cat /proc/meminfo'

or

watch -n 1 'vmstat -s'

Monitor NGINX memory

watch -n 1 'ps axu |grep nginx'

more soon…

Read this guide for Useful OSX Commands (for setting up Apache, PHP, MySQL, Adminer etc on OSX)

50 most useful Linux commands (view here).

View other Linux command informing sites here, here and here.

Donate and make this blog better




Ask a question or recommend an article
[contact-form-7 id=”30″ title=”Ask a Question”]

v1.8 Show users and senda messages to other users

v.71 Show Operating System Name

v1.7 added Meltdown and Spectre patch information

v1.6 Removed -x fom zip directory

V1.5 Restart Network

v1.4 added Useful OSX Commands

Filed Under: Terminal, Ubuntu, VM Tagged With: commands, Linux, terminal

Securing Ubuntu in the cloud

August 9, 2017 by Simon

It is easy to deploy servers to the cloud within a few minutes, you can have a cloud-based server that you (or others can use). ubuntu has a great guide on setting up basic security issues but what do you need to do.

If you do not secure your server expects it to be hacked into. Below are tips on securing your cloud server.

First, read more on scanning your server with Lynis security scan.

Always use up to date software

Always use update software, malicious users can detect what software you use with sites like shodan.io (or use port scan tools) and then look for weaknesses from well-published lists (e.g WordPress, Windows, MySQL, node, LifeRay, Oracle etc). People can even use Google to search for login pages or sites with passwords in HTML (yes that simple).  Once a system is identified by a malicious user they can send automated bots to break into your site (trying millions of passwords a day) or use tools to bypass existing defences (Security researcher Troy Hunt found out it’s child’s play).

Portscan sites like https://mxtoolbox.com/SuperTool.aspx?action=scan are good for knowing what you have exposed.

You can also use local programs like nmap to view open ports

Instal nmap

sudo apt-get install nmap

Find open ports

nmap -v -sT localhost

Starting Nmap 7.01 ( https://nmap.org ) at 2017-08-08 23:57 AEST
Initiating Connect Scan at 23:57
Scanning localhost (127.0.0.1) [1000 ports]
Discovered open port 80/tcp on 127.0.0.1
Discovered open port 3306/tcp on 127.0.0.1
Discovered open port 22/tcp on 127.0.0.1
Discovered open port 9101/tcp on 127.0.0.1
Discovered open port 9102/tcp on 127.0.0.1
Discovered open port 9103/tcp on 127.0.0.1
Completed Connect Scan at 23:57, 0.05s elapsed (1000 total ports)
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00020s latency).
Not shown: 994 closed ports
PORT     STATE SERVICE
22/tcp   open  ssh
80/tcp   open  http
3306/tcp open  mysql
9101/tcp open  jetdirect
9102/tcp open  jetdirect
9103/tcp open  jetdirect

Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 0.17 seconds
           Raw packets sent: 0 (0B) | Rcvd: 0 (0B)

Limit ssh connections

Read more here.

Use ufw to set limits on login attempts

sudo ufw limit ssh comment 'Rate limit hit for openssh server'

Only allow known IP’s access to your valuable ports

sudo ufw allow from 123.123.123.123/32 to any port 22

Delete unwanted firewall rules

sudo ufw status numbered
sudo ufw delete 8

Only allow known IP’s to certain ports

sudo ufw allow from 123.123.123.123 to any port 80/tcp

Also, set outgoing traffic to known active servers and ports

sudo ufw allow out from 123.123.123.123 to any port 22

Don’t use weak/common Diffie-Hellman key for SSL certificates, more information here.

openssl req -new -newkey rsa:4096 -nodes -keyout server.key -out server.csr
 
Generating a 4096 bit RSA private key
...

More info on generating SSL certs here and setting here and setting up Public Key Pinning here.

Intrusion Prevention Software

Do run fail2ban: Guide here https://www.linode.com/docs/security/using-fail2ban-for-security

I use iThemes Security to secure my WordPress and block repeat failed logins from certain IP addresses.

iThemes Security can even lock down your WordPress.

You can set iThemes to auto lock out users on x failed logins

Remember to use allowed whitelists though (it is so easy to lock yourself out of servers).

Passwords

Do have strong passwords and change the root password provided by the hosts. https://howsecureismypassword.net/ is a good site to see how strong your password is from brute force password attempts. https://www.grc.com/passwords.htm is a good site to obtain a strong password.  Do follow Troy Hunt’s blog and twitter account to keep up to date with security issues.

Configure a Firewall Basics

You should install a firewall on your Ubuntu and configure it and also configure a firewall with your hosts (e.g AWS, Vultr, Digital Ocean).

Configure a Firewall on AWS

My AWS server setup guide here. AWS allow you to configure the firewall here in the Amazon Console.

Type Protocol Port Range Source Comment
HTTP TCP 80 0.0.0.0/0 Opens a web server port for later
All ICMP ALL N/A 0.0.0.0/0 Allows you to ping
All traffic ALL All 0.0.0.0/0 Not advisable long term but OK for testing today.
SSH TCP 22 0.0.0.0/0 Not advisable, try and limit this to known IP’s only.
HTTPS TCP 443 0.0.0.0/0 Opens a secure web server port for later

Configure a Firewall on Digital Ocean

Configuring a firewall on Digital Ocean (create a $5/m server here).  You can configure your Digital Ocean droplet firewall by clicking Droplet, Networking then Manage Firewall after logging into Digital Ocean.

Configure a Firewall on Vultr

Configuring a firewall on Vultr (create a $2.5/m server here).

Don’t forget to set IP rules for IPV4 and IPV6, Only set the post you need to allow and ensure applications have strong passwords.

Ubuntu has a firewall built in (documentation).

sudo ufw status

Enable the firewall

sudo ufw enable

Adding common ports

sudo ufw allow ssh/tcp
sudo ufw logging on
sudo ufw allow 22
sudo ufw allow 80
sudo ufw allow 53
sudo ufw allow 443
sudo ufw allow 873
sudo ufw enable
sudo ufw status
sudo ufw allow http
sudo ufw allow https

Add a whitelist for your IP (use http://icanhazip.com/ to get your IP) to ensure you won’t get kicked out of your server.

sudo ufw allow from 123.123.123.123/24 to any port 22

More help here.  Here is a  good guide on ufw commands. Info on port numbers here.

https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers

If you don’t have a  Digital Ocean server for $5 a month click here and if a $2.5 a month Vultr server here.

Backups

rsync is a good way to copy files to another server or use Bacula

sudo apt install bacula

Basics

Initial server setup guide (Digital Ocean).

Sudo (admin user)

Read this guide on the Linux sudo command (the equivalent if run as administrator on Windows).

Users

List users on an Ubuntu OS (or compgen -u)

cut -d: -f1 /etc/passwd

Common output

cut -d: -f1 /etc/passwd
root
daemon
bin
sys
sync
games
man
lp
mail
news
uucp
proxy
www-data
backup
list
irc
gnats
nobody
systemd-timesync
systemd-network
systemd-resolve
systemd-bus-proxy
syslog
_apt
lxd
messagebus
uuidd
dnsmasq
sshd
pollinate
ntp
mysql
clamav

Add User

sudo adduser new_username

e.g

sudo adduser bob
Adding user `bob' ...
Adding new group `bob' (1000) ...
Adding new user `bob' (1000) with group `bob' ...
Creating home directory `/home/bob' ...
etc..

Add user to a group

sudo usermod -a -G MyGroup bob

Show users in a group

getent group MyGroup | awk -F: '{print $4}'

This will show users in a group

Remove a user

sudo userdel username
sudo rm -r /home/username

Rename user

usermod -l new_username old_username

Change user password

sudo passwd username

Groups

Show all groups

compgen -ug

Common output

compgen -g
root
daemon
bin
sys
adm
tty
disk
lp
mail
proxy
sudo
www-data
backup
irc
etc

You can create your own groups but first, you must be aware of group ids

cat /etc/group

Then you can see your systems groups and ids.

Create a group

groupadd -g 999 MyGroup

Permissions

Read this https://help.ubuntu.com/community/FilePermissions

How to list users on Ubuntu.

Read more on setting permissions here.

Chmod help can be found here.

Install Fail2Ban

I used this guide on installing Fail2Ban.

apt-get install fail2ban

Check Fail2Ban often and add blocks to the firewall of known bad IPs

fail2ban-client status

Best practices

Ubuntu has a guide on basic security setup here.

Startup Processes

It is a good idea to review startup processes from time to time.

sudo apt-get install rcconf
sudo rcconf

Accounts

  • Read up on the concept of least privilege access for apps and services here.
  • Read up on chmod permissions.

Updates

Do update your operating system often.

sudo apt-get update
sudo apt-get upgrade

Minimal software

Only install what software you need

Exploits and Keeping up to date

Do keep up to date with exploits and vulnerabilities

  • Follow 0xDUDE on twitter.
  • Read the GDI.Foundation page.
  • Visit the Exploit Database
  • Vulnerability & Exploit Database
  • Subscribe to the Security Now podcast.

Secure your applications

  • NodeJS: Enable logging in applications you install or develop.

Ban repeat Login attempts with FailBan

Fail2Ban config

sudo nano /etc/fail2ban/jail.conf
[sshd]

enabled  = true
port     = ssh
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 3

Hosts File Hardening

sudo nano /etc/host.conf

Add

order bind,hosts
nospoof on

Add a whitelist with your ip on /etc/fail2ban/jail.conf (see this)

[DEFAULT]
# "ignoreip" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not                          
# ban a host which matches an address in this list. Several addresses can be                             
# defined using space separator.
                                                                         
ignoreip = 127.0.0.1 192.168.1.0/24 8.8.8.8

Restart the service

sudo service fail2ban restart
sudo service fail2ban status

Intrusion detection (logging) systems

Tripwire will not block or prevent intrusions but it will log and give you a heads up with risks and things of concern

Install Tripwire.

sudo apt-get install tiger tripwire

Running Tripwire

sudo tiger

This will scan your system for issues of note

sudo tiger
Tiger UN*X security checking system
   Developed by Texas A&M University, 1994
   Updated by the Advanced Research Corporation, 1999-2002
   Further updated by Javier Fernandez-Sanguino, 2001-2015
   Contributions by Francisco Manuel Garcia Claramonte, 2009-2010
   Covered by the GNU General Public License (GPL)

Configuring...

Will try to check using config for 'x86_64' running Linux 4.4.0-89-generic...
--CONFIG-- [con005c] Using configuration files for Linux 4.4.0-89-generic. Using
           configuration files for generic Linux 4.
Tiger security scripts *** 3.2.3, 2008.09.10.09.30 ***
20:42> Beginning security report for simon.
20:42> Starting file systems scans in background...
20:42> Checking password files...
20:42> Checking group files...
20:42> Checking user accounts...
20:42> Checking .rhosts files...
20:42> Checking .netrc files...
20:42> Checking ttytab, securetty, and login configuration files...
20:42> Checking PATH settings...
20:42> Checking anonymous ftp setup...
20:42> Checking mail aliases...
20:42> Checking cron entries...
20:42> Checking 'services' configuration...
20:42> Checking NFS export entries...
20:42> Checking permissions and ownership of system files...
--CONFIG-- [con010c] Filesystem 'fuse.lxcfs' used by 'lxcfs' is not recognised as a valid filesystem
20:42> Checking for indications of break-in...
--CONFIG-- [con010c] Filesystem 'fuse.lxcfs' used by 'lxcfs' is not recognised as a valid filesystem
20:42> Performing rootkit checks...
20:42> Performing system specific checks...
20:46> Performing root directory checks...
20:46> Checking for secure backup devices...
20:46> Checking for the presence of log files...
20:46> Checking for the setting of user's umask...
20:46> Checking for listening processes...
20:46> Checking SSHD's configuration...
20:46> Checking the printers control file...
20:46> Checking ftpusers configuration...
20:46> Checking NTP configuration...
20:46> Waiting for filesystems scans to complete...
20:46> Filesystems scans completed...
20:46> Performing check of embedded pathnames...
20:47> Security report completed for simon.
Security report is in `/var/log/tiger/security.report.simon.170809-20:42'.

My Output.

sudo nano /var/log/tiger/security.report.username.170809-18:42

Security scripts *** 3.2.3, 2008.09.10.09.30 ***
Wed Aug  9 18:42:24 AEST 2017
20:42> Beginning security report for username (x86_64 Linux 4.4.0-89-generic).

# Performing check of passwd files...
# Checking entries from /etc/passwd.
--WARN-- [pass014w] Login (bob) is disabled, but has a valid shell.
--WARN-- [pass014w] Login (root) is disabled, but has a valid shell.
--WARN-- [pass015w] Login ID sync does not have a valid shell (/bin/sync).
--WARN-- [pass012w] Home directory /nonexistent exists multiple times (3) in
         /etc/passwd.
--WARN-- [pass012w] Home directory /run/systemd exists multiple times (2) in
         /etc/passwd.
--WARN-- [pass006w] Integrity of password files questionable (/usr/sbin/pwck
         -r).

# Performing check of group files...

# Performing check of user accounts...
# Checking accounts from /etc/passwd.
--WARN-- [acc021w] Login ID dnsmasq appears to be a dormant account.
--WARN-- [acc022w] Login ID nobody home directory (/nonexistent) is not
         accessible.

# Performing check of /etc/hosts.equiv and .rhosts files...

# Checking accounts from /etc/passwd...

# Performing check of .netrc files...

# Checking accounts from /etc/passwd...

# Performing common access checks for root (in /etc/default/login, /securetty, and /etc/ttytab...
--WARN-- [root001w] Remote root login allowed in /etc/ssh/sshd_config

# Performing check of PATH components...
--WARN-- [path009w] /etc/profile does not export an initial setting for PATH.
# Only checking user 'root'

# Performing check of anonymous FTP...

# Performing checks of mail aliases...
# Checking aliases from /etc/aliases.

# Performing check of `cron' entries...
--WARN-- [cron005w] Use of cron is not restricted

# Performing check of 'services' ...
# Checking services from /etc/services.
--WARN-- [inet003w] The port for service ssmtp is also assigned to service
         urd.
--WARN-- [inet003w] The port for service pipe-server is also assigned to
         service search.

# Performing NFS exports check...

# Performing check of system file permissions...
--ALERT-- [perm023a] /bin/su is setuid to `root'.
--ALERT-- [perm023a] /usr/bin/at is setuid to `daemon'.
--ALERT-- [perm024a] /usr/bin/at is setgid to `daemon'.
--WARN-- [perm001w] The owner of /usr/bin/at should be root (owned by daemon).
--WARN-- [perm002w] The group owner of /usr/bin/at should be root.
--ALERT-- [perm023a] /usr/bin/passwd is setuid to `root'.
--ALERT-- [perm024a] /usr/bin/wall is setgid to `tty'.

# Checking for known intrusion signs...
# Testing for promiscuous interfaces with /bin/ip
# Testing for backdoors in inetd.conf

# Performing check of files in system mail spool...

# Performing check for rookits...
# Running chkrootkit (/usr/sbin/chkrootkit) to perform further checks...
--WARN-- [rootkit004w] Chkrootkit has detected a possible rootkit installation
Possible Linux/Ebury - Operation Windigo installetd

# Performing system specific checks...
# Performing checks for Linux/4...

# Checking boot loader file permissions...
--WARN-- [boot02] The configuration file /boot/grub/menu.lst has group
         permissions. Should be 0600
--FAIL-- [boot02] The configuration file /boot/grub/menu.lst has world
         permissions. Should be 0600
--WARN-- [boot06] The Grub bootloader does not have a password configured.

# Checking for vulnerabilities in inittab configuration...

# Checking for correct umask settings for init scripts...
--WARN-- [misc021w] There are no umask entries in /etc/init.d/rcS

# Checking Logins not used on the system ...

# Checking network configuration
--FAIL-- [lin013f] The system is not protected against Syn flooding attacks
--WARN-- [lin017w] The system is not configured to log suspicious (martian)
         packets

# Verifying system specific password checks...

# Checking OS release...
--WARN-- [osv004w] Unreleased Debian GNU/Linux version `stretch/sid'

# Checking installed packages vs Debian Security Advisories...

# Checking md5sums of installed files

# Checking installed files against packages...
--WARN-- [lin001w] File `/lib/modules/4.4.0-87-generic/modules.dep' does not
         belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-87-generic/modules.alias.bin' does
         not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-87-generic/modules.devname' does
         not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-87-generic/modules.softdep' does
         not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-87-generic/modules.alias' does not
         belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-87-generic/modules.symbols.bin'
         does not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-87-generic/modules.builtin.bin'
         does not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-87-generic/modules.symbols' does
         not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-87-generic/modules.dep.bin' does
         not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-89-generic/modules.dep' does not
         belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-89-generic/modules.alias.bin' does
         not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-89-generic/modules.devname' does
         not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-89-generic/modules.softdep' does
         not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-89-generic/modules.alias' does not
         belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-89-generic/modules.symbols.bin'
         does not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-89-generic/modules.builtin.bin'
         does not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-89-generic/modules.symbols' does
         not belong to any package.
--WARN-- [lin001w] File `/lib/modules/4.4.0-89-generic/modules.dep.bin' does
         not belong to any package.
--WARN-- [lin001w] File `/lib/udev/hwdb.bin' does not belong to any package.

# Performing check of root directory...

# Checking device permissions...
--WARN-- [dev003w] The directory /dev/block resides in a device directory.
--WARN-- [dev003w] The directory /dev/char resides in a device directory.
--WARN-- [dev003w] The directory /dev/cpu resides in a device directory.
--FAIL-- [dev002f] /dev/fuse has world permissions
--WARN-- [dev003w] The directory /dev/hugepages resides in a device directory.
--FAIL-- [dev002f] /dev/kmsg has world permissions
--WARN-- [dev003w] The directory /dev/lightnvm resides in a device directory.
--WARN-- [dev003w] The directory /dev/mqueue resides in a device directory.
--FAIL-- [dev002f] /dev/rfkill has world permissions
--WARN-- [dev003w] The directory /dev/vfio resides in a device directory.

# Checking for existence of log files...
--FAIL-- [logf005f] Log file /var/log/btmp permission should be 660
--FAIL-- [logf007f] Log file /var/log/messages does not exist

# Checking for correct umask settings for user login shells...
--WARN-- [misc021w] There is no umask definition for the dash shell
--WARN-- [misc021w] There is no umask definition for the bash shell

# Checking symbolic links...

# Performing check of embedded pathnames...
20:47> Security report completed for username.

More on Tripwire here.

Hardening PHP

Hardening PHP config (and backing the PHP config it up), first create an info.php file in your website root folder with this info

<?php
phpinfo()
?>

Now look for what PHP file is loadingPHP Config

Back that your PHP config file

TIP: Delete the file with phpinfo() in it as it is a security risk to leave it there.

TIP: Read the OWASP cheat sheet on using PHP securely here and securing php.ini here.

Some common security changes

file_uploads = On
expose_php = Off
error_reporting = E_ALL
display_errors          = Off
display_startup_errors  = Off
log_errors              = On
error_log = /php_errors.log
ignore_repeated_errors  = Off

Don’t forget to review logs, more config changes here.

Antivirus

Yes, it is a good idea to run antivirus in Ubuntu, here is a good list of antivirus software

I am installing ClamAV as it can be installed on the command line and is open source.

sudo apt-get install clamav

ClamAV help here.

Scan a folder

sudo clamscan --max-filesize=3999M --max-scansize=3999M --exclude-dir=/www/* -i -r /

Setup auto-update antivirus definitions

sudo dpkg-reconfigure clamav-freshclam

I set auto updates 24 times a day (every hour) via daemon updates.

tip: Download manual antivirus update definitions. If you only have a 512MB server your update may fail and you may want to stop fresh claim/php/nginx and mysql before you update to ensure the antivirus definitions update. You can move this to a con job and set this to update at set times over daemon to ensure updates happen.

sudo /etc/init.d/clamav-freshclam stop

sudo service php7.0-fpm stop
sudo /etc/init.d/nginx stop
sudo /etc/init.d/mysql stop

sudo freshclam -v
Current working dir is /var/lib/clamav
Max retries == 5
ClamAV update process started at Tue Aug  8 22:22:02 2017
Using IPv6 aware code
Querying current.cvd.clamav.net
TTL: 1152
Software version from DNS: 0.99.2
Retrieving http://db.au.clamav.net/main.cvd
Trying to download http://db.au.clamav.net/main.cvd (IP: 193.1.193.64)
Downloading main.cvd [100%]
Loading signatures from main.cvd
Properly loaded 4566249 signatures from new main.cvd
main.cvd updated (version: 58, sigs: 4566249, f-level: 60, builder: sigmgr)
Querying main.58.82.1.0.C101C140.ping.clamav.net
Retrieving http://db.au.clamav.net/daily.cvd
Trying to download http://db.au.clamav.net/daily.cvd (IP: 193.1.193.64)
Downloading daily.cvd [100%]
Loading signatures from daily.cvd
Properly loaded 1742284 signatures from new daily.cvd
daily.cvd updated (version: 23644, sigs: 1742284, f-level: 63, builder: neo)
Querying daily.23644.82.1.0.C101C140.ping.clamav.net
Retrieving http://db.au.clamav.net/bytecode.cvd
Trying to download http://db.au.clamav.net/bytecode.cvd (IP: 193.1.193.64)
Downloading bytecode.cvd [100%]
Loading signatures from bytecode.cvd
Properly loaded 66 signatures from new bytecode.cvd
bytecode.cvd updated (version: 308, sigs: 66, f-level: 63, builder: anvilleg)
Querying bytecode.308.82.1.0.C101C140.ping.clamav.net
Database updated (6308599 signatures) from db.au.clamav.net (IP: 193.1.193.64)

sudo service php7.0-fpm restart
sudo /etc/init.d/nginx restart
sudo /etc/init.d/mysql restart 

sudo /etc/init.d/clamav-freshclam start

Manual scan with a bash script

Create a bash script

mkdir /script
sudo nano /scripts/updateandscanav.sh

# Include contents below.
# Save and quit

chmod +X /scripts/updateandscanav.sh

Bash script contents to update antivirus definitions.

sudo /etc/init.d/clamav-freshclam stop

sudo service php7.0-fpm stop
sudo /etc/init.d/nginx stop
sudo /etc/init.d/mysql stop

sudo freshclam -v

sudo service php7.0-fpm restart
sudo /etc/init.d/nginx restart
sudo /etc/init.d/mysql restart

sudo /etc/init.d/clamav-freshclam start

sudo clamscan --max-filesize=3999M --max-scansize=3999M -v -r /

Edit the crontab to run the script every hour

crontab -e
1 * * * * /bin/bash /scripts/updateandscanav.sh > /dev/null 2>&1

Uninstalling Clam AV

You may need to uninstall Clamav if you don’t have a lot of memory or find updates are too big.

sudo apt-get remove --auto-remove clamav
sudo apt-get purge --auto-remove clamav

Setup Unattended Ubuntu Security updates

sudo apt-get install unattended-upgrades
sudo unattended-upgrades -d

At login, you should receive

0 updates are security updates.

Other

  • Read this awesome guide.
  • install Fail2Ban
  • Do check your log files if you suspect suspicious activity.

Check out the extensive Hardening a Linux Server guide at thecloud.org.uk: https://thecloud.org.uk/wiki/index.php?title=Hardening_a_Linux_Server

Donate and make this blog better




Ask a question or recommend an article
[contact-form-7 id=”30″ title=”Ask a Question”]

v1.92 added hardening a linux server link

Filed Under: Ads, Advice, Analitics, Analytics, Android, API, App, Apple, Atlassian, AWS, Backup, BitBucket, Blog, Business, Cache, Cloud, Community, Computer, CoronaLabs, Cost, CPI, DB, Development, Digital Ocean, DNS, Domain, Email, Feedback, Firewall, Free, Git, GitHub, GUI, Hosting, Investor, IoT, JIRA, LetsEncrypt, Linux, Malware, Marketing, mobile app, Monatization, Monetization, MongoDB, MySQL, Networking, NGINX, NodeJS, NoSQL, OS, Planning, Project, Project Management, Psychology, push notifications, Raspberry Pi, Redis, Route53, Ruby, Scalability, Scalable, Security, SEO, Server, Share, Software, ssl, Status, Strength, Tech Advice, Terminal, Transfer, Trello, Twitter, Ubuntu, Uncategorized, Video Editing, VLOG, VM, Vultr, Weakness, Web Design, Website, Wordpress Tagged With: antivirus, brute force, Firewall

Primary Sidebar

Poll

What would you like to see more posts about?
Results

Support this Blog

Create your own server today (support me by using these links

Create your own server on UpCloud here ($25 free credit).

Create your own server on Vultr here.

Create your own server on Digital Ocean here ($10 free credit).

Remember you can install the Runcloud server management dashboard here if you need DevOps help.

Advertisement:

Tags

2FA (9) Advice (17) Analytics (9) App (9) Apple (10) AWS (9) Backup (21) Business (8) CDN (8) Cloud (49) Cloudflare (8) Code (8) Development (26) Digital Ocean (13) DNS (11) Domain (27) Firewall (12) Git (7) Hosting (18) HTTPS (6) IoT (9) LetsEncrypt (7) Linux (20) Marketing (11) MySQL (24) NGINX (11) NodeJS (11) OS (10) PHP (13) Scalability (12) Scalable (14) Security (44) SEO (7) Server (26) Software (7) SSH (7) ssl (17) Tech Advice (9) Ubuntu (39) Uncategorized (23) UpCloud (12) VM (44) Vultr (24) Website (14) Wordpress (25)

Disclaimer

Terms And Conditions Of Use All content provided on this "www.fearby.com" blog is for informational purposes only. Views are his own and not his employers. The owner of this blog makes no representations as to the accuracy or completeness of any information on this site or found by following any link on this site. Never make changes to a live site without backing it up first.

Advertisement:

Footer

Popular

  • Backing up your computer automatically with BackBlaze software (no data limit)
  • How to back up an iPhone (including photos and videos) multiple ways
  • Add two factor auth login protection to WordPress with YubiCo hardware YubiKeys and or 2FA Authenticator App
  • Setup two factor authenticator protection at login on Ubuntu or Debian
  • Using the Yubico YubiKey NEO hardware-based two-factor authentication device to improve authentication and logins to OSX and software
  • I moved my domain to UpCloud (on the other side of the world) from Vultr (Sydney) and could not be happier with the performance.
  • Monitor server performance with NixStats and receive alerts by SMS, Push, Email, Telegram etc
  • Speeding up WordPress with the ewww.io ExactDN CDN and Image Compression Plugin
  • Add Google AdWords to your WordPress blog

Security

  • Check the compatibility of your WordPress theme and plugin code with PHP Compatibility Checker
  • Add two factor auth login protection to WordPress with YubiCo hardware YubiKeys and or 2FA Authenticator App
  • Setup two factor authenticator protection at login on Ubuntu or Debian
  • Using the Yubico YubiKey NEO hardware-based two-factor authentication device to improve authentication and logins to OSX and software
  • Setting up DNSSEC on a Namecheap domain hosted on UpCloud using CloudFlare
  • Set up Feature-Policy, Referrer-Policy and Content Security Policy headers in Nginx
  • Securing Google G Suite email by setting up SPF, DKIM and DMARC with Cloudflare
  • Enabling TLS 1.3 SSL on a NGINX Website (Ubuntu 16.04 server) that is using Cloudflare
  • Using the Qualys FreeScan Scanner to test your website for online vulnerabilities
  • Beyond SSL with Content Security Policy, Public Key Pinning etc
  • Upgraded to Wordfence Premium to get real-time login defence, malware scanner and two-factor authentication for WordPress logins
  • Run an Ubuntu VM system audit with Lynis
  • Securing Ubuntu in the cloud
  • No matter what server-provider you are using I strongly recommend you have a hot spare ready on a different provider

Code

  • How to code PHP on your localhost and deploy to the cloud via SFTP with PHPStorm by Jet Brains
  • Useful Java FX Code I use in a project using IntelliJ IDEA and jdk1.8.0_161.jdk
  • No matter what server-provider you are using I strongly recommend you have a hot spare ready on a different provider
  • How to setup PHP FPM on demand child workers in PHP 7.x to increase website traffic
  • Installing Android Studio 3 and creating your first Kotlin Android App
  • PHP 7 code to send object oriented sanitised input data via bound parameters to a MYSQL database
  • How to use Sublime Text editor locally to edit code files on a remote server via SSH
  • Creating your first Java FX app and using the Gluon Scene Builder in the IntelliJ IDEA IDE
  • Deploying nodejs apps in the background and monitoring them with PM2 from keymetrics.io

Tech

  • Backing up your computer automatically with BackBlaze software (no data limit)
  • How to back up an iPhone (including photos and videos) multiple ways
  • US v Huawei: The battle for 5G
  • Check the compatibility of your WordPress theme and plugin code with PHP Compatibility Checker
  • Is OSX Mojave on a 2014 MacBook Pro slower or faster than High Sierra
  • Telstra promised Fibre to the house (FTTP) when I had FTTN and this is what happened..
  • The case of the overheating Mac Book Pro and Occam’s Razor
  • Useful Linux Terminal Commands
  • Useful OSX Terminal Commands
  • Useful Linux Terminal Commands
  • What is the difference between 2D, 3D, 360 Video, AR, AR2D, AR3D, MR, VR and HR?
  • Application scalability on a budget (my journey)
  • Monitor server performance with NixStats and receive alerts by SMS, Push, Email, Telegram etc
  • Why I will never buy a new Apple Laptop until they fix the hardware cooling issues.

Wordpress

  • Replacing Google Analytics with Piwik/Matomo for a locally hosted privacy focused open source analytics solution
  • Setting web push notifications in WordPress with OneSignal
  • Telstra promised Fibre to the house (FTTP) when I had FTTN and this is what happened..
  • Check the compatibility of your WordPress theme and plugin code with PHP Compatibility Checker
  • Add two factor auth login protection to WordPress with YubiCo hardware YubiKeys and or 2FA Authenticator App
  • Monitor server performance with NixStats and receive alerts by SMS, Push, Email, Telegram etc
  • Upgraded to Wordfence Premium to get real-time login defence, malware scanner and two-factor authentication for WordPress logins
  • Wordfence Security Plugin for WordPress
  • Speeding up WordPress with the ewww.io ExactDN CDN and Image Compression Plugin
  • Installing and managing WordPress with WP-CLI from the command line on Ubuntu
  • Moving WordPress to a new self managed server away from CPanel
  • Moving WordPress to a new self managed server away from CPanel

General

  • Backing up your computer automatically with BackBlaze software (no data limit)
  • How to back up an iPhone (including photos and videos) multiple ways
  • US v Huawei: The battle for 5G
  • Using the WinSCP Client on Windows to transfer files to and from a Linux server over SFTP
  • Connecting to a server via SSH with Putty
  • Setting web push notifications in WordPress with OneSignal
  • Infographic: So you have an idea for an app
  • Restoring lost files on a Windows FAT, FAT32, NTFS or Linux EXT, Linux XFS volume with iRecover from diydatarecovery.nl
  • Building faster web apps with google tools and exceed user expectations
  • Why I will never buy a new Apple Laptop until they fix the hardware cooling issues.
  • Telstra promised Fibre to the house (FTTP) when I had FTTN and this is what happened..

Copyright © 2023 · News Pro on Genesis Framework · WordPress · Log in

Some ads on this site use cookies. You can opt-out if of local analytics tracking by scrolling to the bottom of the front page or any article and clicking "You are not opted out. Click here to opt out.". Accept Reject Read More
GDPR, Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT