2 // vim: foldmethod=marker
4 /* Generic exception class
6 if (!class_exists('OAuthException', false)) {
7 class OAuthException extends Exception
16 function __construct($key, $secret, $callback_url = NULL)
19 $this->secret = $secret;
20 $this->callback_url = $callback_url;
25 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
31 // access tokens and request tokens
41 * secret = the token secret
43 function __construct($key, $secret)
46 $this->secret = $secret;
50 * generates the basic string serialization of a token that a server
51 * would respond to request_token and access_token calls with
55 return "oauth_token=" .
56 OAuthUtil::urlencode_rfc3986($this->key) .
57 "&oauth_token_secret=" .
58 OAuthUtil::urlencode_rfc3986($this->secret);
63 return $this->to_string();
68 * A class for implementing a Signature Method
69 * See section 9 ("Signing Requests") in the spec
71 abstract class OAuthSignatureMethod
74 * Needs to return the name of the Signature Method (ie HMAC-SHA1)
77 abstract public function get_name();
80 * Build up the signature
81 * NOTE: The output of this function MUST NOT be urlencoded.
82 * the encoding is handled in OAuthRequest when the final
83 * request is serialized
84 * @param OAuthRequest $request
85 * @param OAuthConsumer $consumer
86 * @param OAuthToken $token
89 abstract public function build_signature($request, $consumer, $token);
92 * Verifies that a given signature is correct
93 * @param OAuthRequest $request
94 * @param OAuthConsumer $consumer
95 * @param OAuthToken $token
96 * @param string $signature
99 public function check_signature($request, $consumer, $token, $signature)
101 $built = $this->build_signature($request, $consumer, $token);
102 return ($built == $signature);
107 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
108 * where the Signature Base String is the text and the key is the concatenated values (each first
109 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
110 * character (ASCII code 38) even if empty.
111 * - Chapter 9.2 ("HMAC-SHA1")
113 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod
120 public function build_signature($request, $consumer, $token)
122 $base_string = $request->get_signature_base_string();
123 $request->base_string = $base_string;
127 ($token) ? $token->secret : ""
130 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
131 $key = implode('&', $key_parts);
134 $r = base64_encode(hash_hmac('sha1', $base_string, $key, true));
140 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
141 * over a secure channel such as HTTPS. It does not use the Signature Base String.
142 * - Chapter 9.4 ("PLAINTEXT")
144 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod
146 public function get_name()
152 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
153 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
154 * empty. The result MUST be encoded again.
155 * - Chapter 9.4.1 ("Generating Signatures")
157 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
158 * OAuthRequest handles this!
160 public function build_signature($request, $consumer, $token)
164 ($token) ? $token->secret : ""
167 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
168 $key = implode('&', $key_parts);
169 $request->base_string = $key;
176 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
177 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
178 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
179 * verified way to the Service Provider, in a manner which is beyond the scope of this
181 * - Chapter 9.3 ("RSA-SHA1")
183 abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod
185 public function get_name()
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
192 // (2) fetch via http using a url provided by the requester
193 // (3) some sort of specific discovery code based on request
195 // Either way should return a string representation of the certificate
196 protected abstract function fetch_public_cert(&$request);
198 // Up to the SP to implement this lookup of keys. Possible ideas are:
199 // (1) do a lookup in a table of trusted certs keyed off of consumer
201 // Either way should return a string representation of the certificate
202 protected abstract function fetch_private_cert(&$request);
204 public function build_signature($request, $consumer, $token)
206 $base_string = $request->get_signature_base_string();
207 $request->base_string = $base_string;
209 // Fetch the private key cert based on the request
210 $cert = $this->fetch_private_cert($request);
212 // Pull the private key ID from the certificate
213 $privatekeyid = openssl_get_privatekey($cert);
215 // Sign using the key
216 $ok = openssl_sign($base_string, $signature, $privatekeyid);
218 // Release the key resource
219 openssl_free_key($privatekeyid);
221 return base64_encode($signature);
224 public function check_signature($request, $consumer, $token, $signature)
226 $decoded_sig = base64_decode($signature);
228 $base_string = $request->get_signature_base_string();
230 // Fetch the public key cert based on the request
231 $cert = $this->fetch_public_cert($request);
233 // Pull the public key ID from the certificate
234 $publickeyid = openssl_get_publickey($cert);
236 // Check the computed signature against the one passed in the query
237 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
239 // Release the key resource
240 openssl_free_key($publickeyid);
249 private $http_method;
251 // for debug purposes
253 public static $version = '1.0';
254 public static $POST_INPUT = 'php://input';
256 function __construct($http_method, $http_url, $parameters = NULL)
258 @$parameters or $parameters = array();
259 $parameters = array_merge(OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
260 $this->parameters = $parameters;
261 $this->http_method = $http_method;
262 $this->http_url = $http_url;
267 * attempt to build up a request from what was passed to the server
269 public static function from_request($http_method = NULL, $http_url = NULL, $parameters = NULL)
271 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
274 @$http_url or $http_url = $scheme .
275 '://' . $_SERVER['HTTP_HOST'] .
277 $_SERVER['SERVER_PORT'] .
278 $_SERVER['REQUEST_URI'];
279 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
281 // We weren't handed any parameters, so let's find the ones relevant to
283 // If you run XML-RPC or similar you should use this to provide your own
284 // parsed parameter-list
286 // Find request headers
287 $request_headers = OAuthUtil::get_headers();
289 // Parse the query-string to find GET parameters
290 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
292 // It's a POST request of the proper content-type, so parse POST
293 // parameters and add those overriding any duplicates from GET
295 $http_method == "POST"
297 $request_headers["Content-Type"],
298 "application/x-www-form-urlencoded"
301 $post_data = OAuthUtil::parse_parameters(
302 file_get_contents(self::$POST_INPUT)
304 $parameters = array_merge($parameters, $post_data);
307 // We have a Authorization-header with OAuth data. Parse the header
308 // and add those overriding any duplicates from GET or POST
309 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
310 $header_parameters = OAuthUtil::split_header(
311 $request_headers['Authorization']
313 $parameters = array_merge($parameters, $header_parameters);
316 // fix for friendica redirect system
318 $http_url = substr($http_url, 0, strpos($http_url, $parameters['pagename']) + strlen($parameters['pagename']));
319 unset($parameters['pagename']);
321 return new OAuthRequest($http_method, $http_url, $parameters);
325 * pretty much a helper function to set up the request
327 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters = NULL)
329 @$parameters or $parameters = array();
331 "oauth_version" => OAuthRequest::$version,
332 "oauth_nonce" => OAuthRequest::generate_nonce(),
333 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
334 "oauth_consumer_key" => $consumer->key
337 $defaults['oauth_token'] = $token->key;
339 $parameters = array_merge($defaults, $parameters);
341 return new OAuthRequest($http_method, $http_url, $parameters);
344 public function set_parameter($name, $value, $allow_duplicates = true)
346 if ($allow_duplicates && isset($this->parameters[$name])) {
347 // We have already added parameter(s) with this name, so add to the list
348 if (is_scalar($this->parameters[$name])) {
349 // This is the first duplicate, so transform scalar (string)
350 // into an array so we can add the duplicates
351 $this->parameters[$name] = array($this->parameters[$name]);
354 $this->parameters[$name][] = $value;
356 $this->parameters[$name] = $value;
360 public function get_parameter($name)
362 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
365 public function get_parameters()
367 return $this->parameters;
370 public function unset_parameter($name)
372 unset($this->parameters[$name]);
376 * The request parameters, sorted and concatenated into a normalized string.
379 public function get_signable_parameters()
381 // Grab all parameters
382 $params = $this->parameters;
384 // Remove oauth_signature if present
385 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
386 if (isset($params['oauth_signature'])) {
387 unset($params['oauth_signature']);
390 return OAuthUtil::build_http_query($params);
394 * Returns the base string of this request
396 * The base string defined as the method, the url
397 * and the parameters (normalized), each urlencoded
398 * and the concated with &.
400 public function get_signature_base_string()
403 $this->get_normalized_http_method(),
404 $this->get_normalized_http_url(),
405 $this->get_signable_parameters()
408 $parts = OAuthUtil::urlencode_rfc3986($parts);
410 return implode('&', $parts);
414 * just uppercases the http method
416 public function get_normalized_http_method()
418 return strtoupper($this->http_method);
422 * parses the url and rebuilds it to be
425 public function get_normalized_http_url()
427 $parts = parse_url($this->http_url);
429 $port = @$parts['port'];
430 $scheme = $parts['scheme'];
431 $host = $parts['host'];
432 $path = @$parts['path'];
434 $port or $port = ($scheme == 'https') ? '443' : '80';
436 if (($scheme == 'https' && $port != '443')
437 || ($scheme == 'http' && $port != '80')
439 $host = "$host:$port";
441 return "$scheme://$host$path";
445 * builds a url usable for a GET request
447 public function to_url()
449 $post_data = $this->to_postdata();
450 $out = $this->get_normalized_http_url();
452 $out .= '?' . $post_data;
458 * builds the data one would send in a POST request
460 public function to_postdata($raw = false)
463 return $this->parameters;
465 return OAuthUtil::build_http_query($this->parameters);
469 * builds the Authorization: header
471 public function to_header($realm = null)
475 $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
478 $out = 'Authorization: OAuth';
480 foreach ($this->parameters as $k => $v) {
481 if (substr($k, 0, 5) != "oauth") continue;
483 throw new OAuthException('Arrays not supported in headers');
485 $out .= ($first) ? ' ' : ',';
486 $out .= OAuthUtil::urlencode_rfc3986($k) .
488 OAuthUtil::urlencode_rfc3986($v) .
495 public function __toString()
497 return $this->to_url();
501 public function sign_request($signature_method, $consumer, $token)
503 $this->set_parameter(
504 "oauth_signature_method",
505 $signature_method->get_name(),
508 $signature = $this->build_signature($signature_method, $consumer, $token);
509 $this->set_parameter("oauth_signature", $signature, false);
512 public function build_signature($signature_method, $consumer, $token)
514 $signature = $signature_method->build_signature($this, $consumer, $token);
519 * util function: current timestamp
521 private static function generate_timestamp()
527 * util function: current nonce
529 private static function generate_nonce()
531 return Friendica\Util\Strings::getRandomHex(32);
537 protected $timestamp_threshold = 300; // in seconds, five minutes
538 protected $version = '1.0'; // hi blaine
539 protected $signature_methods = array();
541 protected $data_store;
543 function __construct($data_store)
545 $this->data_store = $data_store;
548 public function add_signature_method($signature_method)
550 $this->signature_methods[$signature_method->get_name()] =
554 // high level functions
557 * process a request_token request
558 * returns the request token on success
560 public function fetch_request_token(&$request)
562 $this->get_version($request);
564 $consumer = $this->get_consumer($request);
566 // no token required for the initial token request
569 $this->check_signature($request, $consumer, $token);
572 $callback = $request->get_parameter('oauth_callback');
573 $new_token = $this->data_store->new_request_token($consumer, $callback);
579 * process an access_token request
580 * returns the access token on success
582 public function fetch_access_token(&$request)
584 $this->get_version($request);
586 $consumer = $this->get_consumer($request);
588 // requires authorized request token
589 $token = $this->get_token($request, $consumer, "request");
591 $this->check_signature($request, $consumer, $token);
594 $verifier = $request->get_parameter('oauth_verifier');
595 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
601 * verify an api call, checks all the parameters
603 public function verify_request(&$request)
605 $this->get_version($request);
606 $consumer = $this->get_consumer($request);
607 $token = $this->get_token($request, $consumer, "access");
608 $this->check_signature($request, $consumer, $token);
609 return [$consumer, $token];
612 // Internals from here
616 private function get_version(&$request)
618 $version = $request->get_parameter("oauth_version");
620 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
621 // Chapter 7.0 ("Accessing Protected Ressources")
624 if ($version !== $this->version) {
625 throw new OAuthException("OAuth version '$version' not supported");
631 * figure out the signature with some defaults
633 private function get_signature_method(&$request)
636 @$request->get_parameter("oauth_signature_method");
638 if (!$signature_method) {
639 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
640 // parameter is required, and we can't just fallback to PLAINTEXT
641 throw new OAuthException('No signature method parameter. This parameter is required');
646 array_keys($this->signature_methods)
648 throw new OAuthException(
649 "Signature method '$signature_method' not supported " .
650 "try one of the following: " .
651 implode(", ", array_keys($this->signature_methods))
654 return $this->signature_methods[$signature_method];
658 * try to find the consumer for the provided request's consumer key
660 private function get_consumer(&$request)
662 $consumer_key = @$request->get_parameter("oauth_consumer_key");
663 if (!$consumer_key) {
664 throw new OAuthException("Invalid consumer key");
667 $consumer = $this->data_store->lookup_consumer($consumer_key);
669 throw new OAuthException("Invalid consumer");
676 * try to find the token for the provided request's token key
678 private function get_token(&$request, $consumer, $token_type = "access")
680 $token_field = @$request->get_parameter('oauth_token');
681 $token = $this->data_store->lookup_token(
687 throw new OAuthException("Invalid $token_type token: $token_field");
693 * all-in-one function to check the signature on a request
694 * should guess the signature method appropriately
696 private function check_signature(&$request, $consumer, $token)
698 // this should probably be in a different method
699 $timestamp = @$request->get_parameter('oauth_timestamp');
700 $nonce = @$request->get_parameter('oauth_nonce');
702 $this->check_timestamp($timestamp);
703 $this->check_nonce($consumer, $token, $nonce, $timestamp);
705 $signature_method = $this->get_signature_method($request);
707 $signature = $request->get_parameter('oauth_signature');
708 $valid_sig = $signature_method->check_signature(
717 throw new OAuthException("Invalid signature");
722 * check that the timestamp is new enough
724 private function check_timestamp($timestamp)
727 throw new OAuthException(
728 'Missing timestamp parameter. The parameter is required'
731 // verify that timestamp is recentish
733 if (abs($now - $timestamp) > $this->timestamp_threshold) {
734 throw new OAuthException(
735 "Expired timestamp, yours $timestamp, ours $now"
741 * check that the nonce is not repeated
743 private function check_nonce($consumer, $token, $nonce, $timestamp)
746 throw new OAuthException(
747 'Missing nonce parameter. The parameter is required'
750 // verify that the nonce is uniqueish
751 $found = $this->data_store->lookup_nonce(
758 throw new OAuthException("Nonce already used: $nonce");
765 function lookup_consumer($consumer_key)
770 function lookup_token($consumer, $token_type, $token)
775 function lookup_nonce($consumer, $token, $nonce, $timestamp)
780 function new_request_token($consumer, $callback = null)
782 // return a new token attached to this consumer
785 function new_access_token($token, $consumer, $verifier = null)
787 // return a new access token attached to this consumer
788 // for the user associated with this token if the request token
790 // should also invalidate the request token
796 public static function urlencode_rfc3986($input)
798 if (is_array($input)) {
799 return array_map(['OAuthUtil', 'urlencode_rfc3986'], $input);
800 } else if (is_scalar($input)) {
804 str_replace('%7E', '~', rawurlencode($input))
812 // This decode function isn't taking into consideration the above
813 // modifications to the encoding process. However, this method doesn't
814 // seem to be used anywhere so leaving it as is.
815 public static function urldecode_rfc3986($string)
817 return urldecode($string);
820 // Utility function for turning the Authorization: header into
821 // parameters, has to do some unescaping
822 // Can filter out any non-oauth parameters if needed (default behaviour)
823 public static function split_header($header, $only_allow_oauth_parameters = true)
825 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
828 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
829 $match = $matches[0];
830 $header_name = $matches[2][0];
831 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
832 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
833 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
835 $offset = $match[1] + strlen($match[0]);
838 if (isset($params['realm'])) {
839 unset($params['realm']);
845 // helper to try to sort out headers for people who aren't running apache
846 public static function get_headers()
848 if (function_exists('apache_request_headers')) {
849 // we need this to get the actual Authorization: header
850 // because apache tends to tell us it doesn't exist
851 $headers = apache_request_headers();
853 // sanitize the output of apache_request_headers because
854 // we always want the keys to be Cased-Like-This and arh()
855 // returns the headers in the same case as they are in the
858 foreach ($headers as $key => $value) {
862 ucwords(strtolower(str_replace("-", " ", $key)))
867 // otherwise we don't have apache and are just going to have to hope
868 // that $_SERVER actually contains what we need
870 if (isset($_SERVER['CONTENT_TYPE']))
871 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
872 if (isset($_ENV['CONTENT_TYPE']))
873 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
875 foreach ($_SERVER as $key => $value) {
876 if (substr($key, 0, 5) == "HTTP_") {
877 // this is chaos, basically it is just there to capitalize the first
878 // letter of every word that is not an initial HTTP and strip HTTP
883 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
892 // This function takes a input like a=b&a=c&d=e and returns the parsed
893 // parameters like this
894 // array('a' => array('b','c'), 'd' => 'e')
895 public static function parse_parameters($input)
897 if (!isset($input) || !$input) return array();
899 $pairs = explode('&', $input);
901 $parsed_parameters = [];
902 foreach ($pairs as $pair) {
903 $split = explode('=', $pair, 2);
904 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
905 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
907 if (isset($parsed_parameters[$parameter])) {
908 // We have already recieved parameter(s) with this name, so add to the list
909 // of parameters with this name
911 if (is_scalar($parsed_parameters[$parameter])) {
912 // This is the first duplicate, so transform scalar (string) into an array
913 // so we can add the duplicates
914 $parsed_parameters[$parameter] = [$parsed_parameters[$parameter]];
917 $parsed_parameters[$parameter][] = $value;
919 $parsed_parameters[$parameter] = $value;
922 return $parsed_parameters;
925 public static function build_http_query($params)
927 if (!$params) return '';
929 // Urlencode both keys and values
930 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
931 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
932 $params = array_combine($keys, $values);
934 // Parameters are sorted by name, using lexicographical byte value ordering.
935 // Ref: Spec: 9.1.1 (1)
936 uksort($params, 'strcmp');
939 foreach ($params as $parameter => $value) {
940 if (is_array($value)) {
941 // If two or more parameters share the same name, they are sorted by their value
942 // Ref: Spec: 9.1.1 (1)
944 foreach ($value as $duplicate_value) {
945 $pairs[] = $parameter . '=' . $duplicate_value;
948 $pairs[] = $parameter . '=' . $value;
951 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
952 // Each name-value pair is separated by an '&' character (ASCII code 38)
953 return implode('&', $pairs);