2 // vim: foldmethod=marker
4 /* Generic exception class
6 class OAuthException extends Exception {
14 function __construct($key, $secret, $callback_url=NULL) {
16 $this->secret = $secret;
17 $this->callback_url = $callback_url;
20 function __toString() {
21 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
26 // access tokens and request tokens
32 * secret = the token secret
34 function __construct($key, $secret) {
36 $this->secret = $secret;
40 * generates the basic string serialization of a token that a server
41 * would respond to request_token and access_token calls with
43 function to_string() {
44 return "oauth_token=" .
45 OAuthUtil::urlencode_rfc3986($this->key) .
46 "&oauth_token_secret=" .
47 OAuthUtil::urlencode_rfc3986($this->secret);
50 function __toString() {
51 return $this->to_string();
56 * A class for implementing a Signature Method
57 * See section 9 ("Signing Requests") in the spec
59 abstract class OAuthSignatureMethod {
61 * Needs to return the name of the Signature Method (ie HMAC-SHA1)
64 abstract public function get_name();
67 * Build up the signature
68 * NOTE: The output of this function MUST NOT be urlencoded.
69 * the encoding is handled in OAuthRequest when the final
70 * request is serialized
71 * @param OAuthRequest $request
72 * @param OAuthConsumer $consumer
73 * @param OAuthToken $token
76 abstract public function build_signature($request, $consumer, $token);
79 * Verifies that a given signature is correct
80 * @param OAuthRequest $request
81 * @param OAuthConsumer $consumer
82 * @param OAuthToken $token
83 * @param string $signature
86 public function check_signature($request, $consumer, $token, $signature) {
87 $built = $this->build_signature($request, $consumer, $token);
89 // Check for zero length, although unlikely here
90 if (strlen($built) == 0 || strlen($signature) == 0) {
94 if (strlen($built) != strlen($signature)) {
98 // Avoid a timing leak with a (hopefully) time insensitive compare
100 for ($i = 0; $i < strlen($signature); $i++) {
101 $result |= ord($built{$i}) ^ ord($signature{$i});
109 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
110 * where the Signature Base String is the text and the key is the concatenated values (each first
111 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
112 * character (ASCII code 38) even if empty.
113 * - Chapter 9.2 ("HMAC-SHA1")
115 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
116 function get_name() {
120 public function build_signature($request, $consumer, $token) {
121 $base_string = $request->get_signature_base_string();
122 $request->base_string = $base_string;
126 ($token) ? $token->secret : ""
129 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
130 $key = implode('&', $key_parts);
132 return base64_encode(hash_hmac('sha1', $base_string, $key, true));
137 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
138 * over a secure channel such as HTTPS. It does not use the Signature Base String.
139 * - Chapter 9.4 ("PLAINTEXT")
141 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
142 public function get_name() {
147 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
148 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
149 * empty. The result MUST be encoded again.
150 * - Chapter 9.4.1 ("Generating Signatures")
152 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
153 * OAuthRequest handles this!
155 public function build_signature($request, $consumer, $token) {
158 ($token) ? $token->secret : ""
161 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
162 $key = implode('&', $key_parts);
163 $request->base_string = $key;
170 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
171 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
172 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
173 * verified way to the Service Provider, in a manner which is beyond the scope of this
175 * - Chapter 9.3 ("RSA-SHA1")
177 abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
178 public function get_name() {
182 // Up to the SP to implement this lookup of keys. Possible ideas are:
183 // (1) do a lookup in a table of trusted certs keyed off of consumer
184 // (2) fetch via http using a url provided by the requester
185 // (3) some sort of specific discovery code based on request
187 // Either way should return a string representation of the certificate
188 protected abstract function fetch_public_cert(&$request);
190 // Up to the SP to implement this lookup of keys. Possible ideas are:
191 // (1) do a lookup in a table of trusted certs keyed off of consumer
193 // Either way should return a string representation of the certificate
194 protected abstract function fetch_private_cert(&$request);
196 public function build_signature($request, $consumer, $token) {
197 $base_string = $request->get_signature_base_string();
198 $request->base_string = $base_string;
200 // Fetch the private key cert based on the request
201 $cert = $this->fetch_private_cert($request);
203 // Pull the private key ID from the certificate
204 $privatekeyid = openssl_get_privatekey($cert);
206 // Sign using the key
207 $ok = openssl_sign($base_string, $signature, $privatekeyid);
209 // Release the key resource
210 openssl_free_key($privatekeyid);
212 return base64_encode($signature);
215 public function check_signature($request, $consumer, $token, $signature) {
216 $decoded_sig = base64_decode($signature);
218 $base_string = $request->get_signature_base_string();
220 // Fetch the public key cert based on the request
221 $cert = $this->fetch_public_cert($request);
223 // Pull the public key ID from the certificate
224 $publickeyid = openssl_get_publickey($cert);
226 // Check the computed signature against the one passed in the query
227 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
229 // Release the key resource
230 openssl_free_key($publickeyid);
237 protected $parameters;
238 protected $http_method;
240 // for debug purposes
242 public static $version = '1.0';
243 public static $POST_INPUT = 'php://input';
245 function __construct($http_method, $http_url, $parameters=NULL) {
246 $parameters = ($parameters) ? $parameters : array();
247 $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
248 $this->parameters = $parameters;
249 $this->http_method = $http_method;
250 $this->http_url = $http_url;
255 * attempt to build up a request from what was passed to the server
257 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
258 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
261 $http_url = ($http_url) ? $http_url : $scheme .
262 '://' . $_SERVER['SERVER_NAME'] .
264 $_SERVER['SERVER_PORT'] .
265 $_SERVER['REQUEST_URI'];
266 $http_method = ($http_method) ? $http_method : $_SERVER['REQUEST_METHOD'];
268 // We weren't handed any parameters, so let's find the ones relevant to
270 // If you run XML-RPC or similar you should use this to provide your own
271 // parsed parameter-list
273 // Find request headers
274 $request_headers = OAuthUtil::get_headers();
276 // Parse the query-string to find GET parameters
277 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
279 // It's a POST request of the proper content-type, so parse POST
280 // parameters and add those overriding any duplicates from GET
281 if ($http_method == "POST"
282 && isset($request_headers['Content-Type'])
283 && strstr($request_headers['Content-Type'],
284 'application/x-www-form-urlencoded')
286 $post_data = OAuthUtil::parse_parameters(
287 file_get_contents(self::$POST_INPUT)
289 $parameters = array_merge($parameters, $post_data);
292 // We have a Authorization-header with OAuth data. Parse the header
293 // and add those overriding any duplicates from GET or POST
294 if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == 'OAuth ') {
295 $header_parameters = OAuthUtil::split_header(
296 $request_headers['Authorization']
298 $parameters = array_merge($parameters, $header_parameters);
303 return new OAuthRequest($http_method, $http_url, $parameters);
307 * pretty much a helper function to set up the request
309 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
310 $parameters = ($parameters) ? $parameters : array();
311 $defaults = array("oauth_version" => OAuthRequest::$version,
312 "oauth_nonce" => OAuthRequest::generate_nonce(),
313 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
314 "oauth_consumer_key" => $consumer->key);
316 $defaults['oauth_token'] = $token->key;
318 $parameters = array_merge($defaults, $parameters);
320 return new OAuthRequest($http_method, $http_url, $parameters);
323 public function set_parameter($name, $value, $allow_duplicates = true) {
324 if ($allow_duplicates && isset($this->parameters[$name])) {
325 // We have already added parameter(s) with this name, so add to the list
326 if (is_scalar($this->parameters[$name])) {
327 // This is the first duplicate, so transform scalar (string)
328 // into an array so we can add the duplicates
329 $this->parameters[$name] = array($this->parameters[$name]);
332 $this->parameters[$name][] = $value;
334 $this->parameters[$name] = $value;
338 public function get_parameter($name) {
339 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
342 public function get_parameters() {
343 return $this->parameters;
346 public function unset_parameter($name) {
347 unset($this->parameters[$name]);
351 * The request parameters, sorted and concatenated into a normalized string.
354 public function get_signable_parameters() {
355 // Grab all parameters
356 $params = $this->parameters;
358 // Remove oauth_signature if present
359 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
360 if (isset($params['oauth_signature'])) {
361 unset($params['oauth_signature']);
364 return OAuthUtil::build_http_query($params);
368 * Returns the base string of this request
370 * The base string defined as the method, the url
371 * and the parameters (normalized), each urlencoded
372 * and the concated with &.
374 public function get_signature_base_string() {
376 $this->get_normalized_http_method(),
377 $this->get_normalized_http_url(),
378 $this->get_signable_parameters()
381 $parts = OAuthUtil::urlencode_rfc3986($parts);
383 return implode('&', $parts);
387 * just uppercases the http method
389 public function get_normalized_http_method() {
390 return strtoupper($this->http_method);
394 * parses the url and rebuilds it to be
397 public function get_normalized_http_url() {
398 $parts = parse_url($this->http_url);
400 $scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http';
401 $port = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80');
402 $host = (isset($parts['host'])) ? strtolower($parts['host']) : '';
403 $path = (isset($parts['path'])) ? $parts['path'] : '';
405 if (($scheme == 'https' && $port != '443')
406 || ($scheme == 'http' && $port != '80')) {
407 $host = "$host:$port";
409 return "$scheme://$host$path";
413 * builds a url usable for a GET request
415 public function to_url() {
416 $post_data = $this->to_postdata();
417 $out = $this->get_normalized_http_url();
419 $out .= '?'.$post_data;
425 * builds the data one would send in a POST request
427 public function to_postdata() {
428 return OAuthUtil::build_http_query($this->parameters);
432 * builds the Authorization: header
434 public function to_header($realm=null) {
437 $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
440 $out = 'Authorization: OAuth';
443 foreach ($this->parameters as $k => $v) {
444 if (substr($k, 0, 5) != "oauth") continue;
446 throw new OAuthException('Arrays not supported in headers');
448 $out .= ($first) ? ' ' : ',';
449 $out .= OAuthUtil::urlencode_rfc3986($k) .
451 OAuthUtil::urlencode_rfc3986($v) .
458 public function __toString() {
459 return $this->to_url();
463 public function sign_request($signature_method, $consumer, $token) {
464 $this->set_parameter(
465 "oauth_signature_method",
466 $signature_method->get_name(),
469 $signature = $this->build_signature($signature_method, $consumer, $token);
470 $this->set_parameter("oauth_signature", $signature, false);
473 public function build_signature($signature_method, $consumer, $token) {
474 $signature = $signature_method->build_signature($this, $consumer, $token);
479 * util function: current timestamp
481 private static function generate_timestamp() {
486 * util function: current nonce
488 private static function generate_nonce() {
492 return md5($mt . $rand); // md5s look nicer than numbers
497 protected $timestamp_threshold = 300; // in seconds, five minutes
498 protected $version = '1.0'; // hi blaine
499 protected $signature_methods = array();
501 protected $data_store;
503 function __construct($data_store) {
504 $this->data_store = $data_store;
507 public function add_signature_method($signature_method) {
508 $this->signature_methods[$signature_method->get_name()] =
512 // high level functions
515 * process a request_token request
516 * returns the request token on success
518 public function fetch_request_token(&$request) {
519 $this->get_version($request);
521 $consumer = $this->get_consumer($request);
523 // no token required for the initial token request
526 $this->check_signature($request, $consumer, $token);
529 $callback = $request->get_parameter('oauth_callback');
530 $new_token = $this->data_store->new_request_token($consumer, $callback);
536 * process an access_token request
537 * returns the access token on success
539 public function fetch_access_token(&$request) {
540 $this->get_version($request);
542 $consumer = $this->get_consumer($request);
544 // requires authorized request token
545 $token = $this->get_token($request, $consumer, "request");
547 $this->check_signature($request, $consumer, $token);
550 $verifier = $request->get_parameter('oauth_verifier');
551 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
557 * verify an api call, checks all the parameters
559 public function verify_request(&$request) {
560 $this->get_version($request);
561 $consumer = $this->get_consumer($request);
562 $token = $this->get_token($request, $consumer, "access");
563 $this->check_signature($request, $consumer, $token);
564 return array($consumer, $token);
567 // Internals from here
571 private function get_version(&$request) {
572 $version = $request->get_parameter("oauth_version");
574 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
575 // Chapter 7.0 ("Accessing Protected Ressources")
578 if ($version !== $this->version) {
579 throw new OAuthException("OAuth version '$version' not supported");
585 * figure out the signature with some defaults
587 private function get_signature_method($request) {
588 $signature_method = $request instanceof OAuthRequest
589 ? $request->get_parameter("oauth_signature_method")
592 if (!$signature_method) {
593 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
594 // parameter is required, and we can't just fallback to PLAINTEXT
595 throw new OAuthException('No signature method parameter. This parameter is required');
598 if (!in_array($signature_method,
599 array_keys($this->signature_methods))) {
600 throw new OAuthException(
601 "Signature method '$signature_method' not supported " .
602 "try one of the following: " .
603 implode(", ", array_keys($this->signature_methods))
606 return $this->signature_methods[$signature_method];
610 * try to find the consumer for the provided request's consumer key
612 private function get_consumer($request) {
613 $consumer_key = $request instanceof OAuthRequest
614 ? $request->get_parameter("oauth_consumer_key")
617 if (!$consumer_key) {
618 throw new OAuthException("Invalid consumer key");
621 $consumer = $this->data_store->lookup_consumer($consumer_key);
623 throw new OAuthException("Invalid consumer");
630 * try to find the token for the provided request's token key
632 private function get_token($request, $consumer, $token_type="access") {
633 $token_field = $request instanceof OAuthRequest
634 ? $request->get_parameter('oauth_token')
637 $token = $this->data_store->lookup_token(
638 $consumer, $token_type, $token_field
641 throw new OAuthException("Invalid $token_type token: $token_field");
647 * all-in-one function to check the signature on a request
648 * should guess the signature method appropriately
650 private function check_signature($request, $consumer, $token) {
651 // this should probably be in a different method
652 $timestamp = $request instanceof OAuthRequest
653 ? $request->get_parameter('oauth_timestamp')
655 $nonce = $request instanceof OAuthRequest
656 ? $request->get_parameter('oauth_nonce')
659 $this->check_timestamp($timestamp);
660 $this->check_nonce($consumer, $token, $nonce, $timestamp);
662 $signature_method = $this->get_signature_method($request);
664 $signature = $request->get_parameter('oauth_signature');
665 $valid_sig = $signature_method->check_signature(
673 throw new OAuthException("Invalid signature");
678 * check that the timestamp is new enough
680 private function check_timestamp($timestamp) {
682 throw new OAuthException(
683 'Missing timestamp parameter. The parameter is required'
686 // verify that timestamp is recentish
688 if (abs($now - $timestamp) > $this->timestamp_threshold) {
689 throw new OAuthException(
690 "Expired timestamp, yours $timestamp, ours $now"
696 * check that the nonce is not repeated
698 private function check_nonce($consumer, $token, $nonce, $timestamp) {
700 throw new OAuthException(
701 'Missing nonce parameter. The parameter is required'
704 // verify that the nonce is uniqueish
705 $found = $this->data_store->lookup_nonce(
712 throw new OAuthException("Nonce already used: $nonce");
718 class OAuthDataStore {
719 function lookup_consumer($consumer_key) {
723 function lookup_token($consumer, $token_type, $token) {
727 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
731 function new_request_token($consumer, $callback = null) {
732 // return a new token attached to this consumer
735 function new_access_token($token, $consumer, $verifier = null) {
736 // return a new access token attached to this consumer
737 // for the user associated with this token if the request token
739 // should also invalidate the request token
745 public static function urlencode_rfc3986($input) {
746 if (is_array($input)) {
747 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
748 } else if (is_scalar($input)) {
752 str_replace('%7E', '~', rawurlencode($input))
760 // This decode function isn't taking into consideration the above
761 // modifications to the encoding process. However, this method doesn't
762 // seem to be used anywhere so leaving it as is.
763 public static function urldecode_rfc3986($string) {
764 return urldecode($string);
767 // Utility function for turning the Authorization: header into
768 // parameters, has to do some unescaping
769 // Can filter out any non-oauth parameters if needed (default behaviour)
770 // May 28th, 2010 - method updated to tjerk.meesters for a speed improvement.
771 // see http://code.google.com/p/oauth/issues/detail?id=163
772 public static function split_header($header, $only_allow_oauth_parameters = true) {
774 if (preg_match_all('/('.($only_allow_oauth_parameters ? 'oauth_' : '').'[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $header, $matches)) {
775 foreach ($matches[1] as $i => $h) {
776 $params[$h] = OAuthUtil::urldecode_rfc3986(empty($matches[3][$i]) ? $matches[4][$i] : $matches[3][$i]);
778 if (isset($params['realm'])) {
779 unset($params['realm']);
785 // helper to try to sort out headers for people who aren't running apache
786 public static function get_headers() {
787 if (function_exists('apache_request_headers')) {
788 // we need this to get the actual Authorization: header
789 // because apache tends to tell us it doesn't exist
790 $headers = apache_request_headers();
792 // sanitize the output of apache_request_headers because
793 // we always want the keys to be Cased-Like-This and arh()
794 // returns the headers in the same case as they are in the
797 foreach ($headers AS $key => $value) {
801 ucwords(strtolower(str_replace("-", " ", $key)))
806 // otherwise we don't have apache and are just going to have to hope
807 // that $_SERVER actually contains what we need
809 if( isset($_SERVER['CONTENT_TYPE']) )
810 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
811 if( isset($_ENV['CONTENT_TYPE']) )
812 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
814 foreach ($_SERVER as $key => $value) {
815 if (substr($key, 0, 5) == "HTTP_") {
816 // this is chaos, basically it is just there to capitalize the first
817 // letter of every word that is not an initial HTTP and strip HTTP
822 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
831 // This function takes a input like a=b&a=c&d=e and returns the parsed
832 // parameters like this
833 // array('a' => array('b','c'), 'd' => 'e')
834 public static function parse_parameters( $input ) {
835 if (!isset($input) || !$input) return array();
837 $pairs = explode('&', $input);
839 $parsed_parameters = array();
840 foreach ($pairs as $pair) {
841 $split = explode('=', $pair, 2);
842 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
843 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
845 if (isset($parsed_parameters[$parameter])) {
846 // We have already recieved parameter(s) with this name, so add to the list
847 // of parameters with this name
849 if (is_scalar($parsed_parameters[$parameter])) {
850 // This is the first duplicate, so transform scalar (string) into an array
851 // so we can add the duplicates
852 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
855 $parsed_parameters[$parameter][] = $value;
857 $parsed_parameters[$parameter] = $value;
860 return $parsed_parameters;
863 public static function build_http_query($params) {
864 if (!$params) return '';
866 // Urlencode both keys and values
867 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
868 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
869 $params = array_combine($keys, $values);
871 // Parameters are sorted by name, using lexicographical byte value ordering.
872 // Ref: Spec: 9.1.1 (1)
873 uksort($params, 'strcmp');
876 foreach ($params as $parameter => $value) {
877 if (is_array($value)) {
878 // If two or more parameters share the same name, they are sorted by their value
879 // Ref: Spec: 9.1.1 (1)
880 // June 12th, 2010 - changed to sort because of issue 164 by hidetaka
881 sort($value, SORT_STRING);
882 foreach ($value as $duplicate_value) {
883 $pairs[] = $parameter . '=' . $duplicate_value;
886 $pairs[] = $parameter . '=' . $value;
889 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
890 // Each name-value pair is separated by an '&' character (ASCII code 38)
891 return implode('&', $pairs);