Creating host-specific PuTTY shortcuts

When using PuTTY with multiple hosts and/or with multiple sessions, there is always the problem of entering the same information many, many times. Now, you can always go for the key-based SSH login with PuTTY, which is a secure way of doing this, but here, we will present you an easier and simpler way of auto-login using PuTTY shortcuts.

First, you must obtain a copy of the PuTTY client (available here). Now, after downloading it, open PuTTY:

In the Host Name field enter the name of the host, set the port in Port and enter a name for the session in the Saved Sessions text field:

Click Save to save your profile. Now when you double-click on the entry in the Saved Sessions or click on it, click Load and click Open your PuTTY client will automatically connect to it. You can save every host you like in the Saved Sessions:

Now here is the really nice part. Create a shortcut to PuTTY and open its Properties:

Now after the current Target (after the if any, and don’t forget a space), you can add a few arguments to automatically log into a saved session. The possible arguments are:

-load “<session_name>” – for automatically loading a session. Note: <session_name> is a saved session name and not a hostname.

-l <username> – for automatically entering a username on the host.

-pw <password> – for automatically entering a password.

Note: Using the -pw option is not secure in any way. If you use it you are storing your password in plain-text. If you have any doubts about how secure your machine is, please refer to the key-based SSH login.

It is also possible to only use some of those arguments, so for example if you want to load a session and a username you can only use the -load and -l options. Or if you use the same credentials for more than one host (which is bad, bad, bad…), you can omit the -load option. So, an automatic login on the host specified in the session ABlog with username root and password badandtrivial will be:

“D:\<path_to_putty>\putty.exe” -load “ABlog” -l root -pw badandtrivial

Note: This method is not in any way secure. It is merely a method to speed up your work, but stores passwords in plain-text.

So after editing a shortcut’s properties you only click OK to save. You can easily have multiple shortcuts:

Still, secure or not, it can be used for any non critical information. It is not, in any way, more dangerous than storing passwords in browsers…

VN:F [1.9.18_1163]
Rating: 3.3/10 (3 votes cast)

How to setup Apache HTTP and HTTPS virtual hosts

Virtual hosting is a way of hosting several servers on a single machine. This technique is widely used in shared web hosting, because it greatly reduces hosting costs, since multiple customers use one server.

There are three types of virtual hosting:

  • Name-based – when the virtual hosts is determined by its domain. A problem with this approach is that it is completely dependent on the DNS.
  • IP-based – when each site is differentiated via his IP. A natural complication is that this requires a different IP for each site.
  • Port-based – when each site is described with the same domain, but different port. Naturally, the problem that users don’t generally use ports arises. Additionally, some firewalls block uncommon ports.

Using Apache, we will setup two name-based virtual hosts – an HTTP one and an HTTPS one. Both will work on the standard ports 80 for HTTP and 443 for HTTPS. Naturally we will see how to set port-based hosts.

Note: This tutorial assumes standard file places and settings for Apache on CentOS.

Note: The goal of this tutorial is not to provide extensive knowledge on configuring virtual hosts, but to provide a general-purpose working configuration. For more find-tuned configurations refer to the Apache documentation on virtual hosts.

We assume that <domain> is the domain for our virtual host. In the httpd/conf.d directory (usually /etc/httpd/conf.d) create a file called <domain>.conf

Note: It is not necessary to call your file <domain>.conf, but it’s a sort of a convention and makes editing hosts easier. The file for the HTTP virtual host should contain:

# <domain> HTTP Virtual Host
<VirtualHost *:80>
    # General
    ServerAdmin <administrator_e_mail>
    DocumentRoot /var/www/html/<domain>
    ServerName www.<domain>
    ServerAlias <domain>
 
    # Logging
    ErrorLog logs/<domain>-error_log
    CustomLog logs/<domain>-access_log common
</VirtualHost>

<administrator_e_mail> is the e-mail of the site administrator. After you set this file restart the HTTP Server daemon:

service httpd restart

To setup an HTTPS virtual host, again create the <domain>.conf file in the /httpd/conf.d. Again we assume <domain> is the domain-name:

# <domain> HTTPS Virtual Host
<VirtualHost *:443>
    # General
    ServerAdmin <administrator_e_mail>
    DocumentRoot /var/www/html/<domain>
    ServerName www.<domain>
    ServerAlias <domain>
 
    # Logging
    ErrorLog logs/<domain>-ssl_error_log
    TransferLog logs/<domain>-ssl_access_log
    CustomLog logs/<domain>-ssl_request_log "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
    LogLevel warn
 
    # SSL Engine
    SSLEngine on
 
    # SSL Protocol
    SSLProtocol all –SSLv2
 
    # SSL Cipher Suite
    SSLCipherSuite LL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW
 
    # Server Certificate
    SSLCertificateFile <path_to_certificate>
 
    # Server Private Key
    SSLCertificateKeyFile <path_to_private_key>
 
    # SSL Engine Options
    <Files ~ "\.(cgi|shtml|phtml|php3?)$">
        SSLOptions +StdEnvVars
    </Files>
    <Directory "/var/www/cgi-bin">
        SSLOptions +StdEnvVars
    </Directory>
 
    # SSL Protocol Adjusments
    SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown owngrade-1.0 force-response-1.0
</VirtualHost>

Of course, after setting this, restart the HTTP daemon:

service httpd restart

It is easily noticeable, that you can setup port-based virtual hosts quite easy, by using the same domain, but different ports in the .conf file.

Naturally this tutorial is not exhaustive, as such tutorial will be pretty much equal to documentation (which you can find here).

VN:F [1.9.18_1163]
Rating: 7.0/10 (2 votes cast)

Creating and signing certification requests using OpenSSL

In our previous tutorial about creating your own Certificate Authority, we introduced OpenSSL – an open source commercial-grade toolkit, which implements SSL and TLS (Secure Sockets Layer and Transport Layer Security) and provides a general purpose cryptography library. Naturally we continue with creation of certification requests (also called Certificate Signing Request).

Note: In this tutorial (as well as in the previous one) we assume CentOS is the OS of choice.

To create a certificate request we navigate again to /etc/pki/CA:

cd /etc/pki/CA

Now let’s create the certification request. We’ll request a certificate, which will last one year:

openssl req -config openssl.cnf -new -nodes -keyout private/<domain>.key -out <domain>.csr -days 365

Generating a 2048 bit RSA private key
..............................+++
.................................+++
writing new private key to 'private/<domain>.key'
-----
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) [XX]:<country>
State or Province Name (full name) []:<state>
Locality Name (eg, city) [Default City]:<city>
Organization Name (eg, company) [Default Company Ltd]:<organization>
Organizational Unit Name (eg, section) []:<department>
Common Name (eg, your name or your server's hostname) []:<url>
Email Address []:<email>
 
Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

This creates two files, <domain>.key, which is the private key and <domain>.csr, which is the Certificate Signing Request. Restrict the rights to the private key so it readable only by root and the user that will use it:

chown root:globus private/<domain>.key

chmod 0440 private/<domain>.key

So now that we have created the certification request it is time to sign it. Navigate to /etc/pki/CA:

cd /etc/pki/CA

Sign the certificate using this command:

openssl ca -config openssl.cnf -policy policy_anything -out certs/<domain>.crt -infiles <domain>.csr

Using configuration from openssl.cnf
Enter pass phrase for ./private/ca.key:<ca_password>
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Nov 15 18:52:08 2011 GMT
            Not After : Nov 14 18:52:08 2012 GMT
… CERTIFICATE INFORMATION …
Certificate is to be certified until Nov 14 18:52:08 2012 GMT (365 days)
Sign the certificate? [y/n]:y
 
 
1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

After that, you need to remove the certificate request:

rm -f <domain>.csr

After the whole procedure two files are created. <domain>.crt – this is a domain specific certificate for the request. It is put in the certs directory. <certificate_number>.pem is the second file. It is put in the newcerts folder. This is a ready to use X.509 file which contains the information from <domain>.key and from <domain>.crt.

VN:F [1.9.18_1163]
Rating: 0.0/10 (0 votes cast)

Create your own Certificate Authority using OpenSSL on CentOS

OpenSSL is an implementation of the SSL and TLS protocols. It is open-source and is the de-facto standard toolkit for Secure Sockets Layer (SSL) and Transport Layer Security (TLS). It is written in C and also contains a general purpose cryptography library. Being written in C allows for various wrappers for other programming languages to exist.

Installing OpenSSL on CentOS is actually quite easy. All you have to do is enter the following command:

yum install openssl

Note: Depending on your installation configurations OpenSSL may already be installed on your system.

Note: This tutorial uses OpenSSL 1.0.0.

After we install OpenSSL, we need to setup our own Certificate Authority. To do so we first navigate to /etc/pki/CA:

cd /etc/pki/CA

Now we will make a directory where our certificates will be stored:

mkdir certs

Another necessary directory is for the revocation list:

mkdir crl

Note: crl stands for Certificate Revocation List.

Now we must create a directory for storing the unencrypted certificates:

mkdir newcerts

Next, create an empty file index.txt (you may use touch). The index.txt file is the database for certificates. Additionally, create two files containing the next serial number for a certificate and the next serial number for the revocation list:

echo ’01’ > serial

echo ’01’ > crlnumber

Almost ready. Copy the standard openssl config file to you current directory:

cp /etc/pki/tls/openssl.cnf openssl.cnf

And edit the config file (the one stored at /etc/pki/CA/openssl.cnf):

Change this line:

dir             = /etc/pki/CA           # Where everything is kept

to

dir             = .           # Where everything is kept

Change this line:

certificate     = $dir/cacert.pem       # The CA certificate

to

certificate     = $dir/certs/ca.crt       # The CA certificate

And this line:

private_key     = $dir/private/cakey.pem# The private key

to

private_key     = $dir/private/ca.key # The private key

And last, but certainly not least, make /etc/pki/CA/openssl.cnf readable only for you:

chmod 0600 openssl.cnf

After that, the process of creating a certificate authority is actually quite easy. Navigate to /etc/pki/CA:

cd /etc/pki/CA

Enter the following command:

openssl req -config openssl.cnf -new -x509 -extensions v3_ca -keyout private/ca.key -out certs/ca.crt -days 3650

if you want to create a CA valid for 10 years. You will be prompted:

Generating a 2048 bit RSA private key
........+++
.......+++
writing new private key to 'private/ca.key'
Enter PEM pass phrase:<password>
Verifying - Enter PEM pass phrase:<password>
-----
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) [XX]:<country>
State or Province Name (full name) []:<state>
Locality Name (eg, city) [Default City]:<city>
Organization Name (eg, company) [Default Company Ltd]:<organization>
Organizational Unit Name (eg, section) []:<department>
Common Name (eg, your name or your server's hostname) []:<common_name>
Email Address []:<email>

Where common_name is usually formed like ca.<your_domain>, and <email> is usually ca@<your_domain>

Finally, don’t forget to restrict the access to your private key:

chmod 0400 private/ca.key

For more on OpenSSL checkout how to create and sign certificates.

VN:F [1.9.18_1163]
Rating: 10.0/10 (3 votes cast)

Function overloading by return type in C++

Commercial modern day languages often get criticized because they don’t support function overloading by return type. That is to say, functions cannot be distinguished by return type. For example:

int myfunction(int a, int b); float myfunction(int a, int b); char myfunction(int a, int b);

Are not valid. That is kind of bad, because the possibility to overload by return type often improves the quality of code.

But why can’t we overload by return type? Because the return type is not a part of a function’s signature. However, function overloading by type is not only possible in C++, it is actually pretty easy too.

Enter the cast operator. Remember this guy?

class C{ public: operator int() {…} };

“That’s cool, but it cannot be passed arguments!” you may say. True, but we don’t need it to be passed arguments, we can pass arguments using the constructor. Let’s review that with a simple example:

#include <iostream> using namespace std; class TestFunction{ private: int ia, ib; public: TestFunction(int a, int b): ia(a), ib(b){ } operator int(){ return ia * ib; } operator float(){ return (float)ia / (float)ib; } }; int main(){ int int_res = TestFunction(1, 13); //13 float float_res = TestFunction(1, 13); //0.0769231 cout << int_res << endl << float_res; return 0; } Output: 13 0.0769231

We should note, that an essential part of our program is the way we call the “function” like this:

float float_res = TestFunction(1, 13); //0.0769231

If we, for example call:

cout << TestFunction(1, 13);

we will get a compilation error, stating that the <<operator is ambiguous. Because the << operator expects a type from his right-side argument and our TestFunction expect a type from its left-side. Naturally an expression like:

cout << (float)TestFunction(1, 13);

is perfectly valid.

Of course this approach of overloading by return type, can be combined with the ordinary overloading by signature, by simply introducing a little more advanced logic in our constructor (overloading it, saving which constructor was called,  etc.).

VN:F [1.9.18_1163]
Rating: 0.0/10 (0 votes cast)

How to change the number of suggestions in Firefox address bar

One thing I love about Firefox is the ability to tweak almost every aspect of your browsing experience. Another thing I love about Firefox is that once a tweak is discovered it remains valid in all the later versions. This little tweak I’m about to show you, I discovered in Firefox 3 and remains valid till this very day – Firefox 8.

So basically we will see how we can change the number of suggestions in the Firefox address bar:

And of course as a first step, type about:config in the address bar and press Enter:

Press I’ll be careful, I promise! and you will be redirected to a list of configurations:

In the Filter textbox enter browser.urlbar.maxRichResults

Double click on browser.urlbar.maxRichResults and you will be prompted to enter a new value (default is 12). Enter the new value:

And press OK. Close the about:config tab and you are done. You don’t even need to restart Firefox:

VN:F [1.9.18_1163]
Rating: 0.0/10 (0 votes cast)

Customize the Google country-specific search in Firefox

Perhaps you have noticed that by default google.com redirects you to a country-specific version of google based on your IP. This is extremely noticeable when you are travelling or using a proxy. We will see two solutions to the problem.

The first solution is to type http://www.google.com/ncr in your address bar. This sets a cookie in your browser, which on the other hand tells google not to redirect you. This solution however is not the best, since you completely disable the country-specific search and if you delete your browser cookies you will have to repeat the procedure.

Note: This solution is not Firefox-specific and can be implemented with every browser.

The second solution is a bit more elegant, as it allows you to use multiple country-specific versions of google search, it is not cookie based and it doesn’t change the default behavior of google.com.

The second solution utilizes the Firefox search bar:

By default all searches made from the search bar use google.com, however it can be extended to support multiple country-specific google flavors. Let’s show how we can modify it to use google.de as well.

Of course you may ask “What is the point of that? I can always type google.de in my browser”. True, but by extending the search bar, you can finally have a uniform way for doing searches, which makes searches a lot easier.

But let’s see how we can extend the Firefox search bar. Navigate to the searchplugins subdirectory of the Firefox directory (usually C:\Program Files\Mozilla Firefox\searchplugins). You can see several xml files there:

Copy the google.xml file to google.de.xml. Move google.de.xml to the Firefox profile folder\searchplugins (C:\Users\<your username>\AppData\Roaming\Mozilla\Firefox\Profiles\<your Firefox profile name>\searchplugins on Windows 7)

Now change google.de.xml in such way.

Old:

New:

You can see that we have changed the ShortName, the template argument of the second URL tag and the SearchForm.

Restart Firefox and now you can see Google.DE in your search options:

VN:F [1.9.18_1163]
Rating: 1.0/10 (1 vote cast)

Using *args and **kwargs in Python

Python provides a special syntax for function definitions to allow the usage of variable length argument lists. The syntax is the so called *args and **kwargs. Basically the argument preceded with a single asterisk (not necessarily called args) is used for passing the so called non-keyworded argument list, while the double asterisk is used to pass the keyworded argument list. But let’s show all that in a few examples, shall we?

The following code:

def var_args_function(a, b, *args):
    print('a =', a)
    print('b =', b)
    for i in args:
    print('extra arg =', i)

var_args_function(1, 2, 'arg1', -2, 'three', 'last_one')

Results in this output:

a = 1
b = 2
extra arg = arg1
extra arg = -2
extra arg = three
extra arg = last_one

In the example, our function is passed two normal (or so called positional) arguments and four more arguments, all of which are contained in the args variable. The args variable is actually a tuple, and as any tuple it can be iterated, indexed, etc.

Now what about kwargs?

def var_kwargs_function(a, **kwargs):
    print('a =', a)
    for i in kwargs:
        print('kwargs[%s] = %s' % (i, kwargs[i]))

var_kwargs_function(2, var1=1, var2='two', var3='three')

Results in:

a = 2
kwargs[var1] = 1
kwargs[var3] = three
kwargs[var2] = two

But what is kwargs? It is actually a dict and you can do with it anything you do to a normal dict (yes, including changing it, although that is considered bad practice).

A word about order of the arguments – there are two rules you must follow – non-keworded arguments before keworded and formal arguments before argument lists.

For example:

def f(a, b, c, *args, **kwargs) is OK

but

def f(*args, a, **kwargs, b, c) is NOT OK

A word about positioning of default arguments – consider these two functions:

def f(a, *args, b=17):
    print('Function f got', a, args, b)

def g(a, b=17, *args):
    print('Function g got', a, args, b)

The following calls:

f(2,3,4,5)
f(2,3,4,5,b=8)
g(2,3,4,5)
g(2,3,4,5,b=8)

Result in the following:

Function f got 2 (3, 4, 5) 17
Function f got 2 (3, 4, 5) 8
Function g got 2 (4, 5) 3
Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
    g(2,3,4,5,b=8)
TypeError: g() got multiple values for keyword argument 'b'

Let’s finish with calling a function with args and kwargs:

def var_args_n_kwargs_f(a, *args, **kwargs):
    print('a =', a)
    for i in args:
        print('extra arg =', i)
    for i in kwargs:
        print('kwargs[%s] = %s' %(i, kwargs[i]))

args = (-1, -2, -3, 'onearg')
kwargs = {'key1': 'val1', 'key2': 'val2', 'last_key': 'last_val'}

var_args_n_kwargs_f(13, *args, **kwargs)

Will result in:

a = 13
extra arg = -1
extra arg = -2
extra arg = -3
extra arg = onearg
kwargs[key2] = val2
kwargs[key1] = val1
kwargs[last_key] = last_val

Note: You can pass anything that can be casted to tuple as args and

VN:F [1.9.18_1163]
Rating: 6.3/10 (3 votes cast)

Change the Explorer startup folder in Windows 7

Normally when you open Windows Explorer via the button on the taskbar:

Explorer opens the Libraries by default:

Now, we find this rather strange and useless since the Libraries is not one of the most used directories. So in this short tutorial we will show you how you can change that behavior and choose a more appropriate folder as the default.

To change this, right click on the Explorer button in the Taskbar:

Right click on Windows Explorer and choose Properties:

A new window will open:

As you can notice the target of this shortcut is set to %windir%\explorer.exe

A better alternative to use as your default directory is Computer. To change the default directory to it simply enter %SystemRoot%\explorer.exe /E,::{20D04FE0-3AEA-1069-A2D8-08002B30309D} in the Target text field and click OK.

Now when you click the Windows Explorer button it will open Computer:

Note: Alternatively you can open Explorer properties from Start button > All programs > Accessories > right click on Windows Explorer > Properties:

Another alternative for the default folder of Windows Explorer is My Documents. To set it as default simply set the target to %SystemRoot%\explorer.exe /n,::{450D8FBA-AD25-11D0-98A8-0800361B1103}

Basically you can use any folder as long as you know its Globally Unique Identifier (GUID), but expect more on GUIDs in a different tutorial.

Note: If you want to have some fun, why not change your colleagues’ default location to the Recycle Bin – simply use %SystemRoot%\explorer.exe /E,::{645FF040-5081-101B-9F08-00AA002F954E}

VN:F [1.9.18_1163]
Rating: 5.3/10 (3 votes cast)

Run cron jobs within Django using django-cron

Quite often web applications require cron-like behavior which more or less contradicts with the request-response model.

Not many host providers allow users to create a cron jobs, and even if it is possible, if your site relies on an external script it loses its integrity. It no longer is a website, it is a website relying on cron jobs.

Now at first glance, there is not much difference, but such things make migrating harder and/or may cause a lot of problems in the long run.

As we all know Django is an open source web application framework, designed for rapid development. It follows the so called DRY principle and therefore greatly emphasizes on “pluggability”. In this short tutorial we will show you how to “plug-in” a little but very useful Django application called django-cron, which allows you to easily get cron line behavior.

You can visit the project’s site in at http://code.google.com/p/django-cron

Installation is fairly easy:

  • Download the source
  • Place django_cron on your python path
  • Add “django_cron” in the list of installed apps in your settings.py:
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.admin',
    'django_cron',
)
  • In the beginning of your global urls.py file add:
import django_cron
django_cron.autodiscover()
  • Write your crons in a file named cron.py inside the application you want write crons to. Note: The application must be installed in your settings.py

A cron job is fairly easy to write.

Here is an example cron.py file which deletes old files from a fixed directory:

import os
import time
from django_cron import cronScheduler, Job

class DeleteOldFilesCron(Job):
“””A cron which deletes files older than a minute from a fixed directory”””

    run_every = 60*60*24 # run every day

    def job(self):
        path = ‘/var/www/html/media/tmp/’
        files = os.listdir(path)
        for file in files:
            if(time.time() – os.path.getmtime(path + file) > 60):
                os.remove(path + file)

cronScheduler.register(DeleteOldFilesCron)

Naturally you can have several crons in your cron.py

Note: There are some Apache specific configurations which must be taken into account. For more information visit http://code.google.com/p/django-cron/wiki/Install

VN:F [1.9.18_1163]
Rating: 3.0/10 (2 votes cast)