Sunday 27 February 2011

Securing SSH


Requirements


An SSH server should already be installed and running. If it is not, do the following:


yum install openssh-server
/etc/init.d/sshd start


Doing the Work


Most of the steps below involve editing the global SSH server configuration file located at /etc/ssh/sshd_config, and the access control tcpwrapper configuration files /etc/hosts.allow and /etc/hosts.deny. Use your favorite editor to modify these files as root.


Summary of Steps:


Some or all of the following steps may be taken to secure your SSH server. The steps are sorted roughly in order of entirely sensible precaution to completely paranoid:

  1. Choose a strong password
  2. Install "DenyHosts" to auto-block bad clients
  3. Change the default port
  4. Disable insecure Protocol 1; allowing only Protocol 2
  5. Disable root login
  6. Reduce MaxStartups
  7. Reduce LoginGraceTime
  8. Allow only specific users or groups to connect
  9. Allow only specific IP addresses to connect
  10. Allow only users with keys to connect; no passwords allowed
  11. Bind the ssh server to a specific network interface


Steps Explained:



If you do nothing else, it is of utmost importance to choose strong passwords for all accounts, especially root, since it is the #1 attacked account. It is very enlightening to see the accounts on your system that attackers have been targeting lately; to do this either use the lastb command to quickly see recent failed logins of all types, or, better, parse /var/log/secure to get stats only for failed ssh logins. Three examples:

[root@nano ~]# ### top 5 most recently attacked accounts
[root@nano ~]# lastb | awk '{print $1}' | sort | uniq -c | sort -rn | head -5
29 root
24 admin
16 sales
14 test
14 staff

[root@nano ~]# ### top 5 most attacked accounts
[root@nano ~]# awk 'gsub(".*sshd.*Failed password for (invalid user )?", "") {print $1}' /var/log/secure* | sort | uniq -c | sort -rn | head -5
723 root
66 admin
45 test
39 ftpuser
34 mysql

[root@nano ~]# ### top 5 attacker IP addresses (obscured for privacy)
[root@nano ~]# awk 'gsub(".*sshd.*Failed password for (invalid user )?", "") {print $3}' /var/log/secure* | sort | uniq -c | sort -rn | head -5
1042 193.251.XXX.XXX
556 85.21.XXX.XXX
373 218.189.XXX.XXX
284 121.156.XX.XXX
228 121.140.XX.XXX


Fedora uses pam_cracklib.so to force normal users to choose semi-strong passwords of 6 characters or more when changing their passwd, but root can still choose weak passwords anytime he wants (but will be warned). Also note that the first user account added to the system after an installation (using firstboot) is allowed to be weak if you ignore the warning.

You may want to use a utility called "john the ripper" to audit the strength of passwords on your system - if it cracks any too quickly, they're too weak.

Install the "denyhosts" server which watches the /var/log/secure logfile for invalid ssh login attempts, and if a configurable threshold is crossed, they are automatically blocked by being added to /etc/hosts.deny. Install denyhosts, and optionally edit the good default configuration in /etc/denyhosts.conf:

yum install denyhosts
chkconfig denyhosts on
/etc/init.d/denyhosts start


The vast majority of ssh attacks are directed by compromised zombie machines against ssh servers listening on the default port of "22". By changing this port to something else you greatly reduce the risk of an automated break-in. Edit /etc/ssh/sshd_config and change the line which reads "Port 22" to "Port 2222", or any other unused port of your choosing, preferably above 1024. A line preceded by a '#' is the commented out default value.

#Port 22
Port 2222


SSH speaks two protocols: The old and insecure Protocol 1, and the newer Protocol 2. Almost all SSH clients now speak Protocol 2, so it is best to disable the older one. Edit sshd_config to include only Protocol 2, and not both:

#Protocol 2,1
Protocol 2


note: As of Fedora 8 this is unnecessary as only Protocol 2 is enabled by default.

There is no good reason for root to be allowed to interactively login directly; after connecting as a normal user, you can still "su -" to root. edit sshd_config:

#PermitRootLogin yes
PermitRootLogin no


If root login is required - e.g. for remote system backups - you may alternatively permit root to login, but only if using ssh keys, not interactive password entry:

PermitRootLogin without-password


Finally, it's also possible to limit root access to only be able to run specific commands, such as backup scripts (beyond the scope of this article):

PermitRootLogin forced-commands-only


Limit the maximum number of unauthenticated connections that the ssh server will handle at the same time. The smaller this is, the harder it is for script kiddies to make parallel, coordinated cracking attempts with multiple connections. edit sshd_config and change MaxStartups from the default of "10" to "3:50:10". The colon separated values tells the ssh server to, "allow 3 users to attempt logging in at the same time, and to randomly and increasingly drop connection attempts between 3 and the maximum of 10". Note: this should be increased on servers with substantial numbers of valid ssh users logging in.

#MaxStartups 10
MaxStartups 3:50:10


Reduce the maximum amount of time allowed to successfully login before disconnecting. The default of 2 minutes is too much time to hold open an unauthenticated connection attempt (see above); 30 seconds is more than enough time to log in:

#LoginGraceTime 2m
LoginGraceTime 30


By default, all valid users on the system are allowed to log in. A more secure policy is to only allow a whitelist of users or groups to log in. For example, to allow only the users "john", "mary", "joeblow", "joeschmoe", "joejoe", and any username that starts with "joe" to login, add the following line to sshd_config:
AllowUsers john mary joe*

Alternatively, you may instead allow only users who are members of certain groups to login. For example, to allow only the members of the "sshusers" group to connect, first make sure the group exists (groupadd sshusers) and add your users to it (usermod -a -G sshusers username), then add the following line to sshd_config:



AllowGroups sshusers


Allow only users from certain IP addresses to connect. Before allowing specific IPs, the default policy must first be set to DENY to be effective. edit /etc/hosts.deny and add the following line:


sshd: ALL


Next add to /etc/hosts.allow the networks you want to allow. For example, to allow all 254 hosts on the class C network "192.168.1.*", all 16million hosts from the class A network "10.0.0.0", and the lonely IP 24.42.69.101, you would add the following to /etc/hosts.allow:

sshd: 192.168.1.0/255.255.255.0
sshd: 10.0.0.0/255.0.0.0
sshd: 24.42.69.101


You may also allow/deny connections via a firewall, but to maintain sanity it's best to stick to one method or the other.

To remove the possibility of anybody ever guessing a user's password, disable password authentication completely, and require that public/private key pairs be used instead. While much more secure than passwords, a user's private key can still be compromised, especially if not protected by a passphrase. To disable password logins, add the following to sshd_config:

PasswordAuthentication no


By default, the ssh server listens for connections on ALL interfaces (0.0.0.0). If a ssh server is to only be accessible internally, bind it to a LAN IP. For example: edit sshd_config:

ListenAddress 192.168.1.10





Troubleshooting


How to test


If your changes don't seem to be working, remember to restart the sshd server, but DO NOT CLOSE THE ACTIVE SSH CONNECTION in case something goes wrong; attempt to make a new connection first, and undo any changes if necessary, or you may find that you've remotely locked yourself out of the system.

    /etc/init.d/sshd restart



    Using Rsync and SSH Keys, Validating, and Automation

    This document covers using cron, ssh, and rsync to backup files over a local network or the Internet. Part of my goal is to ensure no user intervention is required when the computer is restarted (for passwords, keys, or key managers).

    I like to backup some logging, mail, and configuration information sometimes on hosts across the network and Internet, and here is a way I have found to do it. You'll need these packages installed:
    • rsync
    • openssh
    • cron (or vixie-cron)

    Please note these instructions may be specific to Red Hat Linux versions 7.3, 9, and Fedora Core 3, but I hope they won't be too hard to adapt to almost any *NIX type OS. The man pages for 'ssh' and 'rsync' should be helpful to you if you need to change some things (use the "man ssh" and "man rsync" commands).


    First, I'll define some variables. In my explanation, I will be synchronizing files (copying only new or changed files) one way, and I will be starting this process from the host I want to copy things to. In other words, I will be syncing files from /remote/dir/ on remotehost, asremoteuser, to /this/dir/ on thishost, as thisuser.

    I want to make sure that 'rsync' over 'ssh' works at all before I begin to automate the process, so I test it first as thisuser:


    SSL Email Settings - Outlook

    General Settings

    You can use the following settings if you require Secure POP3, Secure IMAP4 or Secure SMTP over SSL.
    POP3 over SSL Server: yourdomainname.com / mail.yourdomainname.com

    POP3 over SSL Port: 995
    IMAP4 over SSL Server: yourdomainname.com / mail.yourdomainname.com

    IMAP4 over SSL Port: 993
    SMTP over SSL Server: yourdomainname.com / mail.yourdomainname.com

    SMTP over SSL Port: 465

    You can authenticate on these servers using your full email address as the username and corresponding password.

    SSL Settings Guides

    Outlook 2010


    You can follow these steps to change your Outlook 2010 email settings if you want to use our Secure servers for sending and receiving email.

    1. Open Outlook 2010

    2. From the File click on Account Settings and select Account SettingsYou'll then see all of your email accounts listed.

    3. Select the account you wish to modify and click Change

    4. Change the Incoming Mail Server (POP3) to yourdomainname.com / mail.yourdomainname.com and change the Outgoing Mail Server (SMTP) to yourdomainname.com / mail.yourdomainname.com

    5. Click on More Settings...

    6. Select the Advanced tab

    7. There are two check boxes labeled This server requires and encrypted connection (SSL). Check mark both check boxes.

    8. Change the Incoming Server (POP3) to 995. Change the Outgoing Server (SMTP) to 465.

    9. Click OK

    10. Click Next > and then Finish


     

     

    What is difference between shared and dedicated IP addresses

    Each computer connected to the Internet is assigned a unique IP address for the purposes of communication. An IP address is a 32-bit numeric address usually expressed as 4 numbers from 0-255 separated by dots, for example 192.168.0.123. There are billions of addresses possible, however, the number is finite.

    In the Web hosting industry there are two types of IP address...

    • Dedicated IP address (also called static IP) means that a website has its own IP address. Whether you type in your URL or the numeric form of its IP address, both will bring you to the same domain.

    • Shared IP address means that multiple websites share the same address. Web servers can determine by the domain entered in a user's browser which website is being requested. Typing in the IP address will bring you to some kind of generic page instead of the specific site you want.


    Due to the rapid increase of the number of registered domain names and the finite number of IP addresses, Web hosting providers are forced to use shared IP's when possible. In fact, hundreds of websites often share the same address. Static IP hosting is no longer the norm and usually costs more.

    Who needs a dedicated IP ?


    Generally, having a website on a shared IP address will not cause you any harm. However, there are a few cases when a static IP is required...

    • Having your own Private SSL Certificate. Secure e-commerce websites need SSL certificates for accepting credit cards online. Web hosts usually offer a shared SSL certificate where clients can share the Web host's SSL. If you are using your Web hosting provider's shared SSL you don't need a static IP.

    • Anonymous FTP. It means that anyone using the FTP software can access files in a special directory of your site. It's called Anonymous FTP because the user name used to access is "anonymous." Many Web hosting providers require a static IP for the anonymous FTP function to work properly.

    • You want to access your website by FTP or Web browser even when the domain name is inaccessible, such as domain name propagation periods.


    Dedicated IP hosting and search engines


    There has been debate in the SEO industry for awhile regarding whether or not using a dedicated IP address is better than having a shared IP for your website...

    • Some SEOs suppose that there really is no good reason to obtain static IP Web hosting. Your site will not perform any better by having its own static IP.

    • Some others theorize that your choice of dedicated IP hosting vs. shared hosting might slightly affect your rankings (i.e. it's a factor considered by search engines).

    • Yet others suppose that sharing an IP address with known spam or adult sites raises a warning flag with search engines, so some of them may respond by banning the entire IP address from their index.


    Most probably, these fears are greatly exaggerated. Since the majority of sites on the Web are hosted via shared IP, it would be unprofitable to search engines to penalize a site based on IP. Search engines are able to ban anything on a domain name instead of an entire IP neighborhood. So it is search engine safe to use a shared IP hosting. Moreover, almost all hosting will eventually be shared in order to preserve IP addresses.

    Tuesday 22 February 2011

    How do I configure SSL for secure https transactions?

    What is SSL?

    CubeCart can run under a combination of http and https which allows you to send sensitive data such as credit card numbers and other private information between the client computer and server.

    To setup your store to use SSL (Secure Socket Layer) you will first need an SSL certificate. Many hosting companies will either provide (or can offer) "Shared SSL" or the option to buy a "Dedicated SSL" certificate.

    Shared SSL means that your store will run using two domains your master domain name and shared secure domain which may be used by other customers of your hosting company.
    Dedicated SSL means that you will have your own SSL certificate which enable you to run your store on one domain using http and https.

    e.g.
    Shared SSL:
    Master Domain: http://www.example.com
    Shared Secure Domain: https://secureexample.com/username


    Dedicated SSL:
    Master Domain: http://www.example.com
    Secure Domain: https://www.example.com


    Most people prefer to use dedicated SSL as it looks more professional and can improve customer confidence.
    How do I test SSL is working?

    Before we do anything we need to test that the SSL domain has been configured correctly.

    In this example we will assume your webstore is located at http://www.example.com/store

    If you have dedicated SSL simply go to your master doman and store directory using your browser.

    http://www.example.com/store


    You should now be presented with your CubeCart store. If not, you have either typed the wrong URL or your it has not been installed properly.

    To test if you dedicated SSL certificate is working change the protocol in the address bar from http to https.

    https://www.example.com/store and press return.


    If it has been installed correctly the store should reload and a padlock will appear in the status bar of your browser software. If, on the other hand you get any warning messages or other errors please contact your hosting company to resolve the issue.

    If you have shared SSL your hosting company should have given you your secure URL which in most cases will be a domain with folder allocated to you.

    e.g. https://secureexample.com/username


    By going to the address given by your hosting company it should take you to the main index page of your website. If this is the case and you see a padlock on the status bar of your browser it should be setup ok. Again, if you have any error messages or warnings please conatct your hosting company. To check CubeCart under SSL you will need to go to the install location. In our example this would be:

    https://secureexample.com/username/store



    How do I configure CubeCart to operate under SSL?

    Now we know SSL is working we can set CubeCart to run in SSL mode. As SSL is very server intensive only parts of your store will run using it. These include payment pages, administration and registration etc...

    Log into the admin side of your store.

    e.g. http://www.example.com/store/admin


    Once in click the "General Settings" link under the Store Config Section and scroll down to the Directories & Folders section. Here you will be presented with some text boxes and a drop down menu to enable SSL mode.

    1. Root SECURE Public HTML Folder to store: (Include Trailing Slash)
    This is the server folder path from the end of your secure domain name.

    e.g.
    Shared SSL: /username/store/
    Dedicated SSL: /store/


    2. Absolute SECURE URL to store: (Excluding Trailing Slash)
    This is the full address you woudl type in the browser to access your store under SSL.

    e.g.
    Shared: https://secureexample.com/username/store
    Dedicated: https://www.example.com/store


    Double check all the values entered and once happy use the drop down menu to enable SSL. Then scroll to the bottom of the page and click the "Update Settings" button.

    How to allow remote access to mysql using xampp?

    Just make sure that your mysql is binding to a socket on 0.0.0.0 and you should be able to connect to that socket. I guess the default is for mysql to bind to 127.0.0.1, which, of course, is hard to reach from the outside.

    EDIT: The MySQL configuration file should be in .xamppmysqlbinmy.ini. You need to find thebind-address parameter and change it to 0.0.0.0.

    Everyone on your network should then be able to connect that MySQL instance. Of course, that may include people who better shouldn't do that. But as long as there is a password for each mysql user and the instance is not facing the internet, there is not much to worry about.

    Tuesday 1 February 2011

    Linux Kernel Security Hardening /etc/sysctl.conf


    How do I set advanced security options of the TCP/IP stack and virtual memory to improve security and performance of my system? How do I configure Linux kernel to prevent certain kinds of attacks using /etc/sysctl.conf? How do I set Linux kernel parameters?

    sysctl is an interface that allows you to make changes to a running Linux kernel. With /etc/sysctl.conf you can configure various Linux networking and system settings such as:
    1. Limit network-transmitted configuration for IPv4
    2. Limit network-transmitted configuration for IPv6
    3. Turn on execshield protection
    4. Prevent against the common 'syn flood attack'
    5. Turn on source IP address verification
    6. Prevents a cracker from using a spoofing attack against the IP address of the server.
    7. Logs several types of suspicious packets, such as spoofed packets, source-routed packets, and redirects.

    sysctl command

    The sysctl command is used to modify kernel parameters at runtime. /etc/sysctl.conf is a text file containing sysctl values to be read in and set by sysct at boot time. To view current values, enter:
    # sysctl -a
    # sysctl -A
    # sysctl mib
    # sysctl net.ipv4.conf.all.rp_filter

    To load settings, enter:
    # sysctl -p

    Sample /etc/sysctl.conf

    Edit /etc/sysctl.conf and update it as follows. The file is documented with comments. However, I recommend reading the official Linux kernel sysctl tuning help file (see below):
    # The following is suitable for dedicated web server, mail, ftp server etc.
    # ---------------------------------------
    # BOOLEAN Values:
    # a) 0 (zero) - disabled / no / false
    # b) Non zero - enabled / yes / true
    # --------------------------------------
    # Controls IP packet forwarding
    net.ipv4.ip_forward = 0
     
    # Controls source route verification
    net.ipv4.conf.default.rp_filter = 1
     
    # Do not accept source routing
    net.ipv4.conf.default.accept_source_route = 0
     
    # Controls the System Request debugging functionality of the kernel
    kernel.sysrq = 0
     
    # Controls whether core dumps will append the PID to the core filename
    # Useful for debugging multi-threaded applications
    kernel.core_uses_pid = 1
     
    # Controls the use of TCP syncookies
    #net.ipv4.tcp_syncookies = 1
    net.ipv4.tcp_synack_retries = 2
     
    ########## IPv4 networking start ##############
    # Send redirects, if router, but this is just server
    net.ipv4.conf.all.send_redirects = 0
    net.ipv4.conf.default.send_redirects = 0
     
    # Accept packets with SRR option? No
    net.ipv4.conf.all.accept_source_route = 0
     
    # Accept Redirects? No, this is not router
    net.ipv4.conf.all.accept_redirects = 0
    net.ipv4.conf.all.secure_redirects = 0
     
    # Log packets with impossible addresses to kernel log? yes
    net.ipv4.conf.all.log_martians = 1
    net.ipv4.conf.default.accept_source_route = 0
    net.ipv4.conf.default.accept_redirects = 0
    net.ipv4.conf.default.secure_redirects = 0
     
    # Ignore all ICMP ECHO and TIMESTAMP requests sent to it via broadcast/multicast
    net.ipv4.icmp_echo_ignore_broadcasts = 1
     
    # Prevent against the common 'syn flood attack'
    net.ipv4.tcp_syncookies = 1
     
    # Enable source validation by reversed path, as specified in RFC1812
    net.ipv4.conf.all.rp_filter = 1
    net.ipv4.conf.default.rp_filter = 1
     
    ########## IPv6 networking start ##############
    # Number of Router Solicitations to send until assuming no routers are present.
    # This is host and not router
    net.ipv6.conf.default.router_solicitations = 0
     
    # Accept Router Preference in RA?
    net.ipv6.conf.default.accept_ra_rtr_pref = 0
     
    # Learn Prefix Information in Router Advertisement
    net.ipv6.conf.default.accept_ra_pinfo = 0
     
    # Setting controls whether the system will accept Hop Limit settings from a router advertisement
    net.ipv6.conf.default.accept_ra_defrtr = 0
     
    #router advertisements can cause the system to assign a global unicast address to an interface
    net.ipv6.conf.default.autoconf = 0
     
    #how many neighbor solicitations to send out per address?
    net.ipv6.conf.default.dad_transmits = 0
     
    # How many global unicast IPv6 addresses can be assigned to each interface?
    net.ipv6.conf.default.max_addresses = 1
     
    ########## IPv6 networking ends ##############
     
    #Enable ExecShield protection
    kernel.exec-shield = 1
    kernel.randomize_va_space = 1
     
    # TCP and memory optimization
    # increase TCP max buffer size setable using setsockopt()
    #net.ipv4.tcp_rmem = 4096 87380 8388608
    #net.ipv4.tcp_wmem = 4096 87380 8388608
     
    # increase Linux auto tuning TCP buffer limits
    #net.core.rmem_max = 8388608
    #net.core.wmem_max = 8388608
    #net.core.netdev_max_backlog = 5000
    #net.ipv4.tcp_window_scaling = 1
     
    # increase system file descriptor limit
    fs.file-max = 65535
     
    #Allow for more PIDs
    kernel.pid_max = 65536
     
    #Increase system IP port limits
    net.ipv4.ip_local_port_range = 2000 65000

    How to setup your own private name servers on plesk


    You must first have the domain you wish to make your DNS already set up in Plesk. You will also need at least 2 IP's to use for your server. For reference, in this article 'mt-example.com' will refer to the domain name you are using. Make sure to replace this with your actual domain name.
    1. Log into your Plesk control panel as Administrator and select the domain from the Domains list you wish to make DNS.
    2. Select the DNS icon from your services list.
    3. Select the link mt-example.com from the Host list, with Record Type NS and Value ns.mt-example.com
    4. In the Enter nameserver field change the ns.mt-example.com to ns1.mt-example.com and select OK.
    5. From the Tools area select Add Record. For Record type select NS and enter ns2.mt-example.com in the Enter nameserver field and select OK.
    6. Select from your host list ns.mt-example.com with Record type A and change the value to ns1 and selectOK.
    7. From the Tools area select Add Record again. For Record type leave as A, in the Enter domain name add ns2, in the Enter IP address enter your second IP address that you are going to use and select OK.
    8. You should now have 2 Record types with the NS value of ns1.mt-example.com and ns2.mt-example.comand under the Host list you will also have ns1.mt-example.com and ns2.mt-example.com with the Record type of A and they will have 2 separate IP's.
    In order to have these added as DNS values for when you add new domains you will need to change the default DNS record in Plesk.
    1. Select Server from the list on your left.
    2. Select the DNS icon from the Services list.
    3. From the Host list select with record type NS and enter ns1.mt-example.com in the Enter nameserver field and select OK.
    4. From the Tools area select Add New Record. Change the Record type to NS and in the Enter nameserver field input ns2.mt-example.com and select OK.
    If you want to use 2 separate domains for your DNS this is even easier, because Plesk has already created this for you. You must have 2 domains entered in Plesk and assigned separate IP's. You would then only need to create a DNS zone template the same way described earlier, only inputting ns1.mt-example.com and ns2.mt-example.com for your default values.

    NOTE:

    Please remember to substitute mt-example.com with the domain that you are planning on using as your DNS server.