Using PHP/cURL to grok your public IP address

I had the occasion to create a PHP page that displays the server’s current public IP address. Not necessarily a good thing to display. But, I have several internal web sites on a development server where the host names are not available on a public DNS server. Displaying the server’s current public IP address is handy to prevent needing to nslookup my dyndns host name when altering my host file.

So, here is how I did it:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "www.checkip.org");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);

$pattern = '/Your IP:  ([d]{1,3}.[d]{1,3}.[d]{1,3}.[d]{1,3})</span>/';
$matches = array();
preg_match($pattern, $output, $matches);

$yourIP = 'N/A';
if (count($matches) > 1) {
  $yourIP = $matches[1];
}
curl_close($ch);

What I’m doing here is using cURL to get the page at checkip.org and then using a regular expressing to get the IP address returned in that page.

Albeit not completely fault-tolerant, as the web site can change it’s structure, but this type of quick’n’dirty screen scraping was what I needed at the time.

How much weight do I need to lose?

How much weight do I need to lose to attain a healthy body mass? The standard weight charts tell that due to my height (5’10”), frame size (medium), and gender (male), I should weigh from 151 to 163 lbs. Really? I mean I currently weight 213 lbs. Do I really need to lose 50 lbs?

The weight charts do not take into account lean body mass (and no, I’m not saying that I’m 200+ lbs. of muscle). So, given my body fat percentage and a realistic goal of attaining a weight consisting of 20% body fat, how much do I really need to lose?

The answer requires a means for measuring body fat and some math. I have a scale at home that measures my weight and body fat and currently I am 213.2 lbs., 33% of which is fat. Here is a formula to find my ideal body weight:

[latex]W_{g}=frac{W_{c}-W_{c}F{c}}{1-F_{g}}[/latex]

Where Wc is my current weight, Fc is my current body fat percentage, Wg is my goal weight, and Fg is my goal body fat percentage. My ideal body fat percentage for my gender (again, male) and age (38) is between 8 and 19 percent.

Plugging in the numbers for my current weight and body fat and a goal body fat of 19% gives me:

[latex]W_{g}=frac{213.2-213.2times0.33}{1-0.19}[/latex]

The result is an ideal weight of 176.4. Slightly more than what the body fat charts recommend. Perhaps I do have some extra muscle? Maybe?

So, I need to lose about 37 lbs. Or, two Katos. My cat Kato currently weighs 17 lbs. I’m not going to go into whether or not he is at his ideal weight. He’s a big cat – not fat, just big. But, and more importantly, he’s heavy. If I lost the weight amounting to two Katos, think about the stress that would take off my medium frame? And that is the real goal.

iPhone Electronic Formula Calculator

My latest adventure has been in the iPhone/iTouch application development world. The first application to hit the iTunes Store is Formula Sensei, a formula database and calculator. Formula Sensei will encompass a suite of formula calculators, the first of which is the Electronic Formula Calculator. This app has been developed and uploaded for review/approval to the iTunes store. Future editions of Formula Sensei will include financial, real estate, physics, etc. A web site has been set up to provide more information about the product:

formulasensei.com

Update: the E-Formulas app has now been approved for sale! See it at the iTunes Store: E-Formulas.

Apache Performance: Rotate your logs (duh)

Seems kinda silly, doesn’t it? After following all the Apache performance tips found on Google, I noticed that the site I was tuning (rss2.com) had access logs exceeding 2GB in size. Now if you imagine each httpd process having to load a file that size, you can imagine why it took so long for new httpd processes to load.

I configured logrotate to rotate logs each hour when the logs exceeded 100K. What a difference! Of course, restarting Apache every hour helps, too. But the change made a significant difference.

JavaScript Keypress Event – the right way

I had an occassion where I had to capture the “enter” key press in a text box and couldn’t quite remember how to do that. So, like the well-adjusted web developer I am, I Google’d for the answer. I was suprised to find how many different solutions there were and how some of them just plain didn’t work.

I turned to the tried-and-true Prototype library (because that’s how I remembered doing it in the first place). The bonus with using Prototype is that it will actually be browser compatible.

Here is the penultimate solution to capturing an “enter” keypress in an HTML input text box.

The HTML:

<input type="text" name="my_text" id="my_text" value="" />

The JavaScript:

<script type="text/javascript"><!--
function onMyTextKeypress(event)
{
if (Event.KEY_RETURN == event.keyCode) {
// do something usefull
alert('Enter key was pressed.');
}
return;
}

Event.observe('my_text', 'keypress', onMyTextKeypress);
//-->
</script>

Now, don’t forget to include the prototype.js script in the HTML page!

<script type="text/javascript" src="/js/prototype.js"></script>

The JavaScript must execute after the DOM elements are rendered. One way to do it is to put the JavaScript code in a SCRIPT element after the INPUT element. However, another way would be to put the following code in the SCRIPT element in the HEAD element:

Event.observe(window, 'load', function() {
Event.observe(Event.observe('my_text', 'keypress', onMyTextKeypress);
});

I like this method because all the JavaScript can be kept in the HEAD, or in a JS library file, instead of splattering the code throughout the document body.

References:

Prototype Event.observe API

PHPKeyStore Update

The KeyStore API is code complete. Check it out at phpkeystore.org. The current development release can always be installed with PEAR using:

pear install http://phpkeystore.org/download/KeyStore-current.tgz

All that really remains right now is internal tweaking for best practices and performance.

To summarize the functionality, the key management functionality consists of:

  • Loading and storing the key store
  • Creating secret keys, certificate signing requests, importing signed certificates, and deleting key store entries
  • Querying the key store for the existence of an entry and what type of entry it is

And the key usage functionality consists of:

  • Loading the key store
  • Using a public/private key pair to encrypt, decrypt, sign, and verify
  • Using a secret symmetric key to encrypt and decrypt

The current to-do list:

  • Add configuration file for system default values
  • Support file-based passwords
  • Support user-supplied options on the interface methods in order to support cryptographic functionality other than the default, baked-in settings
  • Add failure-case unit tests
  • Code review

Internet/Network Gotchas

The following forty five (45) Internet/network security gotchas are taken from Firewalls and Internet Security – Repelling the Wily Hacker, Second Edition (ISBN: 0-201-63344-X) by William R. Cheswick, et. al.

  1. IP source addresses aren’t trustable.
  2. Fragmented packets have been abused to avoid security checks.
  3. ARP-spoofing can lead to session-hijacking.
  4. Sequence number attacks can be used to subvert address-based authentication.
  5. It is easy to spoof UDP packets.
  6. ICMP Redirect messages can subvert routing tables.
  7. IP source routing can address-based authentication.
  8. It is easy to generate bogus RIP messages.
  9. The inverse DNS tree can be used for name-spoofing.
  10. The DNS cache can be contaminated to foil cross-checks.
  11. IPv6 network numbers may change frequently.
  12. IPv6 host addresses change frequently, too.
  13. WEP is useless.
  14. Attackers have the luxury of using nonstandard equipment.
  15. Return addresses in mail aren’t reliable, and this fact is easily forgotten.
  16. Don’t blindly execute MIME messages.
  17. Don’t trust RPC‘s machine name field.
  18. Rpcbind can call RPC services for its caller.
  19. NIS can often be persuaded to give out password files.
  20. It is sometimes possible to direct machines to phony NIS servers.
  21. If misconfigured, TFTP will had over sensitive files.
  22. Don’t make ftp‘s home directory writable by ftp.
  23. Don’t put a real password file in the anonymous ftp area.
  24. It is easy to wiretap telnet sessions.
  25. The r commands rely on address-based authentication.
  26. Be careful about interpreting WWW format information.
  27. WWW servers should be careful about URLs.
  28. Poorly written query scripts pose a danger to WWW servers.
  29. The MBone can be used to route through some firewalls.
  30. Scalable security administration of peer-to-peer nodes is difficult.
  31. An attacker anywhere on the Internet can probe for X11 servers.
  32. UDP-based services can be abused to create broadcast storms.
  33. Web servers shouldn’t believe uploaded state variables.
  34. Signed code is not necessarily safe code.
  35. [Client-side script] is dangerous.
  36. Users are ill-equipped to make correct security choices.
  37. Humans choose lousy passwords.
  38. There are lots of ways to grab /etc/passwd.
  39. There is no absolute remedy for a denial-of-service attack.
  40. Hackers plant sniffers.
  41. Network monitoring tools can be very dangerous on an exposed machine.
  42. Don’t believe port numbers supplied by outside machines.
  43. It is all but impossible to permit most UDP traffic through a packet filter safely.
  44. A tunnel can be built on top of almost any transport mechanism.
  45. If the connection is vital, don’t use a public network.

Security Truisms in Application Design and Architechture

Designing applications for the web requires an up-front security mind-set. It does not matter if the application takes credit card payments or if it hosts static web content. A public web site is just that: a public portal to computer assets that someone out there on the Internet will eventually find and will want to exploit for whatever nefarious reason entertains their interests, whatever it is.

The purpose of this post is to discuss the web application design and architecture security truisms that I have held true during my experience as a developer and architect. The following fifteen (15) security truisms are taken from Firewalls and Internet Security – Repelling the Wily Hacker, Second Edition (ISBN: 0-201-63344-X) by William R. Cheswick, et. al. These truisms are key to any security model – not just information security. For the purposes of this post, I will discuss how they relate to application design and architecture.

  1. There is no such thing as absolute security. Any web application deployed to a network, be it publicly on the Internet, internally on an Intranet, or even privately on an extranet, will not be absolutely secure. This is due to the fact that it is connected to a network – the level of it’s security has been diminished purely by it’s nature of been deployed. This is a fact.
  2. Security is always a question of economics. The amount of security that a web application design employs is dependent upon the amount of security infrastructure the application owner is willing to pay for. Though tighter security can be bought with hardware cryptography, LDAP servers, etc., it’s always a question of cost vs. how much risk the application owner is willing to accept. In the end, it’s a question of balance.
  3. Keep the level of all your defenses at the same height. This is a tricky one that many people overlook – balance. The level of an application’s should balance the level of security of the environment in which it is being deployed. This includes, but is not limited to, the level of physical and software firewall protection, the amount and type of intrusion detection systems, etc. It doesn’t make a lot of sense to blow out the security architecture of a web application if it’s going to be deployed in your brother’s basement on his Wi-Fi router. Conversely, it makes equally less sense to deploy a an insecure web application in a shared hosting environment that hosts credit card payment applications.
  4. An attacker doesn’t go through security, but around it. The web application should not be designed as another security hole in the web site’s security! Attackers will look for weaknesses in web applications deployed to a web site and exploit them.
  5. Put your defenses in layers.
  6. It’s a bad idea to rely on “security through obscurity.” Compiling the password into the source code, believing it won’t be found because it has been “obscured”, is stupid. I’m sorry, I said it. I’ve seen it done before. Put hope in the cost/benefit of hiding secrets in plain site will only reek havoc in the end.
  7. Keep it simple. Cleaner, well documented code is easier to maintain. Easier maintained code is even easier to secure.
  8. Don’t give a person or a program any more privileges than those necessary to do the job. Developers don’t need access to secured resources. The exception is source code repositories, development databases, development LDAP servers, etc. Web applications should be deployed by deployers, not developers. The production authentication credentials should be provided to system administrators that set up the web application server infrastructure. A truly well designed application architecture will not require a developer or deployer to know the production authentication credentials of protected resources such as databases, LDAP servers, or hardware key stores.
  9. Programming is hard. Secure programming is harder. Don’t make the job harder than it needs to be. Use common components commonly accepted by the global development community. Don’t reinvent the wheel by rewriting cryptography algorithms. Reuse code and see #7.
  10. Security should be an integral part of the original design.
  11. If you do not run a program, it does not matter if it has security holes. If you do not deploy a web application, it does not matter if it is insecure. However, no one will be able to access it.
  12. A program or protocol is insecure until proven secure. Run web application vulnerability scanning tools. You will be surprised what you will find – and what you will learn about secure programming practices.
  13. A chain is only as strong as its weakest link. Our hosting environment can provide us with the strongest firewalls and intrusion detection systems. However, we are writing software, too. The software we write is just one more link the chain. That link must be designed as strong as the rest of the links in chain.
  14. Security is a trade-off with convenience. And, as security often inconveniences users, the application owner will often feel inconvenienced by higher levels of security. This is where discussions on “single-sign-on” begin. For any given company, a users will want to sign-in to the web site once. To sign-in again will be an inconvenience. To have to remember more than one password is even more inconvenient. Ergo, without a “single-sign-on” solution in place, users will feel inconvenienced if they have to sign-in every time the visit a different web site that requires authentication for a given company.
  15. Don’t underestimate the value of your assets. Just because the web application does not perform secure payment transactions does not mean that it isn’t attractive to attackers. Any computer resource on the Internet can be used as a host for an attack for whatever reason.

All this being said, secure web application design is possible, affordable, and necessary. It must be thought out and balanced against the needs of the application owner and deployment environment. As technology professionals, we are all responsible for the web applications that we design, implement, and deploy because, as any software being run in a remote hosting environment, we provide the gateway between our computer assets and the world wide web.