Tuesday, April 22, 2014

Executing remote commands from a Dancer application

I developed an application to execute commands remotely from a Dancer application. It is not secure if you don't do it correctly but sometimes you may need it, if so, make sure the command is not enter as a parameter from the user and nobody can read your username or password to access to the server.

This is an example of how to execute a remote command using Dancer, Net::SSH2 and fork. It is NOT secure at all, it is just to have an idea and to get some lines of code to implement a function to execute a remote command.

How to send the public key to the remote servers?

To allow the remote server accept the connection, it is required this server knows and authorize the key. This is done by send the public key to the remote host execute this command:
cat ~/.ssh/id_rsa.pub | ssh $user@$server 'cat >> ~/.ssh/authorized_keys'
Or this one:
ssh-copy-id -i ~/.ssh/id_rsa.pub $user@$server

There are some comments about this code:
  • The password variable may be optional. 
  • Due to access restriction to the private key I copy it to a directory where the application can read it. Make sure it is only accessible from the dancer application.
  • May be good idea to have a function to parse the command and make sure it does not have malicious commands such as 'rm'.
  • I tried this code with threads but there are modules not thread-safe so I recommend to use fork instead.