Storing Database Credentials (and other stuff) in php.ini

If you’re storing your database password + username and other secure information in just any old .php file in your application, you’re doing it so, very, very, very wrong. If you must physically store these keys to the castle, the old method with Apache used to be SetEnv. Of course, not everyone uses Apache these days (I use Nginx on my *nix boxes).

The best place to store these things is in an .ini file. Specifically, for content that rarely, if ever, changes (I.E. database connection strings) it should be php.ini. Every PHP installation should have one and if you don’t have access to this, it’s time to switch web hosts.

In your php.ini, you can add the following or equivalent settings somewhere in the bottom.

[MyCustomApp]
myapp.cfg.DB_HOST = 'mysql:host=127.0.0.1;dbname=mydatabase'
myapp.cfg.DB_USER = 'dbusername'
myapp.cfg.DB_PASS = 'dbpassword'

Note: MyCustomApp is just the configuration label set to that particular group of settings. It’s good practice to give labels to your configuration settings and group them together. Especially if you move on to have a lot more of them later on.

Here is a very simple bit of code to load the above settings into globally defined variables :

// Very simple loader
function loadConfig( $vars = array() ) {
	foreach( $vars as $v ) {
		define( $v, get_cfg_var( "myapp.cfg.$v" ) );
	}
}

// Then call :
$cfg = array( 'DB_HOST', 'DB_USER', 'DB_PASS' );
loadConfig( $cfg );

Doing this is the far more secure method of setting up most other applications (including *cough* WordPress) as opposed to the old-school way, which I’m sure anyone who’s setup any PHP app in the past has dealt with:

 // Ordinary config.php or some such file 
// (I.E. DON'T DO THIS ANY MORE)
define( 'DB_HOST', 'mysql:host=127.0.0.1;dbname=mydatabase' );
define( 'DB_USER', 'dbusername' );
define( 'DB_PASS', 'dbpassword' );

The best way to prevent information you have on your hands falling into the wrong hands is to not have it in your hands. If some misconfiguration results in raw PHP files being served as text files (this happens far more often than you might think), the only thing you’ve exposed is just the site code, not your DB credentials AWS passwords, secret salts etc…

Caveats

As mentioned above, not everyone will have access to php.ini from their web host (which, as I also said, is a good hint it’s time to switch hosts). You will also need to reload PHP to ensure the new configuration changes will take effect. It’s possible to gracefully shutdown and restart these days, but that will mean a tinsey bit of down time of a few seconds at least so this will need to be done for configuration settings that are critical and yet will change infrequently. Or, if you’re using PHP-FPM with Nginx, you can start another FastCGI instance and have Nginx fail over to that.

Addendum

The PDO driver for MySQL for some reason demands the username and password separately. I thought this is kinda silly since other drivers (E.G. Postgresql) can function just fine with a connection string such as :

pgsql:host=localhost;port=5432;dbname=testdb;user=bruce;password=mypass

Well, to keep the MySQL driver and many others happy, I’ve written a small helper class that intercepts the connection string and breaks it down so the username and password can be kept separate. It also works with the above php.ini trick in that you can now store a complete connection string as php.dsn.mydb or the like as shown in the PDO docs.

/**
 * PDO Connector class
 * Modifies the DSN to parse username and password individually.
 * Optionally, gets the DSN directly from php.ini.
 *
 * @author Eksith Rodrigo <reksith at gmail.com>
 * @license http://opensource.org/licenses/ISC ISC License
 * @version 0.1
 */
 
class Cxn {
	protected $db;
	
	public function __construct( $dbh ) {
		$this->connect( $dbh );
	}
	
	public function getDb() {	
		if ( is_object( $this->db ) ) {
			return $this->db;
		} else {
			die('There was a database problem');
		}
	}
	
	public function __destruct() {
		$this->db = null;
	}

	private function connect( $dbh ) {
		if ( !empty( $this->db ) && is_object( $this->db ) ) {
			return;
		}
		
		try {
			$settings = array(
				PDO::ATTR_TIMEOUT		=> "5",
				//PDO::ATTR_EMULATE_PERPARES	=> false,
				PDO::ATTR_ERRMODE		=> PDO::ERRMODE_EXCEPTION,
				PDO::ATTR_DEFAULT_FETCH_MODE	=> PDO::FETCH_ASSOC,
				PDO::ATTR_PERSISTENT		=> false
			);
			
			$this->_dsn( $dbh, $username, $password );
			$this->db = new PDO( $dbh, $username, $password, $settings );
		} catch ( PDOException $e ) {
			exit( $e->getMessage() );
		}
	}
	
	/**
	 * Extract the username and password from the DSN and rebuild
	 */
	private function _dsn( &$dsn, &$username = '', &$password = '' ) {
		
		/**
		 * No host name with ':' would mean this is a DSN name in php.ini
		 */
		if ( false === strrpos( $dsn, ':' ) ) {
			
			/**
			 * We need get_cfg_var() here because ini_get doesn't work
			 * https://bugs.php.net/bug.php?id=54276
			 */
			$dsn = get_cfg_var( "php.dsn.$dsn" );
		}
		
		/**
		 * Some people use spaces to separate parameters in
		 * DSN strings and this is NOT standard
		 */
		$d = explode( ';', $dsn );
		$m = count( $d );
		$s = '';
		
		for( $i = 0; $i < $m; $i++ ) {
			$n = explode( '=', $d[$i] );

			// Empty parameter? Continue
			if ( count( $n ) <= 1 ) {
				$s .= implode( '', $n ) . ';';
				continue;
			}
			
			switch( trim( $n[0] ) ) {
				case 'uid':
				case 'user':
				case 'username':
					$username = trim( $n[1] );
					break;
				
				case 'pwd':
				case 'pass':
				case 'password':
					$password = trim( $n[1] );
					break;
				
				default: // Some other parameter? Leave as-is
					$s .= implode( '=', $n ) . ';';
			}
		}
		$dsn = $s;
	}
}

You can use this class with :

$cxn = new Cxn( DBH );

Where DBH came from (hopefully) php.ini.

Advertisement

A Playground

Oh, hi there blog! I didn’t forget you existed, but you did become the lovable aunt who likes to talk too much and so you were avoided.

Meanwhile, I’ve been hanging out in place called NeoCities, a throwback to GeoCities, which sadly shut down.

This is a huge deal! Why?

The Web is not the internet

The internet, as we know, is an interconnected network of tubes that funnel nutrients and raw sewage alike through our lovable dispensaries (PC, tablet, smartphone, smartcar, smartfridge, smartloo etc…)

The Web is the said nutrients and sewage. Now we have all been told what nutrients are by the owners of the web. Media, social or otherwise, have fed it to us labeled “nutrients”, but lately we’ve come to understand that this is a whitewashed molasses of contrived crap. You can’t blame these outlets alone since the owners of the web will do whatever they please with their property.

Owners? What owners?!

Who are the owners? Facebook, Google(G+) et. al. And yes, even WordPress to a degree. But I sense some of you have a niggling twitch on the back of your mind. The power of the “owners” of the web has increased in recent years and the alarm is compounded by the fact that the web wasn’t supposed to be owned by anyone. “Wait, it’s my blog/Facebook page/account!” Surely what is “your” property should be yours to do as you please, no? Well, that’s very true, but here we have a hiccup with what exactly “ownership” entails.

You do not own what you do not control.

Facebook, Google and any other entity that holds on to your things for you, creates themes, connects you to people you should know (or rather they think that you should know) and such that you can edit. These are features. But it is subject to their TOS (which excludes far more than spam and “illegal” content). They have every right to control what’s on their property. And it is “their” property, you’re simply renting an apartment there by using yourself as collateral. As the old social media adage goes…

If you’re using a “free” service, you’re the product

Side amusing factoid: Everyone I know, who uses Facebook, hates it.

I use it to keep in touch with friends ‘n stuff and once-in-a-while, I’ll play a game, but it’s such a timesuck, dude!

– Everyone

Back to the awesomeness of NeoCities.

Why is NeoCities awesome?

The early to mid 90s was an era of the www (Wild, Wild, Web) when anyone and everyone can create any sort of a jumble of content – and this is the operative word, folks, “content” – with muddled HTML, dancing Hammer gifs and whole assortment of unwholesomeness that (mostly)everyone loves.

Above all else, you “Owned” your page. You could download it, edit it as you please, share as you please, link who you please and most certainly, the host didn’t “connect” you to people you know or secretly gather usage data on who you visit or bookmarked. These are also features.

Note: A “like” is an acknowledgment. A “share” is a public bookmark. See how the new owners of the web have used existing features and renamed them?

NeoCities captures the www (second definition) to a T and I encourage everyone else to join the club. You’re not a network, you’re not a product. You’re a human being. Please express yourself as one. Right now the service is limited to editing HTML files and uploading small images, but there’s no reason you couldn’t use an outside image hosting service like Imgur.com (which is also free).

I started my experiment with NeoCities a week or so ago and it was still being tweaked at the time. However, you can see the end result. I don’t plan to stop here, of course.

Learn HTML (it’s not terribly complicated, but if you need a place to start, you can copy my layout and stylesheet). Everyone who feels like it should try it out, experiment, mould, create and do whatever.

Let the creator of NeoCities explain it better.

Enjoy!

New Phone II

Well, it’s only been two days since I started using the new BlackBerry 9930 and I can now honestly say… I don’t like it.

Don’t get me wrong; for what it does, it’s very, very good. I can write my emails more easily, text faster, attachments are painless, though I can credit this to our IT department, which *cough* includes yours truly. I can modify office documents painlessly, take better notes, organize practically everything. I can properly multitask during a call, which was pretty shaky at best on the Vortex, and perform many other acrobatic feats.

But there remains one overriding fact that until now I wasn’t able to put my finger on.

It’s Sterile

When I go over my old LG Vortex : It’s slow, has abysmal local storage, a less refined GPS, no GSM capability (the BB can switch networks from CDMA to GSM on-the-fly) so it’s stuck to Verizon, no QWERTY keyboard. The camera is blurry on most photos without an excellent light source, no LED flash, has an average sound quality, freezes constantly when editing documents, doesn’t properly sync or syncs very late with my email (sometimes by hours). It’s got scratches all over from being shoved into my pocket with my keys.

Most of the time, when I really needed to depend on it for some heavy lifting, I couldn’t.

This is usually every Tuesday

By every conceivable measure, my LG Vortex is an order of magnitude inferior to the mighty BB, so I should be falling head over heels for it.

But I can’t love this phone.

A BlackBerry device just doesn’t have a soul, as arbitrary and cheesy as that sounds.

Using a BlackBerry is really like walking into a board room. You can be extremely productive depending on your dexterity and competence as well as the cooperation of the tools co-workers, but you’re still in a board room. It’s not your home, your room, your fortress of solitude. In the end, it’s all about work and productivity and a hefty dose of chest-thumping at owning the gadget (BRIAN!) and no amount of multi-color clips, cases, stickers, bedazzles or desktop themes will fix that.

Then there’s the Market

Or Google Play as it’s called now. No amount of browsing on “App World” for BB returned anything as interesting or creative as on Google Play. Granted, Play has a huge advantage due to the sheer volume of Android devices in the market drawing more developers, but App World draws crowds that just want to do work most of the time with a minor diversion here and there in between.

By far, the most interesting thing I came across App World is the Ghost Radar.

It’s taps into all the sensors of the phone, effectively turning it into a Star Trek style Tricorder of sorts.

And I’ve been living under a rock apparently, because this app has also been available for Android and on iTunes for some time now.

From the App World page,

Ghost Radar™ is an portable application designed to detect paranormal activity. Ghost Radar™ attempts to detect paranormal activity by using various sensors on the device on which it is running. Like traditional paranormal detecting equipment Ghost Radar™ employs sensors that measure electromagnetic fields, vibrations, and sounds. However, traditional paranormal equipment can be easily fooled when simple mundane bursts of normal electromagnetic fields, vibrations and sounds occur. Ghost Radar™ sets itself apart by analyzing the readings from sensors giving indications only when interesting patterns in the readings have been made.

Please visit http://www.spudpickles.com/GhostRadar for more information.

Note: results from this application can not be verified scientifically and therefore should be used for entertainment purposes.

I love the disclaimer at the end. But see, apps like these are numerous on Google Play, which makes its appearance on App World stand out a lot. Reading the comments on some of these apps, I somehow felt that most BB users, or at least the app reviewers, are unhappy people… even on the 5 star ones.

No Rooting

You can’t modify your BB software or OS in any way like you can on an Android. Even on an iPhone, it’s still a bit tricky due to the propietary setup and I have no experience with Windows Phones. You can even get an Android OEM phone (no label or label removed directly from the manufacturer) and got to town on it by modifying anything you please. You can even write your own apps for it if you wish so the possibilities are endless. The walled garden of App World, while it makes things more secure, leaves an odd taste in my mouth. Or maybe it’s just the color scheme?

It’s a bit like feeling like a boarder in your own home. Why am I a stranger, forbidden from exploring every nook and cranny where I live?

And Verizon didn’t help

Leave it to this company to add aggravation when there’s no room for more. After the 5th time deleting its junk applications from the Service Book, I finally managed to keep them out, I think. They haven’t reinstalled themselves yet, but I don’t think I’ll keep the service on the phone around any longer to find out. I still can’t seem to get rid of Bing search.

Just having Bing on the phone, when it didn’t before and now against my will, somehow makes it seem defiled.

My wireless provider in Sri Lanka is Mobitel (I got sick of Dialog even though they’re more popular) and when I switched to GSM on the BB, it automatically connected with AT&T. Apparently Mobitel roaming is provided by them here. I think I’m still able to receive text messages from SL on the Mobitel sim, so I’ll leave it in for now and use an AT&T prepaid SIM on this phone to make calls later.

I’m not too exited about about signing up for a 2-year contract again with Verizon just to get another Android phone, but it’s a better alternative than shelling out more cash to buy a different phone. Besides, on a few of my client locations, Verizon is usually the only provider with enough coverage.

Now if only I can figure out how to remove bloody Bing search from my phone.

OpenBSD: Otherwise known as Marmite

There are a lot of misconceptions about OpenBSD, chief of which is that it’s bulletproof. Well, the default install has had “only two remote holes, in a heck of a long time”, however those of us on planet Earth realise that few people stick to the default install in the first place. If you need your system to do anything aside from being a router or text-only web browser, then sure, default works handily.

The rest may get tedious so feel free to browse away now.

Security is a process

I’ve lost count of how many times this has come up, but it still bears repeating.

It’s not a destination. Never has been and never will be considering vulnerabilities are discovered all the time in other software needed to turn the afore-mentioned brick into a house. Just because you run a very secure OS, doesn’t mean anything else running on it won’t break and let in something bad through the cracks.

From the FAQ :

The packages and ports collection does NOT go through the same thorough security audit that is performed on the OpenBSD base system. Although we strive to keep the quality of the packages collection high, we just do not have enough human resources to ensure the same level of robustness and security.

Introducing any new software to the machine, regardless of a tar download or ports, will create potential vulnerabilities which the sysadmin has to keep an eye on, apply patches and chroot as necessary. I’m sure I don’t need to go over backing up before applying said updates as that’s just common sense.

Current vs Stable

Current is more likely to break, but you also get fixes fairly quickly. Stable is slower to get fixes, but is less likely to break in the first place.

This is pretty much true of any of the BSDs or really most of the Linux distros for that matter so plan accordingly.

Don’t choose current just for needless features on a production system.  Make an informed decision on whether you’re using the full capabilities of a current branch before using it. I generally stick to stable for production systems unless there’s a feature absolutely needed that’s not in stable, which is very rare.

RTFM

The FAQ, the manual and the mailing list are your friends so don’t ignore them.

Always treat these sources from the project site as your primary references. There are many wonderful tutorial sites on the net about configuring, securing (see above), and otherwise using OpenBSD, but the main sources provided on the project site are still your most reliable, up-to-date, and complete reference. Also it has, by far, one of the most comprehensive manuals for an open source project.

I’m by no means an OpenBSD expert, but I’m patient when it comes to learning and I don’t get embarrassed about asking questions if I don’t know something. You never stop learning.

That said, people who say “OpenBSD is pretty easy” or equivalent are pretentious and condescending. OpenBSD has a steep learning curve and downplaying that with statements attesting ease of use only serve to frustrate and offend people just getting into it. It gets “easier” as time goes by and  as you get familiar with the environment, you will end up with a lot of capability in a very secure and stable system.

It takes a lot of reading and familiarization to get your feet wet and even if you come from a *nix background, it never hurts to read-up. OpenBSD’s strong points are security, consistency and predictability. The last two really help when learning the system.

People within the Linux and BSD community can only help their platform of choice by getting rid of the condescension toward novices.

It’s Marmite (I.E. It works for me)

OK, I get it. You don’t have to go on-and-on about how hard it is and how you just don’t understand or how anyone can use it vs, say, another BSD or Linux distro to get the same, if not better, functionality for the same effort.

If any of the other BSD or Linux flavor floats your boat, well then, more power to you.

I’ve been using Nginx + MySQL + PHP + OpenBSD on one particular production site for quite a while and I’ve been very happy. Maintenance has rarely been a problem, albeit it’s more involved due to chrooting, but I’ve had no complaints so far with the site breaking.

If anyone asks me and if it’s appropriate, this is what I’d recommend, not just on security grounds, but also because I found it consistent and reasonably straightforward to keep secure for the forseeable future. And I’m using it on that production site because it was appropriate for my situation.

Quit trying to convert people to your religion in regular face-to-face conversations saying your Kool-Aid is better for everything. You just sound like a bunch of intolerant morons; as if we needed more of those these days. If what someone does with their system isn’t your cup of tea, but doesn’t affect your system or what you do, then mind your own damn business.

Linux vs BSD comparisons?

I’ve gone over this so many times in real life, I don’t have the energy to do it again, but I will say this. Apples and Oranges — Linux is a kernel and you have a zillion different distros (Operating Systems) that use said kernel which specialize in different things or you can roll out your own. Choose or build carefully.

As for how I feel about other people’s opinions on what I choose; I’ll let Denny Crane explain :