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
32 * secret = the token secret
34 function __construct($key, $secret) {
36 $this->secret = $secret;
40 * generates the basic string serialization of a token that a server
41 * would respond to request_token and access_token calls with
43 function to_string() {
44 return "oauth_token=" .
45 OAuthUtil::urlencode_rfc3986($this->key) .
46 "&oauth_token_secret=" .
47 OAuthUtil::urlencode_rfc3986($this->secret);
50 function __toString() {
51 return $this->to_string();
56 * A class for implementing a Signature Method
57 * See section 9 ("Signing Requests") in the spec
59 abstract class OAuthSignatureMethod {
61 * Needs to return the name of the Signature Method (ie HMAC-SHA1)
64 abstract public function get_name();
67 * Build up the signature
68 * NOTE: The output of this function MUST NOT be urlencoded.
69 * the encoding is handled in OAuthRequest when the final
70 * request is serialized
71 * @param OAuthRequest $request
72 * @param OAuthConsumer $consumer
73 * @param OAuthToken $token
76 abstract public function build_signature($request, $consumer, $token);
79 * Verifies that a given signature is correct
80 * @param OAuthRequest $request
81 * @param OAuthConsumer $consumer
82 * @param OAuthToken $token
83 * @param string $signature
86 public function check_signature($request, $consumer, $token, $signature) {
87 $built = $this->build_signature($request, $consumer, $token);
88 return $built == $signature;
93 * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
94 * where the Signature Base String is the text and the key is the concatenated values (each first
95 * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
96 * character (ASCII code 38) even if empty.
97 * - Chapter 9.2 ("HMAC-SHA1")
99 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
100 function get_name() {
104 public function build_signature($request, $consumer, $token) {
105 $base_string = $request->get_signature_base_string();
106 $request->base_string = $base_string;
110 ($token) ? $token->secret : ""
113 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
114 $key = implode('&', $key_parts);
116 return base64_encode(hash_hmac('sha1', $base_string, $key, true));
121 * The PLAINTEXT method does not provide any security protection and SHOULD only be used
122 * over a secure channel such as HTTPS. It does not use the Signature Base String.
123 * - Chapter 9.4 ("PLAINTEXT")
125 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
126 public function get_name() {
131 * oauth_signature is set to the concatenated encoded values of the Consumer Secret and
132 * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
133 * empty. The result MUST be encoded again.
134 * - Chapter 9.4.1 ("Generating Signatures")
136 * Please note that the second encoding MUST NOT happen in the SignatureMethod, as
137 * OAuthRequest handles this!
139 public function build_signature($request, $consumer, $token) {
142 ($token) ? $token->secret : ""
145 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
146 $key = implode('&', $key_parts);
147 $request->base_string = $key;
154 * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
155 * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
156 * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
157 * verified way to the Service Provider, in a manner which is beyond the scope of this
159 * - Chapter 9.3 ("RSA-SHA1")
161 abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
162 public function get_name() {
166 // Up to the SP to implement this lookup of keys. Possible ideas are:
167 // (1) do a lookup in a table of trusted certs keyed off of consumer
168 // (2) fetch via http using a url provided by the requester
169 // (3) some sort of specific discovery code based on request
171 // Either way should return a string representation of the certificate
172 protected abstract function fetch_public_cert(&$request);
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
177 // Either way should return a string representation of the certificate
178 protected abstract function fetch_private_cert(&$request);
180 public function build_signature($request, $consumer, $token) {
181 $base_string = $request->get_signature_base_string();
182 $request->base_string = $base_string;
184 // Fetch the private key cert based on the request
185 $cert = $this->fetch_private_cert($request);
187 // Pull the private key ID from the certificate
188 $privatekeyid = openssl_get_privatekey($cert);
190 // Sign using the key
191 $ok = openssl_sign($base_string, $signature, $privatekeyid);
193 // Release the key resource
194 openssl_free_key($privatekeyid);
196 return base64_encode($signature);
199 public function check_signature($request, $consumer, $token, $signature) {
200 $decoded_sig = base64_decode($signature);
202 $base_string = $request->get_signature_base_string();
204 // Fetch the public key cert based on the request
205 $cert = $this->fetch_public_cert($request);
207 // Pull the public key ID from the certificate
208 $publickeyid = openssl_get_publickey($cert);
210 // Check the computed signature against the one passed in the query
211 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
213 // Release the key resource
214 openssl_free_key($publickeyid);
222 private $http_method;
224 // for debug purposes
226 public static $version = '1.0';
227 public static $POST_INPUT = 'php://input';
229 function __construct($http_method, $http_url, $parameters=NULL) {
230 @$parameters or $parameters = array();
231 $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
232 $this->parameters = $parameters;
233 $this->http_method = $http_method;
234 $this->http_url = $http_url;
239 * attempt to build up a request from what was passed to the server
241 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
242 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
245 @$http_url or $http_url = $scheme .
246 '://' . $_SERVER['HTTP_HOST'] .
248 $_SERVER['SERVER_PORT'] .
249 $_SERVER['REQUEST_URI'];
250 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
252 // We weren't handed any parameters, so let's find the ones relevant to
254 // If you run XML-RPC or similar you should use this to provide your own
255 // parsed parameter-list
257 // Find request headers
258 $request_headers = OAuthUtil::get_headers();
260 // Parse the query-string to find GET parameters
261 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
263 // It's a POST request of the proper content-type, so parse POST
264 // parameters and add those overriding any duplicates from GET
265 if ($http_method == "POST"
266 && @strstr($request_headers["Content-Type"],
267 "application/x-www-form-urlencoded")
269 $post_data = OAuthUtil::parse_parameters(
270 file_get_contents(self::$POST_INPUT)
272 $parameters = array_merge($parameters, $post_data);
275 // We have a Authorization-header with OAuth data. Parse the header
276 // and add those overriding any duplicates from GET or POST
277 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
278 $header_parameters = OAuthUtil::split_header(
279 $request_headers['Authorization']
281 $parameters = array_merge($parameters, $header_parameters);
286 return new OAuthRequest($http_method, $http_url, $parameters);
290 * pretty much a helper function to set up the request
292 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
293 @$parameters or $parameters = array();
294 $defaults = array("oauth_version" => OAuthRequest::$version,
295 "oauth_nonce" => OAuthRequest::generate_nonce(),
296 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
297 "oauth_consumer_key" => $consumer->key);
299 $defaults['oauth_token'] = $token->key;
301 $parameters = array_merge($defaults, $parameters);
303 return new OAuthRequest($http_method, $http_url, $parameters);
306 public function set_parameter($name, $value, $allow_duplicates = true) {
307 if ($allow_duplicates && isset($this->parameters[$name])) {
308 // We have already added parameter(s) with this name, so add to the list
309 if (is_scalar($this->parameters[$name])) {
310 // This is the first duplicate, so transform scalar (string)
311 // into an array so we can add the duplicates
312 $this->parameters[$name] = array($this->parameters[$name]);
315 $this->parameters[$name][] = $value;
317 $this->parameters[$name] = $value;
321 public function get_parameter($name) {
322 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
325 public function get_parameters() {
326 return $this->parameters;
329 public function unset_parameter($name) {
330 unset($this->parameters[$name]);
334 * The request parameters, sorted and concatenated into a normalized string.
337 public function get_signable_parameters() {
338 // Grab all parameters
339 $params = $this->parameters;
341 // Remove oauth_signature if present
342 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
343 if (isset($params['oauth_signature'])) {
344 unset($params['oauth_signature']);
347 return OAuthUtil::build_http_query($params);
351 * Returns the base string of this request
353 * The base string defined as the method, the url
354 * and the parameters (normalized), each urlencoded
355 * and the concated with &.
357 public function get_signature_base_string() {
359 $this->get_normalized_http_method(),
360 $this->get_normalized_http_url(),
361 $this->get_signable_parameters()
364 $parts = OAuthUtil::urlencode_rfc3986($parts);
366 return implode('&', $parts);
370 * just uppercases the http method
372 public function get_normalized_http_method() {
373 return strtoupper($this->http_method);
377 * parses the url and rebuilds it to be
380 public function get_normalized_http_url() {
381 $parts = parse_url($this->http_url);
383 $port = @$parts['port'];
384 $scheme = $parts['scheme'];
385 $host = $parts['host'];
386 $path = @$parts['path'];
388 $port or $port = ($scheme == 'https') ? '443' : '80';
390 if (($scheme == 'https' && $port != '443')
391 || ($scheme == 'http' && $port != '80')) {
392 $host = "$host:$port";
394 return "$scheme://$host$path";
398 * builds a url usable for a GET request
400 public function to_url() {
401 $post_data = $this->to_postdata();
402 $out = $this->get_normalized_http_url();
404 $out .= '?'.$post_data;
410 * builds the data one would send in a POST request
412 public function to_postdata() {
413 return OAuthUtil::build_http_query($this->parameters);
417 * builds the Authorization: header
419 public function to_header($realm=null) {
422 $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"';
425 $out = 'Authorization: OAuth';
428 foreach ($this->parameters as $k => $v) {
429 if (substr($k, 0, 5) != "oauth") continue;
431 throw new OAuthException('Arrays not supported in headers');
433 $out .= ($first) ? ' ' : ',';
434 $out .= OAuthUtil::urlencode_rfc3986($k) .
436 OAuthUtil::urlencode_rfc3986($v) .
443 public function __toString() {
444 return $this->to_url();
448 public function sign_request($signature_method, $consumer, $token) {
449 $this->set_parameter(
450 "oauth_signature_method",
451 $signature_method->get_name(),
454 $signature = $this->build_signature($signature_method, $consumer, $token);
455 $this->set_parameter("oauth_signature", $signature, false);
458 public function build_signature($signature_method, $consumer, $token) {
459 $signature = $signature_method->build_signature($this, $consumer, $token);
464 * util function: current timestamp
466 private static function generate_timestamp() {
471 * util function: current nonce
473 private static function generate_nonce() {
477 return md5($mt . $rand); // md5s look nicer than numbers
482 protected $timestamp_threshold = 300; // in seconds, five minutes
483 protected $version = '1.0'; // hi blaine
484 protected $signature_methods = array();
486 protected $data_store;
488 function __construct($data_store) {
489 $this->data_store = $data_store;
492 public function add_signature_method($signature_method) {
493 $this->signature_methods[$signature_method->get_name()] =
497 // high level functions
500 * process a request_token request
501 * returns the request token on success
503 public function fetch_request_token(&$request) {
504 $this->get_version($request);
506 $consumer = $this->get_consumer($request);
508 // no token required for the initial token request
511 $this->check_signature($request, $consumer, $token);
514 $callback = $request->get_parameter('oauth_callback');
515 $new_token = $this->data_store->new_request_token($consumer, $callback);
521 * process an access_token request
522 * returns the access token on success
524 public function fetch_access_token(&$request) {
525 $this->get_version($request);
527 $consumer = $this->get_consumer($request);
529 // requires authorized request token
530 $token = $this->get_token($request, $consumer, "request");
532 $this->check_signature($request, $consumer, $token);
535 $verifier = $request->get_parameter('oauth_verifier');
536 $new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
542 * verify an api call, checks all the parameters
544 public function verify_request(&$request) {
545 $this->get_version($request);
546 $consumer = $this->get_consumer($request);
547 $token = $this->get_token($request, $consumer, "access");
548 $this->check_signature($request, $consumer, $token);
549 return array($consumer, $token);
552 // Internals from here
556 private function get_version(&$request) {
557 $version = $request->get_parameter("oauth_version");
559 // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
560 // Chapter 7.0 ("Accessing Protected Ressources")
563 if ($version !== $this->version) {
564 throw new OAuthException("OAuth version '$version' not supported");
570 * figure out the signature with some defaults
572 private function get_signature_method(&$request) {
574 @$request->get_parameter("oauth_signature_method");
576 if (!$signature_method) {
577 // According to chapter 7 ("Accessing Protected Ressources") the signature-method
578 // parameter is required, and we can't just fallback to PLAINTEXT
579 throw new OAuthException('No signature method parameter. This parameter is required');
582 if (!in_array($signature_method,
583 array_keys($this->signature_methods))) {
584 throw new OAuthException(
585 "Signature method '$signature_method' not supported " .
586 "try one of the following: " .
587 implode(", ", array_keys($this->signature_methods))
590 return $this->signature_methods[$signature_method];
594 * try to find the consumer for the provided request's consumer key
596 private function get_consumer(&$request) {
597 $consumer_key = @$request->get_parameter("oauth_consumer_key");
598 if (!$consumer_key) {
599 throw new OAuthException("Invalid consumer key");
602 $consumer = $this->data_store->lookup_consumer($consumer_key);
604 throw new OAuthException("Invalid consumer");
611 * try to find the token for the provided request's token key
613 private function get_token(&$request, $consumer, $token_type="access") {
614 $token_field = @$request->get_parameter('oauth_token');
615 $token = $this->data_store->lookup_token(
616 $consumer, $token_type, $token_field
619 throw new OAuthException("Invalid $token_type token: $token_field");
625 * all-in-one function to check the signature on a request
626 * should guess the signature method appropriately
628 private function check_signature(&$request, $consumer, $token) {
629 // this should probably be in a different method
630 $timestamp = @$request->get_parameter('oauth_timestamp');
631 $nonce = @$request->get_parameter('oauth_nonce');
633 $this->check_timestamp($timestamp);
634 $this->check_nonce($consumer, $token, $nonce, $timestamp);
636 $signature_method = $this->get_signature_method($request);
638 $signature = $request->get_parameter('oauth_signature');
639 $valid_sig = $signature_method->check_signature(
647 throw new OAuthException("Invalid signature");
652 * check that the timestamp is new enough
654 private function check_timestamp($timestamp) {
656 throw new OAuthException(
657 'Missing timestamp parameter. The parameter is required'
660 // verify that timestamp is recentish
662 if (abs($now - $timestamp) > $this->timestamp_threshold) {
663 throw new OAuthException(
664 "Expired timestamp, yours $timestamp, ours $now"
670 * check that the nonce is not repeated
672 private function check_nonce($consumer, $token, $nonce, $timestamp) {
674 throw new OAuthException(
675 'Missing nonce parameter. The parameter is required'
678 // verify that the nonce is uniqueish
679 $found = $this->data_store->lookup_nonce(
686 throw new OAuthException("Nonce already used: $nonce");
692 class OAuthDataStore {
693 function lookup_consumer($consumer_key) {
697 function lookup_token($consumer, $token_type, $token) {
701 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
705 function new_request_token($consumer, $callback = null) {
706 // return a new token attached to this consumer
709 function new_access_token($token, $consumer, $verifier = null) {
710 // return a new access token attached to this consumer
711 // for the user associated with this token if the request token
713 // should also invalidate the request token
719 public static function urlencode_rfc3986($input) {
720 if (is_array($input)) {
721 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
722 } else if (is_scalar($input)) {
726 str_replace('%7E', '~', rawurlencode($input))
734 // This decode function isn't taking into consideration the above
735 // modifications to the encoding process. However, this method doesn't
736 // seem to be used anywhere so leaving it as is.
737 public static function urldecode_rfc3986($string) {
738 return urldecode($string);
741 // Utility function for turning the Authorization: header into
742 // parameters, has to do some unescaping
743 // Can filter out any non-oauth parameters if needed (default behaviour)
744 public static function split_header($header, $only_allow_oauth_parameters = true) {
745 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
748 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
749 $match = $matches[0];
750 $header_name = $matches[2][0];
751 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
752 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
753 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
755 $offset = $match[1] + strlen($match[0]);
758 if (isset($params['realm'])) {
759 unset($params['realm']);
765 // helper to try to sort out headers for people who aren't running apache
766 public static function get_headers() {
767 if (function_exists('apache_request_headers')) {
768 // we need this to get the actual Authorization: header
769 // because apache tends to tell us it doesn't exist
770 $headers = apache_request_headers();
772 // sanitize the output of apache_request_headers because
773 // we always want the keys to be Cased-Like-This and arh()
774 // returns the headers in the same case as they are in the
777 foreach( $headers AS $key => $value ) {
781 ucwords(strtolower(str_replace("-", " ", $key)))
786 // otherwise we don't have apache and are just going to have to hope
787 // that $_SERVER actually contains what we need
789 if( isset($_SERVER['CONTENT_TYPE']) )
790 $out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
791 if( isset($_ENV['CONTENT_TYPE']) )
792 $out['Content-Type'] = $_ENV['CONTENT_TYPE'];
794 foreach ($_SERVER as $key => $value) {
795 if (substr($key, 0, 5) == "HTTP_") {
796 // this is chaos, basically it is just there to capitalize the first
797 // letter of every word that is not an initial HTTP and strip HTTP
802 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
811 // This function takes a input like a=b&a=c&d=e and returns the parsed
812 // parameters like this
813 // array('a' => array('b','c'), 'd' => 'e')
814 public static function parse_parameters( $input ) {
815 if (!isset($input) || !$input) return array();
817 $pairs = explode('&', $input);
819 $parsed_parameters = array();
820 foreach ($pairs as $pair) {
821 $split = explode('=', $pair, 2);
822 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
823 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
825 if (isset($parsed_parameters[$parameter])) {
826 // We have already recieved parameter(s) with this name, so add to the list
827 // of parameters with this name
829 if (is_scalar($parsed_parameters[$parameter])) {
830 // This is the first duplicate, so transform scalar (string) into an array
831 // so we can add the duplicates
832 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
835 $parsed_parameters[$parameter][] = $value;
837 $parsed_parameters[$parameter] = $value;
840 return $parsed_parameters;
843 public static function build_http_query($params) {
844 if (!$params) return '';
846 // Urlencode both keys and values
847 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
848 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
849 $params = array_combine($keys, $values);
851 // Parameters are sorted by name, using lexicographical byte value ordering.
852 // Ref: Spec: 9.1.1 (1)
853 uksort($params, 'strcmp');
856 foreach ($params as $parameter => $value) {
857 if (is_array($value)) {
858 // If two or more parameters share the same name, they are sorted by their value
859 // Ref: Spec: 9.1.1 (1)
861 foreach ($value as $duplicate_value) {
862 $pairs[] = $parameter . '=' . $duplicate_value;
865 $pairs[] = $parameter . '=' . $value;
868 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
869 // Each name-value pair is separated by an '&' character (ASCII code 38)
870 return implode('&', $pairs);