Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

ssh-copy-id for automated pubkey append

// it's simple to add one key but this helps when i'm on a machine w/ multiple authorized hosts
// use like `ssh-copy-id ww1.example.com` -- make sure you have `ssh-agent` running and have added keys w/ `ssh-add` (use `ssh-add -L` to check)
// got this from the OpenSSH in Ubuntu, don't have it on mac afaik?

#!/bin/sh

# Shell script to install your public key on a remote machine
# Takes the remote machine name as an argument.
# Obviously, the remote machine must accept password authentication,
# or one of the other keys in your ssh-agent, for this to work.

ID_FILE="${HOME}/.ssh/id_rsa.pub"

if [ "-i" = "$1" ]; then
  shift
  # check if we have 2 parameters left, if so the first is the new ID file
  if [ -n "$2" ]; then
    if expr "$1" : ".*\.pub" >/dev/null; then
      ID_FILE="$1"
    else
      ID_FILE="$1.pub"
    fi
    shift         # and this should leave $1 as the target name
  fi
else
  if [ x$SSH_AUTH_SOCK != x ] && ssh-add -L >/dev/null 2>&1; then
    GET_ID="$GET_ID ssh-add -L"
  fi
fi

if [ -z "`eval $GET_ID`" ] && [ -r "${ID_FILE}" ] ; then
  GET_ID="cat ${ID_FILE}"
fi

if [ -z "`eval $GET_ID`" ]; then
  echo "$0: ERROR: No identities found" >&2
  exit 1
fi

if [ "$#" -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
  echo "Usage: $0 [-i [identity_file]] [user@]machine" >&2
  exit 1
fi

{ eval "$GET_ID" ; } | ssh $1 "umask 077; test -d .ssh || mkdir .ssh ; cat >> .ssh/authorized_keys" || exit 1

cat <<EOF
Now try logging into the machine, with "ssh '$1'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

EOF

ssh remote systems

// This little gem enables me to execute commands on a group of systems
// just run this script and put whatever commands you want after it.. eg
// script.sh uname -a
// and it will execute 'uname -a' on all the listed hosts. make sure you setup
// ssh keys so you don't have to type in a bunch of passwords.

#!/bin/bash
HOSTLIST="web2 web3 web4 vm1 dev"
USER="mylogin"

for H in $HOSTLIST; do
        echo -n "$H: " && ssh $USER@$H $*
done  

Local SOCKS Proxy for Safari

Surfing the web with Safari (3.0.4) on Mac OS X 10.4 can be made a bit more private & secure by setting up a local SOCKS Proxy on an admin user account.
Use the following BASH command-line instructions at your own risk!

I. Setting up a local SOCKS proxy for Safari on a single admin user account


# first enable remote login on your admin user account: System Preferences > Sharing > Services > Remote Login

# test if remote login is enabled
sudo launchctl list | grep com.openssh.sshd                               # com.openssh.sshd
defaults read /System/Library/LaunchDaemons/ssh
netstat -an | awk '/\*\.22[[:space:]]+.*LISTEN$/ {print}'                 # tcp4 ... *.22 ... LISTEN
service --test-if-available ssh; echo $?                                  # 0
service --test-if-configured-on ssh; echo $?                              # 0

# test if sshd daemon supports tcp_wrappers
# cf. http://www.la-samhna.de/library/brutessh.html#5
otool -L /usr/sbin/sshd | grep libwrap                                      

# then make sure you are connected to the internet
ping -c 10 checkip.dyndns.org
curl -L -s --max-time 10 http://checkip.dyndns.org | grep -Eo -m 1 '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}'   


# then set up the local SOCKS Proxy
# cf. http://macapper.com/2007/05/22/advanced-os-x-secure-tunneling-via-ssh

#ssh -q -D 8080 -f -C -N -x $(whoami)@$(ipconfig getifaddr $(route -n get default | awk '/interface:/ { print $2 }') 2>/dev/null)
#ssh -v -D 8080 -f -C -N -x $(whoami)@$(ipconfig getifaddr $(route -n get default | awk '/interface:/ { print $2 }') 2>/dev/null) 

ssh -q -D 8080 -f -C -N -x $(whoami)@127.0.0.1     # cf. AllowUsers $(whoami)@127.0.0.1 below

# ... enter your user account login password


# SSH Without a Password
# http://www.csua.berkeley.edu/~ranga/notes/ssh_nopass.html
# http://homepage.mac.com/kelleherk/iblog/C1901548470/E20061128145420/index.html

# RSA
mkdir -p $HOME/.ssh
chmod -R 0700 $HOME/.ssh
ssh-keygen -t rsa -f $HOME/.ssh/id_rsa -P ''
cp -p $HOME/.ssh/id_rsa.pub $HOME/.ssh/authorized_keys2
chmod 0600 $HOME/.ssh/authorized_keys2
srm -v $HOME/.ssh/id_rsa.pub
#ls -ld $HOME/.ssh
#ls -l $HOME/.ssh/authorized_keys2

# encrypt the known_hosts file
ssh-keygen -H -f $HOME/.ssh/known_hosts 
srm -v $HOME/.ssh/known_hosts.old
chmod 0600 $HOME/.ssh/known_hosts


# securing SSH
# See:
# - man sshd_config
# - sudo nano /private/etc/sshd_config
# - http://switch.richard5.net/2006/09/24/securing-your-ssh-access/ 
# - http://www.mactech.com/articles/mactech/Vol.21/21.02/Security/index.html
# - Mac OS X Security Configuration Guides at http://www.apple.com/server/documentation/

sudo sh -c "
echo '
# added
Protocol 2
PermitRootLogin no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
PubkeyAuthentication yes
AuthorizedKeysFile $HOME/.ssh/authorized_keys2
#KeepAlive yes
MaxAuthTries 3
MaxStartups 3
#UseDNS no
LoginGraceTime 40
LogLevel INFO     # QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG
#AllowUsers $(whoami)      # add more users if you like: ~<TAB><TAB>  (in Terminal.app) or dscl . -list /Users
AllowUsers $(whoami)@127.0.0.1      # cf. ssh -q -D 8080 -f -C -N -x $(whoami)@127.0.0.1 above
#AllowUsers $(whoami)@$(ipconfig getifaddr $(route -n get default | awk '/interface:/ { print $2 }') 2>/dev/null)   # requires internet connection
#AllowGroups sshusersgroup     # cf. dscl . -list /Groups; groups
' >> /private/etc/sshd_config
"


# then open Safari ...

open -a Safari

# ... and go to:
# Safari > Preferences ... > Advanced > Proxies: Change Settings ... 
# > Select a proxy server to configure: SOCKS Proxy > SOCKS Proxy Server: 127.0.0.1 : 8080 > Apply Now


sudo reboot       # ... or just restart: System Preferences > Sharing > Services > Remote Login

ssh -q -D 8080 -f -C -N -x $(whoami)@127.0.0.1      # should now work without password; cf. man ssh_config for configuring SSH shortcuts


# check local SOCKS Proxy setup

scutil --proxy                   # SOCKSProxy : 127.0.0.1, SOCKSEnable : 1, SOCKSPort : 8080

sudo ln -s "/Applications/Utilities/Network Utility.app/Contents/Resources/stroke" /bin/portscan
portscan localhost 8000 8100     # Open TCP Port:  8080  http-alt

lsof -i :22 -P
lsof -i :8080 -P
lsof -i TCP -P
lsof -U -P             # list UNIX domain socket files
sudo lsof -U -P
netstat -n -f inet


#-------------------------- 


# now you can, for example, test if a website can discover your real internal IP address provided your computer
# is behind a DSL router and you have a firewall running (cf. http://textsnippets.com/posts/show/1267)
# cf. http://www.auditmypc.com/internal-ip.html

# first get your internal IP address
ipconfig getifaddr $(route -n get default | awk '/interface:/ { print $2 }')

# note: to run the 'real IP' test you first have to enable Plug-ins, Java & JavaScript in Safari
# Safari > Preferences ... > Security > Enable plug-ins & Enable Java & Enable JavaScript

open -a Safari http://www.auditmypc.com/software_audit.asp
open -a Safari http://www.whatsmyip.org/more/    # Internal (LAN) IP: 127.0.0.1



II. Setting up a local SOCKS proxy for Safari using two different user accounts on the same computer


# The following BASH command-line instructions assume you have a regular user account 
# and an admin user account on the same computer!

# First, log in to the regular user account 
regular_user_name="$(whoami)"
regular_user_path="$HOME"
echo $regular_user_name $regular_user_path    

# note down the output from the echo command
# log out from the regular user account

# Then log in to the admin account for the following instructions!

# first make sure you are connected to the internet
ping -c 10 checkip.dyndns.org
curl -L -s --max-time 10 http://checkip.dyndns.org | grep -Eo -m 1 '([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3}'   

# get internal IP address & set regular user account information
regular_user_name="...insert information from regular user account above..."
regular_user_path="...insert information from regular user account above..."
internal_IP_address=$(ipconfig getifaddr $(route -n get default | awk '/interface:/ { print $2 }'))
echo $internal_IP_address $regular_user_name $regular_user_path

# enable remote login: System Preferences > Sharing > Services > Remote Login

# test if remote login is enabled
service --test-if-available ssh; echo $?               # 0
service --test-if-configured-on ssh; echo $?           # 0


# SSH Without a Password

# admin user account
# RSA
mkdir -p $HOME/.ssh
chmod -R 0700 $HOME/.ssh
ssh-keygen -t rsa -f $HOME/.ssh/id_rsa -P ''
cp -p $HOME/.ssh/id_rsa.pub $HOME/.ssh/authorized_keys2
chmod 0600 $HOME/.ssh/authorized_keys2
srm -v $HOME/.ssh/id_rsa.pub
ls -ld $HOME/.ssh
ls -l $HOME/.ssh

# regular user account
sudo mkdir -p $regular_user_path/.ssh
sudo chmod -R 0700 $regular_user_path/.ssh
sudo cp $HOME/.ssh/authorized_keys2 $regular_user_path/.ssh/authorized_keys2
#scp ~/.ssh/authorized_keys2 $regular_user_name@$internal_IP_address:~/.ssh/authorized_keys2
sudo chown -R $regular_user_name:$regular_user_name $regular_user_path/.ssh
sudo chmod 0600 $regular_user_path/.ssh/authorized_keys2
sudo ls -l $regular_user_path/.ssh
sudo ls -ld $regular_user_path/.ssh

# delete all files in ~/.ssh on both user accounts
#sudo find $regular_user_path/.ssh -type f -exec srm -fv "{}" \;
#find $HOME/.ssh -type f -exec srm -fv "{}" \;


# log in to regular user account via SSH
# enter admin account login password if prompted
ssh -i $HOME/.ssh/id_rsa $regular_user_name@$internal_IP_address     
exit

# encrypt the known_hosts file
ssh-keygen -H -f $HOME/.ssh/known_hosts       
srm -v $HOME/.ssh/known_hosts.old
chmod 0600 $HOME/.ssh/known_hosts

ssh -i $HOME/.ssh/id_rsa $regular_user_name@$internal_IP_address    # test
ls 
exit


# securing SSH
# man sshd_config
# sudo nano /private/etc/sshd_config

sudo sh -c "
echo '
# added
Protocol 2
PermitRootLogin no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
PubkeyAuthentication yes
#AuthorizedKeysFile $regular_user_path/.ssh/authorized_keys2
#KeepAlive yes
MaxAuthTries 3
MaxStartups 3
#UseDNS no
#PermitUserEnvironment yes     # requires ~/.ssh/environment file; see man ssh and man sshd_config
LoginGraceTime 40
LogLevel INFO     # QUIET, FATAL, ERROR, INFO, VERBOSE, DEBUG
#AllowUsers $(whoami) $regular_user_name
AllowUsers $(whoami)@$internal_IP_address $regular_user_name@$internal_IP_address
' >> /private/etc/sshd_config
"


# set up the local SOCKS Proxy
# enter admin account login password if prompted
ssh -q -D 8080 -f -C -N -x $regular_user_name@$internal_IP_address    

open -a Safari

# Safari > Preferences ... > Advanced > Proxies: Change Settings ... 
# > Select a proxy server to configure: SOCKS Proxy > SOCKS Proxy Server: 127.0.0.1 : 8080 > Apply Now

# restart sshd: System Preferences > Sharing > Services > Remote Login

# check local SOCKS Proxy setup
scutil --proxy                    # SOCKSProxy : 127.0.0.1, SOCKSEnable : 1, SOCKSPort : 8080
portscan localhost 8000 8100      # Open TCP Port:  8080  http-alt

ssh -p 22 $regular_user_name@$internal_IP_address ls
ssh -l $regular_user_name $internal_IP_address 'echo hello world; whoami; hostname; logname'

# test privacy of internal IP address
open -a Safari http://www.auditmypc.com/software_audit.asp
open -a Safari http://www.whatsmyip.org/more/ # Internal (LAN) IP: 127.0.0.1


Further information on SSH & Mac OS X:

- Getting started with SSH
- Remote Login With SSH
- SSH Without A Password
- Exit Your SSH Session Without Killing Your Job
- SSH on Mac OS X
- SSH
- ssh tunnelling
- ssh X forwarding debugging
- Tutorial: SSH To Alternate Ports and Enabling Multiple SSH Daemons
- Route All Your Internet Traffic Through a Proxy
- SSH Notes
- SSH Host Key Protection
- Setup the SSH server to use keys for authentication
- Auto-closing SSH tunnels
- SSH Tunnelling (Port Forwarding)
- Defending against brute force ssh attacks
- SSH + Screen = Easy Administration
- SSH SOCKS Proxy From Behind a Gateway
- nylon - flexible Unix proxy server with mirror mode; sudo port install nylon
- tsocks - transparent SOCKS proxying library; sudo port install tsocks
- Create a SOCKS proxy with SSH in Leopard

SSH dynamic forward (Linux)

This command will create a dynamic forward from an SSH client to an SSH server. Basically what this does is allow you to use any local port (8080 in this example) as a proxy for any TCP application.

Feedback, suggestions and comments are all welcome!

# In the following example, we create a dynamic
# forward from port 8080 (client) to port 22 (host.net).

ssh -D 8080 username@host.net

# Now, we'll check out netstat to see what we
# have done.

netstat

# Active Internet connections (w/o servers)
# ...
# tcp 0 0 host.net:ssh client.com:60565 ESTABLISHED
# ...
#
# Awesome! Now we've got the connection. I'll add
# another post telling how to use this port as a
# socks proxy for any TCP application :)

Access subversion repository on Textdrive via ssh

I found it really difficult to get svn via svn+ssh geting to work because I made two erorrs:
I used not my main user. However, only the main user can get shell access necessary for svn via ssh.
I used a wrong path.

In order to get things going set up subversion following the usual directives in the knowledge base and then access your repository like this:
(OS X terminal here)
% svn co svn+ssh://mainuser@yourdomain.tld/home/mainuser/svn/repositoryname/

This should do the trick.

Remember not to use ssh and http(s) at the same time. It's either or.

linux ubuntu ssh login

To replace the normal text password login with ssh public/private key pair....

Generate a pair at home (creates RSA based key pair)
ssh-keygen -t rsa

Enter in a passphrase when it asks.

upload the .pub key to the server
sftp root@<server address>
lcd /home/<your login>/.ssh
put id_rsa.pub


Login to the server normally as root.
Goto the .ssh directory
Append the public key to the authorized_keys
ssh root@<server address>
cd .ssh
cat id_rsa.pub >> authorized_keys


Then check that /etc/ssh/sshd_config has...
RSAAuthentication yes
PubkeyAuthentication yes

... in it

Restart the ssh server
/etc/init.d/ssh reload


Logout.
Try logging in again as root and you should be prompted for passphrase to your ssh key.

Use
ssh -v root@<server address>

to diagnose problems

ssh tunnel with local port forwarding (MySQL)

// ssh tunnel remote mysql to a local port (in this case, 3307)

ssh -2 -f -C -N user@servername.com -L 3307/127.0.0.1/3306

DAAP tunneling / remote iTunes Music Share

// requirements
// * server running mt-daapd/Firefly (alternative server for iTunes music sharing)
// * tunneleling & port-forwading via ssh
// * local bonjour/zeroconf broadcasting using Apple's mDNSProxyResponder
// based on info from <http://wiki.mt-daapd.org/wiki/SSH_Tunnel>
// for more: see Music Blackhole <http://tramchase.com/projects/blackhole>
// Jamie Wilkinson <http://tramchase.com>


ssh USER@SERVERNAME -N -f -L 3690:SERVERNAME:3689 && mDNSProxyResponderPosix 127.0.0.1 musicserver "My remote music server" _daap._tcp. 3689 &

ssh tunnel for mysql

// description of your code here

No forking in background and verbose

ssh -2 -v -c blowfish -C -N user@servername.textdrive.com -L 3370/127.0.0.1/3306



Forking in background

ssh -2 -f -c blowfish -C -N user@servername.textdrive.com -L 3370/127.0.0.1/3306

SSH tunnel for mySQL

Connect to remote mysql server via ssh tunnel:

ssh -f -L 3306:127.0.0.1:3306 username@servername.com sleep 120


Should auto-disconnect when it’s no longer in use.