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) {
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 return ($built == $signature);
99 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
100 * where the Signature Base String is the text and the key is the concatenated values (each first
101 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
102 * character (ASCII code 38) even if empty.
103 * - Chapter 9.2 ("HMAC-SHA1")
105 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
106 function get_name() {
110 public function build_signature($request, $consumer, $token) {
111 $base_string = $request->get_signature_base_string();
112 $request->base_string = $base_string;
116 ($token) ? $token->secret : ""
119 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
120 $key = implode('&', $key_parts);
123 $r = base64_encode(hash_hmac('sha1', $base_string, $key, true));
129 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
130 * over a secure channel such as HTTPS. It does not use the Signature Base String.
131 * - Chapter 9.4 ("PLAINTEXT")
133 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
134 public function get_name() {
139 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
140 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
141 * empty. The result MUST be encoded again.
142 * - Chapter 9.4.1 ("Generating Signatures")
144 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
145 * OAuthRequest handles this!
147 public function build_signature($request, $consumer, $token) {
150 ($token) ? $token->secret : ""
153 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
154 $key = implode('&', $key_parts);
155 $request->base_string = $key;
162 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
163 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
164 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
165 * verified way to the Service Provider, in a manner which is beyond the scope of this
167 * - Chapter 9.3 ("RSA-SHA1")
169 abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
170 public function get_name() {
174 // Up to the SP to implement this lookup of keys. Possible ideas are:
175 // (1) do a lookup in a table of trusted certs keyed off of consumer
176 // (2) fetch via http using a url provided by the requester
177 // (3) some sort of specific discovery code based on request
179 // Either way should return a string representation of the certificate
180 protected abstract function fetch_public_cert(&$request);
182 // Up to the SP to implement this lookup of keys. Possible ideas are:
183 // (1) do a lookup in a table of trusted certs keyed off of consumer
185 // Either way should return a string representation of the certificate
186 protected abstract function fetch_private_cert(&$request);
188 public function build_signature($request, $consumer, $token) {
189 $base_string = $request->get_signature_base_string();
190 $request->base_string = $base_string;
192 // Fetch the private key cert based on the request
193 $cert = $this->fetch_private_cert($request);
195 // Pull the private key ID from the certificate
196 $privatekeyid = openssl_get_privatekey($cert);
198 // Sign using the key
199 $ok = openssl_sign($base_string, $signature, $privatekeyid);
201 // Release the key resource
202 openssl_free_key($privatekeyid);
204 return base64_encode($signature);
207 public function check_signature($request, $consumer, $token, $signature) {
208 $decoded_sig = base64_decode($signature);
210 $base_string = $request->get_signature_base_string();
212 // Fetch the public key cert based on the request
213 $cert = $this->fetch_public_cert($request);
215 // Pull the public key ID from the certificate
216 $publickeyid = openssl_get_publickey($cert);
218 // Check the computed signature against the one passed in the query
219 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
221 // Release the key resource
222 openssl_free_key($publickeyid);
230 private $http_method;
232 // for debug purposes
234 public static $version = '1.0';
235 public static $POST_INPUT = 'php://input';
237 function __construct($http_method, $http_url, $parameters=NULL) {
238 @$parameters or $parameters = array();
239 $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
240 $this->parameters = $parameters;
241 $this->http_method = $http_method;
242 $this->http_url = $http_url;
247 * attempt to build up a request from what was passed to the server
249 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
250 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
253 @$http_url or $http_url = $scheme .
254 '://' . $_SERVER['HTTP_HOST'] .
256 $_SERVER['SERVER_PORT'] .
257 $_SERVER['REQUEST_URI'];
258 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
260 // We weren't handed any parameters, so let's find the ones relevant to
262 // If you run XML-RPC or similar you should use this to provide your own
263 // parsed parameter-list
265 // Find request headers
266 $request_headers = OAuthUtil::get_headers();
268 // Parse the query-string to find GET parameters
269 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
271 // It's a POST request of the proper content-type, so parse POST
272 // parameters and add those overriding any duplicates from GET
273 if ($http_method == "POST"
274 && @strstr($request_headers["Content-Type"],
275 "application/x-www-form-urlencoded")
277 $post_data = OAuthUtil::parse_parameters(
278 file_get_contents(self::$POST_INPUT)
280 $parameters = array_merge($parameters, $post_data);
283 // We have a Authorization-header with OAuth data. Parse the header
284 // and add those overriding any duplicates from GET or POST
285 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
286 $header_parameters = OAuthUtil::split_header(
287 $request_headers['Authorization']
289 $parameters = array_merge($parameters, $header_parameters);
293 // fix for friendica redirect system
295 $http_url = substr($http_url, 0, strpos($http_url,$parameters['pagename'])+strlen($parameters['pagename']));
296 unset( $parameters['pagename'] );
298 return new OAuthRequest($http_method, $http_url, $parameters);
302 * pretty much a helper function to set up the request
304 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
305 @$parameters or $parameters = array();
306 $defaults = array("oauth_version" => OAuthRequest::$version,
307 "oauth_nonce" => OAuthRequest::generate_nonce(),
308 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
309 "oauth_consumer_key" => $consumer->key);
311 $defaults['oauth_token'] = $token->key;
313 $parameters = array_merge($defaults, $parameters);
315 return new OAuthRequest($http_method, $http_url, $parameters);
318 public function set_parameter($name, $value, $allow_duplicates = true) {
319 if ($allow_duplicates && isset($this->parameters[$name])) {
320 // We have already added parameter(s) with this name, so add to the list
321 if (is_scalar($this->parameters[$name])) {
322 // This is the first duplicate, so transform scalar (string)
323 // into an array so we can add the duplicates
324 $this->parameters[$name] = array($this->parameters[$name]);
327 $this->parameters[$name][] = $value;
329 $this->parameters[$name] = $value;
333 public function get_parameter($name) {
334 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
337 public function get_parameters() {
338 return $this->parameters;
341 public function unset_parameter($name) {
342 unset($this->parameters[$name]);
346 * The request parameters, sorted and concatenated into a normalized string.
349 public function get_signable_parameters() {
350 // Grab all parameters
351 $params = $this->parameters;
353 // Remove oauth_signature if present
354 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
355 if (isset($params['oauth_signature'])) {
356 unset($params['oauth_signature']);
359 return OAuthUtil::build_http_query($params);
363 * Returns the base string of this request
365 * The base string defined as the method, the url
366 * and the parameters (normalized), each urlencoded
367 * and the concated with &.
369 public function get_signature_base_string() {
371 $this->get_normalized_http_method(),
372 $this->get_normalized_http_url(),
373 $this->get_signable_parameters()
376 $parts = OAuthUtil::urlencode_rfc3986($parts);
378 return implode('&', $parts);
382 * just uppercases the http method
384 public function get_normalized_http_method() {
385 return strtoupper($this->http_method);
389 * parses the url and rebuilds it to be
392 public function get_normalized_http_url() {
393 $parts = parse_url($this->http_url);
395 $port = @$parts['port'];
396 $scheme = $parts['scheme'];
397 $host = $parts['host'];
398 $path = @$parts['path'];
400 $port or $port = ($scheme == 'https') ? '443' : '80';
402 if (($scheme == 'https' && $port != '443')
403 || ($scheme == 'http' && $port != '80')) {
404 $host = "$host:$port";
406 return "$scheme://$host$path";
410 * builds a url usable for a GET request
412 public function to_url() {
413 $post_data = $this->to_postdata();
414 $out = $this->get_normalized_http_url();
416 $out .= '?'.$post_data;
422 * builds the data one would send in a POST request
424 public function to_postdata($raw = false) {
426 return($this->parameters);
428 return OAuthUtil::build_http_query($this->parameters);
432 * builds the Authorization: header
434 public function to_header($realm=null) {
437 $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
440 $out = 'Authorization: OAuth';
443 foreach ($this->parameters as $k => $v) {
444 if (substr($k, 0, 5) != "oauth") continue;
446 throw new OAuthException('Arrays not supported in headers');
448 $out .= ($first) ? ' ' : ',';
449 $out .= OAuthUtil::urlencode_rfc3986($k) .
451 OAuthUtil::urlencode_rfc3986($v) .
458 public function __toString() {
459 return $this->to_url();
463 public function sign_request($signature_method, $consumer, $token) {
464 $this->set_parameter(
465 "oauth_signature_method",
466 $signature_method->get_name(),
469 $signature = $this->build_signature($signature_method, $consumer, $token);
470 $this->set_parameter("oauth_signature", $signature, false);
473 public function build_signature($signature_method, $consumer, $token) {
474 $signature = $signature_method->build_signature($this, $consumer, $token);
479 * util function: current timestamp
481 private static function generate_timestamp() {
486 * util function: current nonce
488 private static function generate_nonce() {
492 return md5($mt . $rand); // md5s look nicer than numbers
497 protected $timestamp_threshold = 300; // in seconds, five minutes
498 protected $version = '1.0'; // hi blaine
499 protected $signature_methods = array();
501 protected $data_store;
503 function __construct($data_store) {
504 $this->data_store = $data_store;
507 public function add_signature_method($signature_method) {
508 $this->signature_methods[$signature_method->get_name()] =
512 // high level functions
515 * process a request_token request
516 * returns the request token on success
518 public function fetch_request_token(&$request) {
519 $this->get_version($request);
521 $consumer = $this->get_consumer($request);
523 // no token required for the initial token request
526 $this->check_signature($request, $consumer, $token);
529 $callback = $request->get_parameter('oauth_callback');
530 $new_token = $this->data_store->new_request_token($consumer, $callback);
536 * process an access_token request
537 * returns the access token on success
539 public function fetch_access_token(&$request) {
540 $this->get_version($request);
542 $consumer = $this->get_consumer($request);
544 // requires authorized request token
545 $token = $this->get_token($request, $consumer, "request");
547 $this->check_signature($request, $consumer, $token);
550 $verifier = $request->get_parameter('oauth_verifier');
551 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
557 * verify an api call, checks all the parameters
559 public function verify_request(&$request) {
560 $this->get_version($request);
561 $consumer = $this->get_consumer($request);
562 $token = $this->get_token($request, $consumer, "access");
563 $this->check_signature($request, $consumer, $token);
564 return array($consumer, $token);
567 // Internals from here
571 private function get_version(&$request) {
572 $version = $request->get_parameter("oauth_version");
574 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
575 // Chapter 7.0 ("Accessing Protected Ressources")
578 if ($version !== $this->version) {
579 throw new OAuthException("OAuth version '$version' not supported");
585 * figure out the signature with some defaults
587 private function get_signature_method(&$request) {
589 @$request->get_parameter("oauth_signature_method");
591 if (!$signature_method) {
592 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
593 // parameter is required, and we can't just fallback to PLAINTEXT
594 throw new OAuthException('No signature method parameter. This parameter is required');
597 if (!in_array($signature_method,
598 array_keys($this->signature_methods))) {
599 throw new OAuthException(
600 "Signature method '$signature_method' not supported " .
601 "try one of the following: " .
602 implode(", ", array_keys($this->signature_methods))
605 return $this->signature_methods[$signature_method];
609 * try to find the consumer for the provided request's consumer key
611 private function get_consumer(&$request) {
612 $consumer_key = @$request->get_parameter("oauth_consumer_key");
613 if (!$consumer_key) {
614 throw new OAuthException("Invalid consumer key");
617 $consumer = $this->data_store->lookup_consumer($consumer_key);
619 throw new OAuthException("Invalid consumer");
626 * try to find the token for the provided request's token key
628 private function get_token(&$request, $consumer, $token_type="access") {
629 $token_field = @$request->get_parameter('oauth_token');
630 $token = $this->data_store->lookup_token(
631 $consumer, $token_type, $token_field
634 throw new OAuthException("Invalid $token_type token: $token_field");
640 * all-in-one function to check the signature on a request
641 * should guess the signature method appropriately
643 private function check_signature(&$request, $consumer, $token) {
644 // this should probably be in a different method
645 $timestamp = @$request->get_parameter('oauth_timestamp');
646 $nonce = @$request->get_parameter('oauth_nonce');
648 $this->check_timestamp($timestamp);
649 $this->check_nonce($consumer, $token, $nonce, $timestamp);
651 $signature_method = $this->get_signature_method($request);
653 $signature = $request->get_parameter('oauth_signature');
654 $valid_sig = $signature_method->check_signature(
663 throw new OAuthException("Invalid signature");
668 * check that the timestamp is new enough
670 private function check_timestamp($timestamp) {
672 throw new OAuthException(
673 'Missing timestamp parameter. The parameter is required'
676 // verify that timestamp is recentish
678 if (abs($now - $timestamp) > $this->timestamp_threshold) {
679 throw new OAuthException(
680 "Expired timestamp, yours $timestamp, ours $now"
686 * check that the nonce is not repeated
688 private function check_nonce($consumer, $token, $nonce, $timestamp) {
690 throw new OAuthException(
691 'Missing nonce parameter. The parameter is required'
694 // verify that the nonce is uniqueish
695 $found = $this->data_store->lookup_nonce(
702 throw new OAuthException("Nonce already used: $nonce");
708 class OAuthDataStore {
709 function lookup_consumer($consumer_key) {
713 function lookup_token($consumer, $token_type, $token) {
717 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
721 function new_request_token($consumer, $callback = null) {
722 // return a new token attached to this consumer
725 function new_access_token($token, $consumer, $verifier = null) {
726 // return a new access token attached to this consumer
727 // for the user associated with this token if the request token
729 // should also invalidate the request token
735 public static function urlencode_rfc3986($input) {
736 if (is_array($input)) {
737 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
738 } else if (is_scalar($input)) {
742 str_replace('%7E', '~', rawurlencode($input))
750 // This decode function isn't taking into consideration the above
751 // modifications to the encoding process. However, this method doesn't
752 // seem to be used anywhere so leaving it as is.
753 public static function urldecode_rfc3986($string) {
754 return urldecode($string);
757 // Utility function for turning the Authorization: header into
758 // parameters, has to do some unescaping
759 // Can filter out any non-oauth parameters if needed (default behaviour)
760 public static function split_header($header, $only_allow_oauth_parameters = true) {
761 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
764 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
765 $match = $matches[0];
766 $header_name = $matches[2][0];
767 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
768 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
769 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
771 $offset = $match[1] + strlen($match[0]);
774 if (isset($params['realm'])) {
775 unset($params['realm']);
781 // helper to try to sort out headers for people who aren't running apache
782 public static function get_headers() {
783 if (function_exists('apache_request_headers')) {
784 // we need this to get the actual Authorization: header
785 // because apache tends to tell us it doesn't exist
786 $headers = apache_request_headers();
788 // sanitize the output of apache_request_headers because
789 // we always want the keys to be Cased-Like-This and arh()
790 // returns the headers in the same case as they are in the
793 foreach( $headers AS $key => $value ) {
797 ucwords(strtolower(str_replace("-", " ", $key)))
802 // otherwise we don't have apache and are just going to have to hope
803 // that $_SERVER actually contains what we need
805 if( isset($_SERVER['CONTENT_TYPE']) )
806 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
807 if( isset($_ENV['CONTENT_TYPE']) )
808 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
810 foreach ($_SERVER as $key => $value) {
811 if (substr($key, 0, 5) == "HTTP_") {
812 // this is chaos, basically it is just there to capitalize the first
813 // letter of every word that is not an initial HTTP and strip HTTP
818 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
827 // This function takes a input like a=b&a=c&d=e and returns the parsed
828 // parameters like this
829 // array('a' => array('b','c'), 'd' => 'e')
830 public static function parse_parameters( $input ) {
831 if (!isset($input) || !$input) return array();
833 $pairs = explode('&', $input);
835 $parsed_parameters = array();
836 foreach ($pairs as $pair) {
837 $split = explode('=', $pair, 2);
838 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
839 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
841 if (isset($parsed_parameters[$parameter])) {
842 // We have already recieved parameter(s) with this name, so add to the list
843 // of parameters with this name
845 if (is_scalar($parsed_parameters[$parameter])) {
846 // This is the first duplicate, so transform scalar (string) into an array
847 // so we can add the duplicates
848 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
851 $parsed_parameters[$parameter][] = $value;
853 $parsed_parameters[$parameter] = $value;
856 return $parsed_parameters;
859 public static function build_http_query($params) {
860 if (!$params) return '';
862 // Urlencode both keys and values
863 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
864 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
865 $params = array_combine($keys, $values);
867 // Parameters are sorted by name, using lexicographical byte value ordering.
868 // Ref: Spec: 9.1.1 (1)
869 uksort($params, 'strcmp');
872 foreach ($params as $parameter => $value) {
873 if (is_array($value)) {
874 // If two or more parameters share the same name, they are sorted by their value
875 // Ref: Spec: 9.1.1 (1)
877 foreach ($value as $duplicate_value) {
878 $pairs[] = $parameter . '=' . $duplicate_value;
881 $pairs[] = $parameter . '=' . $value;
884 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
885 // Each name-value pair is separated by an '&' character (ASCII code 38)
886 return implode('&', $pairs);