views:

124

answers:

5

I have configured the wildcard DNS of *.mydomain.com and it's all working properly. My question is which of these should I rely on identifying client subdomain requests?

  1. $_SERVER["HTTP_HOST"]
  2. $_SERVER["SERVER_NAME"]
  3. $_SERVER["SCRIPT_URI"]

They all seem to contain the subdomain part I want but after reading this article by Chris: http://shiflett.org/blog/2006/mar/server-name-versus-http-host, I'm lost at sea and there appears to be no safe way to do this?

Any idea on accomplishing this task securely? Which approach would you prefer?

Update: sorry, I meant this post: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

+1  A: 

I'd suggest that you get the current page url, then use a regular expression to check. Be sure to ignore things link www, www2, etc.

sjobe
A: 
$subdomain = explode('.', $_SERVER['HTTP_HOST'], -2);

Returns an array always, and can be empty if there is no sub domain. You should also make sure to notice that this could return www as an array value and that would link to your root domain anyway.

Mark Tomlin
A: 

You can use any but most use HTTP_HOST.

You don't have to worry about 'security' here since you allow a wildcard for your subdomains. You won't be able to stop a user from entering a 'threatening' subdomain and sending a request to your server.

If you want to disallow certain subdomains then you have several options but thats a different question.

zaf
Funny logic. "Don't worry as you can't prevent an attack anyway". What if he can?
Col. Shrapnel
Am I missing some form of attack that exploits the subdomains part of the URL even if the code is just 'identifying' the subdomain?
zaf
@Col. Shrapnel: You cannot prevent attacks. You can only prevent that these attacks are successful.
Gumbo
@Gumbo sure. but I think "you don't have to worry" is wrong conclusion anyway :)
Col. Shrapnel
A: 

Too much talk of such a little problem.
Everyone says its dangerous but noone bother to write a solution, as simple as

$mydomain='example.com';
$subdomain="";
$matches=array();

$pat='!([a-z0-9_]+)\.'.preg_quote($mydomain).'$!i';
if (preg_match($pat,$_SERVER['HTTP_HOST'],$matches)) $subdomain=$matches[1];
Col. Shrapnel
+1  A: 

HTTP_HOST comes directly from the HOST header. Apache does not clean it up in any way. Even for non-wildcard setups, your first virtualhost in your config will receive a request for a HOST header that doesn't match any of your configured vhosts, so you have to be careful with it. Treat it like any other user data. Filter it appropriately before using it.

Rasmus