[LINUX] Install SSL certificates on Apache

Just follow the following steps:

# mv myprivatekey.key /etc/ssl/private

# mv mycertificate.crt /usr/local/share/ca-certificates/

# mv CAcert.crt /usr/local/share/ca-certificates/

# update-ca-certificates

# ll /etc/ssl/certs/ | grep -i mycert

# vim /etc/apache2/sites-enabled/default-ssl.conf
----------------------------------------
[...]
SSLCertificateFile /etc/ssl/certs/mycertificate.pem
SSLCertificateKeyFile /etc/ssl/private/myprivatekey.key
SSLCertificateChainFile /etc/ssl/certs/CAcert.pem
[...]
----------------------------------------

# systemctl restart apache2.service

[LINUX] Extract multiple zip files with password

extract multiple zip files with password

Sometimes visual programs can’t help us. For istance, let’s assume you would like to extract multiple zip files protected with a common password. How can you do that using a desktop environment, or more in general, visual programs? That’s simple, you can’t do that. Fortunately, shell is our friend, so you can use 7z command to extract your zip files.

First thing, install 7z using apt or yum, depending on your Linux distribution, then run the following command within the directory containing your zip-protected files.

~$ for z in *.zip; do 7z x -pPASSWORD -y "$z"; done

You have done!

If you have found this post useful, please visit the Contribute page

[LINUX] Recursively change permissions only on files or dirs

Use the command below to recursively change permissions only on files:

~$ find /<path> -type f -exec chmod 644 {} \;

While use the following command to recursively change permissions only on directories:

~$ find /<path> -type d -exec chmod 755 {} \;

where:
/<path> is the path containing the interested files or directories.
644 assigns permissions of “read/write” on the owner, while “read” on the group and others.
755 assigns permissions of “read/write/execute” on the owner, while “read/execute” on the group and others.

[LINUX] Recursively change permissions on specific file type

Use the following command to recursively change permissions only on specific file type (e.g, all php files in the main path and related sub-directories):

~$ find . -name "*.php" -exec chmod +x {} \;

The command above searches all php files and excute the chmod command to apply the execution permission (+x).

If you have found this post useful, please visit the Contribute page

[LINUX] Type Special Characters

Below you can find a list of keyboard codes to type the corresponding special characters:

` : AltGr-'
{ : AltGr-7
} : AltGr-0
~ : AltGr-ì
¹ : AltGr-1
² : AltGr-2
³ : AltGr-3
¼ : AltGr-4
½ : AltGr-5
⅛ : AltGr-Shift-4
⅜ : AltGr-Shift-5
⅝ : AltGr-Shift-6
⅞ : AltGr-Shift-7
¬ : AltGr-6
“ : AltGr-v
” : AltGr-b
« : AltGr-z
» : AltGr-x
€ : AltGr-e
@ : AltGr-q
← : AltGr-y
→ : AltGr-i
↓ : AltGr-u
< : AltGr-Shift-z
> : AltGr-Shift-x
© : AltGr-Shift-c
® : AltGr-Shift-r
™ : AltGr-Shift-8
× : AltGr-Shift-,
÷ : AltGr-Shift--

[LINUX] Backup your data

Below some of the solutions to backup your data on Linux systems. All backup and restoring procedures should be executed in read-only mode (e.g., running a Live Distro).

Logical backup using find and cpio of the entire file system

~# find / -path '/media' -prune -o -path '/tmp' -prune -o -path '/lost+found' -prune -o -print | cpio -dumpv /media/<backup_dir>

The above command find and copy (preserving original permissions and owners) all directories and files within /. We exclude from backup the following paths: /media, /tmp, /lost+found

Physical backup using dd

~# dd if=/dev/sdXY of=/media/<backup_dir>/<backup_file>.dmp conv=noerror,sync

where X is the character identifying the disk, while Y is the digit identifying the partition. Remove the number of the partition if you like to backup the entire disk (i.e., MBR, partition table and all partitions).

If your partition has some errors, before restoring your data, you can directly work on the dump file to fix the problems. For instance, assuming to have a partition with the old EXT3, run the following command to automatically fix the errors:

~# fsck.ext3 -p /media/<backup_dir>/<backup_file>.dmp

If the above command fails, you can try to manually repair the file system running the command with the -f parameter:

~# fsck.ext3 -f /media/<backup_dir>/<backup_file>.dmp

After all fixes, you can mount the dump file to investigate if everything is OK:

~# mount -o loop,ro -t ext3 /media/<backup_dir>/<backup_file>.dmp /media/<mount_point>

Finally, you can restore all data in a new partition (or disk in case of an entire backup):

~# dd if=/media/<backup_dir>/<backup_file>.dmp of=/dev/sdXY

Hack: you can display the backup/restore progress running the following command:

~# killall -USR1 dd

or

~# ps -ef | grep -i dd
~# kill -USR1 <pid>

Some alternatives to dd
1) sdd: a custom version of dd. You can check the progress of the operation if you run the command with the parameter -time and then press CTRL-/ or CTRL-4 (SIGQUIT).
2) ddrescue: another data recovery tool. Besides copying files from one block to another, it also tries to rescue data in case of read errors.

~# ddrescue -v -r3 /dev/sdXY /media/<backup_dir>/<backup_file>.dmp

where -r3 says to try atmost 3 times on bad sectors.

[LINUX] Audit rules to monitor user activity

Monitoring 1-level directory changes

-a always,exit -F path=</path_dir> -F perm=w -k dir-to-watch

where </path_dir> is the directory you’d like to monitor.

Recursively monitoring directories changes

-a always,exit -F dir=</path_dir> -F perm=w -k dirs-to-watch

where </path_dir> is the path you’d like to recursively monitor.

Monitoring commands executed by specific users (syscall rules)

-a always,exit -F path=</path/command> -F perm=x -F auid>=500 -F auid!=4294967295 -k privileged_users
-a always,exit -F path=</path/command> -F perm=x -F gid=333 -k normal_users

where </path/command> is the command path you’d like to monitor.

Monitoring commands executed by all users (FS rules)

-w </path/command> -p x

where </path/command> is the command path you’d like to monitor.

Excluding specific audit types, e.g. CWD and PATH

-a always,exclude -F msgtype=CWD
-a always,exclude -F msgtype=PATH

[LINUX] Add new APT repository

Adding a new APT repository to a Debian-based distro can be done running the following two commands:

~$ wget -O - <url_key> | sudo apt-key add -
~$ sudo wget -O /etc/apt/sources.list.d/<source>.list <url_source_list>

where:
<url_key> is the URL of the key
<source> is the name of the source
<url_source_list> is the URL of the remote source list file

The first command downloads the corresponding APT key, while the second one adds the repository into a new source list file.

Now you can update APT executing the usual command:

~$ sudo apt-get update

[APACHE] Enable files and directory listing

Sometimes it’s useful to enable files and directory listing (or indexing) to allow users viewing and downloading all the files within a directory.

To enable this feature just add or change the corresponding portion of the Apache configuration. The configuration file is usually /etc/apache2/apache2.conf or /etc/httpd/httpd.conf.

<Directory /files>
	Options Indexes FollowSymLinks MultiViews
	AllowOverride None
	Require all granted
</Directory>

The outcome is showed below:

Directory Listing

If you have found this post useful, please visit the Contribute page

[APACHE] Password Protect a Directory with htaccess

If you like to password protect a directory on your web server, just create a .htaccess file into such a directory and put the following code:

AuthType Basic
AuthName "Restricted Area"
AuthUserFile /path/directory/protect/.htpasswd
require valid-user

Then, generate the corresponding .htpasswd file by executing the following command:

/path/directory/protect$ htpasswd -c .htpasswd admin
New password:
Re-type new password:
Adding password for user admin

Reload your web directory and enter the credentials you’ve just chosen.

[LINUX] aMule instance already running

If you are trying to open aMule but you receive the following error:

Initialising aMule
Checking if there is an instance already running...
There is an instance of aMule already running
Raising current running instance.

then, something went wrong in its last execution. So, you have to first remove the lock file:

~$ rm ~/.aMule/muleLock

If you have found this post useful, please visit the Contribute page

[LINUX] How to Monitor System Performance

You can use the vmstat command to monitor system performance in real-time. vmstat is a tool able to collect stats about system’s memory and processor resource utilization in real time. In order to have an always-active monitoring shell, prepend the watch command to the vmstat command:

~$ watch vmstat -a -S M
Every 2.0s: vmstat -a -S M

procs -----------memory---------- ---swap-- -----io---- -system-- ------cpu-----
 r  b   swpd   free  inact active   si   so    bi    bo   in   cs us sy id wa st
 0  0      0   2961    268    358    0    0   145    38   75  119  0  0 97  2  0

Furthermore, if you’d like to specifically monitor disk reads/writes, you can execute the following command:

~$ watch vmstat -d
Every 2.0s: vmstat -d

disk- ------------reads------------ ------------writes----------- -----IO------
       total merged sectors      ms  total merged sectors      ms    cur    sec
sr0        0      0       0       0      0      0       0       0      0      0
sda    24616   4031  867336  196140   2424  10626  227728 1087716      0     54

[BASH] Best way to concat strings

There are many ways to concat strings in bash, but only one is the best. Let’s see the several methods:

x="debian"
y="linux"

z=$x$y		# does work		$z is "debianlinux"
z="$x$y"	# does work		$z is still "debianlinux"
z="$x9 $y"	# does not work		$z is just "linux"
z="${x}9 ${y}"	# does work (best)	$z is "debian9 linux"

So, in our opinion, the best way is the last one, always using the following syntax to get a variable value: ${VARIABLE}

[BASH] Get the source directory of a bash script

Often it’s very useful declaring a variable with the absolute path of the bash script. In doing so, you can prepend that variable to other sub-path variables (e.g., a sub-dir “logs”).

But, how can we dynamically get the source directory of a bash script? And why is that better than manually writing the static path? That’s better because of this simple reason: if you move the script or rename one of the parent directory where the script is within, you have to remember to update your code as well. Instead, using the following bash string, the absolute path is automatically updated:

$(dirname "${BASH_SOURCE[0]}")

Let’s see a common example where you can use the above code:

#!/bin/bash
TODAY=$(date +"%Y%m%d")
HOSTNAME=$(hostname)

ABSOLUTE_PATH=$(dirname "${BASH_SOURCE[0]}")
FILE_LOG="${ABSOLUTE_PATH}/logs/test.log"

echo "${TODAY} ${HOSTNAME}: Test QWERTY" >> ${FILE_LOG}

[LINUX] Output of the previous executed command

To simply view the output of the previous executed command, you can run the following echo:

~$ echo "$?"

Indeed, $? returns the output code or message of the last executed command. Below a common example:

~$ touch foobar
~$ rm foobar
~$ echo "$?"
0 ~$ rm foobar
rm: cannot remove 'foobar': No such file or directory
~$ echo "$?"
1

A value of 0 means “Success”, while a value of 1 means “Fail”.

[BASH] Check if a file or dir exists

Run the following code to test a file and dir checking.

#!/bin/bash
FILE="/root/test.txt"
DIRECTORY="/sbin"

# IF FILE EXISTS
if [ -f $FILE ]; then
    echo "File $FILE exists."
fi


# IF FILE DOES NOT EXIST
if [ ! -f $FILE ]; then
    echo "File $FILE does not exist."
fi


# IF DIR EXISTS
if [ -d "$DIRECTORY" ]; then
    echo "Dir $DIRECTORY exists."
fi


# IF DIR DOES NOT EXIST
if [ ! -d "$DIRECTORY" ]; then
    echo "Dir $DIRECTORY does not exist."
fi