How to securely activate SSH into your Synology DiskStation with SSH Keys and no root login

I like to have access to my private network at home, wherever I am, and for me the best choice is to have an ssh server available. I use it for privacy reasons, because i don’t want anyone to know what could be my email, what webs do i visit, etc. Like I explained while ago in Jump over private corporate proxy with Firefox (or git, or any SOCKS ready app) through a SSH tunnel.

As I’ve shutdown my own server to avoid the noise, power waste, gain some space, and to stop worrying about hardware or connection failures and I’ve recently purchased and advanced NAS (Synology DiskStation) I would to explain how to securely active ssh on it.

The Synology DiskStation supports both telnet and SSH, but you should never use telnet when dealing with passwords or when you don’t want to be spied, as it is completely insecure.
Everyone should instead use SSH as it is very secure and almost the standard option.

Synology DiskStation DS211
Synology DiskStation DS211

How to enable SSH and users to login

It’s easy to enable SSH on your DiskStation by going to Control Panel > Terminal & checking the box next to Enable SSH Service.
You can now log in with your root username & password. If you need to login with any other user, you need to enable user’s home and let them use login with a shell.
To enable your user’s home, go to Control Panel -> User -> User Home -> There enable the user home service.
To enable your user’s to login with a shell, you have to edit the file /etc/passwd. Here is an example with the common contents when you have 2 users, one with a enabled shell (/bin/sh) the other without:

How to enable SSH with SSH keys

But that’s not enough. Logging in with a username and password isn’t nearly as secure as requiring SSH keys. When you use password based authentication, anyone can try to reach the port and use bruteforce to gain login credentials.
With public keys authentication, you have a private key on your computer, a public key on the SSH server (the Synology DiskStation in this case). When someone tries to log in via SSH, the server looks at the public key and asks for the corresponding private key. No private key, no login.
NOTE: I’m assuming that you have already generated SSH keys. If you haven’t, you can easily find instructions on the Web.
The needed SSH daemon’s config file to allow access via keys differs from original in :
Edit /etc/ssh/sshd_config using vi, I’ve highlighted in a shortened example the changed options to harden SSH:

Save the file and restart the SSH daemon. The easier is to use the GUI/WEB login. Click on the Control Panel -> Terminal. Uncheck Enable SSH Service, apply, check it again, and press apply again.

Enabling your user public key in authorized_keys

Of course you have to copy to your home directory your ssh public key inside a ssh directory and file called authorized_keys. I would recommend to be careful with permissions.

Try logging in now, with a username enabled to login. You won’t be prompted for a password; instead, you’ll get a nice shell see:

To test our hardening Try logging in now, but use a username that doesn’t exist on the server. You won’t be prompted for a password; instead, you’ll see:

No key, no admittance. No passwords accepted. Excellent.

Extra point. No root login, just for localhost.

An allowed ssh root login for a hacker/juanker is like honey for a bear.
So what we will do is to enable ssh public key access just for our localhost..

Edit /etc/ssh/sshd_config using vi, I’ve highlighted in a shortened example the changed options to harden SSH:

And, next, include this Match rule at the end of file, as Match rules may affect all config options below it. Using without-password we allow root login using public key.

One more step is needed, repeat point “Enabling your user public key in authorized_keys” for root user.

Save the file and restart the SSH daemon. The easier is to use the GUI/WEB login. Click on the Control Panel -> Terminal. Uncheck Enable SSH Service, apply, check it again, and press apply again.

Extra point enable root login from a shell using su. DEPRECATED

DEPRECATED
Of course we still need to have root access to Synology, anything can happen.
If along any of the steps, or whatever, you have seen this error message while trying to use ‘su’:
‘su: must be suid to work properly

What is happening is that permissions on binary /bin/busybox are “wrong”, run this as root to fix it.

DEPRECATED

Restart ssh server from CLI

If you want to restart your ssh server from CLI, use this script. Running it in background guarantees that the command will be completed. Because when you launch it, your currrent ssh session will be lost/closed.

 


For some reason, this command is not fully restarting the server or not loading the modified config, so, a workaround in order to restart the ssh server is to restart the whole system.

Important

This adds a nice layer of security, but it also means that you’d better keep backups of your SSH keys, or you are hosed!
If you’ve fucked up and you can’t get a root shell or you need help because using vi is boring, try to look for a config file editor

Jump over private corporate proxy with Firefox (or git, or any SOCKS ready app) through a SSH tunnel

Thanks a lot to text producers. I’ve just copied it here to promote them.

Making the ssh tunnel

Option 1: ssh and direct connect (SOCKS5) : The following line will start the ssh client and connect to username@remote_machine.com. Port 8080 on localhost (127.0.0.1) will listen for requests and send them to the remote machine. The remote machine will then send the packets out as if they originated from itself. The ssh options are in the man page of ssh, but to summarize them in order: Compression, SSH2 only, Quite, Force pseudo-tty allocation, Redirect stdin from /dev/null, and Place the ssh client into “master” mode for connection sharing.

ssh -C2qTnN -D 8080 username@remote_machine.com

Option 2: ssh to squid proxy (HTTP/SSL Proxy) : The following line will also start the ssh client and connect to username@remote_machine.com. Port 8080 on localhost (127.0.0.1) on the current machine will listen for requests and ssh tunnel them to the remote machine. On the remote machine ssh will forward the packets to localhost port 2020. If squid is listening on localhost port 2020 on the remote machine then all requests sent though the ssh tunnel will then be forwarded to squid. You can use squid to block ads and speed up web access. If you need assistance with squid, check out the Calomel.org Squid “how to” page.

ssh -C2qTnN -L 8080:localhost:2020 username@remote_machine.com

Using GIT through a SOCKS proxy

user@debian-machine:~$ cat /somepath/bin/proxy-wrapper
#!/bin/bash
# on Debian systems you will need netcat-openbsd package in order this options to work
nc -xPROXYMACHINE:PORT -X5 $*
user@debian-machine:~$ export GIT_PROXY_COMMAND=”/somepath/bin/proxy-wrapper”
user@debian-machine:~$ git clone git://git.debian.org/git/debian-eeepc/eeepc-acpi-scripts.git
Initialized empty Git repository in /blableblubla/codigo/git/eeepc-acpi-scripts/.git/
remote: Counting objects: 1050, done.
remote: Compressing objects: 100% (554/554), done.
remote: Total 1050 (delta 572), reused 848 (delta 475)
Receiving objects: 100% (1050/1050), 115.39 KiB | 37 KiB/s, done.
Resolving deltas: 100% (572/572), done.

Links and references

Howto to intercommunicate processes in different(remote) machines through DBus

Introduction

In this post I’m going to try to connect two processes in different machines through DBus. The method is a little bit complex, so be patient if you try.
Also is to advert that this has been the result of 3 days of tests (reference1). So maybe this method may be improved with time and use reference2.

Tools (The actors)

  • dbus
  • gabriel
    • socat
    • libssh
  • ssh
  • your apps

Debian official packages are dbus libssh-2 socat
gabriel is not part of Debian yet (but I’ve build one for myself)

Knowledge (Actors curriculum)

In this section I will describe the basics about the tools we are going to use.

DBus. Extracted from DBus page:

D-Bus is a message bus system, a simple way for applications to talk to one another. In addition to interprocess communication, D-Bus helps coordinate process lifecycle; it makes it simple and reliable to code a “single instance” application or daemon, and to launch applications and daemons on demand when their services are needed.

D-Bus supplies both a system daemon (for events such as “new hardware device added” or “printer queue changed”) and a per-user-login-session daemon (for general IPC needs among user applications). Also, the message bus is built on top of a general one-to-one message passing framework, which can be used by any two apps to communicate directly (without going through the message bus daemon). Currently the communicating applications are on one computer, or through unencrypted TCP/IP suitable for use behind a firewall with shared NFS home directories.

Gabriel is a simple utility to enable D-Bus clients to connect to a D-Bus daemon running on a remote machine, through SSH.
This is the main piece of this puzzle. If you are interested in understanding how it works you should take a look at socat and libssh. As I’ve had to take a look at code, and make some modifications, you should read it as a punishment.

Extracted from socat man page:

socat – Multipurpose relay (SOcket CAT)
socat is a command line based utility that establishes two bidirectional byte streams and transfers data between them. Because the streams can be constructed from a large set of different types of data sinks and sources (see address types), and because lots of address options may be applied to the streams, socat can be used for many different purposes. It might be one of the tools that one ‘has already needed´.

Libssh. Extracted from libssh page:

The ssh library was designed to be used by programmers needing a working SSH implementation by the mean of a library. The complete control of the client is made by the programmer. With libssh, you can remotely execute programs, transfer files, use a secure and transparent tunnel for your remote programs. With its Secure FTP implementation, you can play with remote files easily, without third-party programs others than libcrypto (from openssl).

You should know about ssh and about your application.

Architecture

Local host will run gabriel and your application.
Remove host will need a running ssh server, a running dbus server and will need socat installed and ready to use.
We need to run gabriel, that will act as a server that will connect our host to the remote host through SSH. After that gabriel will use this SSH connection to intercommunicate our local application with remote DBus applications by using socat.

Remote DBus communication Architecture
Remote DBus communication Architecture

Howto (Main action)

At the moment I’ve only achieved to connect a process using session-bus, I’m still testing until I get connection through system-bus which was my initial purpose.
After reading next information, you will be able to connect using session bus and system bus.

As I commented somewhere else, I’ve made some modifications on gabriel code. I needed some common parameters as SSH port (my virtualbox testing environment ), better help explanations or add a verbose output.
Gabriel establish a connection with the remote ssh and by socat commands it communicates with the remote DBus “environment”. You should administrate ssh parameters and Dbus parameters to gabriel.

We have to put special attention to -d, –bus-address=BUS_ADDRESS because this info must be gotten from the REMOTE machine.
That address is the one used by processes to communicate through DBUS. It’s something “internal” and automatically done when you use DBus api/library. I’m going to show you where to get it.

DBUS_SESSION_BUS_ADDRESS, DBUS_SYSTEM_BUS_ADDRESS, DBUS_SYSTEM_BUS_DEFAULT_ADDRESS

Again, this info should be gotten from REMOTE machine.
At the moment I don’t know any nice command where to get this info.
We have two main options of DBus buses. System and Session (more info in DBus page).
If you need SESSION bus address, you can choose what it better fits you:

  • You can can get it from process environment
  • You can stole it from any other process suspicious from being involved in DBus activities…
  • You can create your own dbus-daemon (which, actually, I don’t know if it uses it’s own BUS_ADDRESS)

If you need SYSTEM bus address, you can choose what it better fits you:

  • You can can get it from process environment. If it’s not defined, take a look at /etc/dbus-1/system.conf where you should locate a string like <listen>unix:path=/var/run/dbus/system_bus_socket</listen>
  • You can stole it from any other process suspicious from being involved in DBus activities…

Examples:

This command gives you a dbus-daemon in your session with the one you can contact.

Howto (Main action): Back to local host

Those ugly unix:stri:ngs/asdkaj/numbers we have seen is what we need for -d, –bus-address=BUS_ADDRESS.
See a session example:

See a system example:

The moment we have or gabriel server running we (may have nothing) need to set DBUS_XXX_BUS_ADDRESS. Many apps would use, or have, this environment variable to connect to a DBus instance and intercommunicate with other process.
This is is easy, DBUS_XXX_BUS_ADDRESS should be the address gabriel shows few instants after being launched.
When we have defined this environment variable (in command line) we can execute our app, and it will happily communicate with the remote DBus world.
Example:

dbus-browser is a program that uses a session bus.

Curiosity: DBus protocol messages interchanged

Modifying a couple of lines in gabriel can let you see DBus raw protocol messages. It’s a didactic info.
If you enable verbose code at least at level 2, you will get raw DBus protocol messages.

My modifications and hacks

Code will be publish under GLKM project page.

Links and references
  • dbus site
  • gabriel site
  • socat site
  • libssh site
  • reference 1. (informational note, it had implied jumping into gabriel, libssh, and dbus code and testing with a virtualbox machine)
  • reference 2. (personal note, take a look at “Securing traffic between two socat instances using SSL” article in socat page)

Howto access a Virtualbox guest machine throught ssh (or how to port forwarding)

This is not an original article (see references), it’s just an archived one “por si las moscas”.

Introduction

By default, the network connection in Virtualbox is set to NAT, that is every packet coming from the Guest machine is modified so that it seems as it has come from the Host machine. In this way it’s easy for the Guest machine to connect to all the rest of the network (the Internet included) but nobody can start a connection with the Guest Machine since it’s hidden behind the Host one.

So, if you want to use a server service in your Guest machine (i.e. Apache or SSH) you have two choices:

  1. pass to Virtualbox Host network connection;
  2. make Virtualbox forward all the packets arriving to a certain port of the Host machine.

This article will describe how to do the latter, in particular in the case of the ssh server. This is an interesting case because it allows you to simulate very well a quite common condition: connecting to a remote Linux headless machine.

We have a guest machine with a running ssh server which accepts connections on the TCP port 22.
Our goal is to make any packet arriving at a given TCP port (i.e. 2222) of the host machine, to be forwarded to the TCP port 22 of the guest machine.
Fortunately, there is Virtualbox command which permits to do it almost instantly: VBoxManage.

Configuration needed

In our case we will use Debian as the guest machine name (quote in case guest machine name contains spaces), here are the commands that you have to type in the host machine (real one) console as your user (if you use another user it will try to look for its virtual machines):

user@machine $ VBoxManage list vms
VirtualBox Command Line Management Interface Version 1.5.6_OSE
(C) 2005-2008 innotek GmbH
All rights reserved.
Name: debian
Guest OS: Linux 2.6
UUID: 814e25f4-451e-4582-8d34-71a1cd437cdd
Config file: /mnt/extra/virtualizacion/virtualbox/debian/debian.xml
Memory size: 195MB
[…]
user@machine $ VBoxManage setextradata debian “VBoxInternal/Devices/pcnet/0/LUN#0/Config/ssh/HostPort” 2222
VirtualBox Command Line Management Interface Version 1.5.6_OSE
(C) 2005-2008 innotek GmbH
All rights reserved.
user@machine $ VBoxManage setextradata debian “VBoxInternal/Devices/pcnet/0/LUN#0/Config/ssh/GuestPort” 22
VirtualBox Command Line Management Interface Version 1.5.6_OSE
(C) 2005-2008 innotek GmbH
All rights reserved.
user@machine$ VBoxManage setextradata debian “VBoxInternal/Devices/pcnet/0/LUN#0/Config/ssh/Protocol” TCP
VirtualBox Command Line Management Interface Version 1.5.6_OSE
(C) 2005-2008 innotek GmbH
All rights reserved.

HostPort,GuestPort,Protocol are just string examples and can be changed without any consequence. Just remember your choices if you want to remove them later.
I guess you should be careful with pcnet substring, as maybe it should have something to see with your selected network card type.

Testing

Once you have typed the above commands, you need to close the guest machine (a reboot won’t be sufficient), restart it and then connect via ssh with:

anyuser@machine$ ssh -l >user< -p 2222 localhost

Replace localhost with the host machine ip address if you are connecting from another computer.

By the way, you can check which customizations have been already set for your Guest Machine with VBoxManage by typing:

user@machine$ VBoxManage getextradata debian enumerate
VirtualBox Command Line Management Interface Version 1.5.6_OSE
(C) 2005-2008 innotek GmbH
All rights reserved.
Key: GUI/LastWindowPostion, Value: 0,6,1028,820
Key: GUI/Fullscreen, Value: off
Key: GUI/AutoresizeGuest, Value: off
Key: GUI/LastCloseAction, Value: powerOff
Key: GUI/SaveMountedAtRuntime, Value: yes
Key: GUI/Seamless, Value: off
Key: VBoxInternal/Devices/pcnet/0/LUN#0/Config/ssh/HostPort, Value: 2222
Key: VBoxInternal/Devices/pcnet/0/LUN#0/Config/ssh/GuestPort, Value: 22
Key: VBoxInternal/Devices/pcnet/0/LUN#0/Config/ssh/Protocol, Value: TCP

or remove one, for example “VBoxInternal/Devices/pcnet/0/LUN#0/Config/ssh/GuestPort”, by setting it without any value:

user@machine$ VBoxManage setextradata “VBoxInternal/Devices/pcnet/0/LUN#0/Config/ssh/GuestPort”

Links and references

Allowing DISPLAY needed apps in remote machines on local machines to root user using ssh and xauth

Introduction

(As you can read in xauth man pages…)
The xauth program is used to edit and display the authorization information used in connecting to the X server. This program is usually used to extract authorization records from one machine and merge them in on another (as is the case when using remote logins or granting access to other users). Commands (described below) may be entered interactively, on the xauth command line, or in scripts. Note that this program does not contact the X server except when the generate command is used. Normally xauth is not used to create the authority file entry in the first place; xdm does that.

xauth to root user

Para permitir que todo funciones de forma óptima y ssh realice automáticamente la parte responsable de securizar flujos de datos (gráficos y textuales) hay que modificar primero el servidor SSH de la máquina remota (fichero /etc/ssh/sshd_config). Activaremos las dos variables indicadas. Activar estas opciones conllevan ciertos riesgos de seguridad.

/etc/ssh/sshd_config
X11Forwarding yes
AllowTcpForwarding yes

Ahora basta con conectarnos usando la opción -X (X11 forwarding) y -Y (X11 trusted forwarding) del cliente SSH. En Debian -Y es una opción que funciona por defecto si no se especifica nada en otro sitio (~/.ssh/config, /etc/ssh/ssh_config).

usuario@LOCAL:~$ echo $DISPLAY
:0.0
usuario@LOCAL:~$ ssh -Y usuario@maquina-remota
Password:
Linux maquina-remota 2.6.18-3-686 #1 SMP Mon Dec 4 16:41:14 UTC 2006 i686
The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
No mail.
Last login: Mon Mar 5 03:55:53 2007 from XX.XX.XX.XX
usuario@maquina-remota:~$ echo $DISPLAY
localhost:10.0
usuario@maquina-remota:~$ xlogo
[Por pantalla se muestra una ventana con el logotipo X]
usuario@maquina-remota:~$ exit
logout
Connection to XY.XY.XY.XY closed.

[GLKM] Subversion project stats measures with mpy-svn-stats

A simple command line tool called mpy-svn-stats give us nice graphics using svn xml output.

You can see an example GLKM project statistics

It’s quite easy to use, see:

user@machine:/var/www/svn-stats$ mpy-svn-stats -o ./ svn+ssh://localhost/var/lib/svn/glkm/
Will generate PIL graphs.
getting data
running command: “svn -v –xml log svn+ssh://localhost/var/lib/svn/glkm/”
[…ssh stuff…]
done
parsing data
done
calculating stats
done
writing data
done
Have 13 stats objects, 13 of them are wanted.
user@machine:/var/www/svn-stats$ ll
total 48
-rw-r–r– 1 user user 10379 2008-02-06 17:06 changed_paths_multi_author_graph.png
-rw-r–r– 1 user user 10268 2008-02-06 17:06 commits_group_multi_author_graph.png
-rw-r–r– 1 user user 11762 2008-02-06 17:06 index.html
-rw-r–r– 1 user user 10265 2008-02-06 17:06 log_message_length_group_multi_author_graph.png
user@machine:/var/www/svn-stats$

References and links