September 10, 2024

SSH

Login to ssh server without password using keys

If you manage Linux servers all the time, it’s best to use rsa keys to login without your password using a stored key on both ends. To do this, you have to generate a key on your LAPTOP, then transfer it to a folder you create in your home directory on the server. First create that directory:

ssh youruser@ser.ver.ip
password:
mkdir -P .ssh/authorized_keys
exit

Now put a copy of your key there, so from your LAPTOP do:

cat ~/.ssh/id_rsa.pub | ssh youruser@ser.ver.i.p 'cat - >> ~/.ssh/authorized_keys'
password:

If it worked, you should now be able to login to your server like normal, but it won’t ask you for a password anymore 🙂
Now you have to tell SELinux about it so it will allow it:

yum install policycoreutils-python
semanage port -a -t ssh_port_t -p tcp 5150

If this worked you should see sshd listening on a new port like:

semanage port -l | grep ssh
  ssh_port_t                     tcp      1234, 22

If you don’t, stop here and fix it or your ssh won’t work remotely and you may have few clues.

now tell IPTables to allow your new port by changing the –dport value (default 22) to your new port, 1234 in this example.

NOTE: Know what you’re doing with IPTables, or you can uncategorically hoze your machine and LOCK YOURSELF OUT in nasty ways, don’t make mistakes in the below command, or you’ll screw yourself. For example, don’t type port 1234 if your REAL port is 5678, and stuff like that. Beware of IPTables mistakes, everyone makes them and everyone locks themself out at least once 🙂

vi /etc/sysconfig/iptables
  -A INPUT -m state --state NEW -m tcp -p tcp --dport 1234 -j ACCEPT
iptables-restore iptables

Now BEFORE you logout, try logging in from your remote machine, it should work fine. If it works, it will also now survive a reboot with your IPTables firewall rule intact.

remote tunneling over ssh

Let’s say you have a remote server that’s only listening on localhost port 80 (for web) on that remote server, but you want to view it across an ssh tunnel on your laptop. On your SERVER do:

vi /etc/ssh/sshd_config
  GatewayPorts yes

Then, on your LAPTOP do:

ssh -L 1234:localhost:80 yourusername@ser.ver.i.p

Now go to a browser on your LAPTOP and visit http://127.0.0.1:1234 and you should see the website that’s hosted on the server.