Category Archives: Uncategorized

Useful Apache Configuration

Redirecting HTTPS to HTTP (and vice versa)

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}

http://stackoverflow.com/questions/8371/how-do-you-redirect-https-to-http

WordPress .htaccess Rewrite Rule

This .htaccess will rewrite any path not resolving to actual file or directory. It will add “/index.php” prefix into the URL. This is required for wordpress permalink

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Redirecting mydomain.com to www.mydomain.com (or the opposite)

Your user often access your site using www prefix or without it, hence you setup both URL to resolve into your webhost in your DNS. However if you don’t redirect one into the other, search engine might think it’s a completely different site (hence website statistics etc will be wrong). One approach is to do external (301) redirect from one into the other.

RewriteCond %{HTTP_HOST} ^mydomain.com.au [NC]
RewriteRule (.*) http://www.mydomain.com.au/$1 [L,R=301]

Monitoring Apache

To enable apache monitoring, firstly make sure status module is enabled. Find following line on your httpd.conf

LoadModule status_module modules/mod_status.so

Then add following configuration section. The “Allow from” restriction will prevent arbitary IP to view this, so if your ISP provide you with static IP, put it here.


    SetHandler server-status
    Order deny,allow
    Deny from all
    Allow from 

You can monitor your apache server (see worker threads status etc) by going to http://mydomain.com/server-status

 

Stay Tuned!

More to come when I stumble accross them

See Also

Mitigating DoS Attack Using iptables

Continuing from my earlier post about iptables basics, the limit module of iptables can be used to mitigate DoS (Denial of Service) attack. Note that mitigating here means “reducing the damage”. The worst scenario is under a heavy DoS you can’t even SSH and run commands on your server. With iptables you can limit the frequency of packets — enabling you to SSH and take appropriate actions.

Following are the rules I currently use. This will only allow new incoming TCP connection on port 80 & 443 with specified frequency (see limit explanation below):

iptables -A INPUT -j ACCEPT -p tcp --dport 80 -m state --state NEW -m limit --limit 40/s --limit-burst 5 -m comment --comment 'Allow incoming HTTP'
iptables -A INPUT -j ACCEPT -p tcp --dport 443 -m state --state NEW -m limit --limit 40/s --limit-burst 5 -m comment --comment 'Allow incoming HTTPS'
  • -A INPUT: Append to the end of a chain called INPUT
  • -j ACCEPT: When rule match, accept the packet
  • -p tcp: Match only TCP protocol
  • –dport: Match given TCP port
  • -m state: Use the state module
  • –state NEW: Match only packets initiated from new connection. This rule will not match packets exchanged from an existing connections.
  • -m limit: Use the limit module
  • –limit 40/s: If more than 40 packet per second received, decrement one burst point. If no more burst point, reject the packet
  • –limit-burst 5: The initial number of burst point. A “burst” occur when the limit above is reached. On a period where limit is not reached, one burst point is regained, up to this maximum limit. If burst point is 0, subsequent burst will cause the current rule matching to fail — and iptables will try the next rules (if you setup iptables properly the packet should slip through to ‘reject all’ rule)

Add following rule to allow your program making connection to localhost (loopback interface)

iptables -A INPUT -i lo -j ACCEPT

I then append a rule to match packets exchanged from established / related connections. This is important so packet resulted from outbound connections are accepted:

iptables -A INPUT -j ACCEPT -m state --state RELATED,ESTABLISHED -m limit --limit 100/s --limit-burst 50

And finally, reject all packets not accepted by above rules. Be careful before you do this, make sure you’ve added rules to allow SSH (port 22) so you don’t lock yourself out.

iptables -A INPUT -j REJECT

Testing And Continual Adjustment

Finding the correct number for limit and burst could be hard, but what I find useful is to perform continuous monitoring and adjustment. Keep in mind your goal here is to ensure maximum capacity of the server is utilised while protecting it against DoS. One approach I like is to use the iptables LOG target. Assuming I add following rules:

iptables -A INPUT -j ACCEPT -p tcp --dport 80 -m state --state NEW -m limit --limit 40/s --limit-burst 5
iptables -A INPUT -j LOG -p tcp --dport 80 -m state --state NEW --log-prefix 'TCP 80 Burst Exhausted'

If the first rule did not match (eg: because of burst is exhausted), the LOG rule after it will match and print into your syslog (typically /var/log/messages) with prefix “TCP 80 Burst Exhausted”. LOG target will not accept / reject the packet — after logging, iptables will continue checking the subsequent ruless.

The neat thing here is you can grep ‘TCP 80 Burst Exhausted’ /var/log/messages to detect when was last time suspected DoS attack occured. If the suspected attack is determined to be false alarm, your limit and burse setting is too strict, and you should gradually increase it.

Saving and Restoring

Updating rules at specific order can be very tedious, you have to count the terminal screen lines, insert the new rule, delete the old one and so on. There’s one trick you can do, that is to leverage iptables-restore command. Everytime you save the rule using service iptables save /etc/sysconfig/iptables file is updated with your rule specification. You can update this file and restore it using iptables-restore. Beware! A syntax error will cause your rule to be skipped. It’s best to test your command first by adding it to the bottom, and use this method to re-order the rules.

AWS EC2: UNIX User Management and SSH with Password Authentication on Amazon Linux AMI

Once you’ve created your , you will get a private key (generated during the server setup process) and a default UNIX user called ec2-user. By default password authentication is disabled (because it’s plain text password transferred over the internet). You can login using a ssh client from your PC using this command:

ssh -i /path/to/mykeypair.pem 

If you’re on windows and you use Putty it might be slightly more tricky:

  1. First you need PuttyGen tool
  2. Once you’ve downloaded and installed it, open it and select File -> Load private key. Find your keypair file
  3. PuttyGen will display success message if your keypair is valid. Then select Save private key
  4. On your putty connection parameter, go to Connection -> SSH -> Auth and use the above saved file for Private key file for authentication

Generating Encrypted Password

Standard UNIX and commands can be used to manage users on Amazon Linux, however you first need to know how to generate encrypted password. Supposed I want to encrypt my password string “holasenior”, run following commands:

[]# python
Python 2.4.3 (#1, Jan  9 2013, 06:47:03)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import crypt; print

>>> crypt.crypt('holasenior','mysalt123')
'myOZ9FACMq7sA'
>>>

myOZ9FACMq7sA is your encrypted password. mysalt123 is an encryption salt to defent against dictionary attack.

Adding New User

To add new user “ironman” with password “holasenior” encrypted with salt “mysalt123″:

sudo useradd -p myOZ9FACMq7sA ironman

Changing Password of Existing User

To change password of existing user “ec2-user” to “holasenior” encrypted with salt “mysalt123″:

sudo usermod -p myOZ9FACMq7sA ec2-user

SSH with Password Authentication

WARNING: Using plain-text password authentication for SSH is dangerous, your password will be visible over the internet.

To enable password authentication, edit /etc/sshd_config file and find following line and change it to yes

PasswordAuthentication no

Windows 7 nslookup Resolves But Ping And Others Failed

As a wannabe network admin at the office, I’ve been dealing with a really tricky problem for the past few days. Long story short, I have few development servers and I want to setup CNAMEs pointing to it so it’s easy to remember.

The problem is every 15-20min the CNAME will stop resolving. If I try to ping it gives name not found. However nslookup still resolves fine.

I’ve tried many different things with no luck until I finally found the problem: we mistakenly configured multiple public DNS on our DHCP settings alongside our primary internal DNS hosted on Windows Small Business Server 2011 (SBS). As shown below the configuration after we fixed it, only 1 entry is listed pointing to our internal DNS

ipconfig

It seems if multiple DNS servers are configured, windows will pick a primary one at random / round robin. If the primary happens to be the one other than our internal DNS, it won’t be able to resolve the CNAME entries.

This setting can be changed on DHCP configuration tool on SBS as shown below

dhcpconfig

And to make sure internet-wide name resolution still works. The public DNS have to be setup on the internal DNS forwarder on SBS DNS configuration

dnsforwarder

Add to the original confusion was I kept wondering why non CNAME alias still can be resolved all this time. This turns out due to the fact Windows uses not only DNS, but a set of other services to translate hostname into IP:

  1. Client check if the name queried is of its own
  2. Client checks local hosts file (eg: %Systemroot%System32Driversetc)
  3. DNS are queried
  4. NetBIOS

(Quoted from http://support.microsoft.com/kb/172218)

Notice that if DNS fails on step 3 regular PC names still can be resolved using NetBIOS, but in the case of CNAME it wouldn’t work.

Using GMail With Your Own Domain E-mail

If you own a domain name (for small business or so), email will look more professional than . However you might be annoyed having to check multiple mailboxes. Here’s how you can link everything into one GMail mailbox.

Setup Incoming Mail Forwarding On Your Domain Hosting Service

  1. Login into your domain hosting control panel. If you’re on GoDaddy, login to MyAccount and launch E-mail product
  2. Select Create Forward, enter  and forward it to  (you can even add multiple e-mails)
  3. Wait for a few minutes, and at this point you should get incoming mail forwarded to your gmail mailbox

Configure GMail For Sending As

  1. Go to GMail setting (gear icon on the top right), select Accounts and Import
  2. Under Send Mail As section, select Add Another Email You Own, follow the prompt and verification
  3. When sending email, don’t forget to change the From address to

Eclipse Tips and Tricks

Eclipse is such a great tool for Java developer, but many of its feature is hidden and could be a while for a newbie to uncover it. Following is my favourite tips and tricks.

Note: The shortcuts in this post is applicable to Windows only

Type / Resource Searching

With a large project, often it’s tricky to find a particular class, XML file or other resources. Use CTRL+Shift+T to show the Open Type box, or CTRL+Shift+R for Open Resource box. Open types allows you to search for Java classes while open resources behaves more like a filesystem search, typically you would use this to look for XML, HTML, javascript, properties and so on.

You can also do wildcard searching. For example if you’re trying to find a class related to the keyword “Cat”, you can search *Cat*

Declaration /References Searching

While looking at existing program, It’s very common we need to lookup the declaration or a class or variable or search all locations where a particular class or variable is used (reference searching).

To open a declaration of a variable/type: highlight a variable or class/type reference and press F3 or right-click -> Go to declaration

To find references of a variable/type: right click a variable/type and go to the references menu

Keyboard Shortcuts

When you’re doing the same task a million times, cutting the cost of few extra mouse clicks does matter! Shortcuts in eclipse can be viewed/configured via Preferences (General -> Keys). Following are some of my favourite shortcuts:

Action Windows Shortcut Mac Shortcut Note
Toggle comment (on highlighted text) Ctrl+Shift+C Command+C In java this will toggle double forward-slashes comment (//), in XML the syntax per-line
Toggle block comment (on highlighted text) Ctrl+Shift+/ Command+/ In java, enclose the highlighted text with /* comment */, in XML
Switch active view Ctrl+F7 Ctrl+F7 Allow you to switch from Editor to Console, or any other open Views
Switch perspective Ctrl+F8 Ctrl+F8
Run preconfigured maven goals Alt+Shift+X, M Alt+Shit+X, M You can configure the maven goals via Run configuration (Run -> Run Configuration…). You have to focus on a project on the Project Explorer, or an editor window of the project’s resource
Run Unit Test Alt+Shift+X, T Alt+Shit+X, T

* Function keys on Mac require “fn” modifier. Eg: to press F6, press fn+F6

Method Call Hierarchy

This feature allows you to see what other classes calls a particular method. This is very useful when tracing down an exception, or listing the potentially impacted classes when refactoring a method.

Right click on a method, choose open call hierarchy or use CTRL+Alt+H shortcut. When you open the call hierarchy window, you can also expand each node to further drill down who called that method.

Code Generation

Eclipse came with pretty impressive code generation support. Some of my favourites are: getters/setters generators, toString generators, constructor generators, exeception try/catch block generators.

Most of this code generators feature can be accessed via Source menu or CTRL+Alt+S shortcut.

Java Code Template

If you have to include your company’s copyright policy, or some open source license header on every new java class you create, you can setup a code template. From Preferences, go to Java -> Code Style -> Code Template. On “Configure generated code and comments” select box, go to Code -> New Java files. You can insert additional comments on the top.

Configure SVN support

Eclipse doesn’t come with SVN support by default (due to some licensing restriction I think), and configuring one isn’t a straight forward task. Eclipse come with a concept of SVN provider and connector which has to be installed separately, and there are plenty possible options out there (which don’t always work).

To configure SVN support with Subversive provider and SVNKit connector:

  1. Go to Help -> Install New Software -> Select “Indigo” from “work with” dropdown list. This will cause Eclipse to first check all available plugins, and what has already installed (could take 15 min+)
  2. Open the “Collaboration” tree, and search for “Subversive SVN Team Provider”. Tick and continue with the installation process. Eclipse will ask for a restart when it’s done
  3. Installing the provider it’s a bit tricky. Once eclipse has restarted, open the “SVN Repositories” view by going to Windows -> Show View ->Other -> Search for SVN Repositories, and attempt to register / checkout a new repository. Subversive will realize you haven’t got any connector installed, and will show connector installation dialog. Pick the latest version SVNKit connector and install it