How to connect to an SSL OpenLdap

After a lot of troubleshooting I managed to connect to an ssl OpenLdap and I would like to share this information with you.

Some of the problems that you may encounter are:

Ldap host.

Verify, using ping if you have access to the ldap server.

I suggest you try both, IP and hostname. In some configurations the dns name of the ldap host is working fine, but sometimes it doesn't. So try both in case you have problems.

SSL specific problems

For php, try
ldap_connect("ldaps://host", port)
ldap_connect("ldaps://host:port")

If the host you are using to invoke the scripts does not have a ssl certificate installed then you have to add the following line to your ldap.conf:
TLS_REQCERT     never

Sample php script

Here is a sample script to connect to a secured OpenLdap. Also the script assumes that you DON'T have anonymous access to the LDAP server. In case you do have, then just do a bind with no credentials.
You must change the parameters in the beginning of the script in order to match your organization's OpenLdap configuration.


<?php
// Set the parameters below to fit your organization's openldap
$basedn = "DC=example,DC=com";
$login = "user";
$ldapuser = "uid=$login,ou=people,dc=example,dc=com";
$ldappass = "pass";
$filter = "(uid=$login)";
$ldapurl = "ldaps://ldap.example.com:XXX"; 
$LDAPFieldsToFind = array("cn", "mail");
$debug = false;

// Set debugging
if ($debug) {
  ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
}

// connect to ldap server
$ldapconn = ldap_connect($ldapurl) or die ("Couldn't connect");

// binding to ldap server
echo "Trying to bind with $ldapuser - $ldappass\n";
$ldapbind = @ldap_bind($ldapconn, $ldapuser, $ldappass);

if (!$ldapbind) {
  echo "Unable to bind to server $ldapurl\n";
  echo "OpenLdap error message: " . ldap_error($ldapconn) . "\n";
  exit;
}

echo "Bind succesfull\n";
echo "\nSearching in base_dn $basedn - filter: $filter\n";    
$userdetails = ldap_search($ldapconn, $basedn, $filter, $LDAPFieldsToFind);
$info = ldap_get_entries($ldapconn, $userdetails);

for ($x=0; $x<$info["count"]; $x++) {
$email=$info[$x]['mail'][0];
$nam=$info[$x]['cn'][0];
  print "\n\nOpenLdap attributes:\n";
  print "CN is: $nam \n";
  print "Mail is: $email\n";
}
  
if ($x==0) { echo "\nOops, was not found. Please try again."; }

?>

How-to: Execute any linux script using mail

The following guide will show you how to execute a php or any other command line program by sending mail to a specific mail address.

This can be used for many applications. For example say that we want to create a new trouble ticket to our organisation's central ticket/issue management system.

The first step is to create and test the script.
<?php
/*
 * newticket.php
 */
error_reporting(E_ALL);

$user="root";
$password="XXX";
$database="tests";

echo "Connecting...\n";

mysql_connect("localhost",$user,$password);
mysql_select_db($database) or die( "Unable to select database");
$dt = date("F j, Y, g:i a s");
$query="insert ticket (description) values (\"$dt\")";
mysql_query($query) or die(mysql_error());
mysql_close();
?>

This scripts assumes that you have the table ticket created in a mysql database called tests:
CREATE TABLE IF NOT EXISTS `ticket` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
)

If you place it for example in /var/www then you can test the php script from the command line using:
php -q /var/www/newticket.php

If everything is OK, this script will insert one row in table ticket with its field description set as the current datetime.

Now, if you don't already have one, you need to install a mail server. In this example I used postfix. So for debian/ubuntu just type:
sudo aptitude install postfix

Postfix doesn't allow by default mail aliases to execute commands. In order to enable this you have to configure postfix for this by adding the following lines of the file main.cf which is located at /etc/postfix. Edit the file with:
sudo vi /etc/postfix/main.cf

And then add the attributes allow_mail_to_commands and allow_mail_to_files:
allow_mail_to_commands = alias,forward,include
allow_mail_to_files = alias,forward,include

Then we need to edit the /etc/aliases in order to add the mail alias that will execute the script we just created:

# See man 5 aliases for format
postmaster:    root
newticket: "| php -q /var/www/newticket.php" 

Now we have to refresh the aliases used by sendmail by executing the command (rebuilds the data base for the mail aliases file.
sudo newaliases

Finally test the alias just created by running the sendmail like this:
user@host:/var/www$ sendmail newticket
.

Don't forget the "." which marks the end of the message body and tells sendmail to actually send the mail.
Now check your database. If everything went fine, you should have a new row inserted in your ticket table.
If not, then you have to do some troubleshooting by running the mailq program to check your mail queue.

Configure SQuirreL with MySQL


SQuirreL is great because is universal and platform independent. You can use it to connect to almost every database that you can imagine.
The only drawback is that it doesn't ship with the database drivers due to licensing issues.

So here is a step-by-step procedure for connecting to MySQL from SQuirreL.

First of all verify that you have network access to the mysql host and its port. Usually mysql servers run at port 3306, so test the connection from your host:
telnet xxx.xxx.xxx.xxx 3306

If you get something like:
Trying xxx.xxx.xxx.xxx...
telnet: Unable to connect to remote host: Connection refused

then you won't be able to connect.

The correct response you should get is something like:
Trying xxx.xxx.xxx.xxx...
Connected to xxx.xxx.xxx.xxx.

Then you must check that the database user you will be using has access from the host that the squirrel client will run.

You can check the privileges using phpmyadmin, or by command line:
GRANT USAGE ON *.* TO 'user'@'hostname'

Now go to SQuirrel's website, download and install it.

When you run the program you will see on your left pane a list of database drivers. Most of them are not installed, so we have to manually install the drivers we use often, eg MySQL, Oracle, Sybase etc.

Now, download the platform independent mysql jdbc driver from http://dev.mysql.com/downloads/connector/j/

Unzip/untar the downloaded file. In the uncompressed folder you should see a file named mysql-connector-java-X.X.XX-bin.jar. Place this file file into the lib subfolder under SQuirreL's install folder.

This is the mysql jdbc driver.
We are now ready to install the mysql jdbc driver.
Scroll down to the MySQL driver, double-click it and set the Extra Class Path as illustreted below:


Press OK, if everything is fine, then you will see the following screen:


Now you can create your connection(s) to any mysql database(s) by using the aliases tab:



Use the "Test" button to test your connection
Hopefully the connection should be created successfully...

Have fun with your queries!

How-to: Secure ssh connections for a linux host or VM

Follow the steps below in order create a secure setup for connecting from Windows to any host or VM running Linux. You will see that the setup is quite easy and straightforward. You are just steps away from tight security of your hosts.

The only requirement is that the VM should support ssh connections (thus, running sshd).

The method used here is to generate a public/private key pair with a passphrase. The public key is installed on the Linux server/VM and the private key is installed in out putty session.

Generate key using PuTTYgen

First of all get PuTTYgen! There is no install procedure involved...it's just a tiny little program, similar to putty.

Run the program, and press the Generate button:

Now, just move the mouse as instructed, in order to generate randomness:

After some seconds you'll get the following screen:

This is the most important step in order to secure the connections to your VM.
Enter a passphrase, which will be used later to authenticate users who will be using the generated private key.
Finally press the "Save private key" button to save you new private key. This private key file can be distributed to any clients that will connect to your VM.

Import private key into putty

Ok, now we are ready to import our generated key into the required putty session. So we need to go to the SSH properties of the required session. The image below shows exactly the location of private key file setting.
Note that this setting is per session, thus you could have as many key as you want. So every connection could have a different key file, or - for simplicity - if you want you can use the same ppk file for all of your linux hosts.
Finally don't forget to save the session, otherwise the changes will be lost.

Install public key in host/VM

Create the users who should be able to connect to this vm.
Then decide which users will be able to run sudo commands or "su -" and add them to the corresponding group. For example in Debian/Linux this command below adds the user user1 and directly assigns him in the "sudoers" group:
useradd -G sudo -s /bin/bash -m -d /home/user1 user1
and create an .ssh directory in the home directory of each one of them and in this directory create a file named authorized_keys and copy there the generated public key. The value to copy in that file is the one shown in example below, under the title Public key for pasting
    Be careful: You need to scroll down the text box and copy the whole thing!
    Now if you cat the authorized_keys file, it should be in the form:
    ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAt3Tnp4oCf/yHQWDx2/CUu1WcwLt6ZfLETL/fFK+F91mx
    11111111111111111111111111111111UYexCSRHkYG7Ey3uffUOWuSn+BnHy+GVmYOM87SCR5Sl14dz
    XxvNffAw5IjDAUcAi8Um3jPPobSW/2345234552345234523kkkkkkkkkkkkkkkkkkkkkkkkkkkkk1op
    N3aFYpQU20rmWja6J6fPGXwTuTvd/rjJPlKGaz9w0r+hj7CbJU00FN/nAAy0/0000000000000000/xT
    CXRItzBH4SyWfZpfPMf/55555555555555+a505HFU2qPPRjSo15WnvIXw== imported-openssh-ke
    y
    Now save the file and connect from a separate window in order to test the connection.

    Host sshd configuration

    Disable SSH Password Authentication

    In /etc/ssh/sshd_config update or add the following entries:
    ChallengeResponseAuthentication no
    PasswordAuthentication no
    UsePAM no

    Disable ssh root access

    The last step to tight security is to disable ssh root access to this VM.
    This is done by modifying the file /etc/ssh/sshd_config and set the PermitRootLogin property to No:
    PermitRootLogin no

    Check your configuration

    The changes will be applied by restarting you sshd. But before doing so, do a final test of your configuration in order to check that indeed everything is working fine:
    • Connect securely using you ppk
    • You can execute sudo commands
    • You can "su -"
    Then restart your sshd by using the command
    /etc/init.d/ssh restart
    Check again. Now users won't be able to connect to this host using the usual username/password authentication.

    Voila! Now you are ready to use your super safe setup and sleep happily and calmly evereafter!