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);
88 //echo "<pre>"; var_dump($signature, $built, ($built == $signature)); killme();
89 return ($built == $signature);
94 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
95 * where the Signature Base String is the text and the key is the concatenated values (each first
96 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
97 * character (ASCII code 38) even if empty.
98 * - Chapter 9.2 ("HMAC-SHA1")
100 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
101 function get_name() {
105 public function build_signature($request, $consumer, $token) {
106 $base_string = $request->get_signature_base_string();
107 $request->base_string = $base_string;
111 ($token) ? $token->secret : ""
114 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
115 $key = implode('&', $key_parts);
118 $r = base64_encode(hash_hmac('sha1', $base_string, $key, true));
124 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
125 * over a secure channel such as HTTPS. It does not use the Signature Base String.
126 * - Chapter 9.4 ("PLAINTEXT")
128 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
129 public function get_name() {
134 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
135 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
136 * empty. The result MUST be encoded again.
137 * - Chapter 9.4.1 ("Generating Signatures")
139 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
140 * OAuthRequest handles this!
142 public function build_signature($request, $consumer, $token) {
145 ($token) ? $token->secret : ""
148 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
149 $key = implode('&', $key_parts);
150 $request->base_string = $key;
157 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
158 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
159 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
160 * verified way to the Service Provider, in a manner which is beyond the scope of this
162 * - Chapter 9.3 ("RSA-SHA1")
164 abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
165 public function get_name() {
169 // Up to the SP to implement this lookup of keys. Possible ideas are:
170 // (1) do a lookup in a table of trusted certs keyed off of consumer
171 // (2) fetch via http using a url provided by the requester
172 // (3) some sort of specific discovery code based on request
174 // Either way should return a string representation of the certificate
175 protected abstract function fetch_public_cert(&$request);
177 // Up to the SP to implement this lookup of keys. Possible ideas are:
178 // (1) do a lookup in a table of trusted certs keyed off of consumer
180 // Either way should return a string representation of the certificate
181 protected abstract function fetch_private_cert(&$request);
183 public function build_signature($request, $consumer, $token) {
184 $base_string = $request->get_signature_base_string();
185 $request->base_string = $base_string;
187 // Fetch the private key cert based on the request
188 $cert = $this->fetch_private_cert($request);
190 // Pull the private key ID from the certificate
191 $privatekeyid = openssl_get_privatekey($cert);
193 // Sign using the key
194 $ok = openssl_sign($base_string, $signature, $privatekeyid);
196 // Release the key resource
197 openssl_free_key($privatekeyid);
199 return base64_encode($signature);
202 public function check_signature($request, $consumer, $token, $signature) {
203 $decoded_sig = base64_decode($signature);
205 $base_string = $request->get_signature_base_string();
207 // Fetch the public key cert based on the request
208 $cert = $this->fetch_public_cert($request);
210 // Pull the public key ID from the certificate
211 $publickeyid = openssl_get_publickey($cert);
213 // Check the computed signature against the one passed in the query
214 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
216 // Release the key resource
217 openssl_free_key($publickeyid);
225 private $http_method;
227 // for debug purposes
229 public static $version = '1.0';
230 public static $POST_INPUT = 'php://input';
232 function __construct($http_method, $http_url, $parameters=NULL) {
233 @$parameters or $parameters = array();
234 $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
235 $this->parameters = $parameters;
236 $this->http_method = $http_method;
237 $this->http_url = $http_url;
242 * attempt to build up a request from what was passed to the server
244 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
245 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
248 @$http_url or $http_url = $scheme .
249 '://' . $_SERVER['HTTP_HOST'] .
251 $_SERVER['SERVER_PORT'] .
252 $_SERVER['REQUEST_URI'];
253 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
255 // We weren't handed any parameters, so let's find the ones relevant to
257 // If you run XML-RPC or similar you should use this to provide your own
258 // parsed parameter-list
260 // Find request headers
261 $request_headers = OAuthUtil::get_headers();
263 // Parse the query-string to find GET parameters
264 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
266 // It's a POST request of the proper content-type, so parse POST
267 // parameters and add those overriding any duplicates from GET
268 if ($http_method == "POST"
269 && @strstr($request_headers["Content-Type"],
270 "application/x-www-form-urlencoded")
272 $post_data = OAuthUtil::parse_parameters(
273 file_get_contents(self::$POST_INPUT)
275 $parameters = array_merge($parameters, $post_data);
278 // We have a Authorization-header with OAuth data. Parse the header
279 // and add those overriding any duplicates from GET or POST
280 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
281 $header_parameters = OAuthUtil::split_header(
282 $request_headers['Authorization']
284 $parameters = array_merge($parameters, $header_parameters);
288 // fix for friendika redirect system
290 $http_url = substr($http_url, 0, strpos($http_url,$parameters['q'])+strlen($parameters['q']));
291 unset( $parameters['q'] );
293 //echo "<pre>".__function__."\n"; var_dump($http_method, $http_url, $parameters, $_SERVER['REQUEST_URI']); killme();
294 return new OAuthRequest($http_method, $http_url, $parameters);
298 * pretty much a helper function to set up the request
300 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
301 @$parameters or $parameters = array();
302 $defaults = array("oauth_version" => OAuthRequest::$version,
303 "oauth_nonce" => OAuthRequest::generate_nonce(),
304 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
305 "oauth_consumer_key" => $consumer->key);
307 $defaults['oauth_token'] = $token->key;
309 $parameters = array_merge($defaults, $parameters);
311 return new OAuthRequest($http_method, $http_url, $parameters);
314 public function set_parameter($name, $value, $allow_duplicates = true) {
315 if ($allow_duplicates && isset($this->parameters[$name])) {
316 // We have already added parameter(s) with this name, so add to the list
317 if (is_scalar($this->parameters[$name])) {
318 // This is the first duplicate, so transform scalar (string)
319 // into an array so we can add the duplicates
320 $this->parameters[$name] = array($this->parameters[$name]);
323 $this->parameters[$name][] = $value;
325 $this->parameters[$name] = $value;
329 public function get_parameter($name) {
330 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
333 public function get_parameters() {
334 return $this->parameters;
337 public function unset_parameter($name) {
338 unset($this->parameters[$name]);
342 * The request parameters, sorted and concatenated into a normalized string.
345 public function get_signable_parameters() {
346 // Grab all parameters
347 $params = $this->parameters;
349 // Remove oauth_signature if present
350 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
351 if (isset($params['oauth_signature'])) {
352 unset($params['oauth_signature']);
355 return OAuthUtil::build_http_query($params);
359 * Returns the base string of this request
361 * The base string defined as the method, the url
362 * and the parameters (normalized), each urlencoded
363 * and the concated with &.
365 public function get_signature_base_string() {
367 $this->get_normalized_http_method(),
368 $this->get_normalized_http_url(),
369 $this->get_signable_parameters()
372 $parts = OAuthUtil::urlencode_rfc3986($parts);
374 return implode('&', $parts);
378 * just uppercases the http method
380 public function get_normalized_http_method() {
381 return strtoupper($this->http_method);
385 * parses the url and rebuilds it to be
388 public function get_normalized_http_url() {
389 $parts = parse_url($this->http_url);
391 $port = @$parts['port'];
392 $scheme = $parts['scheme'];
393 $host = $parts['host'];
394 $path = @$parts['path'];
396 $port or $port = ($scheme == 'https') ? '443' : '80';
398 if (($scheme == 'https' && $port != '443')
399 || ($scheme == 'http' && $port != '80')) {
400 $host = "$host:$port";
402 return "$scheme://$host$path";
406 * builds a url usable for a GET request
408 public function to_url() {
409 $post_data = $this->to_postdata();
410 $out = $this->get_normalized_http_url();
412 $out .= '?'.$post_data;
418 * builds the data one would send in a POST request
420 public function to_postdata() {
421 return OAuthUtil::build_http_query($this->parameters);
425 * builds the Authorization: header
427 public function to_header($realm=null) {
430 $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
433 $out = 'Authorization: OAuth';
436 foreach ($this->parameters as $k => $v) {
437 if (substr($k, 0, 5) != "oauth") continue;
439 throw new OAuthException('Arrays not supported in headers');
441 $out .= ($first) ? ' ' : ',';
442 $out .= OAuthUtil::urlencode_rfc3986($k) .
444 OAuthUtil::urlencode_rfc3986($v) .
451 public function __toString() {
452 return $this->to_url();
456 public function sign_request($signature_method, $consumer, $token) {
457 $this->set_parameter(
458 "oauth_signature_method",
459 $signature_method->get_name(),
462 $signature = $this->build_signature($signature_method, $consumer, $token);
463 $this->set_parameter("oauth_signature", $signature, false);
466 public function build_signature($signature_method, $consumer, $token) {
467 $signature = $signature_method->build_signature($this, $consumer, $token);
472 * util function: current timestamp
474 private static function generate_timestamp() {
479 * util function: current nonce
481 private static function generate_nonce() {
485 return md5($mt . $rand); // md5s look nicer than numbers
490 protected $timestamp_threshold = 300; // in seconds, five minutes
491 protected $version = '1.0'; // hi blaine
492 protected $signature_methods = array();
494 protected $data_store;
496 function __construct($data_store) {
497 $this->data_store = $data_store;
500 public function add_signature_method($signature_method) {
501 $this->signature_methods[$signature_method->get_name()] =
505 // high level functions
508 * process a request_token request
509 * returns the request token on success
511 public function fetch_request_token(&$request) {
512 $this->get_version($request);
514 $consumer = $this->get_consumer($request);
516 // no token required for the initial token request
519 $this->check_signature($request, $consumer, $token);
522 $callback = $request->get_parameter('oauth_callback');
523 $new_token = $this->data_store->new_request_token($consumer, $callback);
529 * process an access_token request
530 * returns the access token on success
532 public function fetch_access_token(&$request) {
533 $this->get_version($request);
535 $consumer = $this->get_consumer($request);
537 // requires authorized request token
538 $token = $this->get_token($request, $consumer, "request");
540 $this->check_signature($request, $consumer, $token);
543 $verifier = $request->get_parameter('oauth_verifier');
544 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
550 * verify an api call, checks all the parameters
552 public function verify_request(&$request) {
553 $this->get_version($request);
554 $consumer = $this->get_consumer($request);
555 $token = $this->get_token($request, $consumer, "access");
556 $this->check_signature($request, $consumer, $token);
557 return array($consumer, $token);
560 // Internals from here
564 private function get_version(&$request) {
565 $version = $request->get_parameter("oauth_version");
567 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
568 // Chapter 7.0 ("Accessing Protected Ressources")
571 if ($version !== $this->version) {
572 throw new OAuthException("OAuth version '$version' not supported");
578 * figure out the signature with some defaults
580 private function get_signature_method(&$request) {
582 @$request->get_parameter("oauth_signature_method");
584 if (!$signature_method) {
585 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
586 // parameter is required, and we can't just fallback to PLAINTEXT
587 throw new OAuthException('No signature method parameter. This parameter is required');
590 if (!in_array($signature_method,
591 array_keys($this->signature_methods))) {
592 throw new OAuthException(
593 "Signature method '$signature_method' not supported " .
594 "try one of the following: " .
595 implode(", ", array_keys($this->signature_methods))
598 return $this->signature_methods[$signature_method];
602 * try to find the consumer for the provided request's consumer key
604 private function get_consumer(&$request) {
605 $consumer_key = @$request->get_parameter("oauth_consumer_key");
606 if (!$consumer_key) {
607 throw new OAuthException("Invalid consumer key");
610 $consumer = $this->data_store->lookup_consumer($consumer_key);
612 throw new OAuthException("Invalid consumer");
619 * try to find the token for the provided request's token key
621 private function get_token(&$request, $consumer, $token_type="access") {
622 $token_field = @$request->get_parameter('oauth_token');
623 $token = $this->data_store->lookup_token(
624 $consumer, $token_type, $token_field
627 throw new OAuthException("Invalid $token_type token: $token_field");
633 * all-in-one function to check the signature on a request
634 * should guess the signature method appropriately
636 private function check_signature(&$request, $consumer, $token) {
637 // this should probably be in a different method
638 $timestamp = @$request->get_parameter('oauth_timestamp');
639 $nonce = @$request->get_parameter('oauth_nonce');
641 $this->check_timestamp($timestamp);
642 $this->check_nonce($consumer, $token, $nonce, $timestamp);
644 $signature_method = $this->get_signature_method($request);
646 $signature = $request->get_parameter('oauth_signature');
647 $valid_sig = $signature_method->check_signature(
656 throw new OAuthException("Invalid signature");
661 * check that the timestamp is new enough
663 private function check_timestamp($timestamp) {
665 throw new OAuthException(
666 'Missing timestamp parameter. The parameter is required'
669 // verify that timestamp is recentish
671 if (abs($now - $timestamp) > $this->timestamp_threshold) {
672 throw new OAuthException(
673 "Expired timestamp, yours $timestamp, ours $now"
679 * check that the nonce is not repeated
681 private function check_nonce($consumer, $token, $nonce, $timestamp) {
683 throw new OAuthException(
684 'Missing nonce parameter. The parameter is required'
687 // verify that the nonce is uniqueish
688 $found = $this->data_store->lookup_nonce(
695 throw new OAuthException("Nonce already used: $nonce");
701 class OAuthDataStore {
702 function lookup_consumer($consumer_key) {
706 function lookup_token($consumer, $token_type, $token) {
710 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
714 function new_request_token($consumer, $callback = null) {
715 // return a new token attached to this consumer
718 function new_access_token($token, $consumer, $verifier = null) {
719 // return a new access token attached to this consumer
720 // for the user associated with this token if the request token
722 // should also invalidate the request token
728 public static function urlencode_rfc3986($input) {
729 if (is_array($input)) {
730 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
731 } else if (is_scalar($input)) {
735 str_replace('%7E', '~', rawurlencode($input))
743 // This decode function isn't taking into consideration the above
744 // modifications to the encoding process. However, this method doesn't
745 // seem to be used anywhere so leaving it as is.
746 public static function urldecode_rfc3986($string) {
747 return urldecode($string);
750 // Utility function for turning the Authorization: header into
751 // parameters, has to do some unescaping
752 // Can filter out any non-oauth parameters if needed (default behaviour)
753 public static function split_header($header, $only_allow_oauth_parameters = true) {
754 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
757 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
758 $match = $matches[0];
759 $header_name = $matches[2][0];
760 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
761 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
762 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
764 $offset = $match[1] + strlen($match[0]);
767 if (isset($params['realm'])) {
768 unset($params['realm']);
774 // helper to try to sort out headers for people who aren't running apache
775 public static function get_headers() {
776 if (function_exists('apache_request_headers')) {
777 // we need this to get the actual Authorization: header
778 // because apache tends to tell us it doesn't exist
779 $headers = apache_request_headers();
781 // sanitize the output of apache_request_headers because
782 // we always want the keys to be Cased-Like-This and arh()
783 // returns the headers in the same case as they are in the
786 foreach( $headers AS $key => $value ) {
790 ucwords(strtolower(str_replace("-", " ", $key)))
795 // otherwise we don't have apache and are just going to have to hope
796 // that $_SERVER actually contains what we need
798 if( isset($_SERVER['CONTENT_TYPE']) )
799 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
800 if( isset($_ENV['CONTENT_TYPE']) )
801 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
803 foreach ($_SERVER as $key => $value) {
804 if (substr($key, 0, 5) == "HTTP_") {
805 // this is chaos, basically it is just there to capitalize the first
806 // letter of every word that is not an initial HTTP and strip HTTP
811 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
820 // This function takes a input like a=b&a=c&d=e and returns the parsed
821 // parameters like this
822 // array('a' => array('b','c'), 'd' => 'e')
823 public static function parse_parameters( $input ) {
824 if (!isset($input) || !$input) return array();
826 $pairs = explode('&', $input);
828 $parsed_parameters = array();
829 foreach ($pairs as $pair) {
830 $split = explode('=', $pair, 2);
831 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
832 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
834 if (isset($parsed_parameters[$parameter])) {
835 // We have already recieved parameter(s) with this name, so add to the list
836 // of parameters with this name
838 if (is_scalar($parsed_parameters[$parameter])) {
839 // This is the first duplicate, so transform scalar (string) into an array
840 // so we can add the duplicates
841 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
844 $parsed_parameters[$parameter][] = $value;
846 $parsed_parameters[$parameter] = $value;
849 return $parsed_parameters;
852 public static function build_http_query($params) {
853 if (!$params) return '';
855 // Urlencode both keys and values
856 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
857 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
858 $params = array_combine($keys, $values);
860 // Parameters are sorted by name, using lexicographical byte value ordering.
861 // Ref: Spec: 9.1.1 (1)
862 uksort($params, 'strcmp');
865 foreach ($params as $parameter => $value) {
866 if (is_array($value)) {
867 // If two or more parameters share the same name, they are sorted by their value
868 // Ref: Spec: 9.1.1 (1)
870 foreach ($value as $duplicate_value) {
871 $pairs[] = $parameter . '=' . $duplicate_value;
874 $pairs[] = $parameter . '=' . $value;
877 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
878 // Each name-value pair is separated by an '&' character (ASCII code 38)
879 return implode('&', $pairs);