Tag Archives: Tips&Tricks

Generating self-signed SSL certificate/key pair

Here, I present a simple command to generate a self signed SSL certificate/key pair that can be used to secure the communication channel between communicating parties.

$ openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days `echo "365 * 2" | bc` -nodes
Generating a 2048 bit RSA private key
.....................................+++
.....................................+++
unable to write 'random state'
writing new private key to 'key.pem'
-----
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:
Email Address []:

$ ls
cert.pem  key.pem

$ $ date
Mon May 11 15:18:24 EDT 2015

$ openssl x509 -noout -startdate -enddate -in cert.pem
notBefore=May 11 19:12:03 2015 GMT
notAfter=May 10 19:12:03 2017 GMT

Note: -nodes switch skips encryption of the key.

APT: How to prefer local packages over remote?

I recently had to test some of my locally generated MariaDB debian packages. So, created a local repository of generated packages and added it to sources.list file. However, since these packages required some other packages stored on a mirror, I had to add the mirror to the sources.list file as well. Since, this mirror also contained the packages that I intended to test, now when I try to install the packages, APT would always pick/prefer the ones stored on the mirror. How to solve this? How to make APT prefer the local packages instead? Lets start by taking a peek into the sources.list file:

$cat /etc/apt/sources.list
..
# remote repo
deb http://mirror.jmu.edu/pub/mariadb/repo/5.5/ubuntu precise main

# local repo
deb file:///home/nirbhay/project/repo/maria/testing/debian/5.5/debs binary/
..

$ sudo apt-cache policy mariadb-galera-server
mariadb-galera-server:
  Installed: (none)
  Candidate: 5.5.37+maria-1~precise
  Version table:
     5.5.37+maria-1~precise 0
        500 file:/home/nirbhay/project/repo/maria/testing/debian/5.5/debs/ binary/ Packages
        500 http://mirror.jmu.edu/pub/mariadb/repo/5.5/ubuntu/ precise/main i386 Packages

The following tips can help you fix this problem :

  1. If remote and local packages have the same version (as in my case), place one that you want to be preferred higher in sources.list file.

  2. APT prefers authenticated repository over unauthenticated. So, as against the above case, even if the local repository is placed over the remote, APT will prefer remote one if its authenticated and the local repository is not. In that case, –allow-unauthenticated can be used to make local packages take precedence.

  3. In case local and remote packages have different versions, APT would always prefer the package with higher version. However, this rule can be eased by apt-pinning, where a higher priority is assigned to a particular repository. For example, local repository can be pinned with higher priority (or precedence in APT’s context) by adding a file under /etc/apt/preferences.d with .pref extension and the following content :

    Package: *
    Pin: origin ""
    Pin-Priority: 1000
    

    This has been explained really well in this thread.

Lastly, do not forget to run “apt-get update” for changes to take effect.

Generating SSH key pair

SSH key pair is a set of private/public keys used in securing network communication. These keys are normally required for passwordless SSH login to a remote host running SSH daemon (sshd). Here is how you would generate a pair of RSA keys:

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/nirbhay/.ssh/id_rsa):
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/nirbhay/.ssh/id_rsa.
Your public key has been saved in /home/nirbhay/.ssh/id_rsa.pub.
The key fingerprint is:
5f:1a:b5:50:a8:b6:d6:2b:48:1b:b6:df:4c:54:a2:28 nirbhay@nirbhay-VirtualBox
The key's randomart image is:
+--[ RSA 2048]----+
|           ..    |
|          ..     |
|         .o o    |
...
|       .o. = .   |
|       ...o      |
+-----------------+
$ ls ~/.ssh/
id_rsa  id_rsa.pub

Now that we have the private/public key files, all you need to do is copy/append the public key (id_rsa.pub) contents to the remote machine’s ~/.ssh/authorized_keys (600) file. DO NOT share the “private key”.

Note: On debian-based distributions, ssh-keygen is provided by openssh-client package.

Apache2: php file getting downloaded instead?

After having installed all the necessary packages on my fresh Ubuntu, while testing different configurations I came across this problem where the php file was being offered for download when tried to execute via browser! That is, whenever I tried to open a php script through browser, the file was getting downloaded, instead of being executed. If you are a LAMP-fan (like me), you might come across this problem in future or perhaps you are facing it now and have reached here.. 😉 The problem is straight forward :

“the apache server is not able to execute the requested php script (even though the core Apache & PHP packages are installed) and hence offering it for download”

Fortunately, in my case, the resoluton turned out to be simple. While installing php+apache, I missed out the php module for apache, which basically enables apache to handle php scripts. So, I installed it, restarted the apache server and the problem just got resolved!

$ sudo apt-get install libapache2-mod-php5

$ sudo /etc/init.d/apache2 restart

$ find /etc/apache2/ | grep php
/etc/apache2/mods-enabled/php5.load
/etc/apache2/mods-enabled/php5.conf
/etc/apache2/mods-available/php5.load
/etc/apache2/mods-available/php5.conf

C++: Why prefer member initialization list over assignment?

The answer is simple – the latter could be a costly choice. I will try to explain this using a simple example. In the following program we have a class Bar that has a private data member of type Foo (another class). Now, lets say we want to create an object of type Bar initializing its data member with an object of type Foo, something like, Bar obj2(obj1); The following program defines the necessary functions to give an idea of what happens during the creation of such objects.

#include 

using namespace std;

class Foo {
public:
  Foo() { cout << "Foo: default ctor called." << endl; }
  Foo(const Foo &obj) { cout << "Foo: copy ctor called." << endl; }

  Foo & operator =(const Foo &obj)
  {
    cout << "Foo: overloaded assignment operator called." << endl;
    return *this;
  }

  ~Foo() { cout << "Foo: default dtor called." << endl; }
};

class Bar {
public:
  Bar() { cout << "Bar: default ctor called." << endl; }

  /* Parameterized constructor (without member initialization list) */
  Bar(Foo &foo)
  {
    cout << "Bar: ctor taking reference to Foo as param.." << endl;
    m_foo= foo;
  }

  ~Bar() { cout << "Bar: default dtor called." << endl; }

private:
  Foo m_foo;
};

int main()
{
  Foo obj1;
  Bar obj2(obj1);
  return 0;
}

Lets focus on Bar's parameterized constructor & how it affects the output.

..snip..

  /* Parameterized constructor (without member initialization list) */
  Bar(Foo &foo)
  {
    cout << "Bar: ctor taking reference to Foo as param.." << endl;
    m_foo= foo;                             /* Use assignment operator */
  }

..snip..

Output:
Foo: default ctor called.
Foo: default ctor called.
Bar: ctor taking reference to Foo as param..
Foo: overloaded assignment operator called.

Bar: default dtor called.
Foo: default dtor called.
Foo: default dtor called.

As we can see, while Bar's object is being constructed,

  1. Foo's default constructor is first invoked to construct the Foo's part of Bar, and then
  2. Foo's assignment operator is invoked to initialize it with the object supplied as parameter to this constructor.

Said that, let us now see how this can be improved by using member initialization list in Bar's parameterized constructor's definition.

..snip..

  /* Parameterized constructor (with member initialization list) */
  Bar(Foo &foo) : m_foo(foo)
  {
    cout << "Bar: ctor taking reference to Foo as param.." << endl;
  }

..snip..

Output:
Foo: default ctor called.
Foo: copy ctor called.
Bar: ctor taking reference to Foo as param..

Bar: default dtor called.
Foo: default dtor called.
Foo: default dtor called.

Looking at the above output, we can see that during the construction of Bar's object, Foo is being constructed & initialized directly by Foo's copy constructor, instead of using the default constructor to create an uninitialized object followed by the assignment operator.

Hence using member initialization list, one can completely avoid the use for overloaded assignment operator and thus save some precious CPU clocks.

Building a MySQL client program on Linux

Building a C program (client) to connect to MySQL server is simple, but at times it can become a little problematic for a newbie to find all the necessary dependencies (includes/libs). The best option that I would recommend is to use the mysql_config script that comes bundled with the MySQL distribution. This shell script when executed with some options, would print all necessary compiler options/flags/switches required to build a MySQL client program. Lets see it in action!

/**
  @file client_version.c
  Display the client version.
*/

#include 
#include                               /* All public MySQL APIs */

int main()
{
    printf("MySQL client version: %s\n", mysql_get_client_info());
    return 0;
}

# mysql_config's output
> .../bin/mysql_config --cflags --libs
-I/path..to../include  -fPIC -g -fabi-version=2 -fno-omit-frame-pointer -fno-strict-aliasing
-L/path..to../lib -lmysqlclient -lpthread -lm -lrt -ldl

# and now pass it down to the compiler..
> gcc client_version.c `/home/nirbhay/project/repo/bld/trunk/bld/bin/mysql_config --cflags --libs`
.. done

> ./a.out 
MySQL client version: 5.7.2-m12

# whoa.. that worked!

Sometimes, the generated binary would complain of missing shared object file. It can be solved by setting up LD_LIBRARY_PATH to the lib directory containing libmysqlclient.so.NN file.

> ./a.out 
./a.out: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object file: No such file or directory
nirbhay@Nirbhay-lenovo:~/project/sandbox/mysql$ ldd a.out 
	linux-vdso.so.1 =>  (0x00007fffce1ee000)
	libmysqlclient.so.18 => not found
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fca652e6000)
	/lib64/ld-linux-x86-64.so.2 (0x00007fca656a3000)

LD_LIBRARY_PATH=/path..to../lib ./a.out
MySQL client version: 5.7.2-m12

Shell script: recursive find/replace

Lately I had a requirement of finding & replacing a specific string from all the files under a directory tree, while keeping the file permissions intact. Here is the shell script that I eventually came up..

#!/bin/bash

cd target_dir

for _file in `find .`;
do
  if [ ! -d $_file ]; then
    sed "s/SEARCH_STR/REPLACE_STR/g" $_file > tmp; cp tmp $_file; rm tmp;
  fi
done

Hope this would help somebody.. disfrutar!

How to debug signal handlers using GDB

At times, one might want to debug a signal handler using GDB. Looks simple, just set a breakpoint at the entry! But there is tiny glitch. Consider the following program.

/*
  @file : sig.c
*/

#include
#include

void signalhandler(int signum) {
  printf("\n SIGINT caught : %d", signum);
}

int main() {
  signal(SIGINT, (void*)signalhandler);

  while (1) {
    printf("\n looping : inside main()");
    sleep(1);
  }
}

Now, lets try to debug the signal handler function using GDB.

# Set a breakpoint in the signal handler function.
(gdb) b signalhandler 
Breakpoint 1 at 0x40058f: file sig.c, line 5.
(gdb) r
Starting program: /home/nirbhay/project/sandbox/c/signal/a.out 

 looping : inside main()
 looping : inside main()
 looping : inside main()
 looping : inside main()
 looping : inside main()
# And now, Ctrl-C
^C
Program received signal SIGINT, Interrupt.
0x00007ffff7af5120 in __nanosleep_nocancel () at ../sysdeps/unix/syscall-template.S:82
82	../sysdeps/unix/syscall-template.S: No such file or directory.
	in ../sysdeps/unix/syscall-template.S
(gdb)

Its apparent that the signal that we are trying to send to the program is being intercepted by GDB and hence control never enters the signal handler (where we have already set a breakpoint).

In such scenarios, GDB’s handle command can be used. With this command we can alter the default behaviour of GDB towards signals. The handle command takes, as argument, a list of signals (to be handled) followed by actions. Of all the actions, ones that are of interest to us are : nostop (do not re-enter debugger if this signal happens) & pass (let program see this signal).

Lets now watch ’em in action :

(gdb) handle SIGINT nostop pass
SIGINT is used by the debugger.
Are you sure you want to change it? (y or n) y

Signal        Stop	Print	Pass to program	Description
SIGINT        No	Yes	Yes		Interrupt
(gdb) r
Starting program: /home/nirbhay/project/sandbox/c/signal/a.out 

 looping : inside main()
 looping : inside main()
^C
Program received signal SIGINT, Interrupt.

Breakpoint 1, signalhandler (signum=2) at sig.c:5
5	  printf("\n SIGINT caught : %d", signum);
(gdb)