Saturday 28 December 2013

How to Find Which Accounts Are Potential Spammers in cPanel/Exim

So you’ve discovered that all of a sudden your server load has shot and your email inbox is getting filled up with hundreds of bounce backs. You sir may be spamming! Now if you are a spammer, this isnt really much of a shock.


But if you’re not a spammer you may be wondering what happened. Well odds are your website got hacked or your personal machine has a virus/malware. Now usually if your website gets hacked its because you are using an outdated version of your CMS software. Because wordpress doesn’t auto update and we don’t always login every day (especially if your wordpress just hosts a static website) it can be hard to keep up with the constant updates. And of course in doing so all the little hackers out there are now able to exploit whatever security holes you didn’t patch. On top of this it isn’t just the wordpress core we have to worry about, but also the plugins and the themes. Joomla and drupal and practically all other CMS’s follow the same logic. Keep your apps up to date and your chances of being compromised slim down quickly. What happens though when you are compromised? Usually the attacker places a php file on the server that acts as part of a ddos or a script that sends out a ton of spam. If your personal machine was compromised then whatever application you are running to connect to your email (such as outlook, thunderbird, etc) is usually used (or they just grab any IMAP/SMTP connection info) and use that to start spamming.


Ok, so we know that someone on the server is spamming. We don’t know if its a script or if its because someone’s personal machine got attacked. Lets take a look a couple one liners to help out with this. First, lets look at a command which searches for all external logins (meaning the personal local machine was compromised)



$ exigrep @ /var/log/exim_mainlog | grep _login | sed -n 's/.*_login:(.*)S=.*/1/p' | sort | uniq -c
1 test@example.com
3 info@example.com
59 notaspamer@example.com

So this will exigrep through our mail log and return any line containing an @ (meaning pretty much everything) cut out the dovecot_login or courier_login (whichever one you use) and then sort it and count how many instances there are. In this case you can see that the email account notaspamer@example.com is sending much, much more than the other two email accounts it found. This doesn’t immediately mean that its a spamming account, it could be legitimate of course but it gets you on the right path.


Now lets look at a few one liners for checking which user/account has been hacked:



$ exigrep yahoo /var/log/exim_mainlog | grep U= | sed -n 's/.*U=(.*)S=.*/1/p' | sort | uniq -c
3 user1 P=local
74 user2 P=local

So here the user “user2” is sending the most email on the system so we know that this user is likely responsible for the spam. Lets see if we can track down the script!



grep "cwd=" /var/log/exim_mainlog | awk '{for(i=1;i<=10;i++){print $i}}' | sort |uniq -c| grep cwd | sort -n | grep /home/

Running this will look at any lines in the exam log that contains the “cwd” string. This should help narrow it down the folder where the spam is happening. But we can get even more specific! Note that this command doesn’t have as high of a success rate as the previous ones but when it works it saves so much headache.



grep X-PHP-Script /var/spool/exim/input/*/*-H | awk '{print $3}' | sort | uniq -c | sort -nr

Now unlike the others this actually searches the active email queue. So if you have hundreds or thousands of email queued up (and you can check this by running exam -bpc) this should work. It looks for the X-PHP-Script field in the header of the emails. This should be enabled by default in cpanel, if not it can be enabled in the whm. But anyways this should again sort and count exactly which script sent the email! Pretty cool, right!

Friday 20 December 2013

How to Install an SSL Certificate on a Shared IP

It was kind of annoying in the midst of cPanel 11?s release when cPanel discontinued the ability to install an SSL certificate on a shared IP.  Sure, you can do it as ‘nobody’, but this tends to mess up things when you have open_basedir set up or you’re using suPHP. Sometimes you might not have another IP to use, or you’re using an IP-based monitoring system and don’t want to complicate things. I, personally, prefer to install my shared SSL certificates on the shared IP. But that’s just me…and I’m right about everything.


There is a crafty way to get around this limitation, though it does require root access and it can be a little tedious when it’s something you have to do on a normal basis. Come on cPanel, just let us do this again so we don’t have to keep coming up with workarounds. I assume at this point that you already know how to use WHM to install a certificate, and you’re aware that the hostname for the certificate has to correspond with a user already on the server.


First, hop into WHM ~> Install a SSL Certificate and Setup the Domain and install the SSL normally, BUT, in the user field, put ‘nobody’ and finish the installation.


Now that the certificate is installed, you need to force cPanel to accept its fate to allow a shared SSL on the main IP. Go into /var/cpanel/userdata and run the following commands, noting that $user should be replaced with the username owning the SSL domain, $ssldomain.



mv nobody/$ssldomain_SSL* $user/

replace nobody $user — $user/*

Then edit ./nobody/main and remove the SSL domain from the sub_domains list, and run /scripts/rebuildhttpdconf to rebuild the Apache configuration, then restart Apache for the changes to take effect. Voila.


IF this is a shared SSL certificate (meaning, other users on the server can call it via https://$ssldomain/~$user):


You’ll want the SSL to show as the shared certificate on the server, which you can either select from the dropdown in WHM ~> SSL Hosts, or run:



echo $sslhostname > /var/cpanel/.sharedcrtname

If you use mod_php with open_basedir, and/or you have mod_userdir enabled, you need to exclude the user ‘owning’ the SSL certificate from both, to allow other sites on the server to use its certificate. These can both be set in WHM ~> Security Center

Thursday 19 December 2013

ChkRootKit Installation

About Chkrootkit


chkrootkit is a collection of tools to detect the presence of rootkits, and is a gift to Linux systems administrators for two specific reasons:

  1. it is a free, open source utility, and available for multiple distros,

  2. it detects almost all the latest rootkits out there, since the open source community of contributors keeps it up to date.


Over time, the Chkrootkit scan engine has also improved, making it faster, which is especially useful in performing detailed kernel checks against a number of supported kit detections.

A few great features of chkrootkit are that it detects more than 60 old and new kits, is capable of detecting network interfaces in promiscuous mode, can efficiently detect altered lastlog and wtmp files (which in turn alerts admins about intrusions), has easy command-line access with straightforward options, and has a verbose output mode to help admins automate tasks.

chkrootkit uses C and shell scripts to perform a detailed process check, and scans systems binaries to detect kit signatures. Upon detection, in most cases, it can remove rootkits too. It also has a few algorithms that can report trends of a possible rootkit, even if it is not yet officially supported. The following lists the chkrootkit internal programs and what each of them do.





























chkrootkit ProgramPurpose
chkrootkitMain script to check for tampered system files
strings.cDetects and performs string replacement
ifpromisc.cChecks network interface for promiscuous mode
chklastlog.c, chkwtmp.cChecks if lastlog and wtmp entries are deleted
chkproc.c, chkdirs.cChecks for Linux kernel module-based Trojans

Installation

Follow these steps to install ChkRootKit

cd /usr/local/src/

– Down load the chkrootkit.
# wget http://www.spenneberg.org/chkrootkit-mirror/files/chkrootkit.tar.gz
# wget ftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz

- Unpack the chkrootkit you just downloaded.
# tar -xvzf chkrootkit.tar.gz

- Change to new directory
# cd chkrootkit-*
(select the version )

- Compile chkrootkit
# make sense

- Run chkrootkit
# ./chkrootkit

How to setup a daily scan report?

- Load crontab
# crontab -e

- Add this line to the top:
===============================================================>
0 1 * * * (cd /usr/local/src/chkrootkit*; ./chkrootkit 2>&1 | mail -s “chkrootkit output” email@domain.com)
===============================================================>

Monday 16 December 2013

Fixing rndc error in WHM/cPanel (ndc: connection failed: connection refused)

It is quite a common occurrence in cPanel to receive such an error as rndc:
connect failed: connection refused

To get your name servers working, you will need to eliminate this error, it
is quite a simple fix and can be completed in a few minutes via the
standard cPanel /scripts
1. Login to your server as root via SSH
2. Run: /scripts/updatenow
3. Run: /scripts/fixndc

This will fix your problems some of the time, but if it does not, do the
following steps:
1. Login to your server as root via SSH
2. Run: vi /etc/rndc.conf (or vi /etc/namedb/rndc.conf on FreeBSD)
replace all instances of "rndc-key" with "rndckey"
3. Run: vi /etc/named.conf (or vi /etc/namedb/named.conf on FreeBSD)
replace all instances of "rndc-key" with "rndckey"
4. Run: /scripts/fixnamed
5. Run: /scripts/fixndc
6. If you received an error in the last step, run /scripts/fixndc another
time.
7. Restart named (on RH this is service named restart)

If you are still having issues, try checking out the cpanel forums, or
contact cpanel support for more help.

Saturday 14 December 2013

Helpful Exim Commands

1. To check the number of emails present in the queue:# exim -bpc2. To check the emails present in the queue with the mail id and sender ID:# exim -bp
# exim -bp | less

3. To view the header of a particular email using mail ID:

# exim -MvH mail_id

4.  To view the body of a particular email using mail ID:

# exim -Mvb mail_id

5. To view a message's logs:

# exim -Mvl mail_id




  1. To trace path:



exim -d -bt user@domain.com




  1. To get sorted list of email sender in exim queue:



exim -bpr | grep "<" | awk {'print $4'} |cut -d "<" -f 2 | cut -d ">" -f 1 | sort -n | uniq -c| sort -n




  1. To check the script that will originate spam mails:



grep "cwd=" /var/log/exim_mainlog|awk '{for(i=1;i<=10;i++){print $i}}'|sort| uniq -c|grep cwd|sort -n




  1. If we need to find out exact spamming script. To do this, run following command:



ps auxwwwe | grep user | grep --color=always "/home/user/public_html/templates/" | head



10.  To delete the emails of a specific user:

grep -lr 'user@domain.com' /var/spool/exim/input/ | sed -e 's/^./([a-zA-Z0-9-])-[DH]$/1/g' | xargs exim -Mrm



exim -bp | grep "user_email-account" | awk '{print $3}' | xargs exim -Mrm




  1. To delete Frozen emails from the email queue:



grep -R -l '*** Frozen' /var/spool/exim/msglog/*|cut -b26-|xargs exim -Mrm



exim -bp| grep frozen | awk '{print $3}'| xargs exim -Mrm



exiqgrep -z -i | xargs exim -Mrm



12.  To delete Spam emails from the email queue:

#  grep -R -l [SPAM] /var/spool/exim/msglog/*|cut -b26-|xargs exim -Mrm


  1. To check the no. of frozen mails:



exiqgrep -z -c




  1. To check exim logs:



tail -f /var/log/exim_mainlog




  1. Force delivery of one message:



exim -M mail_id




  1. Force another queue run:



exim -qf




  1. Force another queue run and attempt to flush frozen messages:



exim -qff



Precautions:
1)Turn on the SMTP tweak. It will block the users to bypass the mail server for sending out spam.
2)Turn on blacklisting ability in whm.
3)Use spamassassin to stop receiving spam mails.

Friday 13 December 2013

Backup a Database using Management Studio

If you are a VPS or Dedicated Server customer running SQL Server on your Server, this article will walk you through how to backup a database and make a copy of a database using Management Studio Express.



Step 1


You will first need to connect to your database server, using SQL Server Management Studio Express. Please see our article “How to connect to a database using SQL Server Management Studio Express” if you require assistance with this.

For this example, we will backup the database named “backmeup” to our “C:backup” folder.

Once connected to your database server, you will need to browse to your database in the left window pane of Management Studio.

Right Click on your database, and under “Tasks” choose “Back Up…
le_sqlbackup_ms1










Step 2


A new window will open where we will configure where to save the database backup file.

You will want to ensure that the “Backup type” is set to “Full” to get a Full backup of your database.

Now, highlight the Destination file that is already in the list by clicking on it, and Click “Remove“.
le_sqlbackup_ms2











Step 3


Now, Click “Add…” to specify where to save the backup file.
le_sqlbackup_ms3







 

Step 4


A window will pop up, asking you where to save the backup file. Enter a location of your choice. For this example, we will save it to “C:Backupbackmeup-Full-041608.bak“.

Note that this is the entire actual filepath.
le_sqlbackup_ms4











Step 5


Now, we have to make sure that the backup you are creating overwrites all existing backup sets, as appending it to an existing set can cause conflicts when attempting to perform a restore. On the left-hand side of the window, click on ‘Options‘, and then click on ‘Overwrite all existing backup sets‘.
le_sqlbackup_ms5











Step 6


Once this option is in place, all that is left to do is to run the backup! Click “OK” to begin the database backup.
le_sqlbackup_ms6







Step 7


If the database backed up successfully, you should receive a message as pictured below.

le_sqlbackup_ms7

 

 

 

 

 

 

 

 

 

 

 

If at any point you require assistance, please do not hesitate to contact your Technical Support team!

Thursday 12 December 2013

Installing CSF on Linux Server (ConfigServer Firewall)

This guide will walk you through installing CSF on a VPS/Dedicated server.

Preparing the server



After logging in via SSH (as root!) we will need to download the CSF firewall itself, let's make a temporary directory called "tmp" first and then move into it and download latest version of CSF:

mkdir tmp
cd tmp
wget http://configserver.com/free/csf.tgz


Once CSF is downloaded, we will need to extract the archive containing it and move into the directory it creates:

tar xf csf.tgz
cd csf


We are now ready to install CSF.

Installing CSF on a server with cPanel



CSF includes integration with control panels such as cPanel, in order to install it for a cPanel based server, we would execute the install script that is meant for cPanel.

./install.cpanel.sh


Installing CSF on a server without cPanel



If you do not have cPanel on your server and would still like to install CSF, you can certainly do so. Execute the following command:

./install.sh


Configuring CSF - allowing ports



Configuring your firewall is required for it to function correctly. Let's open the CSF configuration file:

nano /etc/csf/csf.conf


To turn the firewall on, inside the editor, navigate down until you see TESTING="1" and change it to TESTING="0".

All blocks are commented inside (a comment is a line that starts with a #) for you to understand what each section does, for example to add a incoming TCP port to the allow list, we would edit this variable:

TCP_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995,2077,2078,2082,2083,2086,2087,2095,2096"


To allow incoming MySQL connections we would add 3306 to the list:

TCP_IN = "20,21,22,25,53,80,110,143,443,465,587,993,995,2077,2078,2082,2083,2086,2087,2095,2096,3306"


When you make the changes, hit CTRL+X to exit the editor and press Y when it asks you if you want to overwrite the file.

Don’t forget to:


  1. Configure the TCP_IN, TCP_OUT, UDP_IN and UDP_OUT options in the csf configuration to suite your server

  2. Restart csf and lfd


  3. Set TESTING to 0 once you’re happy with the firewall




CSF is preconfigured to work on a cPanel server with all the standard cPanel
ports open. It also auto-configures your SSH port if it’s non-standard on
installation.

You should ensure that kernel logging daemon (klogd) is enabled. Typically, VPS
servers have this disabled and you should check /etc/init.d/syslog and make
sure that any klogd lines are not commented out. If you change the file,
remember to restart syslog.

Now – login to your cPanel server’s WHM as root and go to the bottom  left menu. If already logged in then reload the page. In Plugins – you  will see: ConfigServer Security Firewall
The firewall is STOPPED by default – it is not running. We need to configured it, and then take it out of Test Mode.

Click on Firewall Configuration

ETH_DEVICE =: Set this to eth+

TCP_IN/TCP_OUT/UDP_IN/UDP_OUT  = : These are the ports you want to leave open for your server to  operate. If you change the default SSH port make sure to add it here.  Also add any other services you might have running such as Shoutcast or  game servers. By default most of the ports used should already be  configured.

MONOLITHIC_KERNEL = : 0 Only change this to 1 if your firewall will not start – otherwise leave it as it.

LF_DSHIELD  = 0: Change this option to 86400. This is an automatic updated list of  known attacking IPs. Enabling this will stop them from being able to  connect to your server.

Spam Protection Alerts
If you want to add some spam protection, CSF can help. Look in the configuraiton for the following:

LF_SCRIPT_ALERT  = 0 change this to 1. This will send an email alert to the system  administrator when the limit configured below is reached within an hour.

LF_SCRIPT_LIMIT = 100 change this to 250. This will alert you when any scripts sends out 250 email messages in an hour.

Configuration Complete – Almost
Scroll down to the bottom and click on Change to save the settings. Then click Restart csf+lfd

You should see a big page of ACCEPT and near the bottom you should see:

csf: TESTING mode is enabled – don’t forget to disable it in the configuration
Starting lfd:[  OK  ]

Click on Return

Now TEST all your services to make sure  everything is working – SSH, FTP, http. After you do a few quick tests  go back into the Firewall Configuration page.

TESTING = 1 change this to 0 and click Change at the bottom. Then Restart csf+lfd

That’s it, the firewall is successfully installed and running!!

Firewall Status: Running – you should see this on the main CSF page in WHM.

Uninstallation



Removing csf and lfd is even more simple:

cd /etc/csf
sh uninstall.sh


 

How to change main hostname and IP of WHM/cPanel machine

One thing you’ll probably run into sometime is changing the hostname and IP address of a cPanel machine.. whether you’re cloning it for a quick start or if you’ve taken it over.. moving it to a different datacenter, etc..


This is based on CentOS 6…

First, grab a license for the new IP address you’re going to use..

Next, edit the following files with the new information and restart the network:
/etc/sysconfig/network-scripts/ifcfg-eth0
/etc/sysconfig/network

Next, remove /etc/.whostgrft (this will restart the cpanel setup screen)
Next, edit /etc/wwwacct.conf

Log into whm as root and run through the setup..
Next, run /scripts/rebuildhttpdconf

Afterwards, you’ll find some other files that still may have old info.. here are some:
/etc/hosts
/etc/localdomains
/etc/mail_reverse_dns

You might still see old info in the httpd.conf file, so manually edit it and run:

/usr/local/cpanel/bin/apache_conf_distiller –update
If you come across other changes that need to be made, please comment below!

Server Setup & Configuration - cPanel / WHM

Steps to Install CPANEL on your VPS or Dedicated Server


Make sure that your VPS server has enough resources to be able to run cPanel. Minimum of 512 MB of memory to run Cpanel (1GB is recommended).


Before installing Cpanel, its good to setup a basic clean compile environment and get your server up to date with the latest patches and software updates.


[root@server1 /]#  yum install selinux coreutils binutils make dialog gcc gcc-* glib*
[root@server1 /]#  yum install libexi* libjpe* libpng* gifl* freetype curl curl-* xmlrpc
[root@server1 /]#  yum upgrade kernel*
[root@server1 /]#  yum update


Once you got the basics, time to install Cpanel/WHM:


[root@server1 /]#  cd
[root@server1 /]#  wget http://layer1.cpanel.net/cpanel-universal-install.sea
[root@server1 /]#  chmod 700 ./cpanel-universal-install.sea
[root@server1 /]#  ./cpanel-universal-install.sea


(The above will take you 30 minutes to an hour or so to finish)


After you have the base install done, it would be a good idea to run the 'checkperlmodules' a couple of times at least until it runs clean without trying to compile new modules so that you get all the required Perl modules you need to run Cpanel properly installed on your server:


[root@server1 /]#  /scripts/checkperlmodules


(Typically needs to be run about 3 times till it runs clean)


Once you have Cpanel installed, connect to WHM and go through the initial setup wizard to setup your server hostname, licensing, DNS servers, IP addresses, etc:


http://(your server primary IP):2086/


That's the basic rundown!


At this point, you will have a basic copy of Cpanel installed but it won't be configured or optimized and your system won't have any security hardening, configurations, or optimizations either. To do that properly, you will have another couple hours of work ahead of you if you are experienced (a couple of days if you aren't) to get things fully setup and working properly the way they should.

Tuesday 10 December 2013

Linux Maldet - Installation

This guide will help you through installing LMD (Linux Malware Detect) on your VPS or Dedicated servers
You will need to be logged in as root to the server over SSH.
Let's create a temporary directory and navigate into it, followed by downloading the latest release of maldet:



# mkdir tmp
# cd tmp
# wget http://www.rfxn.com/downloads/maldetect-current.tar.gz

Extract the archive containing LMD and navigate into the directory it creates:



# tar xf maldetect-current.tar.gz && cd maldetect-*

Warning: Version may vary, you can check the current directory listing with the command `ls` Once you're inside execute the install script:



#  ./install.sh

This will automatically install a cronjob inside /etc/cron.daily/maldet as well, it will make LMD execute daily and scan local cPanel accounts for possible malware.
Usage is fairly simple, to scan user's home directory or any other directory you would simply execute:



#      maldet -a /home/user

Any path is alright. Please note that LMD runs great with ClamAV.


Setting up e-mail alerts
LMD has an option to alert you each time it detects malware, please review these configuration variables inside /usr/local/maldetect/conf.maldet
variable     value     description
email_alert     1 or 0     enable or disable e-mail alerts
email_addr      e-mail address      target e-mail for notifications, should be put in quotes like: "root@domain.com"
Other configuration variables that you should look into:
variable     value     description
quar_hits     number     if the number is different than 0, enables automatic quarantine
maxfilesize      size      makes LMD skip files larger than set size, for example "512k" (512 K


Friday 6 December 2013

SSH - PuTTYgen

In the interest of security, remote login into our Unix/Linux machines is only allowed over cryptographically protected connections using the secure shell (SSH) protocol, even where the connection remains within the department.

Our commonly used Windows SSH client software is PuTTY. When installing, always use the latest version. Especially if you use a version older than PuTTY 0.61, we strongly recommend that you upgrade now to benefit from Kerberos support.

Installation

If you are on a Lab-managed Windows machine and the latest version of PuTTY is not yet available, then you can install it yourself (even without an Administrator account) via the Systems Management “Advertised Programs” installer, or via \didcotswdistputty.

The installer may manifest itself as a small white rectangle in your task bar; otherwise, get to it via: Start Menu | Settings | Control Panel | Advertised Programs.

Basic configuration

The PuTTY installer places an icon on your desktop ("Shortcut to PuTTY", an image of two computers suffering a mutual lightning strike). When you start it up, you will see a small “PuTTY Configuration” window.



In there, for convenience, you should save all the PuTTY settings needed to talk to a particular server as a “Session”. The following example shows this for one of the Lab's main Linux SSH servers: “ssh-remote-0.cl.cam.ac.uk”.

Under “Category” select “Session” (you probably are already there).
In the “Host Name (or IP Address)” box, type: “ssh-remote-0.cl.cam.ac.uk”
Also check that you have “Port 22” and “Protocol: SSH”
Type a name for your session configuration into the “Saved Sessions” box, (e.g., “cl” or “ssh-remote-0”).
Click “Save”
Under “Category”, select “Windows | Translation” and choose the “UTF-8” character encoding.
Under “Category”, select “Connection | Data”. Enter your Unix login name (CRSID) into the “Auto-login username” field, or alternatively make sure that “When username is not specified: Use system username (your-crsid)” is selected. [This will avoid that you have to type in you user name each time.]
set auto-login username

Under “Category” select “Connection | SSH | Tunnels”:


In the box “X11 forwarding” tick “Enable X11 forwarding”. (This option, together with running an X11 server such as that provided by MobaXterm, XMing (both avaiable as free versions or eXceed, will allow your Unix applications to open windows on your Windows PC.
Under “Category” select “Connection | SSH | Auth | GSSAPI”:
Kerberos session

Make sure that both “Attempt GSSAPI authentication” and “Allow GSSAPI credential delegation” are selected. [This means that if your Windows machine has already a valid Kerberos ticket from our Active Domain controller, both authentication and forwarding of the Kerberos ticket such that the Linux server can access your home directory will all just work automatically.]
Under “Category” go back to “Session” and click “Save” once more.
Public/private key authentication

If you can use Kerberos/GSSAPI authentication (as configured above), then there is usually no need to configure ssh public keys. Your login will work fine without.

Kerberos authentication will not work in two situations:

You use a Windows computer where you have not logged into the AD.CL.CAM.AC.UK Kerberos domain, for example a private computer not managed by the Lab.
You are setting up TortoiseSVN with PuTTY to access a Subversion repository for editing the Lab’s website.
In both cases, you will have to generate an SSH public/private key pair, which PuTTY can then use to authenticate your identity during login. The generated private key must be made available to PuTTY, usually via starting the Pageant tool. The generated corresponding public key must be appended in your Linux home directory to the file “.ssh/authorized_keys”.

The following description explains two options for duing this in more detail.

On Linux

On a lab Linux machine, run the command: “ssh-keygen -t rsa”

This will create a public/private key pair and leave them in your filespace under Linux. Please ensure you use a secure pass phrase to protect this.

This has the side effect of creating a .ssh subdirectory structure in your home directory, where the key pair will be stored. You will find the newly generated public key in “~/.ssh/id_rsa.pub”; copy it.

Then “cd ~/.ssh” and edit “authorized_keys”, pasting the public key into a new line on its own. Just as detailed below you will need to add a section saying where the key can be used from, which should be as specific as possible. The end result should look like:

from="*.cl.cam.ac.uk" ssh-rsa AAAAB3NzaC1yc2EAAAADA […] onHiVNh0IkKift27RZL1 spqr1@example.cl.cam.ac.uk

On Windows



On a Windows machine, run “Puttygen” from the “Putty” Start Menu programs group.
Click on the “Generate” button.
Move the cursor continually over the blank space, as instructed, to generate a random key.
In the Key_comment box, replace any text with your own identifier, i.e. @cl.cam.ac.uk (see the image example below).
Set a passphrase. (This can be a password or a phrase.)
The key is the text that appears in the box below Public key for pasting into OpenSSH authorized_keys file:; copy that. Do not click Save public key and use the contents of the resulting file; that will not work.

Saving the public key

If this file does not exist then navigate to “\fileruserfiles
unix_home.ssh” and create a new file called “authorized_keys” (taking care not to leave it with a .txt suffix).
Click here if directory does not exist.

Note: If you are setting up keys for use with Subversion and Tortoise, email this public key to pagemaster.
Please ensure you give the Key comment field a meaningful name
i.e your CRSID, as shown in the example above.

Paste the public key into an empty line at the bottom of the file. Then, in front of the public key on that line, you need to state where the key can be used from, i.e on which domain. This needs to be as specific as possible. So for a lab managed machine, type:

“from="*.cl.cam.ac.uk"”

or for a laptop using Eduroam within Cambridge

“from="*.cam.ac.uk"”

followed by a space as shown in the example below:



Save the file

If the directory does not exist:

Map a drive to “\fileruserfiles
unix_home”
Run a command Window (Type “CMD” in Start, Run).
Change to the new drive letter you have just mapped.
Type “mkdir .ssh” to create the .ssh directory.
You can now create the “authorized_keys” file.
Back to Saving Public key

from="*.cl.cam.ac.uk"


Save the file

Saving the private key

You now need to save the private key to your local disc:

Click on the “Save private key” button.
Save the file locally on your PC. A logical place is in the Start->All Programs->Startup area of YOUR login under Documents and Settings. When it is saved here, “Pageant” (the program that activates your encryption keys) is set to run at start up everytime you (and only you) login to that PC.
(Note: For laptop use, you should have a different key on each machine, which is easily identifiable in case of loss.

Troubleshooting and refinements

The above represents the basic necessities for getting the setup working.

If you have suggestions to improve the arrangements, please contact the Windows administrators.

Other areas of the “PuTTY” configuration window allows you to alter the colour scheme, and so on. Remember to “Load” your session before making your changes, and “Save” your session afterwards.

If you are experiencing trouble logging into PuTTY, you may want to change the PuTTY settings so the Unix shell window doesn't close automatically, but logs the results of what happens, so you can send to a Windows Administrator:

Changing window settings:

Load your session (i.e “Computer lab”, which was our earlier example).
Under “Category”, select “Session”
Under “Close window on exit”, select the appropriate radio button, i.e. “Never”
Save your session.
Setting up Logging:

Load your Session.
Under “Category”, select “Session, Logging”.
Under “Session logging:”, select the appropriate radio button, i.e. “Log all session output”.
Under “Log file name:”, browse to a suitable location to save the logfile and give the logfile a name.
Under “What to do if the log file already exists:”, select the appropriate radio button, i.e. “Always append to the end of it”.
Save your session.
"No Supported authentication methods" error

When setting up PuTTY you may experience the above error message.

One possible cause is that the domain you have specified in the “authorized_keys” file and the domain your computer believes it resides in are not the same.

To resolve this issue, try whether you can login after removing the “from="*.cl.cam.ac.uk"” prefix from your authorized_keys file temporarily.

If so, then lookup your computer’s domain name:

Right click “My Computer” and select “Properties”
Click on the “Computer Name” tab. Here you will see your domain, i.e. “cl.cam.ac.uk”.
The domain written as part of the “from=” command in the “authorized_keys” file should match the domain listed here under the “Computer Name” tab.
Edit “authorized_keys” accordingly, save it, and try another PuTTY session.
If this still does not resolve your issue, it could be an absence of a reverse mapping of your IP address. You will need to contact a Windows administrator for further help.

How To Create SSH Keys with PuTTY to Connect to a VPS

Benefits of Public & Private SSH Keys





If your headless, or remote, VPS is visible over the Internet, you should use public key authentication instead of passwords, if at all possible. This is because SSH keys provide a more secure way of logging in compared to using a password alone. While a password can eventually be cracked with a brute-force attack, SSH keys are nearly impossible to decipher by brute force alone. With public key authentication, every computer has (i) a public and (ii) a private "key" (two mathematically-linked algorithms that are effectively impossible to crack).

Today, OpenSSH is the default SSH implementaion on Unix-like systems such as Linux and OS X. Key-based authentication is the most secure of several modes of authentication usable with OpenSSH, such as plain passwords and Kerberos tickets. Other authentication methods are only used in very specific situations. SSH can use either "RSA" (Rivest-Shamir-Adleman) or "DSA" ("Digital Signature Algorithm") keys. Both of these were considered state-of-the-art algorithms when SSH was invented, but DSA has come to be seen as less secure in recent years. RSA is the only recommended choice for new keys, so this tutorial uses "RSA key" and "SSH key" interchangeably.

When you log in to your DigitalOcean VPS, the SSH server uses the public key to "lock" messages in a way that can only be "unlocked" by your private key. This means that even the most resourceful attacker cannot snoop on, or interfere with, your session. As an extra security measure, some users and most SSH programs store the private key in a passphrase-protected format, to provide a window of time in which you can disable your compromised public key, should your computer be stolen or broken in to. For these reasons, public key authentication is a much better solution than passwords for most people. In fact, by not employing a passphrase on your private key, you will have the ability to automate parts of your configuration management with secure, automatic log-ins, such as incremental off-site backups, manage your DigitalOcean assets via the DigitalOcean API, and more.



Key-Based SSH Logins


You can save the same public key on as many cloud servers as you'd like, while your private key is saved on a client from which you log in to the server. Then, you can disable the normal username/password login procedure, which means that only people with a valid private/public key pair can log in; making your system more secure, because it will be impervious to brute-force attacks.



Automate the Creation of New Droplets


Another useful purpose that SSH keys can serve is in the creation of DigitalOcean droplets. As you know, when you spin up a droplet, you have to wait for an e-mail with your password. Although this email is very convenient, there is a more secure (and faster) way of gaining access to your new cloud server without the need for email. This can be done by saving your public key in the DigitalOcean Control Panel. To accomplish this:





  • First complete the section in this tutorial titled Generating OpenSSH-compatible Keys for Use with PuTTY.






  • Then, skip to Step Three of How to Use SSH Keys with DigitalOcean Droplets.


Prerequisites


This tutorial assumes that you are familiar with DigitalOcean's guide on How to Log Into Your Droplet with PuTTY (for windows users).







PuTTY Key Generator (a.k.a. PuTTYgen)





While PuTTY is a client program for SSH (in addition to Telnet and Rlogin), it is not a port of or otherwise based on OpenSSH. Consequently, PuTTY does not have native support for reading OpenSSH's SSH-2 private key files. However, PuTTY does have a companion named PuTTYgen (an RSA and DSA key generation utility), that can convert OpenSSH private key files into PuTTY's format; allowing you to connect to your cloud server from a Windows machine, with the added security that SSH keys provide.

PuTTYgen is a (free) open-source utility and can be downloaded from the maintainer's website. PuTTYgen is what you will use to generate your SSH keys for use in PuTTY. To start, all you need to do is download the exectuable files (.exe) and save them on the computer that you'll use to connect to your VPS, e.g. on the desktop. You will not need to "install" PuTTYgen, because it is a standalone application.



Generating OpenSSH-compatible Keys for Use with PuTTY





To generate a set of RSA keys with PuTTYgen:





  1. Start the PuTTYgen utility, by double-clicking on its .exe file;







  1. For Type of key to generate, select SSH-2 RSA;







  1. In the Number of bits in a generated key field, specify either 2048 or 4096 (increasing the bits makes it harder to crack the key by brute-force methods);







  1. Click the Generate button;







  1. Move your mouse pointer around in the blank area of the Key section, below the progress bar (to generate some randomness) until the progress bar is full;







  1. A private/ public key pair has now been generated;







  1. In the Key comment field, enter any comment you'd like, to help you identify this key pair, later (e.g. your e-mail address; home; office; etc.) -- the key comment is particularly useful in the event you end up creating more than one key pair;







  1. Optional: Type a passphrase in the Key passphrase field & re-type the same passphrase in the Confirm passphrase field (if you would like to use your keys for automated processes, however, you should not create a passphrase);







  1. Click the Save public key button & choose whatever filename you'd like (some users create a folder in their computer named my_keys);







  1. Click the Save private key button & choose whatever filename you'd like (you can save it in the same location as the public key, but it should be a location that only you can access and that you will NOT lose! If you lose your keys and have disabled username/password logins, you will no longer be able log in!);







  1. Right-click in the text field labeled Public key for pasting into OpenSSH authorized_keys file and choose Select All;






  1. Right-click again in the same text field and choose Copy.



NOTE: PuTTY and OpenSSH use different formats for public SSH keys. If the SSH Key you copied starts with "---- BEGIN SSH2 PUBLIC KEY ...", it is in the wrong format. Be sure to follow the instructions carefully. Your key should start with "ssh-rsa AAAA ...."



Save The Public Key On The Server





Now, you need to paste the copied public key in the file ~/.ssh/authorized_keys on your server.





  1. Log in to your destination server; see How to Log Into Your Droplet with PuTTY (for windows users)







  1. If your SSH folder does not yet exist, create it manually:



mkdir ~/.ssh
chmod 0700 ~/.ssh
touch ~/.ssh/authorized_keys
chmod 0644 ~/.ssh/authorized_keys





  1. Paste the SSH public key into your ~/.ssh/authorized_keys file (see Installing and Using the Vim Text Editor on an Cloud Server):



sudo vim ~/.ssh/authorized_keys





  1. Tap the i key on your keyboard & right-click your mouse to paste.






  1. To save, tap the following keys on your keyboard (in this order): Esc:wqEnter.


Create a PuTTY Profile to Save Your Server's Settings





In PuTTY, you can create (and save) profiles for connections to your various SSH servers, so you don't have to remember, and continually re-type, redundant information.





  1. Start PuTTY by double-clicking its executable file;







  1. PuTTY's initial window is the Session Category (navigate PuTTY's various categories, along the left-hand side of the window);







  1. In the Host Name field, enter the IP address of your VPS or its fully qualified domain name (FQDN); see How to Set Up a Host Name with DigitalOcean







  1. Enter the port number in the Port field (for added security, consider changing your server's SSH port to a non-standard port. See Step Five of Initial Server Setup with Ubuntu 12.04







  1. Select SSH under Protocol;







  1. Along the left-hand side of the window, select the Data sub-category, under Connection;







  1. Specify the username that you plan on using, when logging in to the SSH server, and whose profile you're saving, in the Auto-login username field;

  2. Expand the SSH sub-category, under Connection;







  1. Highlight the Auth sub-category and click the Browse button, on the right-hand side of the PuTTY window;







  1. Browse your file system and select your previously-created private key;







  1. Return to the Session Category and enter a name for this profile in the Saved Sessionsfield, e.g. user@123.456.78.9 or user@host.yourdomain.tld;






  1. Click the Save button for the Load, Save or Delete a stored session area.



Now you can go ahead and log in to user@1.2.3.4 and you will not be prompted for a password. However, if you had set a passphrase on your public key, you will be asked to enter the passphrase at that time (and every time you log in, in the future).



Disable Username/Password Logins





Once you have verified that your key-based logins are working, you may elect to disable username/password logins to achieve better security. To do this, you need to edit your SSH server's configuration file. On Debian/ Ubuntu systems, this file is located at/etc/ssh/sshd_config.



sudo vim /etc/ssh/sshd_config


Tap the i key on your keyboard and edit the lines, referenced below:



[...]
PasswordAuthentication no
[...]
UsePAM no
[...]


To save, tap the following keys on your keyboard (in this order): Esc:wqEnter. Now, reload the SSH server's configuration:



sudo reload ssh

Thursday 5 December 2013

BRINGING UP LOOPBACK INTERFACE: RTNETLINK answers: File exists / OPERATION NOT SUPPORTED

One of our VPS suddenly not showing when running the command ifconfig Also while restarting network, I was getting the following error.

OpenVZ – RHEL/CentOS 6.5 Container Networking Bug

No active network interfaces:

[root@vps ~]# ifconfig
[root@vps ~]#


 [root@vps ~]# /etc/init.d/network restart
Shutting down loopback interface:                          [  OK  ]
Bringing up loopback interface:  RTNETLINK answers: Operation not supported
Failed to bring up lo.
[FAILED]
Bringing up interface venet0:  RTNETLINK answers: Operation not supported
Failed to bring up venet0.
[FAILED]
RTNETLINK answers: File exists
RTNETLINK answers: File exists
RTNETLINK answers: File exists
RTNETLINK answers: File exists
RTNETLINK answers: File exists
RTNETLINK answers: File exists
RTNETLINK answers: File exists
RTNETLINK answers: File exists
RTNETLINK answers: File exists


Fix : The issue was with iproute package. The package got updated automatically and it was not excluded in yum updates. To fix the issue, you need to downgrade the package iproute.


How to solve (CentOS 6 64Bit):

Until the OpenVZ developers create an official fix, you can downgrade the iproute package as follows:

1. From your OpenVZ Hostmachine, download the old RPM:

[root@vps ~]#  wget http://repo.smartservermanagement.com/misc/iproute-2.6.32-23.el6.x86_64.rpm


2. Copy this inside the container:
[root@vps ~]#  cp /root/iproute-2.6.32-23.el6.x86_64.rpm /vz/private/<CTID>/root/


3. Console into the VPS, forcefully remove the current iproute package, and replace with old one:

[root@vps ~]#  vzctl enter <CTID>
[root@vps ~]#  rpm -e iproute-2.6.32-31.el6.x86_64 –nodeps
[root@vps ~]# rpm -ivh /root/iproute-2.6.32-23.el6.x86_64.rpm


4. Restart the network service

[root@vps ~]# service network restart


Don’t forget if you have automated yum updates configured (e.g. cPanel does this), add iproute* to the exclude= line in /etc/yum.conf for the time being.

Wednesday 4 December 2013