2 // vim: foldmethod=marker
4 /* Generic exception class
6 if (!class_exists('OAuthException')) {
7 class OAuthException
extends Exception
{
16 function __construct($key, $secret, $callback_url=NULL) {
18 $this->secret
= $secret;
19 $this->callback_url
= $callback_url;
22 function __toString() {
23 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
28 // access tokens and request tokens
34 * secret = the token secret
36 function __construct($key, $secret) {
38 $this->secret
= $secret;
42 * generates the basic string serialization of a token that a server
43 * would respond to request_token and access_token calls with
45 function to_string() {
46 return "oauth_token=" .
47 OAuthUtil
::urlencode_rfc3986($this->key
) .
48 "&oauth_token_secret=" .
49 OAuthUtil
::urlencode_rfc3986($this->secret
);
52 function __toString() {
53 return $this->to_string();
58 * A class for implementing a Signature Method
59 * See section 9 ("Signing Requests") in the spec
61 abstract class OAuthSignatureMethod
{
63 * Needs to return the name of the Signature Method (ie HMAC-SHA1)
66 abstract public function get_name();
69 * Build up the signature
70 * NOTE: The output of this function MUST NOT be urlencoded.
71 * the encoding is handled in OAuthRequest when the final
72 * request is serialized
73 * @param OAuthRequest $request
74 * @param OAuthConsumer $consumer
75 * @param OAuthToken $token
78 abstract public function build_signature($request, $consumer, $token);
81 * Verifies that a given signature is correct
82 * @param OAuthRequest $request
83 * @param OAuthConsumer $consumer
84 * @param OAuthToken $token
85 * @param string $signature
88 public function check_signature($request, $consumer, $token, $signature) {
89 $built = $this->build_signature($request, $consumer, $token);
90 return $built == $signature;
95 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
96 * where the Signature Base String is the text and the key is the concatenated values (each first
97 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
98 * character (ASCII code 38) even if empty.
99 * - Chapter 9.2 ("HMAC-SHA1")
101 class OAuthSignatureMethod_HMAC_SHA1
extends OAuthSignatureMethod
{
102 function get_name() {
106 public function build_signature($request, $consumer, $token) {
107 $base_string = $request->get_signature_base_string();
108 $request->base_string
= $base_string;
112 ($token) ?
$token->secret
: ""
115 $key_parts = OAuthUtil
::urlencode_rfc3986($key_parts);
116 $key = implode('&', $key_parts);
118 return base64_encode(hash_hmac('sha1', $base_string, $key, true));
123 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
124 * over a secure channel such as HTTPS. It does not use the Signature Base String.
125 * - Chapter 9.4 ("PLAINTEXT")
127 class OAuthSignatureMethod_PLAINTEXT
extends OAuthSignatureMethod
{
128 public function get_name() {
133 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
134 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
135 * empty. The result MUST be encoded again.
136 * - Chapter 9.4.1 ("Generating Signatures")
138 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
139 * OAuthRequest handles this!
141 public function build_signature($request, $consumer, $token) {
144 ($token) ?
$token->secret
: ""
147 $key_parts = OAuthUtil
::urlencode_rfc3986($key_parts);
148 $key = implode('&', $key_parts);
149 $request->base_string
= $key;
156 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
157 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
158 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
159 * verified way to the Service Provider, in a manner which is beyond the scope of this
161 * - Chapter 9.3 ("RSA-SHA1")
163 abstract class OAuthSignatureMethod_RSA_SHA1
extends OAuthSignatureMethod
{
164 public function get_name() {
168 // Up to the SP to implement this lookup of keys. Possible ideas are:
169 // (1) do a lookup in a table of trusted certs keyed off of consumer
170 // (2) fetch via http using a url provided by the requester
171 // (3) some sort of specific discovery code based on request
173 // Either way should return a string representation of the certificate
174 protected abstract function fetch_public_cert(&$request);
176 // Up to the SP to implement this lookup of keys. Possible ideas are:
177 // (1) do a lookup in a table of trusted certs keyed off of consumer
179 // Either way should return a string representation of the certificate
180 protected abstract function fetch_private_cert(&$request);
182 public function build_signature($request, $consumer, $token) {
183 $base_string = $request->get_signature_base_string();
184 $request->base_string
= $base_string;
186 // Fetch the private key cert based on the request
187 $cert = $this->fetch_private_cert($request);
189 // Pull the private key ID from the certificate
190 $privatekeyid = openssl_get_privatekey($cert);
192 // Sign using the key
193 $ok = openssl_sign($base_string, $signature, $privatekeyid);
195 // Release the key resource
196 openssl_free_key($privatekeyid);
198 return base64_encode($signature);
201 public function check_signature($request, $consumer, $token, $signature) {
202 $decoded_sig = base64_decode($signature);
204 $base_string = $request->get_signature_base_string();
206 // Fetch the public key cert based on the request
207 $cert = $this->fetch_public_cert($request);
209 // Pull the public key ID from the certificate
210 $publickeyid = openssl_get_publickey($cert);
212 // Check the computed signature against the one passed in the query
213 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
215 // Release the key resource
216 openssl_free_key($publickeyid);
224 private $http_method;
226 // for debug purposes
228 public static $version = '1.0';
229 public static $POST_INPUT = 'php://input';
231 function __construct($http_method, $http_url, $parameters=NULL) {
232 @$parameters or $parameters = array();
233 $parameters = array_merge( OAuthUtil
::parse_parameters(parse_url($http_url, PHP_URL_QUERY
)), $parameters);
234 $this->parameters
= $parameters;
235 $this->http_method
= $http_method;
236 $this->http_url
= $http_url;
241 * attempt to build up a request from what was passed to the server
243 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
244 $scheme = (!isset($_SERVER['HTTPS']) ||
$_SERVER['HTTPS'] != "on")
247 @$http_url or $http_url = $scheme .
248 '://' . $_SERVER['HTTP_HOST'] .
250 $_SERVER['SERVER_PORT'] .
251 $_SERVER['REQUEST_URI'];
252 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
254 // We weren't handed any parameters, so let's find the ones relevant to
256 // If you run XML-RPC or similar you should use this to provide your own
257 // parsed parameter-list
259 // Find request headers
260 $request_headers = OAuthUtil
::get_headers();
262 // Parse the query-string to find GET parameters
263 $parameters = OAuthUtil
::parse_parameters($_SERVER['QUERY_STRING']);
265 // It's a POST request of the proper content-type, so parse POST
266 // parameters and add those overriding any duplicates from GET
267 if ($http_method == "POST"
268 && @strstr
($request_headers["Content-Type"],
269 "application/x-www-form-urlencoded")
271 $post_data = OAuthUtil
::parse_parameters(
272 file_get_contents(self
::$POST_INPUT)
274 $parameters = array_merge($parameters, $post_data);
277 // We have a Authorization-header with OAuth data. Parse the header
278 // and add those overriding any duplicates from GET or POST
279 if (@substr
($request_headers['Authorization'], 0, 6) == "OAuth ") {
280 $header_parameters = OAuthUtil
::split_header(
281 $request_headers['Authorization']
283 $parameters = array_merge($parameters, $header_parameters);
288 return new OAuthRequest($http_method, $http_url, $parameters);
292 * pretty much a helper function to set up the request
294 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
295 @$parameters or $parameters = array();
296 $defaults = array("oauth_version" => OAuthRequest
::$version,
297 "oauth_nonce" => OAuthRequest
::generate_nonce(),
298 "oauth_timestamp" => OAuthRequest
::generate_timestamp(),
299 "oauth_consumer_key" => $consumer->key
);
301 $defaults['oauth_token'] = $token->key
;
303 $parameters = array_merge($defaults, $parameters);
305 return new OAuthRequest($http_method, $http_url, $parameters);
308 public function set_parameter($name, $value, $allow_duplicates = true) {
309 if ($allow_duplicates && isset($this->parameters
[$name])) {
310 // We have already added parameter(s) with this name, so add to the list
311 if (is_scalar($this->parameters
[$name])) {
312 // This is the first duplicate, so transform scalar (string)
313 // into an array so we can add the duplicates
314 $this->parameters
[$name] = array($this->parameters
[$name]);
317 $this->parameters
[$name][] = $value;
319 $this->parameters
[$name] = $value;
323 public function get_parameter($name) {
324 return isset($this->parameters
[$name]) ?
$this->parameters
[$name] : null;
327 public function get_parameters() {
328 return $this->parameters
;
331 public function unset_parameter($name) {
332 unset($this->parameters
[$name]);
336 * The request parameters, sorted and concatenated into a normalized string.
339 public function get_signable_parameters() {
340 // Grab all parameters
341 $params = $this->parameters
;
343 // Remove oauth_signature if present
344 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
345 if (isset($params['oauth_signature'])) {
346 unset($params['oauth_signature']);
349 return OAuthUtil
::build_http_query($params);
353 * Returns the base string of this request
355 * The base string defined as the method, the url
356 * and the parameters (normalized), each urlencoded
357 * and the concated with &.
359 public function get_signature_base_string() {
361 $this->get_normalized_http_method(),
362 $this->get_normalized_http_url(),
363 $this->get_signable_parameters()
366 $parts = OAuthUtil
::urlencode_rfc3986($parts);
368 return implode('&', $parts);
372 * just uppercases the http method
374 public function get_normalized_http_method() {
375 return strtoupper($this->http_method
);
379 * parses the url and rebuilds it to be
382 public function get_normalized_http_url() {
383 $parts = parse_url($this->http_url
);
385 $port = @$parts['port'];
386 $scheme = $parts['scheme'];
387 $host = $parts['host'];
388 $path = @$parts['path'];
390 $port or $port = ($scheme == 'https') ?
'443' : '80';
392 if (($scheme == 'https' && $port != '443')
393 ||
($scheme == 'http' && $port != '80')) {
394 $host = "$host:$port";
396 return "$scheme://$host$path";
400 * builds a url usable for a GET request
402 public function to_url() {
403 $post_data = $this->to_postdata();
404 $out = $this->get_normalized_http_url();
406 $out .= '?'.$post_data;
412 * builds the data one would send in a POST request
414 public function to_postdata() {
415 return OAuthUtil
::build_http_query($this->parameters
);
419 * builds the Authorization: header
421 public function to_header($realm=null) {
424 $out = 'Authorization: OAuth realm="' . OAuthUtil
::urlencode_rfc3986($realm) . '"';
427 $out = 'Authorization: OAuth';
430 foreach ($this->parameters
as $k => $v) {
431 if (substr($k, 0, 5) != "oauth") continue;
433 throw new OAuthException('Arrays not supported in headers');
435 $out .= ($first) ?
' ' : ',';
436 $out .= OAuthUtil
::urlencode_rfc3986($k) .
438 OAuthUtil
::urlencode_rfc3986($v) .
445 public function __toString() {
446 return $this->to_url();
450 public function sign_request($signature_method, $consumer, $token) {
451 $this->set_parameter(
452 "oauth_signature_method",
453 $signature_method->get_name(),
456 $signature = $this->build_signature($signature_method, $consumer, $token);
457 $this->set_parameter("oauth_signature", $signature, false);
460 public function build_signature($signature_method, $consumer, $token) {
461 $signature = $signature_method->build_signature($this, $consumer, $token);
466 * util function: current timestamp
468 private static function generate_timestamp() {
473 * util function: current nonce
475 private static function generate_nonce() {
479 return md5($mt . $rand); // md5s look nicer than numbers
484 protected $timestamp_threshold = 300; // in seconds, five minutes
485 protected $version = '1.0'; // hi blaine
486 protected $signature_methods = array();
488 protected $data_store;
490 function __construct($data_store) {
491 $this->data_store
= $data_store;
494 public function add_signature_method($signature_method) {
495 $this->signature_methods
[$signature_method->get_name()] =
499 // high level functions
502 * process a request_token request
503 * returns the request token on success
505 public function fetch_request_token(&$request) {
506 $this->get_version($request);
508 $consumer = $this->get_consumer($request);
510 // no token required for the initial token request
513 $this->check_signature($request, $consumer, $token);
516 $callback = $request->get_parameter('oauth_callback');
517 $new_token = $this->data_store
->new_request_token($consumer, $callback);
523 * process an access_token request
524 * returns the access token on success
526 public function fetch_access_token(&$request) {
527 $this->get_version($request);
529 $consumer = $this->get_consumer($request);
531 // requires authorized request token
532 $token = $this->get_token($request, $consumer, "request");
534 $this->check_signature($request, $consumer, $token);
537 $verifier = $request->get_parameter('oauth_verifier');
538 $new_token = $this->data_store
->new_access_token($token, $consumer, $verifier);
544 * verify an api call, checks all the parameters
546 public function verify_request(&$request) {
547 $this->get_version($request);
548 $consumer = $this->get_consumer($request);
549 $token = $this->get_token($request, $consumer, "access");
550 $this->check_signature($request, $consumer, $token);
551 return array($consumer, $token);
554 // Internals from here
558 private function get_version(&$request) {
559 $version = $request->get_parameter("oauth_version");
561 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
562 // Chapter 7.0 ("Accessing Protected Ressources")
565 if ($version !== $this->version
) {
566 throw new OAuthException("OAuth version '$version' not supported");
572 * figure out the signature with some defaults
574 private function get_signature_method(&$request) {
576 @$request->get_parameter("oauth_signature_method");
578 if (!$signature_method) {
579 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
580 // parameter is required, and we can't just fallback to PLAINTEXT
581 throw new OAuthException('No signature method parameter. This parameter is required');
584 if (!in_array($signature_method,
585 array_keys($this->signature_methods
))) {
586 throw new OAuthException(
587 "Signature method '$signature_method' not supported " .
588 "try one of the following: " .
589 implode(", ", array_keys($this->signature_methods
))
592 return $this->signature_methods
[$signature_method];
596 * try to find the consumer for the provided request's consumer key
598 private function get_consumer(&$request) {
599 $consumer_key = @$request->get_parameter("oauth_consumer_key");
600 if (!$consumer_key) {
601 throw new OAuthException("Invalid consumer key");
604 $consumer = $this->data_store
->lookup_consumer($consumer_key);
606 throw new OAuthException("Invalid consumer");
613 * try to find the token for the provided request's token key
615 private function get_token(&$request, $consumer, $token_type="access") {
616 $token_field = @$request->get_parameter('oauth_token');
617 $token = $this->data_store
->lookup_token(
618 $consumer, $token_type, $token_field
621 throw new OAuthException("Invalid $token_type token: $token_field");
627 * all-in-one function to check the signature on a request
628 * should guess the signature method appropriately
630 private function check_signature(&$request, $consumer, $token) {
631 // this should probably be in a different method
632 $timestamp = @$request->get_parameter('oauth_timestamp');
633 $nonce = @$request->get_parameter('oauth_nonce');
635 $this->check_timestamp($timestamp);
636 $this->check_nonce($consumer, $token, $nonce, $timestamp);
638 $signature_method = $this->get_signature_method($request);
640 $signature = $request->get_parameter('oauth_signature');
641 $valid_sig = $signature_method->check_signature(
649 throw new OAuthException("Invalid signature");
654 * check that the timestamp is new enough
656 private function check_timestamp($timestamp) {
658 throw new OAuthException(
659 'Missing timestamp parameter. The parameter is required'
662 // verify that timestamp is recentish
664 if (abs($now - $timestamp) > $this->timestamp_threshold
) {
665 throw new OAuthException(
666 "Expired timestamp, yours $timestamp, ours $now"
672 * check that the nonce is not repeated
674 private function check_nonce($consumer, $token, $nonce, $timestamp) {
676 throw new OAuthException(
677 'Missing nonce parameter. The parameter is required'
680 // verify that the nonce is uniqueish
681 $found = $this->data_store
->lookup_nonce(
688 throw new OAuthException("Nonce already used: $nonce");
694 class OAuthDataStore
{
695 function lookup_consumer($consumer_key) {
699 function lookup_token($consumer, $token_type, $token) {
703 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
707 function new_request_token($consumer, $callback = null) {
708 // return a new token attached to this consumer
711 function new_access_token($token, $consumer, $verifier = null) {
712 // return a new access token attached to this consumer
713 // for the user associated with this token if the request token
715 // should also invalidate the request token
721 public static function urlencode_rfc3986($input) {
722 if (is_array($input)) {
723 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
724 } else if (is_scalar($input)) {
728 str_replace('%7E', '~', rawurlencode($input))
736 // This decode function isn't taking into consideration the above
737 // modifications to the encoding process. However, this method doesn't
738 // seem to be used anywhere so leaving it as is.
739 public static function urldecode_rfc3986($string) {
740 return urldecode($string);
743 // Utility function for turning the Authorization: header into
744 // parameters, has to do some unescaping
745 // Can filter out any non-oauth parameters if needed (default behaviour)
746 public static function split_header($header, $only_allow_oauth_parameters = true) {
747 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
750 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE
, $offset) > 0) {
751 $match = $matches[0];
752 $header_name = $matches[2][0];
753 $header_content = (isset($matches[5])) ?
$matches[5][0] : $matches[4][0];
754 if (preg_match('/^oauth_/', $header_name) ||
!$only_allow_oauth_parameters) {
755 $params[$header_name] = OAuthUtil
::urldecode_rfc3986($header_content);
757 $offset = $match[1] +
strlen($match[0]);
760 if (isset($params['realm'])) {
761 unset($params['realm']);
767 // helper to try to sort out headers for people who aren't running apache
768 public static function get_headers() {
769 if (function_exists('apache_request_headers')) {
770 // we need this to get the actual Authorization: header
771 // because apache tends to tell us it doesn't exist
772 $headers = apache_request_headers();
774 // sanitize the output of apache_request_headers because
775 // we always want the keys to be Cased-Like-This and arh()
776 // returns the headers in the same case as they are in the
779 foreach( $headers AS $key => $value ) {
783 ucwords(strtolower(str_replace("-", " ", $key)))
788 // otherwise we don't have apache and are just going to have to hope
789 // that $_SERVER actually contains what we need
791 if( isset($_SERVER['CONTENT_TYPE']) )
792 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
793 if( isset($_ENV['CONTENT_TYPE']) )
794 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
796 foreach ($_SERVER as $key => $value) {
797 if (substr($key, 0, 5) == "HTTP_") {
798 // this is chaos, basically it is just there to capitalize the first
799 // letter of every word that is not an initial HTTP and strip HTTP
804 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
813 // This function takes a input like a=b&a=c&d=e and returns the parsed
814 // parameters like this
815 // array('a' => array('b','c'), 'd' => 'e')
816 public static function parse_parameters( $input ) {
817 if (!isset($input) ||
!$input) return array();
819 $pairs = explode('&', $input);
821 $parsed_parameters = array();
822 foreach ($pairs as $pair) {
823 $split = explode('=', $pair, 2);
824 $parameter = OAuthUtil
::urldecode_rfc3986($split[0]);
825 $value = isset($split[1]) ? OAuthUtil
::urldecode_rfc3986($split[1]) : '';
827 if (isset($parsed_parameters[$parameter])) {
828 // We have already recieved parameter(s) with this name, so add to the list
829 // of parameters with this name
831 if (is_scalar($parsed_parameters[$parameter])) {
832 // This is the first duplicate, so transform scalar (string) into an array
833 // so we can add the duplicates
834 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
837 $parsed_parameters[$parameter][] = $value;
839 $parsed_parameters[$parameter] = $value;
842 return $parsed_parameters;
845 public static function build_http_query($params) {
846 if (!$params) return '';
848 // Urlencode both keys and values
849 $keys = OAuthUtil
::urlencode_rfc3986(array_keys($params));
850 $values = OAuthUtil
::urlencode_rfc3986(array_values($params));
851 $params = array_combine($keys, $values);
853 // Parameters are sorted by name, using lexicographical byte value ordering.
854 // Ref: Spec: 9.1.1 (1)
855 uksort($params, 'strcmp');
858 foreach ($params as $parameter => $value) {
859 if (is_array($value)) {
860 // If two or more parameters share the same name, they are sorted by their value
861 // Ref: Spec: 9.1.1 (1)
863 foreach ($value as $duplicate_value) {
864 $pairs[] = $parameter . '=' . $duplicate_value;
867 $pairs[] = $parameter . '=' . $value;
870 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
871 // Each name-value pair is separated by an '&' character (ASCII code 38)
872 return implode('&', $pairs);