Get ssh key fingerprint for comparing safely

SSh keys can be long and unwieldy to compare. Many platforms digest them to md5 formats for non disclosure such as github.

This command will give you the digested fingerprint of an ssh key in linux / Mac.

ssh-keygen -lf .ssh/id_rsa.pub -E md5

nJoy 😉

Automatically passing ssh password in scripts especially to ESX where passwordless ssh is hard

First you need to install sshpass.

  • Ubuntu/Debian: apt-get install sshpass
  • Fedora/CentOS: yum install sshpass
  • Arch: pacman -S sshpass

Example:

sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM

Custom port example:

sshpass -p "YOUR_PASSWORD" ssh -o StrictHostKeyChecking=no YOUR_USERNAME@SOME_SITE.COM:2400

from : https://stackoverflow.com/questions/12202587/automatically-enter-ssh-password-with-script

 

This works better for me though for sshfs:

echo $mypassword | sshfs -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no user@host mountpoint -o workaround=rename -o password_stdin 

 

 

nJoy 😉

 

Script to verify that a path is synchronized across multiple machines via ssh

This is a script I wrote for work to look through a number of remote servers via ssh (shared keys or include a .pem (id_rsa) file to compare a paths and all it’s subfolders.

The result is a report of which files are out of synch and if duplicates found they are listed separately.

#!/bin/bash
## Parameters  sync_check [-i id.pem] [-u <user for ssh>] -p <path_to_diff>  <target-system-IP1> <target-system-IP2> ...

# David Saliba [dx@sudoall.com]

RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color


PEMFILE=""
SSH_USER="root"

function usage {
	echo 
	echo -e "\t$0 usage as follows :"
	echo -e "\t$0 [-i <pem_file>] [-u <ssh_user_name>] -p <path_to_diff> <ref-system-IPADDR1> <target-system-IP1> <target-system-IP2>..."
	echo 
}


[ $# -le 2 ] && echo && echo -e "${RED}Incorrect number of parameters ${NC}" && usage && exit 128


while getopts "i:u:p:" opt; do
echo $opt $OPTARG
  case $opt in
  	i ) PEMFILE=$OPTARG; shift $((OPTIND-1)); OPTIND=1 ; 
          if [[ -f "$PEMFILE" ]]; then 
              PEMFILE="-i ""$PEMFILE" 
          else
          	  echo "Pemfile : $PEMFILE not found. Quitting .. " 
          	  exit 1  
          fi
          ;;
	u ) SSH_USER=$OPTARG ; shift $((OPTIND-1)); OPTIND=1 ;;
	p ) PATH_TO_CHECK=$OPTARG ; shift $((OPTIND-1)); OPTIND=1 ;;
    * ) usage
       exit 128
  esac
done



extfile="_target.md5.sync_check"

		echo; echo

rm -f /tmp/*.sync_check
for i in $* ; do
	ipcalc -cs $i
	if [ $? == 0 ] ; then
		echo -n "Retrieving Signature List from ..  :[$i] : " 
		ssh $PEMFILE $SSH_USER@$i "hostname"

		COMMAND="ssh $PEMFILE $SSH_USER@$i \"find  $PATH_TO_CHECK -type f -exec md5sum {} \\; | sed -e 's/^/$i\t/'| sort -k 2 \""
		#echo "Running : $COMMAND  /tmp/$i""_target.md5.sync_check"
		bash -c "$COMMAND" > /tmp/$i$extfile
		
	else
		echo "Parameter $i not a valid IP skipping .."
	fi
done

echo ;echo; echo "Comparing data ... "; echo

 OLDIFS=$IFS; 
 IFS=$'\n'; 

 for i in `cat /tmp/*.sync_check  | sort -k3 | uniq -f 1 -c | sort | egrep -v "^[\ \t]*$#" | sort -k4 ` ;do 
 	
 	NUMBER_OF_HITS=`echo "$i" | awk '{print ($1)}'`

 	echo $i

 	if [ $NUMBER_OF_HITS -gt 1 ] ; then
 		
 		MD5Onward=`echo "$i" | awk '{print substr($0, index($0,$3))}'`
		echo -e -n "${YELLOW}"	
			grep -h "$MD5Onward" /tmp/*.sync_check  | awk '{print "\t\t",NR, $0}'
		echo -e -n "${NC}"	


 	fi


 done ;

 IFS=$OLDIFS


echo
echo




link to file here: http://jist.sudoall.com/sync_check/sync_check.sh

nJoy 😉

Run a local script on remote machine with parameters

So you have a script on the local machine and you want to run it remotely and pass arguments to it :


ssh user@remote 'cat | bash /dev/stdin param1 param2 .. paramN' < /usr/scripts/localscript.sh

😉 nJoy

 

Disabling IPv6, breaks SSH X11 Forwarding in Linux CENTOS and UBUNTU all versions

This was a weird one. It took me ages to discover why SSH X11 died at some point after tuning a box.

It so happens that disabling IPv6 ( not used on my networks) is assumed in SSH at some point and if you disable it (which many people say is a way to avoid systems using IPv6 to other boxes and ignore IPv4 provisions like firewall settings, routes etc..)

So re-enable the IPv6 in /etc/sysctl.conf or /etc/sysconfig/network or other networking script locations, if you need this functionality.

If i find any other counter indication I’ll drop a note and link.

nJoy 😉

Using Puttygen to create a ssh key and passwordless login with putty to Centos.

The ssh password-less login works in a  simple way. Though sometime people find it confusing.

The basics:

>  Client side has a private key pointed to by

>  Server side has the public key of the client.

On your client box create a public and private key set using (for putty) puttygen. (In linux all you need to use is ssh-keygen.

Please look at the page here : https://www.puttygen.com

On the server :

If not already there create a folder /<user_home>/.ssh  e.g. /root/.ssh and in that folder create a file named authorized_keys. This file will store all the public keys that a given user with matching private key, can use. Easy way echo “<paste here>” >  ~/.ssh/authorized_keys

mkdir ~/.ssh

echo “ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIBz7Pml97wSzFMSr1W84rA0Mm8MY8I1jKdAmMcF4sw5GilormHJQRYI8siT1XPaLJFAO20ziZg9YrJFp+roKC34gpe1myFWUz944iucrLIQznZwPDJbMKxQXwzj1LUPmt7eXPzwM1ztvcG8HOoZlTt2B6hOAVWAHxlZNzPq/9y1Fw== rsa-key-20131124” > ~/.ssh/authorized_keys

chmod 600 ~/.ssh/authorized_keys

chmod 700 /~/.ssh

Once this is done you can add the private key to the client under ssh -> Auth -> private key.

Select back the session and save it as usual in Putty.

If you get the error “Server refused our key” it probably means you still have SElinux enabled.

To fix this:

restorecon -R -v /root/.ssh

 

That should work.

nJoy 😉

Recording a session for a user when he / she logs in ssh

 

To start recording each session add this to the users .profile file

DATE=$(date +”%Y%m%d%H%M”)
mkdir /log/$DATE
script -t 2>/log/$DATE/bashlogs.timing -aqf /log/$DATE/bashlogs.script

 

to playback go to

/log/<timestamp>

and run

scriptreplay  bashlogs.timing bashlogs.script 3

where the 3 is the speed up factor.

nJoy;

 

Using Stunnel to Encrypt Unsecure Connections

So you’re a fully signed up ‘tin foil hatter’ and you have an old app that communicates over the internet but doesn’t use SSL?

Not to worry, there is a solution for you and its called stunnel.

Stunnel is available for both Linux and Windows, and simply put creates an SSL tunnel from one machine or server to another.

So why use stunnel? Well stunnel…

… provides an extra layer of security to an internet based application.
… secures data previously transmitted in plain text.
… protects your exploitable services by hiding them behind stunnel.

So what else can it be used for? Well…

… you could use it to fool certain websites into thinking you are in a different location.
… it can be used as a simple ‘bouncer’ for pretty much anything!

 

In my example I wanted to provide a little security to my simple ‘Munin’ monitoring solution (I’ll write something about that at a later date). Munin checks the servers status by ‘telnet’ to the munin-node running on the target server/pc, so if you are monitoring a remote server you have data about your system flying about everywhere! Also it means that there is a naked telnet port open on your server, which although you can lock it down by only allowing connections from a specific IP etc. doesn’t work to well if your on a dynamic IP and still leaves unencrypted data flying about the ether. Ok so in this case security isn’t that vital and none of the data is particularly sensitive. But if it uses TCP and you want to provide an extra layer of protection stunnel can do it.

As an added bonus stunnel is extremely easy to setup.

The rest of this post is based around a CentOS installation. But its pretty much the same on Debian/Ubuntu… just replace ‘yum’ with ‘apt-get’. The Windows install is even easier and the configs are in the same format as the Linux confs so you can easily adapt the instructions bellow!

Firstly lets install stunnel on the client machine (In the case of my example this is actually my ‘server’ machine in Munin, but for example if you wanted to secure SMTP communications this would be the machine sending the emails).

Although in this post I’ve used Munin as an example it really is easy to modify these instructions to fit any service. Simply change the ports!

Install using Yum:

yum install stunnel

(Now I cant remember exactly but I think stunnel is not on the default CentOS repos… so you can add the RPMforge repos like I tend to do: http://www.rpmrepo.org/RPMforge/Using)

Install from source:

wget http://mirror.hudecof.net/stunnel/stunnel-4.22.tar.gz
tar zxf stunnel-4.22.tar.gz
cd stunnel-4.22
./configure
make
make install

Configuration:

On CentOS the default location for the stunnel.conf is /etc/stunnel/ so open this file in your editor of choice:

vi /etc/stunnel/stunnel.conf

Lets set the following options:

#chroot = /var/run/stunnel
setuid = nobody
setgid = nobody
pid = /stunnel.pid
client = yes
debug=7

And create a service:

[tomcat]
accept = 9090
connect = 8080

Now as you can see here I’ve set the listener to 127.0.0.1 but you could set this to all interfaces or a specific one by omitting or replacing the 127.0.0.1: The ‘connect’ setting is the servers hostname or IP address and the port that the stunnel ‘server’ is listening on. Another example of using stunnel could be to direct all web requests onto another server using a secure layer:

[www]
accept = 80
connect = myserver.hotname.com:8080

You would then setup the ‘server’ stunnel to listen on 8080 and connect to the local (or even a remote!) web server.

Ok thats it for the client side for now. Lets look at the server:

Install stunnel as per the installation instructions above.

On CentOS the default location for the stunnel.conf is /etc/stunnel/ so open this file in your editor of choice:

vi /etc/stunnel/stunnel.conf

Set the following options:

cert = /etc/stunnel/stunnel.pem
chroot = /var/run/stunnel
setuid = nobody
setgid = nobody
pid = /stunnel.pid
debug=7

And create a service:

[tomcat]
accept = 9090
connect = 8080

[www]
accept = 8080
connect = myserver.hostname.com:80

With a bit of messing around with DNS or hosts files we could use stunnel to bounce our connection to any server for example www.bbc.co.uk! But that’s not really what we’re covering in this article and I’m guessing if you have your reasons for doing something like that you can figure it out on your own.

OK we’re nearly ready to start stunnel. But the observant amongst you will have noticed that stunnel.pem certificate file that we set in the server options doesn’t exist! So lets create one now!

openssl req -new -x509 -days 3650 -nodes -out /etc/stunnel/stunnel.pem -keyout /etc/stunnel/stunnel.pem

Right now lets start stunnel, on both machines simply run the following command:

/usr/sbin/stunnel /etc/stunnel/stunnel.conf

Now lets test it! If the service we’ve setup can be talked to with telnet (eg. Munin or SMTP) then we can test this very simply from the client machine:

telnet localhost:4948

You should get the following back:

Trying 127.0.0.1…
Connected to localhost (127.0.0.1).
Escape character is ‘^]’.
# munin node at mysever.hostname.com

(Now its a little confusing because ‘Connected to localhost’ is actually the response from the munin-node on the remote server!)

As you can see your telnet session has gone into stunnel locally, been transmitted from stunnel on the local machine to stunnel on the server and then from stunnel into the Munin node on the server! Magic!

Stunnel startup script:

Now you can either start stunnel every time your machine starts up manually, add it to the crontab (if you try and start stunnel again and its already running the second instance will just close, but it leaves a mess in your /var/log/secure so don’t do it to often) or use a simple startup script like this one I ( used ) to use:

#!/bin/bash
    if [ -f /var/run/stunnel/stunnel.pid ]; then
        ps aux |grep -v grep |grep $pid |grep stunnel > /dev/null
        if [ $? = 0 ]; then
            echo “Server is already running !!”
        else
            echo “Pid file exists but process not found … trying to start stunnel”
            /usr/sbin/stunnel /etc/stunnel/stunnel.conf
        fi
        rm -f /tmp/stunnelrun > /dev/null
    else
        echo “Pid file not found. Starting stunnel.”
        /usr/sbin/stunnel  /etc/stunnel/stunnel.conf
    fi

This is a very simple script I knocked up in a few mins. I later replaced it with an init script that I wrote when I had a little more time. But I’m going to post that as another article as I have a bit more to say about that (including some adaptation to make general init scripts for various programs)

To use the above script to start stunnel do the following:

cd /usr/local/sbin
vi stunnel-run

Paste in the above code.
Save and exit.

chmod +x stunnel-run

Test by doing the following:

./stunnel-run

Now add it to the crontab:

crontab -e

Insert the following line:

*/15 * * * * /usr/local/sbin/stunnel-run 2>&1 > /dev/null

Now your system will run the stunnel-run script every 15mins, checking if stunnel is running and starting stunnel if it is not running. You could simply start stunnel every 15mins as it will exit if it finds it can not use the ports its been assigned, but that leaves a mess in your secure log.

Some of you I’m sure are thinking ‘why use stunnel you could use a vpn or xyz’. Well yes, there are many ways of skinning this cat, stunnel is a simple and versatile one but not the ultimate jack of all trades. Use it where you see fit!

Screen script for multi-user session or reminding you to create a screen on logon

A common problem when many people share large systems as the same user ( I know .. I know but anyways move on )  is that when you logon you might want to take over where someone else left off. Also sometimes you want to share a session with someone for supervision or just team experience.

Screen tool in linux is fantastic for this. I wrote this script to allow people to be reminded to have a screen session and if already there allow you to log on to the screen by either taking over the session or sharing it with the other user.

installation of screen is as easy as :

 

sudo yum install screen -y

or for you debbie penguins out there

 

sudo apt-get install screen -y

 

The script goes like this :

## Screen profile for user session sharing
## by David Saliba (copyleft) 2013 

#!/bin/bash

function greet {
 clear
 cat /etc/motd
 echo "Hostname:" `hostname `
 echo
 ifconfig | grep inet | egrep -v "inet6|localhost|127\.0\.0\.1"
 echo
 #  df -h /
 echo "Welcome ! #  No screen session  #"   
}

function newscreen {

 echo "Would you like to create a new session  ? (Y/n)"

  read -t 10 b
  if [[ $b == "N" || $b == "n" ]]; then
 { # Dummy if no just continue
  echo 
 }
 else
 {
  
  echo " Remember to use <CTRL> + A and then d to leave the screen session active or just disconnect "
  echo -n "Creating "
         sleep 1; echo -n "." ;sleep 1; echo -n "."; sleep 1; echo -n "."
  exec screen -S Workarea
 }
 fi
}

if [ -z "$STY" ]; then
 firstscreen=$(screen -list | grep "(" | cut -f 2 | head -n 1)
# echo $firstscreen

 if [ ! -z "$firstscreen" ]; then
 {
         echo "Found screen ($firstscreen).Do you want to jump on it (Y), or share the session (X)? (Default Y in 10s)"
         read -t 10 a
     if [[ $a == "N" || $a == "n" ]]; then
        {
         greet
        }
     elif [[ $a == "X" || $a == "x" ]]; then
        {
         echo -n "Joining "
         sleep 1; echo -n "." ;sleep 1; echo -n ".";
         exec screen -x $firstscreen
        }
     else
        {
         echo -n "Connecting and taking over"
         sleep 1; echo -n "." ;sleep 1; echo -n ".";
         exec screen -r -d $firstscreen
        }
     fi
 }
 else
 {
   greet   str3amuK
   newscreen
 }
 fi
fi

 

Save this script under /etc/profile.d/screen.sh or some other name you will recognize.

 

Starting vnc on Display 0 ( local display ) from a remote ssh session

i.e. You wnet home need your desktop have ssh no vnc !! Here is the easy solution..

Install x11vnc.

$ DISPLAY=localhost:0 x11vnc &

connect to the display using vnc et voila !

BTW Teamviewer also USED TO WORK but no longer in ver 8 so thanks VNC for not being obsolete..

nJoy 🙂