2 // vim: foldmethod=marker
4 /* Generic exception class
6 class OAuthException extends Exception {/*{{{*/
10 class OAuthConsumer {/*{{{*/
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]";
25 class OAuthToken {/*{{{*/
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=" . OAuthUtil::urlencode_rfc3986($this->key) .
45 "&oauth_token_secret=" . OAuthUtil::urlencode_rfc3986($this->secret);
48 function __toString() {/*{{{*/
49 return $this->to_string();
53 class OAuthSignatureMethod {/*{{{*/
54 public function check_signature(&$request, $consumer, $token, $signature) {
55 $built = $this->build_signature($request, $consumer, $token);
56 return $built == $signature;
60 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {/*{{{*/
61 function get_name() {/*{{{*/
65 public function build_signature($request, $consumer, $token) {/*{{{*/
66 $base_string = $request->get_signature_base_string();
67 $request->base_string = $base_string;
71 ($token) ? $token->secret : ""
74 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
75 $key = implode('&', $key_parts);
77 return base64_encode( hash_hmac('sha1', $base_string, $key, true));
81 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {/*{{{*/
82 public function get_name() {/*{{{*/
86 public function build_signature($request, $consumer, $token) {/*{{{*/
88 OAuthUtil::urlencode_rfc3986($consumer->secret)
92 array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
97 $raw = implode("&", $sig);
99 $request->base_string = $raw;
101 return OAuthUtil::urlencode_rfc3986($raw);
105 class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {/*{{{*/
106 public function get_name() {/*{{{*/
110 protected function fetch_public_cert(&$request) {/*{{{*/
111 // not implemented yet, ideas are:
112 // (1) do a lookup in a table of trusted certs keyed off of consumer
113 // (2) fetch via http using a url provided by the requester
114 // (3) some sort of specific discovery code based on request
116 // either way should return a string representation of the certificate
117 throw Exception("fetch_public_cert not implemented");
120 protected function fetch_private_cert(&$request) {/*{{{*/
121 // not implemented yet, ideas are:
122 // (1) do a lookup in a table of trusted certs keyed off of consumer
124 // either way should return a string representation of the certificate
125 throw Exception("fetch_private_cert not implemented");
128 public function build_signature(&$request, $consumer, $token) {/*{{{*/
129 $base_string = $request->get_signature_base_string();
130 $request->base_string = $base_string;
132 // Fetch the private key cert based on the request
133 $cert = $this->fetch_private_cert($request);
135 // Pull the private key ID from the certificate
136 $privatekeyid = openssl_get_privatekey($cert);
138 // Sign using the key
139 $ok = openssl_sign($base_string, $signature, $privatekeyid);
141 // Release the key resource
142 openssl_free_key($privatekeyid);
144 return base64_encode($signature);
147 public function check_signature(&$request, $consumer, $token, $signature) {/*{{{*/
148 $decoded_sig = base64_decode($signature);
150 $base_string = $request->get_signature_base_string();
152 // Fetch the public key cert based on the request
153 $cert = $this->fetch_public_cert($request);
155 // Pull the public key ID from the certificate
156 $publickeyid = openssl_get_publickey($cert);
158 // Check the computed signature against the one passed in the query
159 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
161 // Release the key resource
162 openssl_free_key($publickeyid);
168 class OAuthRequest {/*{{{*/
170 private $http_method;
172 // for debug purposes
174 public static $version = '1.0';
176 function __construct($http_method, $http_url, $parameters=NULL) {/*{{{*/
177 @$parameters or $parameters = array();
178 $this->parameters = $parameters;
179 $this->http_method = $http_method;
180 $this->http_url = $http_url;
185 * attempt to build up a request from what was passed to the server
187 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {/*{{{*/
188 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") ? 'http' : 'https';
189 @$http_url or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
190 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
192 $request_headers = OAuthRequest::get_headers();
194 // let the library user override things however they'd like, if they know
195 // which parameters to use then go for it, for example XMLRPC might want to
198 $req = new OAuthRequest($http_method, $http_url, $parameters);
200 // collect request parameters from query string (GET) and post-data (POST) if appropriate (note: POST vars have priority)
201 $req_parameters = $_GET;
202 if ($http_method == "POST" && @strstr($request_headers["Content-Type"], "application/x-www-form-urlencoded") ) {
203 $req_parameters = array_merge($req_parameters, $_POST);
206 // next check for the auth header, we need to do some extra stuff
207 // if that is the case, namely suck in the parameters from GET or POST
208 // so that we can include them in the signature
209 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
210 $header_parameters = OAuthRequest::split_header($request_headers['Authorization']);
211 $parameters = array_merge($req_parameters, $header_parameters);
212 $req = new OAuthRequest($http_method, $http_url, $parameters);
213 } else $req = new OAuthRequest($http_method, $http_url, $req_parameters);
220 * pretty much a helper function to set up the request
222 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {/*{{{*/
223 @$parameters or $parameters = array();
224 $defaults = array("oauth_version" => OAuthRequest::$version,
225 "oauth_nonce" => OAuthRequest::generate_nonce(),
226 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
227 "oauth_consumer_key" => $consumer->key);
228 $parameters = array_merge($defaults, $parameters);
231 $parameters['oauth_token'] = $token->key;
233 return new OAuthRequest($http_method, $http_url, $parameters);
236 public function set_parameter($name, $value) {/*{{{*/
237 $this->parameters[$name] = $value;
240 public function get_parameter($name) {/*{{{*/
241 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
244 public function get_parameters() {/*{{{*/
245 return $this->parameters;
249 * Returns the normalized parameters of the request
251 * This will be all (except oauth_signature) parameters,
252 * sorted first by key, and if duplicate keys, then by
255 * The returned string will be all the key=value pairs
260 public function get_signable_parameters() {/*{{{*/
261 // Grab all parameters
262 $params = $this->parameters;
264 // Remove oauth_signature if present
265 if (isset($params['oauth_signature'])) {
266 unset($params['oauth_signature']);
269 // Urlencode both keys and values
270 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
271 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
272 $params = array_combine($keys, $values);
274 // Sort by keys (natsort)
275 uksort($params, 'strcmp');
277 // Generate key=value pairs
279 foreach ($params as $key=>$value ) {
280 if (is_array($value)) {
281 // If the value is an array, it's because there are multiple
282 // with the same key, sort them, then add all the pairs
284 foreach ($value as $v2) {
285 $pairs[] = $key . '=' . $v2;
288 $pairs[] = $key . '=' . $value;
292 // Return the pairs, concated with &
293 return implode('&', $pairs);
297 * Returns the base string of this request
299 * The base string defined as the method, the url
300 * and the parameters (normalized), each urlencoded
301 * and the concated with &.
303 public function get_signature_base_string() {/*{{{*/
305 $this->get_normalized_http_method(),
306 $this->get_normalized_http_url(),
307 $this->get_signable_parameters()
310 $parts = OAuthUtil::urlencode_rfc3986($parts);
312 return implode('&', $parts);
316 * just uppercases the http method
318 public function get_normalized_http_method() {/*{{{*/
319 return strtoupper($this->http_method);
323 * parses the url and rebuilds it to be
326 public function get_normalized_http_url() {/*{{{*/
327 $parts = parse_url($this->http_url);
329 $port = @$parts['port'];
330 $scheme = $parts['scheme'];
331 $host = $parts['host'];
332 $path = @$parts['path'];
334 $port or $port = ($scheme == 'https') ? '443' : '80';
336 if (($scheme == 'https' && $port != '443')
337 || ($scheme == 'http' && $port != '80')) {
338 $host = "$host:$port";
340 return "$scheme://$host$path";
344 * builds a url usable for a GET request
346 public function to_url() {/*{{{*/
347 $out = $this->get_normalized_http_url() . "?";
348 $out .= $this->to_postdata();
353 * builds the data one would send in a POST request
355 * TODO(morten.fangel):
356 * this function might be easily replaced with http_build_query()
357 * and corrections for rfc3986 compatibility.. but not sure
359 public function to_postdata() {/*{{{*/
361 foreach ($this->parameters as $k => $v) {
363 foreach ($v as $va) {
364 $total[] = OAuthUtil::urlencode_rfc3986($k) . "[]=" . OAuthUtil::urlencode_rfc3986($va);
367 $total[] = OAuthUtil::urlencode_rfc3986($k) . "=" . OAuthUtil::urlencode_rfc3986($v);
370 $out = implode("&", $total);
375 * builds the Authorization: header
377 public function to_header() {/*{{{*/
378 $out ='Authorization: OAuth realm=""';
380 foreach ($this->parameters as $k => $v) {
381 if (substr($k, 0, 5) != "oauth") continue;
382 if (is_array($v)) throw new OAuthException('Arrays not supported in headers');
383 $out .= ',' . OAuthUtil::urlencode_rfc3986($k) . '="' . OAuthUtil::urlencode_rfc3986($v) . '"';
388 public function __toString() {/*{{{*/
389 return $this->to_url();
393 public function sign_request($signature_method, $consumer, $token) {/*{{{*/
394 $this->set_parameter("oauth_signature_method", $signature_method->get_name());
395 $signature = $this->build_signature($signature_method, $consumer, $token);
396 $this->set_parameter("oauth_signature", $signature);
399 public function build_signature($signature_method, $consumer, $token) {/*{{{*/
400 $signature = $signature_method->build_signature($this, $consumer, $token);
405 * util function: current timestamp
407 private static function generate_timestamp() {/*{{{*/
412 * util function: current nonce
414 private static function generate_nonce() {/*{{{*/
418 return md5($mt . $rand); // md5s look nicer than numbers
422 * util function for turning the Authorization: header into
423 * parameters, has to do some unescaping
425 private static function split_header($header) {/*{{{*/
426 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
429 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
430 $match = $matches[0];
431 $header_name = $matches[2][0];
432 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
433 $params[$header_name] = OAuthUtil::urldecode_rfc3986( $header_content );
434 $offset = $match[1] + strlen($match[0]);
437 if (isset($params['realm'])) {
438 unset($params['realm']);
445 * helper to try to sort out headers for people who aren't running apache
447 private static function get_headers() {/*{{{*/
448 if (function_exists('apache_request_headers')) {
449 // we need this to get the actual Authorization: header
450 // because apache tends to tell us it doesn't exist
451 return apache_request_headers();
453 // otherwise we don't have apache and are just going to have to hope
454 // that $_SERVER actually contains what we need
456 foreach ($_SERVER as $key => $value) {
457 if (substr($key, 0, 5) == "HTTP_") {
458 // this is chaos, basically it is just there to capitalize the first
459 // letter of every word that is not an initial HTTP and strip HTTP
461 $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_", " ", substr($key, 5)))));
469 class OAuthServer {/*{{{*/
470 protected $timestamp_threshold = 300; // in seconds, five minutes
471 protected $version = 1.0; // hi blaine
472 protected $signature_methods = array();
474 protected $data_store;
476 function __construct($data_store) {/*{{{*/
477 $this->data_store = $data_store;
480 public function add_signature_method($signature_method) {/*{{{*/
481 $this->signature_methods[$signature_method->get_name()] =
485 // high level functions
488 * process a request_token request
489 * returns the request token on success
491 public function fetch_request_token(&$request) {/*{{{*/
492 $this->get_version($request);
494 $consumer = $this->get_consumer($request);
496 // no token required for the initial token request
499 $this->check_signature($request, $consumer, $token);
501 $new_token = $this->data_store->new_request_token($consumer);
507 * process an access_token request
508 * returns the access token on success
510 public function fetch_access_token(&$request) {/*{{{*/
511 $this->get_version($request);
513 $consumer = $this->get_consumer($request);
515 // requires authorized request token
516 $token = $this->get_token($request, $consumer, "request");
519 $this->check_signature($request, $consumer, $token);
521 $new_token = $this->data_store->new_access_token($token, $consumer);
527 * verify an api call, checks all the parameters
529 public function verify_request(&$request) {/*{{{*/
530 $this->get_version($request);
531 $consumer = $this->get_consumer($request);
532 $token = $this->get_token($request, $consumer, "access");
533 $this->check_signature($request, $consumer, $token);
534 return array($consumer, $token);
537 // Internals from here
541 private function get_version(&$request) {/*{{{*/
542 $version = $request->get_parameter("oauth_version");
546 if ($version && $version != $this->version) {
547 throw new OAuthException("OAuth version '$version' not supported");
553 * figure out the signature with some defaults
555 private function get_signature_method(&$request) {/*{{{*/
557 @$request->get_parameter("oauth_signature_method");
558 if (!$signature_method) {
559 $signature_method = "PLAINTEXT";
561 if (!in_array($signature_method,
562 array_keys($this->signature_methods))) {
563 throw new OAuthException(
564 "Signature method '$signature_method' not supported try one of the following: " . implode(", ", array_keys($this->signature_methods))
567 return $this->signature_methods[$signature_method];
571 * try to find the consumer for the provided request's consumer key
573 private function get_consumer(&$request) {/*{{{*/
574 $consumer_key = @$request->get_parameter("oauth_consumer_key");
575 if (!$consumer_key) {
576 throw new OAuthException("Invalid consumer key");
579 $consumer = $this->data_store->lookup_consumer($consumer_key);
581 throw new OAuthException("Invalid consumer");
588 * try to find the token for the provided request's token key
590 private function get_token(&$request, $consumer, $token_type="access") {/*{{{*/
591 $token_field = @$request->get_parameter('oauth_token');
592 $token = $this->data_store->lookup_token(
593 $consumer, $token_type, $token_field
596 throw new OAuthException("Invalid $token_type token: $token_field");
602 * all-in-one function to check the signature on a request
603 * should guess the signature method appropriately
605 private function check_signature(&$request, $consumer, $token) {/*{{{*/
606 // this should probably be in a different method
607 $timestamp = @$request->get_parameter('oauth_timestamp');
608 $nonce = @$request->get_parameter('oauth_nonce');
610 $this->check_timestamp($timestamp);
611 $this->check_nonce($consumer, $token, $nonce, $timestamp);
613 $signature_method = $this->get_signature_method($request);
615 $signature = $request->get_parameter('oauth_signature');
616 $valid_sig = $signature_method->check_signature(
624 throw new OAuthException("Invalid signature");
629 * check that the timestamp is new enough
631 private function check_timestamp($timestamp) {/*{{{*/
632 // verify that timestamp is recentish
634 if ($now - $timestamp > $this->timestamp_threshold) {
635 throw new OAuthException("Expired timestamp, yours $timestamp, ours $now");
640 * check that the nonce is not repeated
642 private function check_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
643 // verify that the nonce is uniqueish
644 $found = $this->data_store->lookup_nonce($consumer, $token, $nonce, $timestamp);
646 throw new OAuthException("Nonce already used: $nonce");
654 class OAuthDataStore {/*{{{*/
655 function lookup_consumer($consumer_key) {/*{{{*/
659 function lookup_token($consumer, $token_type, $token) {/*{{{*/
663 function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
667 function new_request_token($consumer) {/*{{{*/
668 // return a new token attached to this consumer
671 function new_access_token($token, $consumer) {/*{{{*/
672 // return a new access token attached to this consumer
673 // for the user associated with this token if the request token
675 // should also invalidate the request token
681 /* A very naive dbm-based oauth storage
683 class SimpleOAuthDataStore extends OAuthDataStore {/*{{{*/
686 function __construct($path = "oauth.gdbm") {/*{{{*/
687 $this->dbh = dba_popen($path, 'c', 'gdbm');
690 function __destruct() {/*{{{*/
691 dba_close($this->dbh);
694 function lookup_consumer($consumer_key) {/*{{{*/
695 $rv = dba_fetch("consumer_$consumer_key", $this->dbh);
699 $obj = unserialize($rv);
700 if (!($obj instanceof OAuthConsumer)) {
706 function lookup_token($consumer, $token_type, $token) {/*{{{*/
707 $rv = dba_fetch("${token_type}_${token}", $this->dbh);
711 $obj = unserialize($rv);
712 if (!($obj instanceof OAuthToken)) {
718 function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
719 if (dba_exists("nonce_$nonce", $this->dbh)) {
722 dba_insert("nonce_$nonce", "1", $this->dbh);
727 function new_token($consumer, $type="request") {/*{{{*/
729 $secret = time() + time();
730 $token = new OAuthToken($key, md5(md5($secret)));
731 if (!dba_insert("${type}_$key", serialize($token), $this->dbh)) {
732 throw new OAuthException("doooom!");
737 function new_request_token($consumer) {/*{{{*/
738 return $this->new_token($consumer, "request");
741 function new_access_token($token, $consumer) {/*{{{*/
743 $token = $this->new_token($consumer, 'access');
744 dba_delete("request_" . $token->key, $this->dbh);
749 class OAuthUtil {/*{{{*/
750 public static function urlencode_rfc3986($input) {/*{{{*/
751 if (is_array($input)) {
752 return array_map(array('OAuthUtil','urlencode_rfc3986'), $input);
753 } else if (is_scalar($input)) {
754 return str_replace('+', ' ',
755 str_replace('%7E', '~', rawurlencode($input)));
762 // This decode function isn't taking into consideration the above
763 // modifications to the encoding process. However, this method doesn't
764 // seem to be used anywhere so leaving it as is.
765 public static function urldecode_rfc3986($string) {/*{{{*/
766 return rawurldecode($string);