2 // vim: foldmethod=marker
4 /* Generic exception class
7 use Friendica\Network\FKOAuthDataStore;
9 if (!class_exists('OAuthException', false)) {
10 class OAuthException extends Exception
21 function __construct($key, $secret, $callback_url = NULL)
24 $this->secret = $secret;
25 $this->callback_url = $callback_url;
30 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
36 // access tokens and request tokens
46 * secret = the token secret
51 function __construct($key, $secret)
54 $this->secret = $secret;
58 * generates the basic string serialization of a token that a server
59 * would respond to request_token and access_token calls with
63 return "oauth_token=" .
64 OAuthUtil::urlencode_rfc3986($this->key) .
65 "&oauth_token_secret=" .
66 OAuthUtil::urlencode_rfc3986($this->secret);
71 return $this->to_string();
76 * A class for implementing a Signature Method
77 * See section 9 ("Signing Requests") in the spec
79 abstract class OAuthSignatureMethod
82 * Needs to return the name of the Signature Method (ie HMAC-SHA1)
86 abstract public function get_name();
89 * Build up the signature
90 * NOTE: The output of this function MUST NOT be urlencoded.
91 * the encoding is handled in OAuthRequest when the final
92 * request is serialized
94 * @param OAuthRequest $request
95 * @param OAuthConsumer $consumer
96 * @param OAuthToken $token
99 abstract public function build_signature(OAuthRequest $request, OAuthConsumer $consumer, OAuthToken $token = null);
102 * Verifies that a given signature is correct
104 * @param OAuthRequest $request
105 * @param OAuthConsumer $consumer
106 * @param OAuthToken $token
107 * @param string $signature
110 public function check_signature(OAuthRequest $request, OAuthConsumer $consumer, $signature, OAuthToken $token = null)
112 $built = $this->build_signature($request, $consumer, $token);
113 return ($built == $signature);
118 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
119 * where the Signature Base String is the text and the key is the concatenated values (each first
120 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
121 * character (ASCII code 38) even if empty.
122 * - Chapter 9.2 ("HMAC-SHA1")
124 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod
132 * @param OAuthRequest $request
133 * @param OAuthConsumer $consumer
134 * @param OAuthToken $token
137 public function build_signature(OAuthRequest $request, OAuthConsumer $consumer, OAuthToken $token = null)
139 $base_string = $request->get_signature_base_string();
140 $request->base_string = $base_string;
144 ($token) ? $token->secret : ""
147 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
148 $key = implode('&', $key_parts);
151 $r = base64_encode(hash_hmac('sha1', $base_string, $key, true));
157 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
158 * over a secure channel such as HTTPS. It does not use the Signature Base String.
159 * - Chapter 9.4 ("PLAINTEXT")
161 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod
163 public function get_name()
169 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
170 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
171 * empty. The result MUST be encoded again.
172 * - Chapter 9.4.1 ("Generating Signatures")
174 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
175 * OAuthRequest handles this!
182 public function build_signature(OAuthRequest $request, OAuthConsumer $consumer, OAuthToken $token = null)
186 ($token) ? $token->secret : ""
189 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
190 $key = implode('&', $key_parts);
191 $request->base_string = $key;
198 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
199 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
200 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
201 * verified way to the Service Provider, in a manner which is beyond the scope of this
203 * - Chapter 9.3 ("RSA-SHA1")
205 abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod
207 public function get_name()
212 // Up to the SP to implement this lookup of keys. Possible ideas are:
213 // (1) do a lookup in a table of trusted certs keyed off of consumer
214 // (2) fetch via http using a url provided by the requester
215 // (3) some sort of specific discovery code based on request
217 // Either way should return a string representation of the certificate
218 protected abstract function fetch_public_cert(&$request);
220 // Up to the SP to implement this lookup of keys. Possible ideas are:
221 // (1) do a lookup in a table of trusted certs keyed off of consumer
223 // Either way should return a string representation of the certificate
224 protected abstract function fetch_private_cert(&$request);
226 public function build_signature(OAuthRequest $request, OAuthConsumer $consumer, OAuthToken $token = null)
228 $base_string = $request->get_signature_base_string();
229 $request->base_string = $base_string;
231 // Fetch the private key cert based on the request
232 $cert = $this->fetch_private_cert($request);
234 // Pull the private key ID from the certificate
235 $privatekeyid = openssl_get_privatekey($cert);
237 // Sign using the key
238 openssl_sign($base_string, $signature, $privatekeyid);
240 // Release the key resource
241 openssl_free_key($privatekeyid);
243 return base64_encode($signature);
246 public function check_signature(OAuthRequest $request, OAuthConsumer $consumer, $signature, OAuthToken $token = null)
248 $decoded_sig = base64_decode($signature);
250 $base_string = $request->get_signature_base_string();
252 // Fetch the public key cert based on the request
253 $cert = $this->fetch_public_cert($request);
255 // Pull the public key ID from the certificate
256 $publickeyid = openssl_get_publickey($cert);
258 // Check the computed signature against the one passed in the query
259 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
261 // Release the key resource
262 openssl_free_key($publickeyid);
271 private $http_method;
273 // for debug purposes
275 public static $version = '1.0';
276 public static $POST_INPUT = 'php://input';
278 function __construct($http_method, $http_url, $parameters = NULL)
280 @$parameters or $parameters = array();
281 $parameters = array_merge(OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
282 $this->parameters = $parameters;
283 $this->http_method = $http_method;
284 $this->http_url = $http_url;
289 * attempt to build up a request from what was passed to the server
291 * @param string|null $http_method
292 * @param string|null $http_url
293 * @param string|null $parameters
294 * @return OAuthRequest
296 public static function from_request($http_method = NULL, $http_url = NULL, $parameters = NULL)
298 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
301 @$http_url or $http_url = $scheme .
302 '://' . $_SERVER['HTTP_HOST'] .
304 $_SERVER['SERVER_PORT'] .
305 $_SERVER['REQUEST_URI'];
306 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
308 // We weren't handed any parameters, so let's find the ones relevant to
310 // If you run XML-RPC or similar you should use this to provide your own
311 // parsed parameter-list
313 // Find request headers
314 $request_headers = OAuthUtil::get_headers();
316 // Parse the query-string to find GET parameters
317 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
319 // It's a POST request of the proper content-type, so parse POST
320 // parameters and add those overriding any duplicates from GET
322 $http_method == "POST"
324 $request_headers["Content-Type"],
325 "application/x-www-form-urlencoded"
328 $post_data = OAuthUtil::parse_parameters(
329 file_get_contents(self::$POST_INPUT)
331 $parameters = array_merge($parameters, $post_data);
334 // We have a Authorization-header with OAuth data. Parse the header
335 // and add those overriding any duplicates from GET or POST
336 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
337 $header_parameters = OAuthUtil::split_header(
338 $request_headers['Authorization']
340 $parameters = array_merge($parameters, $header_parameters);
343 // fix for friendica redirect system
345 $http_url = substr($http_url, 0, strpos($http_url, $parameters['pagename']) + strlen($parameters['pagename']));
346 unset($parameters['pagename']);
348 return new OAuthRequest($http_method, $http_url, $parameters);
352 * pretty much a helper function to set up the request
354 * @param OAuthConsumer $consumer
355 * @param OAuthToken $token
356 * @param string $http_method
357 * @param string $http_url
358 * @param array|null $parameters
359 * @return OAuthRequest
361 public static function from_consumer_and_token(OAuthConsumer $consumer, $http_method, $http_url, array $parameters = null, OAuthToken $token = null)
363 @$parameters or $parameters = array();
365 "oauth_version" => OAuthRequest::$version,
366 "oauth_nonce" => OAuthRequest::generate_nonce(),
367 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
368 "oauth_consumer_key" => $consumer->key
371 $defaults['oauth_token'] = $token->key;
373 $parameters = array_merge($defaults, $parameters);
375 return new OAuthRequest($http_method, $http_url, $parameters);
378 public function set_parameter($name, $value, $allow_duplicates = true)
380 if ($allow_duplicates && isset($this->parameters[$name])) {
381 // We have already added parameter(s) with this name, so add to the list
382 if (is_scalar($this->parameters[$name])) {
383 // This is the first duplicate, so transform scalar (string)
384 // into an array so we can add the duplicates
385 $this->parameters[$name] = array($this->parameters[$name]);
388 $this->parameters[$name][] = $value;
390 $this->parameters[$name] = $value;
394 public function get_parameter($name)
396 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
399 public function get_parameters()
401 return $this->parameters;
404 public function unset_parameter($name)
406 unset($this->parameters[$name]);
410 * The request parameters, sorted and concatenated into a normalized string.
414 public function get_signable_parameters()
416 // Grab all parameters
417 $params = $this->parameters;
419 // Remove oauth_signature if present
420 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
421 if (isset($params['oauth_signature'])) {
422 unset($params['oauth_signature']);
425 return OAuthUtil::build_http_query($params);
429 * Returns the base string of this request
431 * The base string defined as the method, the url
432 * and the parameters (normalized), each urlencoded
433 * and the concated with &.
435 public function get_signature_base_string()
438 $this->get_normalized_http_method(),
439 $this->get_normalized_http_url(),
440 $this->get_signable_parameters()
443 $parts = OAuthUtil::urlencode_rfc3986($parts);
445 return implode('&', $parts);
449 * just uppercases the http method
451 public function get_normalized_http_method()
453 return strtoupper($this->http_method);
457 * parses the url and rebuilds it to be
460 public function get_normalized_http_url()
462 $parts = parse_url($this->http_url);
464 $port = @$parts['port'];
465 $scheme = $parts['scheme'];
466 $host = $parts['host'];
467 $path = @$parts['path'];
469 $port or $port = ($scheme == 'https') ? '443' : '80';
471 if (($scheme == 'https' && $port != '443')
472 || ($scheme == 'http' && $port != '80')
474 $host = "$host:$port";
476 return "$scheme://$host$path";
480 * builds a url usable for a GET request
482 public function to_url()
484 $post_data = $this->to_postdata();
485 $out = $this->get_normalized_http_url();
487 $out .= '?' . $post_data;
493 * builds the data one would send in a POST request
496 * @return array|string
498 public function to_postdata(bool $raw = false)
501 return $this->parameters;
503 return OAuthUtil::build_http_query($this->parameters);
507 * builds the Authorization: header
509 * @param string|null $realm
511 * @throws OAuthException
513 public function to_header($realm = null)
517 $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
520 $out = 'Authorization: OAuth';
522 foreach ($this->parameters as $k => $v) {
523 if (substr($k, 0, 5) != "oauth") continue;
525 throw new OAuthException('Arrays not supported in headers');
527 $out .= ($first) ? ' ' : ',';
528 $out .= OAuthUtil::urlencode_rfc3986($k) .
530 OAuthUtil::urlencode_rfc3986($v) .
537 public function __toString()
539 return $this->to_url();
543 public function sign_request(OAuthSignatureMethod $signature_method, $consumer, $token)
545 $this->set_parameter(
546 "oauth_signature_method",
547 $signature_method->get_name(),
550 $signature = $this->build_signature($signature_method, $consumer, $token);
551 $this->set_parameter("oauth_signature", $signature, false);
554 public function build_signature(OAuthSignatureMethod $signature_method, $consumer, $token)
556 $signature = $signature_method->build_signature($this, $consumer, $token);
561 * util function: current timestamp
563 private static function generate_timestamp()
569 * util function: current nonce
571 private static function generate_nonce()
573 return Friendica\Util\Strings::getRandomHex(32);
579 protected $timestamp_threshold = 300; // in seconds, five minutes
580 protected $version = '1.0'; // hi blaine
581 /** @var OAuthSignatureMethod[] */
582 protected $signature_methods = array();
584 /** @var FKOAuthDataStore */
585 protected $data_store;
587 function __construct(FKOAuthDataStore $data_store)
589 $this->data_store = $data_store;
592 public function add_signature_method(OAuthSignatureMethod $signature_method)
594 $this->signature_methods[$signature_method->get_name()] =
598 // high level functions
601 * process a request_token request
602 * returns the request token on success
604 * @param OAuthRequest $request
605 * @return OAuthToken|null
606 * @throws OAuthException
608 public function fetch_request_token(OAuthRequest $request)
610 $this->get_version($request);
612 $consumer = $this->get_consumer($request);
614 // no token required for the initial token request
617 $this->check_signature($request, $consumer, $token);
620 $callback = $request->get_parameter('oauth_callback');
621 $new_token = $this->data_store->new_request_token($consumer, $callback);
627 * process an access_token request
628 * returns the access token on success
630 * @param OAuthRequest $request
632 * @throws OAuthException
634 public function fetch_access_token(OAuthRequest $request)
636 $this->get_version($request);
638 $consumer = $this->get_consumer($request);
640 // requires authorized request token
641 $token = $this->get_token($request, $consumer, "request");
643 $this->check_signature($request, $consumer, $token);
646 $verifier = $request->get_parameter('oauth_verifier');
647 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
653 * verify an api call, checks all the parameters
655 * @param OAuthRequest $request
657 * @throws OAuthException
659 public function verify_request(OAuthRequest $request)
661 $this->get_version($request);
662 $consumer = $this->get_consumer($request);
663 $token = $this->get_token($request, $consumer, "access");
664 $this->check_signature($request, $consumer, $token);
665 return [$consumer, $token];
668 // Internals from here
673 * @param OAuthRequest $request
675 * @throws OAuthException
677 private function get_version(OAuthRequest $request)
679 $version = $request->get_parameter("oauth_version");
681 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
682 // Chapter 7.0 ("Accessing Protected Ressources")
685 if ($version !== $this->version) {
686 throw new OAuthException("OAuth version '$version' not supported");
692 * figure out the signature with some defaults
694 * @param OAuthRequest $request
695 * @return OAuthSignatureMethod
696 * @throws OAuthException
698 private function get_signature_method(OAuthRequest $request)
701 @$request->get_parameter("oauth_signature_method");
703 if (!$signature_method) {
704 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
705 // parameter is required, and we can't just fallback to PLAINTEXT
706 throw new OAuthException('No signature method parameter. This parameter is required');
711 array_keys($this->signature_methods)
713 throw new OAuthException(
714 "Signature method '$signature_method' not supported " .
715 "try one of the following: " .
716 implode(", ", array_keys($this->signature_methods))
719 return $this->signature_methods[$signature_method];
723 * try to find the consumer for the provided request's consumer key
725 * @param OAuthRequest $request
726 * @return OAuthConsumer
727 * @throws OAuthException
729 private function get_consumer(OAuthRequest $request)
731 $consumer_key = @$request->get_parameter("oauth_consumer_key");
732 if (!$consumer_key) {
733 throw new OAuthException("Invalid consumer key");
736 $consumer = $this->data_store->lookup_consumer($consumer_key);
738 throw new OAuthException("Invalid consumer");
745 * try to find the token for the provided request's token key
747 * @param OAuthRequest $request
749 * @param string $token_type
750 * @return OAuthToken|null
751 * @throws OAuthException
753 private function get_token(OAuthRequest &$request, $consumer, $token_type = "access")
755 $token_field = @$request->get_parameter('oauth_token');
756 $token = $this->data_store->lookup_token(
762 throw new OAuthException("Invalid $token_type token: $token_field");
768 * all-in-one function to check the signature on a request
769 * should guess the signature method appropriately
771 * @param OAuthRequest $request
772 * @param OAuthConsumer $consumer
773 * @param OAuthToken|null $token
774 * @throws OAuthException
776 private function check_signature(OAuthRequest $request, OAuthConsumer $consumer, OAuthToken $token = null)
778 // this should probably be in a different method
779 $timestamp = @$request->get_parameter('oauth_timestamp');
780 $nonce = @$request->get_parameter('oauth_nonce');
782 $this->check_timestamp($timestamp);
783 $this->check_nonce($consumer, $token, $nonce, $timestamp);
785 $signature_method = $this->get_signature_method($request);
787 $signature = $request->get_parameter('oauth_signature');
788 $valid_sig = $signature_method->check_signature(
796 throw new OAuthException("Invalid signature");
801 * check that the timestamp is new enough
803 * @param int $timestamp
804 * @throws OAuthException
806 private function check_timestamp($timestamp)
809 throw new OAuthException(
810 'Missing timestamp parameter. The parameter is required'
813 // verify that timestamp is recentish
815 if (abs($now - $timestamp) > $this->timestamp_threshold) {
816 throw new OAuthException(
817 "Expired timestamp, yours $timestamp, ours $now"
823 * check that the nonce is not repeated
825 * @param OAuthConsumer $consumer
826 * @param OAuthToken $token
827 * @param string $nonce
828 * @param int $timestamp
829 * @throws OAuthException
831 private function check_nonce(OAuthConsumer $consumer, OAuthToken $token, $nonce, int $timestamp)
834 throw new OAuthException(
835 'Missing nonce parameter. The parameter is required'
838 // verify that the nonce is uniqueish
839 $found = $this->data_store->lookup_nonce(
846 throw new OAuthException("Nonce already used: $nonce");
853 function lookup_consumer($consumer_key)
858 function lookup_token(OAuthConsumer $consumer, $token_type, $token_id)
863 function lookup_nonce(OAuthConsumer $consumer, OAuthToken $token, $nonce, int $timestamp)
868 function new_request_token(OAuthConsumer $consumer, $callback = null)
870 // return a new token attached to this consumer
873 function new_access_token(OAuthToken $token, OAuthConsumer $consumer, $verifier = null)
875 // return a new access token attached to this consumer
876 // for the user associated with this token if the request token
878 // should also invalidate the request token
884 public static function urlencode_rfc3986($input)
886 if (is_array($input)) {
887 return array_map(['OAuthUtil', 'urlencode_rfc3986'], $input);
888 } else if (is_scalar($input)) {
892 str_replace('%7E', '~', rawurlencode($input))
900 // This decode function isn't taking into consideration the above
901 // modifications to the encoding process. However, this method doesn't
902 // seem to be used anywhere so leaving it as is.
903 public static function urldecode_rfc3986($string)
905 return urldecode($string);
908 // Utility function for turning the Authorization: header into
909 // parameters, has to do some unescaping
910 // Can filter out any non-oauth parameters if needed (default behaviour)
911 public static function split_header($header, $only_allow_oauth_parameters = true)
913 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
916 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
917 $match = $matches[0];
918 $header_name = $matches[2][0];
919 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
920 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
921 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
923 $offset = $match[1] + strlen($match[0]);
926 if (isset($params['realm'])) {
927 unset($params['realm']);
933 // helper to try to sort out headers for people who aren't running apache
934 public static function get_headers()
936 if (function_exists('apache_request_headers')) {
937 // we need this to get the actual Authorization: header
938 // because apache tends to tell us it doesn't exist
939 $headers = apache_request_headers();
941 // sanitize the output of apache_request_headers because
942 // we always want the keys to be Cased-Like-This and arh()
943 // returns the headers in the same case as they are in the
946 foreach ($headers as $key => $value) {
950 ucwords(strtolower(str_replace("-", " ", $key)))
955 // otherwise we don't have apache and are just going to have to hope
956 // that $_SERVER actually contains what we need
958 if (isset($_SERVER['CONTENT_TYPE']))
959 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
960 if (isset($_ENV['CONTENT_TYPE']))
961 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
963 foreach ($_SERVER as $key => $value) {
964 if (substr($key, 0, 5) == "HTTP_") {
965 // this is chaos, basically it is just there to capitalize the first
966 // letter of every word that is not an initial HTTP and strip HTTP
971 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
980 // This function takes a input like a=b&a=c&d=e and returns the parsed
981 // parameters like this
982 // array('a' => array('b','c'), 'd' => 'e')
983 public static function parse_parameters($input)
985 if (!isset($input) || !$input) return array();
987 $pairs = explode('&', $input);
989 $parsed_parameters = [];
990 foreach ($pairs as $pair) {
991 $split = explode('=', $pair, 2);
992 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
993 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
995 if (isset($parsed_parameters[$parameter])) {
996 // We have already recieved parameter(s) with this name, so add to the list
997 // of parameters with this name
999 if (is_scalar($parsed_parameters[$parameter])) {
1000 // This is the first duplicate, so transform scalar (string) into an array
1001 // so we can add the duplicates
1002 $parsed_parameters[$parameter] = [$parsed_parameters[$parameter]];
1005 $parsed_parameters[$parameter][] = $value;
1007 $parsed_parameters[$parameter] = $value;
1010 return $parsed_parameters;
1013 public static function build_http_query($params)
1015 if (!$params) return '';
1017 // Urlencode both keys and values
1018 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
1019 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
1020 $params = array_combine($keys, $values);
1022 // Parameters are sorted by name, using lexicographical byte value ordering.
1023 // Ref: Spec: 9.1.1 (1)
1024 uksort($params, 'strcmp');
1027 foreach ($params as $parameter => $value) {
1028 if (is_array($value)) {
1029 // If two or more parameters share the same name, they are sorted by their value
1030 // Ref: Spec: 9.1.1 (1)
1032 foreach ($value as $duplicate_value) {
1033 $pairs[] = $parameter . '=' . $duplicate_value;
1036 $pairs[] = $parameter . '=' . $value;
1039 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
1040 // Each name-value pair is separated by an '&' character (ASCII code 38)
1041 return implode('&', $pairs);