how to verify the requesting server in php?

2019-01-12 08:05发布

问题:

I have a php page "server1.com/page1.php" (not real) and another page "server2.com/page2.php"

page1.php response according to the parameter passed by URL which can come from any server.

but how can i check that whether "server1.com/page1.php" is called from "server2.com/page2.php" or not.

thanks in advance

回答1:

There are many ways this could be implemented.

This easiest way is to check the $_SERVER['HTTP_REFERER'] to see if it matches, although this is not 100% reliable, and is not true security.

A second method would be to use PHP's session functionality. This would require that the two servers use a shared session tracking area though, which is a much more advanced server setup.

A third method would be to use a shared MySQL server that both can access to verify requests. This will introduce latency, which may slow down the request a bit.

A fourth method would be to use a call back to the originating server to verify it did make the request. Server2 makes the request to Server1, then Server1 contacts Server2 and asks if the request it just received actually came from it.

A fifth method is to sign your request using a private/public key pair. This way you can verify for sure that the request came specifically from the server it claims it is.



回答2:

I've done this before, using hashing, a known secret and a timestamp. The timestamp is necessary to ensure that a potential eavesdropper cannot replay this process at any time they choose.

  • Server 1 gets the time, rounds it to the nearest minute
  • Concatenate it with a known secret stored in a file (a long random string, say 40 characters)
  • Take a SHA1 of the concatenated string (or whatever hashing system you prefer1)
  • Send to server 2
  • Server 2 does the same process with the rounded time below and above the current time, which allows for some inaccuracy in server clocks.

Optionally, I'd consider adding in the hash of the username, so that even if a replay attack was possible, it would be locked to a single username.

1 These days SHA1 sounds a bit too fast. The algorithms for password_hash would probably be much better, as they are intentionally slower - and you can configure extra rounds trivially if you wish.



回答3:

Have page1.php set a session variable that page2.php checks for.



标签: php security