How to non-interactive/unattended password login to ssh (using sshpass and ssh_askpass)

  • sshpass@man is a noninteractive ssh password provider. Its an less secure alternative to public key authentication. sshpass only works if the password prompt ends in assword:.
## install
$ apt-get install sshpass | yum install sshpass (EPEL) | pacman -S sshpass

'-p PASSWORD' take password from cli
'-e' take password from SSHPASS env var

# need to disable host key checking
$ sshpass -p PASSWORD ssh -o StrictHostKeyChecking=no user@host

# rsync (and scp) over password ssh
$ SSHPASS=PASSWORD rsync --rsh='sshpass -e ssh -l user' host:path .
$ sshpass -p PASSWORD scp user@host:path .

from sshpass@cyberciti

  • ssh@man using SSH_ASKPASS. If ssh does not have a terminal associated with it but DISPLAY and SSH_ASKPASS are set, it will execute the program specified by SSH_ASKPASS and open an X11 window to read the passphrase.
$ vi
$ export DISPLAY=:0 ; export SSH_ASKPASS=`pwd`/
$ setsid ssh -o StrictHostKeyChecking=no user@host

from ssh password from stdin


How to generate SSL CSR (certificate signing request) and self-signed certificates for Apache/Nginx (using OpenSSL)

  • OpenSSL is an open-source implementation of the SSL and TLS protocols.
'req' PKCS#10 certificate request and certificate generating utility.
'-x509' outputs a self signed certificate instead of a certificate request
'-newkey alg:file' creates a new certificate request and a new private key
'-keyout filename' filename to write the newly created private key to
'-out filename' filename to write to
'-days n' number of days to certify the certificate for, defaults to 30 for x509

# create private key 'key.pem' and generate a certificate signing request 'req.pem'
$ openssl req -newkey rsa:1024 -keyout key.pem -out req.pem
$ openssl genrsa -out key.pem 1024 ; openssl req -new -key key.pem -out req.pem

# generate a self signed root certificate 'cert.pem' and private key 'key.pem'
$ openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365

from openssl-req@man

'-nodes' if a private key is created it will not be encrypted

# generate a self signed root certificate '$CERT.csr' for apache, and private key '$CERT.key'
$ export CERT=/etc/httpd/ssl/server
$ openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out $CERT.key
$ chmod 600 $CERT.key
$ openssl req -new -key $CERT.key -out $CERT.csr
$ openssl x509 -req -in $CERT.csr -signkey $CERT.key -out $CERT.crt -days 365
# edit SSLCertificateFile $CERT.crt and SSLCertificateKeyFile $CERT.key

# same
$ export CERT=/etc/httpd/ssl/server
$ openssl req -x509 -nodes -newkey rsa:2048 -keyout $CERT.key -out $CERT.crt -days 365

# same but using 'make testcert'
$ cd /usr/share/ssl/certs ; make testcert

# same but using 'crypto-utils'
$ sudo yum install crypto-utils | sudo apt-get install crypto-utils
$ genkey your_FQDN
# edit SSLCertificateFile and SSLCertificateKeyFile

from How to Create Self-Signed SSL Certificates and Keys for Apache

$ nginx -V
TLS SNI support enabled
$ mkdir -p /etc/nginx/ssl/ ; cd $_

# create private key; asks for passphrase
$ openssl genrsa -des3 -out self-ssl.key 2048
# create a certificate signing request - CSR
$ openssl req -new -key self-ssl.key -out self-ssl.csr
# optional remove passphrase
$ cp -v self-ssl.{key,original} ; openssl rsa -in self-ssl.original -out self-ssl.key ; rm -v self-ssl.original
# create certificate
$ openssl x509 -req -days 365 -in self-ssl.csr -signkey self-ssl.key -out self-ssl.crt
# configure nginx
$ cat etc/nginx/virtual/.conf
server {
  listen 443;
  ssl on;
  ssl_certificate /path/to/self-ssl.crt;
  ssl_certificate_key /path/to/self-ssl.key;

# verify certificates
$ openssl verify pem-file
$ openssl verify self-ssl.crt

from HowTo: Create a Self-Signed SSL Certificate on Nginx For CentOS / RHEL

How to protect servers (ssh, apache, asterisk, …) from brute-force attacks (using fail2ban)

## install
$ sudo yum install failban (EPEL) | sudo apt-get install fail2ban

## configure fail2bain, in '/etc/fail2ban/jail.conf'
$ cat /etc/fail2ban/jail.conf
# 1 - generic configuration
# "bantime" is the number of seconds that a host is banned
bantime  = 600
# ip addresses that should be excluded from fail2ban rules
ignoreip =
# A host is banned if it has generated "maxretry" during the last "findtime" seconds.
findtime = 600
maxretry = 3
# 2 - define ban actions
# config file in '/etc/fail2ban/action.d' used when ban is needed; default uses iptables to ban an IP on all ports when it fails authentication
banaction = iptables-multiport
# calls banaction script; default is 'action_' which passes the name, port, protocol, and chain to the script; other values are 'action_mw' to ban and send an e-mail
action_ = %(banaction)s[name=%(__name__)s, port="%(port)s", protocol="%(protocol)s", chain="%($
action = %(action_)s

# 3 - application-specific jails
enabled  = true
port     = ssh
# file in '/etc/fail2ban/filter.d' telling how to parse the log file, see failregex in '/etc/fail2ban/filter.d/sshd.conf'
filter   = sshd
# what files to parse for failures
logpath  = /var/log/auth.log

## configure firewall, iptables in our case
$ cat /etc/fail2ban/action.d/iptables-multiport.conf
# commands executed when fail2ban starts and stop; it creates a new chain for given port (see above)
actionstart/actionstop = ...
# commands executed when banning and unbanning an ip; basically drops the packet 
actionban = iptables -I fail2ban-<name> 1 -s <ip> -j DROP
actionunban = iptables -D fail2ban-<name> -s <ip> -j <blocktype>

$ sudo service fail2ban restart
$ sudo iptables -L
Chain INPUT (policy ACCEPT)
fail2ban-ssh  tcp  --  anywhere             anywhere             multiport dports ssh
Chain fail2ban-ssh (1 references)
DROP       all  --  anywhere            
RETURN     all  --  anywhere             anywhere

from How To Protect SSH with fail2ban on Debian 7

# enable predefined Apache jails, if not already enabled
$ cat /etc/fail2ban/jail.conf
# detect password authentication failures
enabled  = true
enabled = true
# uses default action, otherwise set
$ cat /etc/fail2ban/jail.conf
banaction = iptables-multiport
$ sudo systemctl restart fail2ban | sudo service fail2ban restart

# check and manage Fail2ban banning status
$ sudo fail2ban-client status
# ban/unban a given IP address
$ sudo fail2ban-client set [name-of-jail] banip [ip-address]

from How to configure fail2ban to protect Apache HTTP server

Same but for asterisk both with and without Asterisk Security Framework (Asterisk 10+)

$ cat /etc/fail2ban/filter.d/asterisk.conf
# regex to match the password failures messages in the logfile. The host must be matched by a group named "host". 
# The tag "<HOST>" can be used for standard IP/hostname matching and is only an alias for (?:::f{4,6}:)?(?P<host>S+)
# without asterisk security framework
#failregex = SECURITY.* SecurityEvent="FailedACL".*RemoteAddress=".+?/.+?/<HOST>/.+?".*
            SECURITY.* SecurityEvent="InvalidAccountID".*RemoteAddress=".+?/.+?/<HOST>/.+?".*
            SECURITY.* SecurityEvent="ChallengeResponseFailed".*RemoteAddress=".+?/.+?/<HOST>/.+?".*
            SECURITY.* SecurityEvent="InvalidPassword".*RemoteAddress=".+?/.+?/<HOST>/.+?".*
# with asterisk security framework
failregex = SECURITY.* SecurityEvent="FailedACL".*RemoteAddress=".+?/.+?/<HOST>/.+?".*
            SECURITY.* SecurityEvent="InvalidAccountID".*RemoteAddress=".+?/.+?/<HOST>/.+?".*
            SECURITY.* SecurityEvent="ChallengeResponseFailed".*RemoteAddress=".+?/.+?/<HOST>/.+?".*
            SECURITY.* SecurityEvent="InvalidPassword".*RemoteAddress=".+?/.+?/<HOST>/.+?".*

# regex to ignore. If this regex matches, the line is ignored.
ignoreregex =

$ cat /etc/fail2ban/jail.conf
enabled  = true
filter   = asterisk
action   = iptables-allports[name=ASTERISK, protocol=all]
           sendmail-whois[name=ASTERISK, dest=root,]
# without asterisk security framework
#logpath  = /var/log/asterisk/messages
# with asterisk security framework
logpath  = /var/log/asterisk/security

# cat /etc/fail2ban/jail.conf

$ cat /etc/asterisk/logger.conf
dateformat=%F %T

$ service iptables start; service fail2ban start
$ iptables -L -v
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
2104K 414M fail2ban-ASTERISK all — any any anywhere anywhere

from Fail2Ban (with iptables) and asterisk

How to unlock root, add admin privileges (using sudo) and reset root password in Linux

  • How to unlock root from login (and ssh)
# set a password will unlock root
$ sudo passwd

# to lock back use '-l'
$ sudo passwd -l root

# to enable/disable root ssh login
$ cat /etc/ssh/sshd_config
PermitRootLogin yes
$ service sshd restart

see passwd@man

  • How to add administrator privileges to users
# add user to sudo(rhel) or wheel(ubuntu) group
$ sudo usedmod -a -G wheel username
$ newgrp wheel

# if not defined, define a group to allow to execute any command
# note: need to be in 'sudo/whell' to edit sudoers
$ cat /etc/sudoers
%wheel ALL=(ALL) ALL
# same but without password
# optionally set sudo session timeout (default is 15 mins, <0 never expires, 0 asks every time for password)
Defaults env_reset,timestamp_timeout=10

# if you get 'username is not in the sudoers file' then
# reboot into recovery mode (or single-user mode)
$ mount -o remount,rw /
$ usermod -a -G sudo username
$ exit

see sudoers@man

  • How to reset root password using single-user mode
# pre-GRUB2, boot into single-user mode by 'esc' or 'shift' to enter GRUB menu and append '1' (for runlevel 1)

# in GRUB2 root passwd is now required to operate in single-user mode so 
# find 'linux' line and replace 'rhgb quiet' with 'init=/bin/sh' (or 'rd.break' to drop to emergency mode)

# ctrl+x to boot
$ passwd
$ exit (or reboot) 

# if 'passwd' is read-only then
$ mount -o remount,rw /

# alternatively to single-user mode is boot into recovery (ubuntu only)

from lostpassword@ubuntu and resetpasswd@centos

How to sign/verify a Git tags and commits (using GnuPG)

  • git-tag@man is used to create, list, delete or verify a tag object signed with gnupg.
# install gnupg
$ sudo apt-get install gnupg2 | sudo yum install gnupg2

# from git-tag
'-s/--sign' make a GPG-signed tag, using the default e-mail address’s key
'-u/--local-user=<key-id>' make a GPG-signed tag, using the given key (defaults to 'user.signingkey')
'-v/--verify' verify the gpg signature of the given tag names.

# create key pair, asks for; note: use rng-tools to increase entropy
$ gpg --gen-key
$ gpg --list-secret-keys | grep ^sec
# either use '-u' or
$ git config --global user.signingkey [gpg-key-id]

# create a signed tab with private key
$ git tag --sign [signed-tag-name] -m "message"

# make public key available by storing as raw object and importing them
$ gpg --list-keys
$ gpg -a --export [gpg-key-id] | git hash-object -w --stdin
[object SHA]
# tag key with a name
$ git tag -a [object SHA] maintainer-pgp-pub
# import keys
$ git show maintainer-pgp-pub | gpg --import

# verify a tag signature
$ git tag --verify [signed-tag-name]

from Git Tools – Signing Your Work

  • git-commit@man record changes to the repository.
    As of 1.7.9 it’s possible to sign your commits with your private/secret key.
    As of 1.8.3 and later, “git merge” and “git pull” can be told to inspect and reject when merging a commit that does not carry a trusted GPG signature with the –verify-signatures command.
# from git-commit
'-S<keyid>/--gpg-sign=<keyid>' GPG-sign commit using the given key (defaults to 'user.signingkey')
# from git-log
'--show-signature' check the validity of a signed commit object by passing the signature to 'gpg --verify' and show the output
# from git-merge
'--verify-signatures' verify that the commits being merged have good and trusted GPG signatures and abort the merge in case they do not
'-S' sign the resulting merge commit itself

# sign commit
$ git config --global user.signingkey 8EE30EAB
$ git commit -m "message" -S

# show and verify signature in commit message
$ git log --show-signature 
gpg: Signature made ...
gpg: Good signature from ...

# verify and reject merge if has commits not signed
$ git merge --verify-signatures non-verify
fatal: Commit ab06180 does not have a GPG signature.

from Git Tools – Signing Your Work

How to encrypt/decrypt/sign/verify files in Linux (using GnuPG, PKZIP and 7z)

  • gnupg/gnupg@man GPL-licensed alternative to PGP, an encryption/decryption program that provides cryptographic privacy and authentication for data communication.

Using symmetric-key algorithms – use same key for encryption and decryption

# install
$ sudo apt-get install gnupg2 | sudo yum install gnupg2

'-c/--symmetric' encrypt with a symmetric cipher using a passphrase using '-cipher-algo' (default is CAST5)

# encrypting a file, asks for passphrase; generates encrypted 'filename.gpg'
$ gpg -c filename

'-d' decrypt to stdout, use '-o/--output'; if the decrypted file is signed, the signature is also verified

# decrypt file, asks for passphrase
$ gpg filename.gpg or  gpg -o filename -d filename.gpg

from Linux: HowTo Encrypt And Decrypt Files With A Password and How to create an encrypted zip file on Linux

Using public-key algorithms – use public key to encrypt or verify digital signature; and private/secret key to decrypt or sign with digital signature

# random number generator for entropy see
$ sudo apt-get install rng-tools | sudo yum install rng-tools
$ cat /etc/default/rng-tools
$ service rng-tools start

'-s/--sign' make a signature (to .sig)
'-e/--encrypt' encrypt data (to .asc or .gpg, see '-a')
'-s -e' signed and encrypted message
'-c -s' signed and symmetrically encrypted message
'-c -e' message that may be decrypted via a secret key or a passphrase
'-c -s -e' signed message that may be decrypted via a secret key or a passphrase

'-a/--armor' create ASCII armored output, .asc is generated instead of .gpg
'-u/--local-user name' secret key to use, defaults to first; usefull if you have more then one secret key
'-r/--recipient name' public key of recipient; if this option or --hidden-recipient is not specified, GnuPG asks for the user-id unless --default-recipient is given

# create key pair, asks for
$ gpg --gen-key
# optionally, create revocation certificate; used to invalidate key pair
$ gpg --gen-revoke

# lists public/private keys
$ gpg --list-keys ; gpg --list-secret-keys
# export public keys to share with everyone
$ gpg -a --export > public.key
# import others public keys
$ gpg --import public.key
# search for public keys in a keyserver; default keyserver is 'hkp://'
$ gpg --keyserver --search-keys search_parameters
# send public key 'KEYID' to keyserver
$ gpg --keyserver --send-keys KEYID
# get public key from keyserver
$ gpg --keyserver --recv-key KEYID
# delete public/private keys
$ gpg --delete-key ; gpg --delete-secret-key

# encrypt with your public key and signs with your private key; use '-u' if you have more then one private key
$ gpg --encrypt --sign -a -r -o filename.asc filename
# decrypt and verify signature using private key, asks for passpharse
$ gpg --decrypt filename.asc -o filename

# sign with your private key; generates 'filename.sig'
$ gpg --sign -a -o filename.sig filename
# verify signature and recover original file
$ gpg --decrypt -o filename filename.sig
# generate a detached signature and verify signature
$ gpg --detach-sig filename.sig ; gpg --verify filename.sig filename

from The GNU Privacy Handbook
front-ends for GnuPG: KGPG@wiki and Seahorse@wiki/How to PGP encrypt, decrypt or digitally sign files via GnuPG GUI

# encrypt using zip; it supports
$ zip --password MY_SECRET files
# decrypt
$ unzip

# encrypt using 7zip; 7z archiver supports AES-256 encryption algorithm with SHA-256 hash algorithm based key generation
$ 7za a -tzip -pMY_SECRET -mem=AES256 files
# decrypt
$ 7za e

# encrypt using tar + gnugp symmetric key
$ tar czvpf - files | gpg --symmetric --cipher-algo aes256 -o secure.tar.gz.gpg
# decrypt
$ gpg -d secure.tar.gz.gpg | tar xzvf - 

from How to create an encrypted zip file on Linux

How to encrypt files, directories and partitions in Linux (using eCryptFS and Cryptsetup)

  • ecryptfs/ECryptfs@wiki/ecryptfs@man is a filesystem-level encryption, kernel-native stacked cryptographic filesystem for Linux (not FUSE-based). Only certain files or directories are encrypted selectively. EncFS is a filesystem in user-space/FUSE.
# install
$ sudo apt-get install ecryptfs-utils | yum install ecryptfs-utils | sudo pacman -S ecryptfs-utils
$ sudo modprobe ecryptfs

# creates encrypted ~/.Private and decrypted ~/Private; PAM-module will at login automatically decrypted ~/.Private into ~/Private, and at logout unmounted ~/Private and encrypted ~/Private back into the ~/.Private
$ ecryptfs-setup-private

# mount/encrypt /srv w/ layover where lower directory is same as mount-point
$ mount -t ecryptfs /srv /srv

# unmount to hide data
$ unmount /srv

# automatically mounting
$ cat /mnt/usb/passwd_file.txt
# ecryptfs_sig must be same as /root/.ecryptfs/sig-cache.txt
$ cat /root/.ecryptfsrc
$ cat /etc/fstab
/dev/sdb1       /mnt/usb        ext3     ro       0 0
/srv            /srv            ecryptfs defaults 0 0

From How to encrypt files and directories with eCryptFS on Linux and How To Encrypt Directories/Partitions With eCryptfs On Debian Squeeze

  • DMCrypt+LUKS is full-disk encryption solutions which means that the entire disk is encrypted. CipherShed is an TrueCrypt-fork opensource alternative.
# install
$ sudo apt-get install cryptsetup | sudo yum install cryptsetup-luks

# encrypt /dev/xvdc; asked for passphrase
$ cryptsetup -y -v luksFormat /dev/xvdc
# initialize volume
$ cryptsetup luksOpen /dev/xvdc backup2
$ ls -l /dev/mapper/backup2
$ cryptsetup -v status backup2

# zero-out, create filesystem and mount LUKS partition
$ pv -tpreb /dev/zero | dd of=/dev/mapper/backup2 bs=128M
$ mkfs.ext4 /dev/mapper/backup2
$ mkdir /backup2 ; mount /dev/mapper/backup2 /backup2

# unmount and secure data
$ umount /backup2
$ cryptsetup luksClose backup2

# remount encrypted partition
$ cryptsetup luksOpen /dev/xvdc backup2
$ mount /dev/mapper/backup2 /backup2

# change LUKS passphrase
$ cryptsetup luksDump /dev/xvdc
$ cryptsetup luksAddKey /dev/xvdc
$ cryptsetup luksRemoveKey /dev/xvdc

From Linux Hard Disk Encryption With DMCrypt+LUKS

How to set immutable/unchangeable files in Linux (using chattr)

  • Immutable flag: no renaming, no symbolic link creation, no execution, no writable, only superuser can unset the attribute
$ chattr +i file
$ lsattr file
----i--------e- file
$ > file
-bash: file: Permission denied

# same but for directories, recursive
$ chattr -R +i dir
rm -rf dir/
rm: cannot remove 'dir/': Operation not permitted
  • Append flag: can only be open in append mode for writing.
$ chattr +a anothefile
$ > anothefile
-bash: anothefile: Operation not permitted
$ >> anothefile

from 5 ‘chattr’ Commands to Make Important Files IMMUTABLE (Unchangeable) in Linux

How to use two factor Google authenticator (TOTP) in SSH and GDM logins

Google’s two factor adds a time-based one time token/password algorithm TOTP – Time-base One-Time Password OTP to the regular username+password authentication.

  • Client-side apps: install Android or any of the other apps.

  • Server-side install

# using pre-compiled binaries from repos
$ apt-get install libpam-google-authenticator
$ yum install google-authenticator (needs EPEL)
# alternatively, to compile see

# generate authentication key, answer yes
$ google-authenticator
# you will see a secret key and it's QR code, enter enther on your client-side app

# enable google authenticator on sshd
$ cat /etc/pam.d/sshd
auth required
$ cat /etc/ssh/sshd_config
ChallengeResponseAuthentication yes
$ service ssh restart | systemctl restart sshd

# enable google authenticator on gdm
$ cat /etc/pam.d/gdm-password
auth required

from How to set up two-factor authentication for SSH login on Linux and Secure Your Linux Desktop and SSH Login Using Two Factor Google Authenticator.

freeotp is a two-factor authentication client using one-time password protocols, from Red Hat. Supports Android and iOS. Implements ​HOTP and ​TOTP.

Since any standards-compliant HOTP or TOTP server should work with FreeOTP, there is no absolute need for the project to produce its own server-side code. See Using OTP Tokens and 2FA with FreeIPA 4.0.

How to monitor file access on Linux using auditd


# install
$ sudo apt-get install install auditd | yum install auditd
$ chkconfig auditd on | systemctl enable auditd.service ; systemctl start auditd.service

# watch/audit a /etc/passwd file for war=write+append+read and w/ filterkey=password-file
$ auditctl -w /etc/passwd -p war -k password-file
# audit /etc/shadow for read+write+execute+append w/ filterkey=shadow-file
$ auditctl -w /etc/shadow -k shadow-file -p rwxa
# suppress auditing for mount syscall exits
$ auditctl -a exit,never -S mount
# audit executes to /tmp
$ auditctl -w /tmp -p e -k webserver-watch-tmp
# audit all syscalls by pid 1005
$ auditctl -a entry,always -S all -F pid=1005

# log is in /var/log/audit/audit.log but can use ausearch instead, see

# find out who changed or accessed a file /etc/passwd
$ ausearch -f /etc/passwd
type=PATH msg=audit(03/16/2007 14:52:59.985:55) : name=/etc/passwd flags=follow,open inode=23087346 dev=08:02 mode=file,644 ouid=root ogid=root rdev=00:00
type=CWD msg=audit(03/16/2007 14:52:59.985:55) :  cwd=/webroot/home/lighttpd
type=FS_INODE msg=audit(03/16/2007 14:52:59.985:55) : inode=23087346 inode_uid=root inode_gid=root inode_dev=08:02 inode_rdev=00:00
type=FS_WATCH msg=audit(03/16/2007 14:52:59.985:55) : watch_inode=23087346 watch=passwd filterkey=password-file perm=read,write,append perm_mask=read
type=SYSCALL msg=audit(03/16/2007 14:52:59.985:55) : arch=x86_64 syscall=open success=yes exit=3 a0=7fbffffcb4 a1=0 a2=2 a3=6171d0 items=1 pid=12551 auid=unknown(4294967295) uid=lighttpd gid=lighttpd euid=lighttpd suid=lighttpd fsuid=lighttpd egid=lighttpd sgid=lighttpd fsgid=lighttpd comm=grep exe=/bin/grep

# same but by date and filterkey and using command rm
$ ausearch -ts today -k password-file -x rm

# list active rules
$ auditctl -l
(using audit rules in file)
$ cat /etc/audit/audit.rules
# first rule - delete all, and increase buffer
-b 1024
# monitor unlink/rmdir/open syscalls
-a exit,always -S unlink -S rmdir -S open
# monitor write+  and change in file properties (read/write/execute) of the following files.
-w /etc/group -p wa
-w /etc/passwd -p wa
-w /etc/shadow -p wa
-w /etc/sudoers -p wa
# lock the audit configuration to prevent any modification of this file.
-e 2
$ service auditd restart

# non-recursive directory audit
# watch is really a syscall rule in disguise
$ auditctl -w /home/raven/public_html -p war -k raven-pubhtmlwatch
-a exit,always -F dir=/home/raven/public_html -F perm=war -F key=raven-pubhtmlwatch
# use this instead
-a exit,always -F path=/home/raven/public_html -F perm=war -F key=raven-pubhtmlwatch

# daily rotate log
$ service auditd rotate

from Howto monitor file access on Linux using auditd and Linux audit files to see who made changes to a file