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
38 * secret = the token secret
40 function __construct($key, $secret) {
42 $this->secret = $secret;
46 * generates the basic string serialization of a token that a server
47 * would respond to request_token and access_token calls with
49 function to_string() {
50 return "oauth_token=" .
51 OAuthUtil::urlencode_rfc3986($this->key) .
52 "&oauth_token_secret=" .
53 OAuthUtil::urlencode_rfc3986($this->secret);
56 function __toString() {
57 return $this->to_string();
62 * A class for implementing a Signature Method
63 * See section 9 ("Signing Requests") in the spec
65 abstract class OAuthSignatureMethod {
67 * Needs to return the name of the Signature Method (ie HMAC-SHA1)
70 abstract public function get_name();
73 * Build up the signature
74 * NOTE: The output of this function MUST NOT be urlencoded.
75 * the encoding is handled in OAuthRequest when the final
76 * request is serialized
77 * @param OAuthRequest $request
78 * @param OAuthConsumer $consumer
79 * @param OAuthToken $token
82 abstract public function build_signature($request, $consumer, $token);
85 * Verifies that a given signature is correct
86 * @param OAuthRequest $request
87 * @param OAuthConsumer $consumer
88 * @param OAuthToken $token
89 * @param string $signature
92 public function check_signature($request, $consumer, $token, $signature) {
93 $built = $this->build_signature($request, $consumer, $token);
94 //echo "<pre>"; var_dump($signature, $built, ($built == $signature)); killme();
95 return ($built == $signature);
100 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
101 * where the Signature Base String is the text and the key is the concatenated values (each first
102 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
103 * character (ASCII code 38) even if empty.
104 * - Chapter 9.2 ("HMAC-SHA1")
106 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
107 function get_name() {
111 public function build_signature($request, $consumer, $token) {
112 $base_string = $request->get_signature_base_string();
113 $request->base_string = $base_string;
117 ($token) ? $token->secret : ""
120 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
121 $key = implode('&', $key_parts);
124 $r = base64_encode(hash_hmac('sha1', $base_string, $key, true));
130 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
131 * over a secure channel such as HTTPS. It does not use the Signature Base String.
132 * - Chapter 9.4 ("PLAINTEXT")
134 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
135 public function get_name() {
140 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
141 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
142 * empty. The result MUST be encoded again.
143 * - Chapter 9.4.1 ("Generating Signatures")
145 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
146 * OAuthRequest handles this!
148 public function build_signature($request, $consumer, $token) {
151 ($token) ? $token->secret : ""
154 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
155 $key = implode('&', $key_parts);
156 $request->base_string = $key;
163 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
164 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
165 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
166 * verified way to the Service Provider, in a manner which is beyond the scope of this
168 * - Chapter 9.3 ("RSA-SHA1")
170 abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
171 public function get_name() {
175 // Up to the SP to implement this lookup of keys. Possible ideas are:
176 // (1) do a lookup in a table of trusted certs keyed off of consumer
177 // (2) fetch via http using a url provided by the requester
178 // (3) some sort of specific discovery code based on request
180 // Either way should return a string representation of the certificate
181 protected abstract function fetch_public_cert(&$request);
183 // Up to the SP to implement this lookup of keys. Possible ideas are:
184 // (1) do a lookup in a table of trusted certs keyed off of consumer
186 // Either way should return a string representation of the certificate
187 protected abstract function fetch_private_cert(&$request);
189 public function build_signature($request, $consumer, $token) {
190 $base_string = $request->get_signature_base_string();
191 $request->base_string = $base_string;
193 // Fetch the private key cert based on the request
194 $cert = $this->fetch_private_cert($request);
196 // Pull the private key ID from the certificate
197 $privatekeyid = openssl_get_privatekey($cert);
199 // Sign using the key
200 $ok = openssl_sign($base_string, $signature, $privatekeyid);
202 // Release the key resource
203 openssl_free_key($privatekeyid);
205 return base64_encode($signature);
208 public function check_signature($request, $consumer, $token, $signature) {
209 $decoded_sig = base64_decode($signature);
211 $base_string = $request->get_signature_base_string();
213 // Fetch the public key cert based on the request
214 $cert = $this->fetch_public_cert($request);
216 // Pull the public key ID from the certificate
217 $publickeyid = openssl_get_publickey($cert);
219 // Check the computed signature against the one passed in the query
220 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
222 // Release the key resource
223 openssl_free_key($publickeyid);
231 private $http_method;
233 // for debug purposes
235 public static $version = '1.0';
236 public static $POST_INPUT = 'php://input';
238 function __construct($http_method, $http_url, $parameters=NULL) {
239 @$parameters or $parameters = array();
240 $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
241 $this->parameters = $parameters;
242 $this->http_method = $http_method;
243 $this->http_url = $http_url;
248 * attempt to build up a request from what was passed to the server
250 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
251 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
254 @$http_url or $http_url = $scheme .
255 '://' . $_SERVER['HTTP_HOST'] .
257 $_SERVER['SERVER_PORT'] .
258 $_SERVER['REQUEST_URI'];
259 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
261 // We weren't handed any parameters, so let's find the ones relevant to
263 // If you run XML-RPC or similar you should use this to provide your own
264 // parsed parameter-list
266 // Find request headers
267 $request_headers = OAuthUtil::get_headers();
269 // Parse the query-string to find GET parameters
270 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
272 // It's a POST request of the proper content-type, so parse POST
273 // parameters and add those overriding any duplicates from GET
274 if ($http_method == "POST"
275 && @strstr($request_headers["Content-Type"],
276 "application/x-www-form-urlencoded")
278 $post_data = OAuthUtil::parse_parameters(
279 file_get_contents(self::$POST_INPUT)
281 $parameters = array_merge($parameters, $post_data);
284 // We have a Authorization-header with OAuth data. Parse the header
285 // and add those overriding any duplicates from GET or POST
286 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
287 $header_parameters = OAuthUtil::split_header(
288 $request_headers['Authorization']
290 $parameters = array_merge($parameters, $header_parameters);
294 // fix for friendica redirect system
296 $http_url = substr($http_url, 0, strpos($http_url,$parameters['pagename'])+strlen($parameters['pagename']));
297 unset( $parameters['pagename'] );
299 //echo "<pre>".__function__."\n"; var_dump($http_method, $http_url, $parameters, $_SERVER['REQUEST_URI']); killme();
300 return new OAuthRequest($http_method, $http_url, $parameters);
304 * pretty much a helper function to set up the request
306 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
307 @$parameters or $parameters = array();
308 $defaults = array("oauth_version" => OAuthRequest::$version,
309 "oauth_nonce" => OAuthRequest::generate_nonce(),
310 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
311 "oauth_consumer_key" => $consumer->key);
313 $defaults['oauth_token'] = $token->key;
315 $parameters = array_merge($defaults, $parameters);
317 return new OAuthRequest($http_method, $http_url, $parameters);
320 public function set_parameter($name, $value, $allow_duplicates = true) {
321 if ($allow_duplicates && isset($this->parameters[$name])) {
322 // We have already added parameter(s) with this name, so add to the list
323 if (is_scalar($this->parameters[$name])) {
324 // This is the first duplicate, so transform scalar (string)
325 // into an array so we can add the duplicates
326 $this->parameters[$name] = array($this->parameters[$name]);
329 $this->parameters[$name][] = $value;
331 $this->parameters[$name] = $value;
335 public function get_parameter($name) {
336 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
339 public function get_parameters() {
340 return $this->parameters;
343 public function unset_parameter($name) {
344 unset($this->parameters[$name]);
348 * The request parameters, sorted and concatenated into a normalized string.
351 public function get_signable_parameters() {
352 // Grab all parameters
353 $params = $this->parameters;
355 // Remove oauth_signature if present
356 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
357 if (isset($params['oauth_signature'])) {
358 unset($params['oauth_signature']);
361 return OAuthUtil::build_http_query($params);
365 * Returns the base string of this request
367 * The base string defined as the method, the url
368 * and the parameters (normalized), each urlencoded
369 * and the concated with &.
371 public function get_signature_base_string() {
373 $this->get_normalized_http_method(),
374 $this->get_normalized_http_url(),
375 $this->get_signable_parameters()
378 $parts = OAuthUtil::urlencode_rfc3986($parts);
380 return implode('&', $parts);
384 * just uppercases the http method
386 public function get_normalized_http_method() {
387 return strtoupper($this->http_method);
391 * parses the url and rebuilds it to be
394 public function get_normalized_http_url() {
395 $parts = parse_url($this->http_url);
397 $port = @$parts['port'];
398 $scheme = $parts['scheme'];
399 $host = $parts['host'];
400 $path = @$parts['path'];
402 $port or $port = ($scheme == 'https') ? '443' : '80';
404 if (($scheme == 'https' && $port != '443')
405 || ($scheme == 'http' && $port != '80')) {
406 $host = "$host:$port";
408 return "$scheme://$host$path";
412 * builds a url usable for a GET request
414 public function to_url() {
415 $post_data = $this->to_postdata();
416 $out = $this->get_normalized_http_url();
418 $out .= '?'.$post_data;
424 * builds the data one would send in a POST request
426 public function to_postdata($raw = false) {
428 return($this->parameters);
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 //echo __file__.__line__.__function__."<pre>"; var_dump($consumer); die();
565 $token = $this->get_token($request, $consumer, "access");
566 $this->check_signature($request, $consumer, $token);
567 return array($consumer, $token);
570 // Internals from here
574 private function get_version(&$request) {
575 $version = $request->get_parameter("oauth_version");
577 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
578 // Chapter 7.0 ("Accessing Protected Ressources")
581 if ($version !== $this->version) {
582 throw new OAuthException("OAuth version '$version' not supported");
588 * figure out the signature with some defaults
590 private function get_signature_method(&$request) {
592 @$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->get_parameter("oauth_consumer_key");
616 if (!$consumer_key) {
617 throw new OAuthException("Invalid consumer key");
620 $consumer = $this->data_store->lookup_consumer($consumer_key);
622 throw new OAuthException("Invalid consumer");
629 * try to find the token for the provided request's token key
631 private function get_token(&$request, $consumer, $token_type="access") {
632 $token_field = @$request->get_parameter('oauth_token');
633 $token = $this->data_store->lookup_token(
634 $consumer, $token_type, $token_field
637 throw new OAuthException("Invalid $token_type token: $token_field");
643 * all-in-one function to check the signature on a request
644 * should guess the signature method appropriately
646 private function check_signature(&$request, $consumer, $token) {
647 // this should probably be in a different method
648 $timestamp = @$request->get_parameter('oauth_timestamp');
649 $nonce = @$request->get_parameter('oauth_nonce');
651 $this->check_timestamp($timestamp);
652 $this->check_nonce($consumer, $token, $nonce, $timestamp);
654 $signature_method = $this->get_signature_method($request);
656 $signature = $request->get_parameter('oauth_signature');
657 $valid_sig = $signature_method->check_signature(
666 throw new OAuthException("Invalid signature");
671 * check that the timestamp is new enough
673 private function check_timestamp($timestamp) {
675 throw new OAuthException(
676 'Missing timestamp parameter. The parameter is required'
679 // verify that timestamp is recentish
681 if (abs($now - $timestamp) > $this->timestamp_threshold) {
682 throw new OAuthException(
683 "Expired timestamp, yours $timestamp, ours $now"
689 * check that the nonce is not repeated
691 private function check_nonce($consumer, $token, $nonce, $timestamp) {
693 throw new OAuthException(
694 'Missing nonce parameter. The parameter is required'
697 // verify that the nonce is uniqueish
698 $found = $this->data_store->lookup_nonce(
705 throw new OAuthException("Nonce already used: $nonce");
711 class OAuthDataStore {
712 function lookup_consumer($consumer_key) {
716 function lookup_token($consumer, $token_type, $token) {
720 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
724 function new_request_token($consumer, $callback = null) {
725 // return a new token attached to this consumer
728 function new_access_token($token, $consumer, $verifier = null) {
729 // return a new access token attached to this consumer
730 // for the user associated with this token if the request token
732 // should also invalidate the request token
738 public static function urlencode_rfc3986($input) {
739 if (is_array($input)) {
740 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
741 } else if (is_scalar($input)) {
745 str_replace('%7E', '~', rawurlencode($input))
753 // This decode function isn't taking into consideration the above
754 // modifications to the encoding process. However, this method doesn't
755 // seem to be used anywhere so leaving it as is.
756 public static function urldecode_rfc3986($string) {
757 return urldecode($string);
760 // Utility function for turning the Authorization: header into
761 // parameters, has to do some unescaping
762 // Can filter out any non-oauth parameters if needed (default behaviour)
763 public static function split_header($header, $only_allow_oauth_parameters = true) {
764 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
767 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
768 $match = $matches[0];
769 $header_name = $matches[2][0];
770 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
771 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
772 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
774 $offset = $match[1] + strlen($match[0]);
777 if (isset($params['realm'])) {
778 unset($params['realm']);
784 // helper to try to sort out headers for people who aren't running apache
785 public static function get_headers() {
786 if (function_exists('apache_request_headers')) {
787 // we need this to get the actual Authorization: header
788 // because apache tends to tell us it doesn't exist
789 $headers = apache_request_headers();
791 // sanitize the output of apache_request_headers because
792 // we always want the keys to be Cased-Like-This and arh()
793 // returns the headers in the same case as they are in the
796 foreach( $headers AS $key => $value ) {
800 ucwords(strtolower(str_replace("-", " ", $key)))
805 // otherwise we don't have apache and are just going to have to hope
806 // that $_SERVER actually contains what we need
808 if( isset($_SERVER['CONTENT_TYPE']) )
809 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
810 if( isset($_ENV['CONTENT_TYPE']) )
811 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
813 foreach ($_SERVER as $key => $value) {
814 if (substr($key, 0, 5) == "HTTP_") {
815 // this is chaos, basically it is just there to capitalize the first
816 // letter of every word that is not an initial HTTP and strip HTTP
821 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
830 // This function takes a input like a=b&a=c&d=e and returns the parsed
831 // parameters like this
832 // array('a' => array('b','c'), 'd' => 'e')
833 public static function parse_parameters( $input ) {
834 if (!isset($input) || !$input) return array();
836 $pairs = explode('&', $input);
838 $parsed_parameters = array();
839 foreach ($pairs as $pair) {
840 $split = explode('=', $pair, 2);
841 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
842 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
844 if (isset($parsed_parameters[$parameter])) {
845 // We have already recieved parameter(s) with this name, so add to the list
846 // of parameters with this name
848 if (is_scalar($parsed_parameters[$parameter])) {
849 // This is the first duplicate, so transform scalar (string) into an array
850 // so we can add the duplicates
851 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
854 $parsed_parameters[$parameter][] = $value;
856 $parsed_parameters[$parameter] = $value;
859 return $parsed_parameters;
862 public static function build_http_query($params) {
863 if (!$params) return '';
865 // Urlencode both keys and values
866 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
867 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
868 $params = array_combine($keys, $values);
870 // Parameters are sorted by name, using lexicographical byte value ordering.
871 // Ref: Spec: 9.1.1 (1)
872 uksort($params, 'strcmp');
875 foreach ($params as $parameter => $value) {
876 if (is_array($value)) {
877 // If two or more parameters share the same name, they are sorted by their value
878 // Ref: Spec: 9.1.1 (1)
880 foreach ($value as $duplicate_value) {
881 $pairs[] = $parameter . '=' . $duplicate_value;
884 $pairs[] = $parameter . '=' . $value;
887 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
888 // Each name-value pair is separated by an '&' character (ASCII code 38)
889 return implode('&', $pairs);