Mediawiki : Restricting POST request’s to API using IP Whitelisting

A simple hack that can make sure that your API doesn’t fall into the wrong hands.
* Firstly, make an array of allowed IPs. This can be in the CIDR format ( 127.0.0.1/32 ) or ususal IP ( 127.0.0.1 ). You can define them in your YourExtension.php as:-

/*Allow only internal IP range to do the POST request */
$wgAllowedInternalIPs = array( '127.0.0.1', '::1' );

* Now, on the top of your API definition, add

class ApiBounceHandler extends ApiBase {
	public function execute() {
		global $wgAllowedInternalIPs;
		$requestIP = $this->getRequest()->getIP();
		$inRangeIP = false;
		foreach( $wgAllowedInternalIPs as $BounceHandlerInternalIPs ) {
			if ( IP::isInRange( $requestIP, $BounceHandlerInternalIPs ) ) {
				$inRangeIP = true;
				break;
			}
		}
		if ( !$inRangeIP ) {
			wfDebugLog( 'Extension_name', "POST received from restricted IP $requestIP" );
			return false;
		}
	}
}

Please note, IP::isInRange() can take up strings in the format ( 127.0.0.1 or 127.0.0.1/32 – the subnet ).
This will make sure that your API ran for the right IP. Happy Hacking!

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s