MDL-70424 auth: Avoid random changes to $CFG->auth
[moodle.git] / enrol / lti / ims-blti / OAuth.php
blob3077787a41793ba363f5c061ab3a8e3772126b70
1 <?php
2 // vim: foldmethod=marker
4 $OAuth_last_computed_siguature = false;
6 /* Generic exception class
7 */
8 class OAuthException extends \Exception {
9 // pass
12 class OAuthConsumer {
13 public $key;
14 public $secret;
16 function __construct($key, $secret, $callback_url=NULL) {
17 $this->key = $key;
18 $this->secret = $secret;
19 $this->callback_url = $callback_url;
22 function __toString() {
23 return "OAuthConsumer[key=$this->key,secret=$this->secret]";
27 class OAuthToken {
28 // access tokens and request tokens
29 public $key;
30 public $secret;
32 /**
33 * key = the token
34 * secret = the token secret
36 function __construct($key, $secret) {
37 $this->key = $key;
38 $this->secret = $secret;
41 /**
42 * generates the basic string serialization of a token that a server
43 * would respond to request_token and access_token calls with
45 function to_string() {
46 return "oauth_token=" .
47 OAuthUtil::urlencode_rfc3986($this->key) .
48 "&oauth_token_secret=" .
49 OAuthUtil::urlencode_rfc3986($this->secret);
52 function __toString() {
53 return $this->to_string();
57 class OAuthSignatureMethod {
58 public function check_signature(&$request, $consumer, $token, $signature) {
59 $built = $this->build_signature($request, $consumer, $token);
60 return $built == $signature;
64 class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {
65 function get_name() {
66 return "HMAC-SHA1";
69 public function build_signature($request, $consumer, $token) {
70 global $OAuth_last_computed_signature;
71 $OAuth_last_computed_signature = false;
73 $base_string = $request->get_signature_base_string();
74 $request->base_string = $base_string;
76 $key_parts = array(
77 $consumer->secret,
78 ($token) ? $token->secret : ""
81 $key_parts = OAuthUtil::urlencode_rfc3986($key_parts);
82 $key = implode('&', $key_parts);
84 $computed_signature = base64_encode(hash_hmac('sha1', $base_string, $key, true));
85 $OAuth_last_computed_signature = $computed_signature;
86 return $computed_signature;
91 class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod {
92 public function get_name() {
93 return "PLAINTEXT";
96 public function build_signature($request, $consumer, $token) {
97 $sig = array(
98 OAuthUtil::urlencode_rfc3986($consumer->secret)
101 if ($token) {
102 array_push($sig, OAuthUtil::urlencode_rfc3986($token->secret));
103 } else {
104 array_push($sig, '');
107 $raw = implode("&", $sig);
108 // for debug purposes
109 $request->base_string = $raw;
111 return OAuthUtil::urlencode_rfc3986($raw);
115 class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {
116 public function get_name() {
117 return "RSA-SHA1";
120 protected function fetch_public_cert(&$request) {
121 // not implemented yet, ideas are:
122 // (1) do a lookup in a table of trusted certs keyed off of consumer
123 // (2) fetch via http using a url provided by the requester
124 // (3) some sort of specific discovery code based on request
126 // either way should return a string representation of the certificate
127 throw Exception("fetch_public_cert not implemented");
130 protected function fetch_private_cert(&$request) {
131 // not implemented yet, ideas are:
132 // (1) do a lookup in a table of trusted certs keyed off of consumer
134 // either way should return a string representation of the certificate
135 throw Exception("fetch_private_cert not implemented");
138 public function build_signature(&$request, $consumer, $token) {
139 $base_string = $request->get_signature_base_string();
140 $request->base_string = $base_string;
142 // Fetch the private key cert based on the request
143 $cert = $this->fetch_private_cert($request);
145 // Pull the private key ID from the certificate
146 $privatekeyid = openssl_get_privatekey($cert);
148 // Sign using the key
149 $ok = openssl_sign($base_string, $signature, $privatekeyid);
151 // Release the key resource
152 openssl_free_key($privatekeyid);
154 return base64_encode($signature);
157 public function check_signature(&$request, $consumer, $token, $signature) {
158 $decoded_sig = base64_decode($signature);
160 $base_string = $request->get_signature_base_string();
162 // Fetch the public key cert based on the request
163 $cert = $this->fetch_public_cert($request);
165 // Pull the public key ID from the certificate
166 $publickeyid = openssl_get_publickey($cert);
168 // Check the computed signature against the one passed in the query
169 $ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
171 // Release the key resource
172 openssl_free_key($publickeyid);
174 return $ok == 1;
178 class OAuthRequest {
179 private $parameters;
180 private $http_method;
181 private $http_url;
182 // for debug purposes
183 public $base_string;
184 public static $version = '1.0';
185 public static $POST_INPUT = 'php://input';
187 function __construct($http_method, $http_url, $parameters=NULL) {
188 @$parameters or $parameters = array();
189 $this->parameters = $parameters;
190 $this->http_method = $http_method;
191 $this->http_url = $http_url;
196 * attempt to build up a request from what was passed to the server
198 public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
199 $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
200 ? 'http'
201 : 'https';
202 $port = "";
203 if ( $_SERVER['SERVER_PORT'] != "80" && $_SERVER['SERVER_PORT'] != "443" &&
204 strpos(':', $_SERVER['HTTP_HOST']) < 0 ) {
205 $port = ':' . $_SERVER['SERVER_PORT'] ;
207 @$http_url or $http_url = $scheme .
208 '://' . $_SERVER['HTTP_HOST'] .
209 $port .
210 $_SERVER['REQUEST_URI'];
211 @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
213 // We weren't handed any parameters, so let's find the ones relevant to
214 // this request.
215 // If you run XML-RPC or similar you should use this to provide your own
216 // parsed parameter-list
217 if (!$parameters) {
218 // Find request headers
219 $request_headers = OAuthUtil::get_headers();
221 // Parse the query-string to find GET parameters
222 $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
224 $ourpost = $_POST;
225 // Deal with magic_quotes
226 // http://www.php.net/manual/en/security.magicquotes.disabling.php
227 if ( get_magic_quotes_gpc() ) {
228 $outpost = array();
229 foreach ($_POST as $k => $v) {
230 $v = stripslashes($v);
231 $ourpost[$k] = $v;
234 // Add POST Parameters if they exist
235 $parameters = array_merge($parameters, $ourpost);
237 // We have a Authorization-header with OAuth data. Parse the header
238 // and add those overriding any duplicates from GET or POST
239 if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
240 $header_parameters = OAuthUtil::split_header(
241 $request_headers['Authorization']
243 $parameters = array_merge($parameters, $header_parameters);
248 return new OAuthRequest($http_method, $http_url, $parameters);
252 * pretty much a helper function to set up the request
254 public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
255 @$parameters or $parameters = array();
256 $defaults = array("oauth_version" => OAuthRequest::$version,
257 "oauth_nonce" => OAuthRequest::generate_nonce(),
258 "oauth_timestamp" => OAuthRequest::generate_timestamp(),
259 "oauth_consumer_key" => $consumer->key);
260 if ($token)
261 $defaults['oauth_token'] = $token->key;
263 $parameters = array_merge($defaults, $parameters);
265 // Parse the query-string to find and add GET parameters
266 $parts = parse_url($http_url);
267 if ( !empty($parts['query']) ) {
268 $qparms = OAuthUtil::parse_parameters($parts['query']);
269 $parameters = array_merge($qparms, $parameters);
273 return new OAuthRequest($http_method, $http_url, $parameters);
276 public function set_parameter($name, $value, $allow_duplicates = true) {
277 if ($allow_duplicates && isset($this->parameters[$name])) {
278 // We have already added parameter(s) with this name, so add to the list
279 if (is_scalar($this->parameters[$name])) {
280 // This is the first duplicate, so transform scalar (string)
281 // into an array so we can add the duplicates
282 $this->parameters[$name] = array($this->parameters[$name]);
285 $this->parameters[$name][] = $value;
286 } else {
287 $this->parameters[$name] = $value;
291 public function get_parameter($name) {
292 return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
295 public function get_parameters() {
296 return $this->parameters;
299 public function unset_parameter($name) {
300 unset($this->parameters[$name]);
304 * The request parameters, sorted and concatenated into a normalized string.
305 * @return string
307 public function get_signable_parameters() {
308 // Grab all parameters
309 $params = $this->parameters;
311 // Remove oauth_signature if present
312 // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
313 if (isset($params['oauth_signature'])) {
314 unset($params['oauth_signature']);
317 return OAuthUtil::build_http_query($params);
321 * Returns the base string of this request
323 * The base string defined as the method, the url
324 * and the parameters (normalized), each urlencoded
325 * and the concated with &.
327 public function get_signature_base_string() {
328 $parts = array(
329 $this->get_normalized_http_method(),
330 $this->get_normalized_http_url(),
331 $this->get_signable_parameters()
334 $parts = OAuthUtil::urlencode_rfc3986($parts);
336 return implode('&', $parts);
340 * just uppercases the http method
342 public function get_normalized_http_method() {
343 return strtoupper($this->http_method);
347 * parses the url and rebuilds it to be
348 * scheme://host/path
350 public function get_normalized_http_url() {
351 $parts = parse_url($this->http_url);
353 $port = @$parts['port'];
354 $scheme = $parts['scheme'];
355 $host = $parts['host'];
356 $path = @$parts['path'];
358 $port or $port = ($scheme == 'https') ? '443' : '80';
360 if (($scheme == 'https' && $port != '443')
361 || ($scheme == 'http' && $port != '80')) {
362 $host = "$host:$port";
364 return "$scheme://$host$path";
368 * builds a url usable for a GET request
370 public function to_url() {
371 $post_data = $this->to_postdata();
372 $out = $this->get_normalized_http_url();
373 if ($post_data) {
374 $out .= '?'.$post_data;
376 return $out;
380 * builds the data one would send in a POST request
382 public function to_postdata() {
383 return OAuthUtil::build_http_query($this->parameters);
387 * builds the Authorization: header
389 public function to_header() {
390 $out ='Authorization: OAuth realm=""';
391 $total = array();
392 foreach ($this->parameters as $k => $v) {
393 if (substr($k, 0, 5) != "oauth") continue;
394 if (is_array($v)) {
395 throw new OAuthException('Arrays not supported in headers');
397 $out .= ',' .
398 OAuthUtil::urlencode_rfc3986($k) .
399 '="' .
400 OAuthUtil::urlencode_rfc3986($v) .
401 '"';
403 return $out;
406 public function __toString() {
407 return $this->to_url();
411 public function sign_request($signature_method, $consumer, $token) {
412 $this->set_parameter(
413 "oauth_signature_method",
414 $signature_method->get_name(),
415 false
417 $signature = $this->build_signature($signature_method, $consumer, $token);
418 $this->set_parameter("oauth_signature", $signature, false);
421 public function build_signature($signature_method, $consumer, $token) {
422 $signature = $signature_method->build_signature($this, $consumer, $token);
423 return $signature;
427 * util function: current timestamp
429 private static function generate_timestamp() {
430 return time();
434 * util function: current nonce
436 private static function generate_nonce() {
437 $mt = microtime();
438 $rand = mt_rand();
440 return md5($mt . $rand); // md5s look nicer than numbers
444 class OAuthServer {
445 protected $timestamp_threshold = 300; // in seconds, five minutes
446 protected $version = 1.0; // hi blaine
447 protected $signature_methods = array();
449 protected $data_store;
451 function __construct($data_store) {
452 $this->data_store = $data_store;
455 public function add_signature_method($signature_method) {
456 $this->signature_methods[$signature_method->get_name()] =
457 $signature_method;
460 // high level functions
463 * process a request_token request
464 * returns the request token on success
466 public function fetch_request_token(&$request) {
467 $this->get_version($request);
469 $consumer = $this->get_consumer($request);
471 // no token required for the initial token request
472 $token = NULL;
474 $this->check_signature($request, $consumer, $token);
476 $new_token = $this->data_store->new_request_token($consumer);
478 return $new_token;
482 * process an access_token request
483 * returns the access token on success
485 public function fetch_access_token(&$request) {
486 $this->get_version($request);
488 $consumer = $this->get_consumer($request);
490 // requires authorized request token
491 $token = $this->get_token($request, $consumer, "request");
494 $this->check_signature($request, $consumer, $token);
496 $new_token = $this->data_store->new_access_token($token, $consumer);
498 return $new_token;
502 * verify an api call, checks all the parameters
504 public function verify_request(&$request) {
505 global $OAuth_last_computed_signature;
506 $OAuth_last_computed_signature = false;
507 $this->get_version($request);
508 $consumer = $this->get_consumer($request);
509 $token = $this->get_token($request, $consumer, "access");
510 $this->check_signature($request, $consumer, $token);
511 return array($consumer, $token);
514 // Internals from here
516 * version 1
518 private function get_version(&$request) {
519 $version = $request->get_parameter("oauth_version");
520 if (!$version) {
521 $version = 1.0;
523 if ($version && $version != $this->version) {
524 throw new OAuthException("OAuth version '$version' not supported");
526 return $version;
530 * figure out the signature with some defaults
532 private function get_signature_method(&$request) {
533 $signature_method =
534 @$request->get_parameter("oauth_signature_method");
535 if (!$signature_method) {
536 $signature_method = "PLAINTEXT";
538 if (!in_array($signature_method,
539 array_keys($this->signature_methods))) {
540 throw new OAuthException(
541 "Signature method '$signature_method' not supported " .
542 "try one of the following: " .
543 implode(", ", array_keys($this->signature_methods))
546 return $this->signature_methods[$signature_method];
550 * try to find the consumer for the provided request's consumer key
552 private function get_consumer(&$request) {
553 $consumer_key = @$request->get_parameter("oauth_consumer_key");
554 if (!$consumer_key) {
555 throw new OAuthException("Invalid consumer key");
558 $consumer = $this->data_store->lookup_consumer($consumer_key);
559 if (!$consumer) {
560 throw new OAuthException("Invalid consumer");
563 return $consumer;
567 * try to find the token for the provided request's token key
569 private function get_token(&$request, $consumer, $token_type="access") {
570 $token_field = @$request->get_parameter('oauth_token');
571 if ( !$token_field) return false;
572 $token = $this->data_store->lookup_token(
573 $consumer, $token_type, $token_field
575 if (!$token) {
576 throw new OAuthException("Invalid $token_type token: $token_field");
578 return $token;
582 * all-in-one function to check the signature on a request
583 * should guess the signature method appropriately
585 private function check_signature(&$request, $consumer, $token) {
586 // this should probably be in a different method
587 global $OAuth_last_computed_signature;
588 $OAuth_last_computed_signature = false;
590 $timestamp = @$request->get_parameter('oauth_timestamp');
591 $nonce = @$request->get_parameter('oauth_nonce');
593 $this->check_timestamp($timestamp);
594 $this->check_nonce($consumer, $token, $nonce, $timestamp);
596 $signature_method = $this->get_signature_method($request);
598 $signature = $request->get_parameter('oauth_signature');
599 $valid_sig = $signature_method->check_signature(
600 $request,
601 $consumer,
602 $token,
603 $signature
606 if (!$valid_sig) {
607 $ex_text = "Invalid signature";
608 if ( $OAuth_last_computed_signature ) {
609 $ex_text = $ex_text . " ours= $OAuth_last_computed_signature yours=$signature";
611 throw new OAuthException($ex_text);
616 * check that the timestamp is new enough
618 private function check_timestamp($timestamp) {
619 // verify that timestamp is recentish
620 $now = time();
621 if ($now - $timestamp > $this->timestamp_threshold) {
622 throw new OAuthException(
623 "Expired timestamp, yours $timestamp, ours $now"
629 * check that the nonce is not repeated
631 private function check_nonce($consumer, $token, $nonce, $timestamp) {
632 // verify that the nonce is uniqueish
633 $found = $this->data_store->lookup_nonce(
634 $consumer,
635 $token,
636 $nonce,
637 $timestamp
639 if ($found) {
640 throw new OAuthException("Nonce already used: $nonce");
646 class OAuthDataStore {
647 function lookup_consumer($consumer_key) {
648 // implement me
651 function lookup_token($consumer, $token_type, $token) {
652 // implement me
655 function lookup_nonce($consumer, $token, $nonce, $timestamp) {
656 // implement me
659 function new_request_token($consumer) {
660 // return a new token attached to this consumer
663 function new_access_token($token, $consumer) {
664 // return a new access token attached to this consumer
665 // for the user associated with this token if the request token
666 // is authorized
667 // should also invalidate the request token
672 class OAuthUtil {
673 public static function urlencode_rfc3986($input) {
674 if (is_array($input)) {
675 return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
676 } else if (is_scalar($input)) {
677 return str_replace(
678 '+',
679 ' ',
680 str_replace('%7E', '~', rawurlencode($input))
682 } else {
683 return '';
688 // This decode function isn't taking into consideration the above
689 // modifications to the encoding process. However, this method doesn't
690 // seem to be used anywhere so leaving it as is.
691 public static function urldecode_rfc3986($string) {
692 return urldecode($string);
695 // Utility function for turning the Authorization: header into
696 // parameters, has to do some unescaping
697 // Can filter out any non-oauth parameters if needed (default behaviour)
698 public static function split_header($header, $only_allow_oauth_parameters = true) {
699 $pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
700 $offset = 0;
701 $params = array();
702 while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
703 $match = $matches[0];
704 $header_name = $matches[2][0];
705 $header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
706 if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
707 $params[$header_name] = OAuthUtil::urldecode_rfc3986($header_content);
709 $offset = $match[1] + strlen($match[0]);
712 if (isset($params['realm'])) {
713 unset($params['realm']);
716 return $params;
719 // helper to try to sort out headers for people who aren't running apache
720 public static function get_headers() {
721 if (function_exists('apache_request_headers')) {
722 // we need this to get the actual Authorization: header
723 // because apache tends to tell us it doesn't exist
724 return apache_request_headers();
726 // otherwise we don't have apache and are just going to have to hope
727 // that $_SERVER actually contains what we need
728 $out = array();
729 foreach ($_SERVER as $key => $value) {
730 if (substr($key, 0, 5) == "HTTP_") {
731 // this is chaos, basically it is just there to capitalize the first
732 // letter of every word that is not an initial HTTP and strip HTTP
733 // code from przemek
734 $key = str_replace(
735 " ",
736 "-",
737 ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
739 $out[$key] = $value;
742 return $out;
745 // This function takes a input like a=b&a=c&d=e and returns the parsed
746 // parameters like this
747 // array('a' => array('b','c'), 'd' => 'e')
748 public static function parse_parameters( $input ) {
749 if (!isset($input) || !$input) return array();
751 $pairs = explode('&', $input);
753 $parsed_parameters = array();
754 foreach ($pairs as $pair) {
755 $split = explode('=', $pair, 2);
756 $parameter = OAuthUtil::urldecode_rfc3986($split[0]);
757 $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : '';
759 if (isset($parsed_parameters[$parameter])) {
760 // We have already recieved parameter(s) with this name, so add to the list
761 // of parameters with this name
763 if (is_scalar($parsed_parameters[$parameter])) {
764 // This is the first duplicate, so transform scalar (string) into an array
765 // so we can add the duplicates
766 $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
769 $parsed_parameters[$parameter][] = $value;
770 } else {
771 $parsed_parameters[$parameter] = $value;
774 return $parsed_parameters;
777 public static function build_http_query($params) {
778 if (!$params) return '';
780 // Urlencode both keys and values
781 $keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
782 $values = OAuthUtil::urlencode_rfc3986(array_values($params));
783 $params = array_combine($keys, $values);
785 // Parameters are sorted by name, using lexicographical byte value ordering.
786 // Ref: Spec: 9.1.1 (1)
787 uksort($params, 'strcmp');
789 $pairs = array();
790 foreach ($params as $parameter => $value) {
791 if (is_array($value)) {
792 // If two or more parameters share the same name, they are sorted by their value
793 // Ref: Spec: 9.1.1 (1)
794 natsort($value);
795 foreach ($value as $duplicate_value) {
796 $pairs[] = $parameter . '=' . $duplicate_value;
798 } else {
799 $pairs[] = $parameter . '=' . $value;
802 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
803 // Each name-value pair is separated by an '&' character (ASCII code 38)
804 return implode('&', $pairs);