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);
91 // Check for zero length, although unlikely here
92 if (strlen($built) == 0 || strlen($signature) == 0) {
96 if (strlen($built) != strlen($signature)) {
100 // Avoid a timing leak with a (hopefully) time insensitive compare
102 for ($i = 0; $i < strlen($signature); $i++) {
103 $result |= ord($built{$i}) ^ ord($signature{$i});
111 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
112 * where the Signature Base String is the text and the key is the concatenated values (each first
113 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
114 * character (ASCII code 38) even if empty.
115 * - Chapter 9.2 ("HMAC-SHA1")
117 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
118 function get_name() {
122 public function build_signature($request, $consumer, $token) {
123 $base_string = $request->get_signature_base_string();
124 $request->base_string = $base_string;
128 ($token) ? $token->secret : ""
131 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
132 $key = implode('&', $key_parts);
134 return base64_encode(hash_hmac('sha1', $base_string, $key, true));
139 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
140 * over a secure channel such as HTTPS. It does not use the Signature Base String.
141 * - Chapter 9.4 ("PLAINTEXT")
143 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
144 public function get_name() {
149 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
150 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
151 * empty. The result MUST be encoded again.
152 * - Chapter 9.4.1 ("Generating Signatures")
154 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
155 * OAuthRequest handles this!
157 public function build_signature($request, $consumer, $token) {
160 ($token) ? $token->secret : ""
163 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
164 $key = implode('&', $key_parts);
165 $request->base_string = $key;
172 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
173 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
174 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
175 * verified way to the Service Provider, in a manner which is beyond the scope of this
177 * - Chapter 9.3 ("RSA-SHA1")
179 abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
180 public function get_name() {
184 // Up to the SP to implement this lookup of keys. Possible ideas are:
185 // (1) do a lookup in a table of trusted certs keyed off of consumer
186 // (2) fetch via http using a url provided by the requester
187 // (3) some sort of specific discovery code based on request
189 // Either way should return a string representation of the certificate
190 protected abstract function fetch_public_cert(&$request);
192 // Up to the SP to implement this lookup of keys. Possible ideas are:
193 // (1) do a lookup in a table of trusted certs keyed off of consumer
195 // Either way should return a string representation of the certificate
196 protected abstract function fetch_private_cert(&$request);
198 public function build_signature($request, $consumer, $token) {
199 $base_string = $request->get_signature_base_string();
200 $request->base_string = $base_string;
202 // Fetch the private key cert based on the request
203 $cert = $this->fetch_private_cert($request);
205 // Pull the private key ID from the certificate
206 $privatekeyid = openssl_get_privatekey($cert);
208 // Sign using the key
209 $ok = openssl_sign($base_string, $signature, $privatekeyid);
211 // Release the key resource
212 openssl_free_key($privatekeyid);
214 return base64_encode($signature);
217 public function check_signature($request, $consumer, $token, $signature) {
218 $decoded_sig = base64_decode($signature);
220 $base_string = $request->get_signature_base_string();
222 // Fetch the public key cert based on the request
223 $cert = $this->fetch_public_cert($request);
225 // Pull the public key ID from the certificate
226 $publickeyid = openssl_get_publickey($cert);
228 // Check the computed signature against the one passed in the query
229 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
231 // Release the key resource
232 openssl_free_key($publickeyid);
239 protected $parameters;
240 protected $http_method;
242 // for debug purposes
244 public static $version = '1.0';
245 public static $POST_INPUT = 'php://input';
247 function __construct($http_method, $http_url, $parameters=NULL) {
248 $parameters = ($parameters) ? $parameters : array();
249 $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
250 $this->parameters = $parameters;
251 $this->http_method = $http_method;
252 $this->http_url = $http_url;
257 * attempt to build up a request from what was passed to the server
259 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
260 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
263 $http_url = ($http_url) ? $http_url : $scheme .
264 '://' . $_SERVER['SERVER_NAME'] .
266 $_SERVER['SERVER_PORT'] .
267 $_SERVER['REQUEST_URI'];
268 $http_method = ($http_method) ? $http_method : $_SERVER['REQUEST_METHOD'];
270 // We weren't handed any parameters, so let's find the ones relevant to
272 // If you run XML-RPC or similar you should use this to provide your own
273 // parsed parameter-list
275 // Find request headers
276 $request_headers = OAuthUtil::get_headers();
278 // Parse the query-string to find GET parameters
279 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
281 // It's a POST request of the proper content-type, so parse POST
282 // parameters and add those overriding any duplicates from GET
283 if ($http_method == "POST"
284 && isset($request_headers['Content-Type'])
285 && strstr($request_headers['Content-Type'],
286 'application/x-www-form-urlencoded')
288 $post_data = OAuthUtil::parse_parameters(
289 file_get_contents(self::$POST_INPUT)
291 $parameters = array_merge($parameters, $post_data);
294 // We have a Authorization-header with OAuth data. Parse the header
295 // and add those overriding any duplicates from GET or POST
296 if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == 'OAuth ') {
297 $header_parameters = OAuthUtil::split_header(
298 $request_headers['Authorization']
300 $parameters = array_merge($parameters, $header_parameters);
305 return new OAuthRequest($http_method, $http_url, $parameters);
309 * pretty much a helper function to set up the request
311 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
312 $parameters = ($parameters) ? $parameters : array();
313 $defaults = array("oauth_version" => OAuthRequest::$version,
314 "oauth_nonce" => OAuthRequest::generate_nonce(),
315 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
316 "oauth_consumer_key" => $consumer->key);
318 $defaults['oauth_token'] = $token->key;
320 $parameters = array_merge($defaults, $parameters);
322 return new OAuthRequest($http_method, $http_url, $parameters);
325 public function set_parameter($name, $value, $allow_duplicates = true) {
326 if ($allow_duplicates && isset($this->parameters[$name])) {
327 // We have already added parameter(s) with this name, so add to the list
328 if (is_scalar($this->parameters[$name])) {
329 // This is the first duplicate, so transform scalar (string)
330 // into an array so we can add the duplicates
331 $this->parameters[$name] = array($this->parameters[$name]);
334 $this->parameters[$name][] = $value;
336 $this->parameters[$name] = $value;
340 public function get_parameter($name) {
341 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
344 public function get_parameters() {
345 return $this->parameters;
348 public function unset_parameter($name) {
349 unset($this->parameters[$name]);
353 * The request parameters, sorted and concatenated into a normalized string.
356 public function get_signable_parameters() {
357 // Grab all parameters
358 $params = $this->parameters;
360 // Remove oauth_signature if present
361 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
362 if (isset($params['oauth_signature'])) {
363 unset($params['oauth_signature']);
366 return OAuthUtil::build_http_query($params);
370 * Returns the base string of this request
372 * The base string defined as the method, the url
373 * and the parameters (normalized), each urlencoded
374 * and the concated with &.
376 public function get_signature_base_string() {
378 $this->get_normalized_http_method(),
379 $this->get_normalized_http_url(),
380 $this->get_signable_parameters()
383 $parts = OAuthUtil::urlencode_rfc3986($parts);
385 return implode('&', $parts);
389 * just uppercases the http method
391 public function get_normalized_http_method() {
392 return strtoupper($this->http_method);
396 * parses the url and rebuilds it to be
399 public function get_normalized_http_url() {
400 $parts = parse_url($this->http_url);
402 $scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http';
403 $port = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80');
404 $host = (isset($parts['host'])) ? strtolower($parts['host']) : '';
405 $path = (isset($parts['path'])) ? $parts['path'] : '';
407 if (($scheme == 'https' && $port != '443')
408 || ($scheme == 'http' && $port != '80')) {
409 $host = "$host:$port";
411 return "$scheme://$host$path";
415 * builds a url usable for a GET request
417 public function to_url() {
418 $post_data = $this->to_postdata();
419 $out = $this->get_normalized_http_url();
421 $out .= '?'.$post_data;
427 * builds the data one would send in a POST request
429 public function to_postdata() {
430 return OAuthUtil::build_http_query($this->parameters);
434 * builds the Authorization: header
436 public function to_header($realm=null) {
439 $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
442 $out = 'Authorization: OAuth';
445 foreach ($this->parameters as $k => $v) {
446 if (substr($k, 0, 5) != "oauth") continue;
448 throw new OAuthException('Arrays not supported in headers');
450 $out .= ($first) ? ' ' : ',';
451 $out .= OAuthUtil::urlencode_rfc3986($k) .
453 OAuthUtil::urlencode_rfc3986($v) .
460 public function __toString() {
461 return $this->to_url();
465 public function sign_request($signature_method, $consumer, $token) {
466 $this->set_parameter(
467 "oauth_signature_method",
468 $signature_method->get_name(),
471 $signature = $this->build_signature($signature_method, $consumer, $token);
472 $this->set_parameter("oauth_signature", $signature, false);
475 public function build_signature($signature_method, $consumer, $token) {
476 $signature = $signature_method->build_signature($this, $consumer, $token);
481 * util function: current timestamp
483 private static function generate_timestamp() {
488 * util function: current nonce
490 private static function generate_nonce() {
494 return md5($mt . $rand); // md5s look nicer than numbers
499 protected $timestamp_threshold = 300; // in seconds, five minutes
500 protected $version = '1.0'; // hi blaine
501 protected $signature_methods = array();
503 protected $data_store;
505 function __construct($data_store) {
506 $this->data_store = $data_store;
509 public function add_signature_method($signature_method) {
510 $this->signature_methods[$signature_method->get_name()] =
514 // high level functions
517 * process a request_token request
518 * returns the request token on success
520 public function fetch_request_token(&$request) {
521 $this->get_version($request);
523 $consumer = $this->get_consumer($request);
525 // no token required for the initial token request
528 $this->check_signature($request, $consumer, $token);
531 $callback = $request->get_parameter('oauth_callback');
532 $new_token = $this->data_store->new_request_token($consumer, $callback);
538 * process an access_token request
539 * returns the access token on success
541 public function fetch_access_token(&$request) {
542 $this->get_version($request);
544 $consumer = $this->get_consumer($request);
546 // requires authorized request token
547 $token = $this->get_token($request, $consumer, "request");
549 $this->check_signature($request, $consumer, $token);
552 $verifier = $request->get_parameter('oauth_verifier');
553 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
559 * verify an api call, checks all the parameters
561 public function verify_request(&$request) {
562 $this->get_version($request);
563 $consumer = $this->get_consumer($request);
564 $token = $this->get_token($request, $consumer, "access");
565 $this->check_signature($request, $consumer, $token);
566 return array($consumer, $token);
569 // Internals from here
573 private function get_version(&$request) {
574 $version = $request->get_parameter("oauth_version");
576 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
577 // Chapter 7.0 ("Accessing Protected Ressources")
580 if ($version !== $this->version) {
581 throw new OAuthException("OAuth version '$version' not supported");
587 * figure out the signature with some defaults
589 private function get_signature_method($request) {
590 $signature_method = $request instanceof OAuthRequest
591 ? $request->get_parameter("oauth_signature_method")
594 if (!$signature_method) {
595 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
596 // parameter is required, and we can't just fallback to PLAINTEXT
597 throw new OAuthException('No signature method parameter. This parameter is required');
600 if (!in_array($signature_method,
601 array_keys($this->signature_methods))) {
602 throw new OAuthException(
603 "Signature method '$signature_method' not supported " .
604 "try one of the following: " .
605 implode(", ", array_keys($this->signature_methods))
608 return $this->signature_methods[$signature_method];
612 * try to find the consumer for the provided request's consumer key
614 private function get_consumer($request) {
615 $consumer_key = $request instanceof OAuthRequest
616 ? $request->get_parameter("oauth_consumer_key")
619 if (!$consumer_key) {
620 throw new OAuthException("Invalid consumer key");
623 $consumer = $this->data_store->lookup_consumer($consumer_key);
625 throw new OAuthException("Invalid consumer");
632 * try to find the token for the provided request's token key
634 private function get_token($request, $consumer, $token_type="access") {
635 $token_field = $request instanceof OAuthRequest
636 ? $request->get_parameter('oauth_token')
639 $token = $this->data_store->lookup_token(
640 $consumer, $token_type, $token_field
643 throw new OAuthException("Invalid $token_type token: $token_field");
649 * all-in-one function to check the signature on a request
650 * should guess the signature method appropriately
652 private function check_signature($request, $consumer, $token) {
653 // this should probably be in a different method
654 $timestamp = $request instanceof OAuthRequest
655 ? $request->get_parameter('oauth_timestamp')
657 $nonce = $request instanceof OAuthRequest
658 ? $request->get_parameter('oauth_nonce')
661 $this->check_timestamp($timestamp);
662 $this->check_nonce($consumer, $token, $nonce, $timestamp);
664 $signature_method = $this->get_signature_method($request);
666 $signature = $request->get_parameter('oauth_signature');
667 $valid_sig = $signature_method->check_signature(
675 throw new OAuthException("Invalid signature");
680 * check that the timestamp is new enough
682 private function check_timestamp($timestamp) {
684 throw new OAuthException(
685 'Missing timestamp parameter. The parameter is required'
688 // verify that timestamp is recentish
690 if (abs($now - $timestamp) > $this->timestamp_threshold) {
691 throw new OAuthException(
692 "Expired timestamp, yours $timestamp, ours $now"
698 * check that the nonce is not repeated
700 private function check_nonce($consumer, $token, $nonce, $timestamp) {
702 throw new OAuthException(
703 'Missing nonce parameter. The parameter is required'
706 // verify that the nonce is uniqueish
707 $found = $this->data_store->lookup_nonce(
714 throw new OAuthException("Nonce already used: $nonce");
720 class OAuthDataStore {
721 function lookup_consumer($consumer_key) {
725 function lookup_token($consumer, $token_type, $token) {
729 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
733 function new_request_token($consumer, $callback = null) {
734 // return a new token attached to this consumer
737 function new_access_token($token, $consumer, $verifier = null) {
738 // return a new access token attached to this consumer
739 // for the user associated with this token if the request token
741 // should also invalidate the request token
747 public static function urlencode_rfc3986($input) {
748 if (is_array($input)) {
749 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
750 } else if (is_scalar($input)) {
754 str_replace('%7E', '~', rawurlencode($input))
762 // This decode function isn't taking into consideration the above
763 // modifications to the encoding process. However, this method doesn't
764 // seem to be used anywhere so leaving it as is.
765 public static function urldecode_rfc3986($string) {
766 return urldecode($string);
769 // Utility function for turning the Authorization: header into
770 // parameters, has to do some unescaping
771 // Can filter out any non-oauth parameters if needed (default behaviour)
772 // May 28th, 2010 - method updated to tjerk.meesters for a speed improvement.
773 public static function split_header($header, $only_allow_oauth_parameters = true) {
775 if (preg_match_all('/('.($only_allow_oauth_parameters ? 'oauth_' : '').'[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $header, $matches)) {
776 foreach ($matches[1] as $i => $h) {
777 $params[$h] = OAuthUtil::urldecode_rfc3986(empty($matches[3][$i]) ? $matches[4][$i] : $matches[3][$i]);
779 if (isset($params['realm'])) {
780 unset($params['realm']);
786 // helper to try to sort out headers for people who aren't running apache
787 public static function get_headers() {
788 if (function_exists('apache_request_headers')) {
789 // we need this to get the actual Authorization: header
790 // because apache tends to tell us it doesn't exist
791 $headers = apache_request_headers();
793 // sanitize the output of apache_request_headers because
794 // we always want the keys to be Cased-Like-This and arh()
795 // returns the headers in the same case as they are in the
798 foreach ($headers AS $key => $value) {
802 ucwords(strtolower(str_replace("-", " ", $key)))
807 // otherwise we don't have apache and are just going to have to hope
808 // that $_SERVER actually contains what we need
810 if( isset($_SERVER['CONTENT_TYPE']) )
811 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
812 if( isset($_ENV['CONTENT_TYPE']) )
813 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
815 foreach ($_SERVER as $key => $value) {
816 if (substr($key, 0, 5) == "HTTP_") {
817 // this is chaos, basically it is just there to capitalize the first
818 // letter of every word that is not an initial HTTP and strip HTTP
823 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
832 // This function takes a input like a=b&a=c&d=e and returns the parsed
833 // parameters like this
834 // array('a' => array('b','c'), 'd' => 'e')
835 public static function parse_parameters( $input ) {
836 if (!isset($input) || !$input) return array();
838 $pairs = explode('&', $input);
840 $parsed_parameters = array();
841 foreach ($pairs as $pair) {
842 $split = explode('=', $pair, 2);
843 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
844 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
846 if (isset($parsed_parameters[$parameter])) {
847 // We have already recieved parameter(s) with this name, so add to the list
848 // of parameters with this name
850 if (is_scalar($parsed_parameters[$parameter])) {
851 // This is the first duplicate, so transform scalar (string) into an array
852 // so we can add the duplicates
853 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
856 $parsed_parameters[$parameter][] = $value;
858 $parsed_parameters[$parameter] = $value;
861 return $parsed_parameters;
864 public static function build_http_query($params) {
865 if (!$params) return '';
867 // Urlencode both keys and values
868 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
869 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
870 $params = array_combine($keys, $values);
872 // Parameters are sorted by name, using lexicographical byte value ordering.
873 // Ref: Spec: 9.1.1 (1)
874 uksort($params, 'strcmp');
877 foreach ($params as $parameter => $value) {
878 if (is_array($value)) {
879 // If two or more parameters share the same name, they are sorted by their value
880 // Ref: Spec: 9.1.1 (1)
881 // June 12th, 2010 - changed to sort because of issue 164 by hidetaka
882 sort($value, SORT_STRING);
883 foreach ($value as $duplicate_value) {
884 $pairs[] = $parameter . '=' . $duplicate_value;
887 $pairs[] = $parameter . '=' . $value;
890 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
891 // Each name-value pair is separated by an '&' character (ASCII code 38)
892 return implode('&', $pairs);