2 // vim: foldmethod=marker
4 /* Generic exception class
6 class OAuthException extends Exception {
14 function __construct($key, $secret, $callback_url=NULL) {
16 $this->secret = $secret;
17 $this->callback_url = $callback_url;
20 function __toString() {
21 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
26 // access tokens and request tokens
36 * secret = the token secret
38 function __construct($key, $secret) {
40 $this->secret = $secret;
44 * generates the basic string serialization of a token that a server
45 * would respond to request_token and access_token calls with
47 function to_string() {
48 return "oauth_token=" .
49 OAuthUtil::urlencode_rfc3986($this->key) .
50 "&oauth_token_secret=" .
51 OAuthUtil::urlencode_rfc3986($this->secret);
54 function __toString() {
55 return $this->to_string();
60 * A class for implementing a Signature Method
61 * See section 9 ("Signing Requests") in the spec
63 abstract class OAuthSignatureMethod {
65 * Needs to return the name of the Signature Method (ie HMAC-SHA1)
68 abstract public function get_name();
71 * Build up the signature
72 * NOTE: The output of this function MUST NOT be urlencoded.
73 * the encoding is handled in OAuthRequest when the final
74 * request is serialized
75 * @param OAuthRequest $request
76 * @param OAuthConsumer $consumer
77 * @param OAuthToken $token
80 abstract public function build_signature($request, $consumer, $token);
83 * Verifies that a given signature is correct
84 * @param OAuthRequest $request
85 * @param OAuthConsumer $consumer
86 * @param OAuthToken $token
87 * @param string $signature
90 public function check_signature($request, $consumer, $token, $signature) {
91 $built = $this->build_signature($request, $consumer, $token);
92 //echo "<pre>"; var_dump($signature, $built, ($built == $signature)); killme();
93 return ($built == $signature);
98 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
99 * where the Signature Base String is the text and the key is the concatenated values (each first
100 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
101 * character (ASCII code 38) even if empty.
102 * - Chapter 9.2 ("HMAC-SHA1")
104 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
105 function get_name() {
109 public function build_signature($request, $consumer, $token) {
110 $base_string = $request->get_signature_base_string();
111 $request->base_string = $base_string;
115 ($token) ? $token->secret : ""
118 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
119 $key = implode('&', $key_parts);
122 $r = base64_encode(hash_hmac('sha1', $base_string, $key, true));
128 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
129 * over a secure channel such as HTTPS. It does not use the Signature Base String.
130 * - Chapter 9.4 ("PLAINTEXT")
132 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
133 public function get_name() {
138 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
139 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
140 * empty. The result MUST be encoded again.
141 * - Chapter 9.4.1 ("Generating Signatures")
143 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
144 * OAuthRequest handles this!
146 public function build_signature($request, $consumer, $token) {
149 ($token) ? $token->secret : ""
152 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
153 $key = implode('&', $key_parts);
154 $request->base_string = $key;
161 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
162 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
163 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
164 * verified way to the Service Provider, in a manner which is beyond the scope of this
166 * - Chapter 9.3 ("RSA-SHA1")
168 abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
169 public function get_name() {
173 // Up to the SP to implement this lookup of keys. Possible ideas are:
174 // (1) do a lookup in a table of trusted certs keyed off of consumer
175 // (2) fetch via http using a url provided by the requester
176 // (3) some sort of specific discovery code based on request
178 // Either way should return a string representation of the certificate
179 protected abstract function fetch_public_cert(&$request);
181 // Up to the SP to implement this lookup of keys. Possible ideas are:
182 // (1) do a lookup in a table of trusted certs keyed off of consumer
184 // Either way should return a string representation of the certificate
185 protected abstract function fetch_private_cert(&$request);
187 public function build_signature($request, $consumer, $token) {
188 $base_string = $request->get_signature_base_string();
189 $request->base_string = $base_string;
191 // Fetch the private key cert based on the request
192 $cert = $this->fetch_private_cert($request);
194 // Pull the private key ID from the certificate
195 $privatekeyid = openssl_get_privatekey($cert);
197 // Sign using the key
198 $ok = openssl_sign($base_string, $signature, $privatekeyid);
200 // Release the key resource
201 openssl_free_key($privatekeyid);
203 return base64_encode($signature);
206 public function check_signature($request, $consumer, $token, $signature) {
207 $decoded_sig = base64_decode($signature);
209 $base_string = $request->get_signature_base_string();
211 // Fetch the public key cert based on the request
212 $cert = $this->fetch_public_cert($request);
214 // Pull the public key ID from the certificate
215 $publickeyid = openssl_get_publickey($cert);
217 // Check the computed signature against the one passed in the query
218 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
220 // Release the key resource
221 openssl_free_key($publickeyid);
229 private $http_method;
231 // for debug purposes
233 public static $version = '1.0';
234 public static $POST_INPUT = 'php://input';
236 function __construct($http_method, $http_url, $parameters=NULL) {
237 @$parameters or $parameters = array();
238 $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
239 $this->parameters = $parameters;
240 $this->http_method = $http_method;
241 $this->http_url = $http_url;
246 * attempt to build up a request from what was passed to the server
248 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
249 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
252 @$http_url or $http_url = $scheme .
253 '://' . $_SERVER['HTTP_HOST'] .
255 $_SERVER['SERVER_PORT'] .
256 $_SERVER['REQUEST_URI'];
257 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
259 // We weren't handed any parameters, so let's find the ones relevant to
261 // If you run XML-RPC or similar you should use this to provide your own
262 // parsed parameter-list
264 // Find request headers
265 $request_headers = OAuthUtil::get_headers();
267 // Parse the query-string to find GET parameters
268 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
270 // It's a POST request of the proper content-type, so parse POST
271 // parameters and add those overriding any duplicates from GET
272 if ($http_method == "POST"
273 && @strstr($request_headers["Content-Type"],
274 "application/x-www-form-urlencoded")
276 $post_data = OAuthUtil::parse_parameters(
277 file_get_contents(self::$POST_INPUT)
279 $parameters = array_merge($parameters, $post_data);
282 // We have a Authorization-header with OAuth data. Parse the header
283 // and add those overriding any duplicates from GET or POST
284 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
285 $header_parameters = OAuthUtil::split_header(
286 $request_headers['Authorization']
288 $parameters = array_merge($parameters, $header_parameters);
292 // fix for friendika redirect system
294 $http_url = substr($http_url, 0, strpos($http_url,$parameters['q'])+strlen($parameters['q']));
295 unset( $parameters['q'] );
297 //echo "<pre>".__function__."\n"; var_dump($http_method, $http_url, $parameters, $_SERVER['REQUEST_URI']); killme();
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() {
425 return OAuthUtil::build_http_query($this->parameters);
429 * builds the Authorization: header
431 public function to_header($realm=null) {
434 $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
437 $out = 'Authorization: OAuth';
440 foreach ($this->parameters as $k => $v) {
441 if (substr($k, 0, 5) != "oauth") continue;
443 throw new OAuthException('Arrays not supported in headers');
445 $out .= ($first) ? ' ' : ',';
446 $out .= OAuthUtil::urlencode_rfc3986($k) .
448 OAuthUtil::urlencode_rfc3986($v) .
455 public function __toString() {
456 return $this->to_url();
460 public function sign_request($signature_method, $consumer, $token) {
461 $this->set_parameter(
462 "oauth_signature_method",
463 $signature_method->get_name(),
466 $signature = $this->build_signature($signature_method, $consumer, $token);
467 $this->set_parameter("oauth_signature", $signature, false);
470 public function build_signature($signature_method, $consumer, $token) {
471 $signature = $signature_method->build_signature($this, $consumer, $token);
476 * util function: current timestamp
478 private static function generate_timestamp() {
483 * util function: current nonce
485 private static function generate_nonce() {
489 return md5($mt . $rand); // md5s look nicer than numbers
494 protected $timestamp_threshold = 300; // in seconds, five minutes
495 protected $version = '1.0'; // hi blaine
496 protected $signature_methods = array();
498 protected $data_store;
500 function __construct($data_store) {
501 $this->data_store = $data_store;
504 public function add_signature_method($signature_method) {
505 $this->signature_methods[$signature_method->get_name()] =
509 // high level functions
512 * process a request_token request
513 * returns the request token on success
515 public function fetch_request_token(&$request) {
516 $this->get_version($request);
518 $consumer = $this->get_consumer($request);
520 // no token required for the initial token request
523 $this->check_signature($request, $consumer, $token);
526 $callback = $request->get_parameter('oauth_callback');
527 $new_token = $this->data_store->new_request_token($consumer, $callback);
533 * process an access_token request
534 * returns the access token on success
536 public function fetch_access_token(&$request) {
537 $this->get_version($request);
539 $consumer = $this->get_consumer($request);
541 // requires authorized request token
542 $token = $this->get_token($request, $consumer, "request");
544 $this->check_signature($request, $consumer, $token);
547 $verifier = $request->get_parameter('oauth_verifier');
548 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
554 * verify an api call, checks all the parameters
556 public function verify_request(&$request) {
557 $this->get_version($request);
558 $consumer = $this->get_consumer($request);
559 //echo __file__.__line__.__function__."<pre>"; var_dump($consumer); die();
560 $token = $this->get_token($request, $consumer, "access");
561 $this->check_signature($request, $consumer, $token);
562 return array($consumer, $token);
565 // Internals from here
569 private function get_version(&$request) {
570 $version = $request->get_parameter("oauth_version");
572 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
573 // Chapter 7.0 ("Accessing Protected Ressources")
576 if ($version !== $this->version) {
577 throw new OAuthException("OAuth version '$version' not supported");
583 * figure out the signature with some defaults
585 private function get_signature_method(&$request) {
587 @$request->get_parameter("oauth_signature_method");
589 if (!$signature_method) {
590 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
591 // parameter is required, and we can't just fallback to PLAINTEXT
592 throw new OAuthException('No signature method parameter. This parameter is required');
595 if (!in_array($signature_method,
596 array_keys($this->signature_methods))) {
597 throw new OAuthException(
598 "Signature method '$signature_method' not supported " .
599 "try one of the following: " .
600 implode(", ", array_keys($this->signature_methods))
603 return $this->signature_methods[$signature_method];
607 * try to find the consumer for the provided request's consumer key
609 private function get_consumer(&$request) {
610 $consumer_key = @$request->get_parameter("oauth_consumer_key");
611 if (!$consumer_key) {
612 throw new OAuthException("Invalid consumer key");
615 $consumer = $this->data_store->lookup_consumer($consumer_key);
617 throw new OAuthException("Invalid consumer");
624 * try to find the token for the provided request's token key
626 private function get_token(&$request, $consumer, $token_type="access") {
627 $token_field = @$request->get_parameter('oauth_token');
628 $token = $this->data_store->lookup_token(
629 $consumer, $token_type, $token_field
632 throw new OAuthException("Invalid $token_type token: $token_field");
638 * all-in-one function to check the signature on a request
639 * should guess the signature method appropriately
641 private function check_signature(&$request, $consumer, $token) {
642 // this should probably be in a different method
643 $timestamp = @$request->get_parameter('oauth_timestamp');
644 $nonce = @$request->get_parameter('oauth_nonce');
646 $this->check_timestamp($timestamp);
647 $this->check_nonce($consumer, $token, $nonce, $timestamp);
649 $signature_method = $this->get_signature_method($request);
651 $signature = $request->get_parameter('oauth_signature');
652 $valid_sig = $signature_method->check_signature(
661 throw new OAuthException("Invalid signature");
666 * check that the timestamp is new enough
668 private function check_timestamp($timestamp) {
670 throw new OAuthException(
671 'Missing timestamp parameter. The parameter is required'
674 // verify that timestamp is recentish
676 if (abs($now - $timestamp) > $this->timestamp_threshold) {
677 throw new OAuthException(
678 "Expired timestamp, yours $timestamp, ours $now"
684 * check that the nonce is not repeated
686 private function check_nonce($consumer, $token, $nonce, $timestamp) {
688 throw new OAuthException(
689 'Missing nonce parameter. The parameter is required'
692 // verify that the nonce is uniqueish
693 $found = $this->data_store->lookup_nonce(
700 throw new OAuthException("Nonce already used: $nonce");
706 class OAuthDataStore {
707 function lookup_consumer($consumer_key) {
711 function lookup_token($consumer, $token_type, $token) {
715 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
719 function new_request_token($consumer, $callback = null) {
720 // return a new token attached to this consumer
723 function new_access_token($token, $consumer, $verifier = null) {
724 // return a new access token attached to this consumer
725 // for the user associated with this token if the request token
727 // should also invalidate the request token
733 public static function urlencode_rfc3986($input) {
734 if (is_array($input)) {
735 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
736 } else if (is_scalar($input)) {
740 str_replace('%7E', '~', rawurlencode($input))
748 // This decode function isn't taking into consideration the above
749 // modifications to the encoding process. However, this method doesn't
750 // seem to be used anywhere so leaving it as is.
751 public static function urldecode_rfc3986($string) {
752 return urldecode($string);
755 // Utility function for turning the Authorization: header into
756 // parameters, has to do some unescaping
757 // Can filter out any non-oauth parameters if needed (default behaviour)
758 public static function split_header($header, $only_allow_oauth_parameters = true) {
759 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
762 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
763 $match = $matches[0];
764 $header_name = $matches[2][0];
765 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
766 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
767 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
769 $offset = $match[1] + strlen($match[0]);
772 if (isset($params['realm'])) {
773 unset($params['realm']);
779 // helper to try to sort out headers for people who aren't running apache
780 public static function get_headers() {
781 if (function_exists('apache_request_headers')) {
782 // we need this to get the actual Authorization: header
783 // because apache tends to tell us it doesn't exist
784 $headers = apache_request_headers();
786 // sanitize the output of apache_request_headers because
787 // we always want the keys to be Cased-Like-This and arh()
788 // returns the headers in the same case as they are in the
791 foreach( $headers AS $key => $value ) {
795 ucwords(strtolower(str_replace("-", " ", $key)))
800 // otherwise we don't have apache and are just going to have to hope
801 // that $_SERVER actually contains what we need
803 if( isset($_SERVER['CONTENT_TYPE']) )
804 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
805 if( isset($_ENV['CONTENT_TYPE']) )
806 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
808 foreach ($_SERVER as $key => $value) {
809 if (substr($key, 0, 5) == "HTTP_") {
810 // this is chaos, basically it is just there to capitalize the first
811 // letter of every word that is not an initial HTTP and strip HTTP
816 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
825 // This function takes a input like a=b&a=c&d=e and returns the parsed
826 // parameters like this
827 // array('a' => array('b','c'), 'd' => 'e')
828 public static function parse_parameters( $input ) {
829 if (!isset($input) || !$input) return array();
831 $pairs = explode('&', $input);
833 $parsed_parameters = array();
834 foreach ($pairs as $pair) {
835 $split = explode('=', $pair, 2);
836 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
837 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
839 if (isset($parsed_parameters[$parameter])) {
840 // We have already recieved parameter(s) with this name, so add to the list
841 // of parameters with this name
843 if (is_scalar($parsed_parameters[$parameter])) {
844 // This is the first duplicate, so transform scalar (string) into an array
845 // so we can add the duplicates
846 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
849 $parsed_parameters[$parameter][] = $value;
851 $parsed_parameters[$parameter] = $value;
854 return $parsed_parameters;
857 public static function build_http_query($params) {
858 if (!$params) return '';
860 // Urlencode both keys and values
861 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
862 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
863 $params = array_combine($keys, $values);
865 // Parameters are sorted by name, using lexicographical byte value ordering.
866 // Ref: Spec: 9.1.1 (1)
867 uksort($params, 'strcmp');
870 foreach ($params as $parameter => $value) {
871 if (is_array($value)) {
872 // If two or more parameters share the same name, they are sorted by their value
873 // Ref: Spec: 9.1.1 (1)
875 foreach ($value as $duplicate_value) {
876 $pairs[] = $parameter . '=' . $duplicate_value;
879 $pairs[] = $parameter . '=' . $value;
882 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
883 // Each name-value pair is separated by an '&' character (ASCII code 38)
884 return implode('&', $pairs);