diff --git a/lib/php-jwt/README.md b/lib/php-jwt/README.md
index b1a7a3a2063..9c8b5455b69 100644
--- a/lib/php-jwt/README.md
+++ b/lib/php-jwt/README.md
@@ -23,7 +23,7 @@ Example
use \Firebase\JWT\JWT;
$key = "example_key";
-$token = array(
+$payload = array(
"iss" => "http://example.org",
"aud" => "http://example.com",
"iat" => 1356999524,
@@ -36,7 +36,7 @@ $token = array(
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
* for a list of spec-compliant algorithms.
*/
-$jwt = JWT::encode($token, $key);
+$jwt = JWT::encode($payload, $key);
$decoded = JWT::decode($jwt, $key, array('HS256'));
print_r($decoded);
@@ -93,14 +93,14 @@ ehde/zUxo6UvS7UrBQIDAQAB
-----END PUBLIC KEY-----
EOD;
-$token = array(
+$payload = array(
"iss" => "example.org",
"aud" => "example.com",
"iat" => 1356999524,
"nbf" => 1357000000
);
-$jwt = JWT::encode($token, $privateKey, 'RS256');
+$jwt = JWT::encode($payload, $privateKey, 'RS256');
echo "Encode:\n" . print_r($jwt, true) . "\n";
$decoded = JWT::decode($jwt, $publicKey, array('RS256'));
diff --git a/lib/php-jwt/composer.json b/lib/php-jwt/composer.json
index b76ffd19106..25d1cfa96ad 100644
--- a/lib/php-jwt/composer.json
+++ b/lib/php-jwt/composer.json
@@ -2,6 +2,10 @@
"name": "firebase/php-jwt",
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
"homepage": "https://github.com/firebase/php-jwt",
+ "keywords": [
+ "php",
+ "jwt"
+ ],
"authors": [
{
"name": "Neuman Vong",
@@ -24,6 +28,6 @@
}
},
"require-dev": {
- "phpunit/phpunit": " 4.8.35"
+ "phpunit/phpunit": ">=4.8 <=9"
}
}
diff --git a/lib/php-jwt/src/BeforeValidException.php b/lib/php-jwt/src/BeforeValidException.php
index a6ee2f7c690..fdf82bd9429 100644
--- a/lib/php-jwt/src/BeforeValidException.php
+++ b/lib/php-jwt/src/BeforeValidException.php
@@ -3,5 +3,4 @@ namespace Firebase\JWT;
class BeforeValidException extends \UnexpectedValueException
{
-
}
diff --git a/lib/php-jwt/src/ExpiredException.php b/lib/php-jwt/src/ExpiredException.php
index 3597370a6de..7f7d0568248 100644
--- a/lib/php-jwt/src/ExpiredException.php
+++ b/lib/php-jwt/src/ExpiredException.php
@@ -3,5 +3,4 @@ namespace Firebase\JWT;
class ExpiredException extends \UnexpectedValueException
{
-
}
diff --git a/lib/php-jwt/src/JWK.php b/lib/php-jwt/src/JWK.php
new file mode 100644
index 00000000000..1d273917403
--- /dev/null
+++ b/lib/php-jwt/src/JWK.php
@@ -0,0 +1,171 @@
+
+ * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
+ * @link https://github.com/firebase/php-jwt
+ */
+class JWK
+{
+ /**
+ * Parse a set of JWK keys
+ *
+ * @param array $jwks The JSON Web Key Set as an associative array
+ *
+ * @return array An associative array that represents the set of keys
+ *
+ * @throws InvalidArgumentException Provided JWK Set is empty
+ * @throws UnexpectedValueException Provided JWK Set was invalid
+ * @throws DomainException OpenSSL failure
+ *
+ * @uses parseKey
+ */
+ public static function parseKeySet(array $jwks)
+ {
+ $keys = array();
+
+ if (!isset($jwks['keys'])) {
+ throw new UnexpectedValueException('"keys" member must exist in the JWK Set');
+ }
+ if (empty($jwks['keys'])) {
+ throw new InvalidArgumentException('JWK Set did not contain any keys');
+ }
+
+ foreach ($jwks['keys'] as $k => $v) {
+ $kid = isset($v['kid']) ? $v['kid'] : $k;
+ if ($key = self::parseKey($v)) {
+ $keys[$kid] = $key;
+ }
+ }
+
+ if (0 === \count($keys)) {
+ throw new UnexpectedValueException('No supported algorithms found in JWK Set');
+ }
+
+ return $keys;
+ }
+
+ /**
+ * Parse a JWK key
+ *
+ * @param array $jwk An individual JWK
+ *
+ * @return resource|array An associative array that represents the key
+ *
+ * @throws InvalidArgumentException Provided JWK is empty
+ * @throws UnexpectedValueException Provided JWK was invalid
+ * @throws DomainException OpenSSL failure
+ *
+ * @uses createPemFromModulusAndExponent
+ */
+ private static function parseKey(array $jwk)
+ {
+ if (empty($jwk)) {
+ throw new InvalidArgumentException('JWK must not be empty');
+ }
+ if (!isset($jwk['kty'])) {
+ throw new UnexpectedValueException('JWK must contain a "kty" parameter');
+ }
+
+ switch ($jwk['kty']) {
+ case 'RSA':
+ if (\array_key_exists('d', $jwk)) {
+ throw new UnexpectedValueException('RSA private keys are not supported');
+ }
+ if (!isset($jwk['n']) || !isset($jwk['e'])) {
+ throw new UnexpectedValueException('RSA keys must contain values for both "n" and "e"');
+ }
+
+ $pem = self::createPemFromModulusAndExponent($jwk['n'], $jwk['e']);
+ $publicKey = \openssl_pkey_get_public($pem);
+ if (false === $publicKey) {
+ throw new DomainException(
+ 'OpenSSL error: ' . \openssl_error_string()
+ );
+ }
+ return $publicKey;
+ default:
+ // Currently only RSA is supported
+ break;
+ }
+ }
+
+ /**
+ * Create a public key represented in PEM format from RSA modulus and exponent information
+ *
+ * @param string $n The RSA modulus encoded in Base64
+ * @param string $e The RSA exponent encoded in Base64
+ *
+ * @return string The RSA public key represented in PEM format
+ *
+ * @uses encodeLength
+ */
+ private static function createPemFromModulusAndExponent($n, $e)
+ {
+ $modulus = JWT::urlsafeB64Decode($n);
+ $publicExponent = JWT::urlsafeB64Decode($e);
+
+ $components = array(
+ 'modulus' => \pack('Ca*a*', 2, self::encodeLength(\strlen($modulus)), $modulus),
+ 'publicExponent' => \pack('Ca*a*', 2, self::encodeLength(\strlen($publicExponent)), $publicExponent)
+ );
+
+ $rsaPublicKey = \pack(
+ 'Ca*a*a*',
+ 48,
+ self::encodeLength(\strlen($components['modulus']) + \strlen($components['publicExponent'])),
+ $components['modulus'],
+ $components['publicExponent']
+ );
+
+ // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
+ $rsaOID = \pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
+ $rsaPublicKey = \chr(0) . $rsaPublicKey;
+ $rsaPublicKey = \chr(3) . self::encodeLength(\strlen($rsaPublicKey)) . $rsaPublicKey;
+
+ $rsaPublicKey = \pack(
+ 'Ca*a*',
+ 48,
+ self::encodeLength(\strlen($rsaOID . $rsaPublicKey)),
+ $rsaOID . $rsaPublicKey
+ );
+
+ $rsaPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
+ \chunk_split(\base64_encode($rsaPublicKey), 64) .
+ '-----END PUBLIC KEY-----';
+
+ return $rsaPublicKey;
+ }
+
+ /**
+ * DER-encode the length
+ *
+ * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
+ * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
+ *
+ * @param int $length
+ * @return string
+ */
+ private static function encodeLength($length)
+ {
+ if ($length <= 0x7F) {
+ return \chr($length);
+ }
+
+ $temp = \ltrim(\pack('N', $length), \chr(0));
+
+ return \pack('Ca*', 0x80 | \strlen($temp), $temp);
+ }
+}
diff --git a/lib/php-jwt/src/JWT.php b/lib/php-jwt/src/JWT.php
index 33e2ed4edf3..4ccc1a96c23 100644
--- a/lib/php-jwt/src/JWT.php
+++ b/lib/php-jwt/src/JWT.php
@@ -1,6 +1,7 @@
array('openssl', 'SHA256'),
'HS256' => array('hash_hmac', 'SHA256'),
- 'HS512' => array('hash_hmac', 'SHA512'),
'HS384' => array('hash_hmac', 'SHA384'),
+ 'HS512' => array('hash_hmac', 'SHA512'),
'RS256' => array('openssl', 'SHA256'),
'RS384' => array('openssl', 'SHA384'),
'RS512' => array('openssl', 'SHA512'),
@@ -49,11 +54,11 @@ class JWT
/**
* Decodes a JWT string into a PHP object.
*
- * @param string $jwt The JWT
- * @param string|array $key The key, or map of keys.
- * If the algorithm used is asymmetric, this is the public key
- * @param array $allowed_algs List of supported verification algorithms
- * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
+ * @param string $jwt The JWT
+ * @param string|array|resource $key The key, or map of keys.
+ * If the algorithm used is asymmetric, this is the public key
+ * @param array $allowed_algs List of supported verification algorithms
+ * Supported algorithms are 'ES256', 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
*
* @return object The JWT's payload as a PHP object
*
@@ -68,13 +73,13 @@ class JWT
*/
public static function decode($jwt, $key, array $allowed_algs = array())
{
- $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;
+ $timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp;
if (empty($key)) {
throw new InvalidArgumentException('Key may not be empty');
}
- $tks = explode('.', $jwt);
- if (count($tks) != 3) {
+ $tks = \explode('.', $jwt);
+ if (\count($tks) != 3) {
throw new UnexpectedValueException('Wrong number of segments');
}
list($headb64, $bodyb64, $cryptob64) = $tks;
@@ -93,10 +98,15 @@ class JWT
if (empty(static::$supported_algs[$header->alg])) {
throw new UnexpectedValueException('Algorithm not supported');
}
- if (!in_array($header->alg, $allowed_algs)) {
+ if (!\in_array($header->alg, $allowed_algs)) {
throw new UnexpectedValueException('Algorithm not allowed');
}
- if (is_array($key) || $key instanceof \ArrayAccess) {
+ if ($header->alg === 'ES256') {
+ // OpenSSL expects an ASN.1 DER sequence for ES256 signatures
+ $sig = self::signatureToDER($sig);
+ }
+
+ if (\is_array($key) || $key instanceof \ArrayAccess) {
if (isset($header->kid)) {
if (!isset($key[$header->kid])) {
throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
@@ -112,11 +122,11 @@ class JWT
throw new SignatureInvalidException('Signature verification failed');
}
- // Check if the nbf if it is defined. This is the time that the
+ // Check the nbf if it is defined. This is the time that the
// token can actually be used. If it's not yet that time, abort.
if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
throw new BeforeValidException(
- 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->nbf)
+ 'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->nbf)
);
}
@@ -125,7 +135,7 @@ class JWT
// correctly used the nbf claim).
if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
throw new BeforeValidException(
- 'Cannot handle token prior to ' . date(DateTime::ISO8601, $payload->iat)
+ 'Cannot handle token prior to ' . \date(DateTime::ISO8601, $payload->iat)
);
}
@@ -144,7 +154,7 @@ class JWT
* @param string $key The secret key.
* If the algorithm used is asymmetric, this is the private key
* @param string $alg The signing algorithm.
- * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
+ * Supported algorithms are 'ES256', 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
* @param mixed $keyId
* @param array $head An array with header elements to attach
*
@@ -159,18 +169,18 @@ class JWT
if ($keyId !== null) {
$header['kid'] = $keyId;
}
- if ( isset($head) && is_array($head) ) {
- $header = array_merge($head, $header);
+ if (isset($head) && \is_array($head)) {
+ $header = \array_merge($head, $header);
}
$segments = array();
$segments[] = static::urlsafeB64Encode(static::jsonEncode($header));
$segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));
- $signing_input = implode('.', $segments);
+ $signing_input = \implode('.', $segments);
$signature = static::sign($signing_input, $key, $alg);
$segments[] = static::urlsafeB64Encode($signature);
- return implode('.', $segments);
+ return \implode('.', $segments);
}
/**
@@ -179,7 +189,7 @@ class JWT
* @param string $msg The message to sign
* @param string|resource $key The secret key
* @param string $alg The signing algorithm.
- * Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
+ * Supported algorithms are 'ES256', 'HS256', 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
*
* @return string An encrypted message
*
@@ -191,15 +201,18 @@ class JWT
throw new DomainException('Algorithm not supported');
}
list($function, $algorithm) = static::$supported_algs[$alg];
- switch($function) {
+ switch ($function) {
case 'hash_hmac':
- return hash_hmac($algorithm, $msg, $key, true);
+ return \hash_hmac($algorithm, $msg, $key, true);
case 'openssl':
$signature = '';
- $success = openssl_sign($msg, $signature, $key, $algorithm);
+ $success = \openssl_sign($msg, $signature, $key, $algorithm);
if (!$success) {
throw new DomainException("OpenSSL unable to sign data");
} else {
+ if ($alg === 'ES256') {
+ $signature = self::signatureFromDER($signature, 256);
+ }
return $signature;
}
}
@@ -225,9 +238,9 @@ class JWT
}
list($function, $algorithm) = static::$supported_algs[$alg];
- switch($function) {
+ switch ($function) {
case 'openssl':
- $success = openssl_verify($msg, $signature, $key, $algorithm);
+ $success = \openssl_verify($msg, $signature, $key, $algorithm);
if ($success === 1) {
return true;
} elseif ($success === 0) {
@@ -235,19 +248,19 @@ class JWT
}
// returns 1 on success, 0 on failure, -1 on error.
throw new DomainException(
- 'OpenSSL error: ' . openssl_error_string()
+ 'OpenSSL error: ' . \openssl_error_string()
);
case 'hash_hmac':
default:
- $hash = hash_hmac($algorithm, $msg, $key, true);
- if (function_exists('hash_equals')) {
- return hash_equals($signature, $hash);
+ $hash = \hash_hmac($algorithm, $msg, $key, true);
+ if (\function_exists('hash_equals')) {
+ return \hash_equals($signature, $hash);
}
- $len = min(static::safeStrlen($signature), static::safeStrlen($hash));
+ $len = \min(static::safeStrlen($signature), static::safeStrlen($hash));
$status = 0;
for ($i = 0; $i < $len; $i++) {
- $status |= (ord($signature[$i]) ^ ord($hash[$i]));
+ $status |= (\ord($signature[$i]) ^ \ord($hash[$i]));
}
$status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash));
@@ -266,23 +279,23 @@ class JWT
*/
public static function jsonDecode($input)
{
- if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
+ if (\version_compare(PHP_VERSION, '5.4.0', '>=') && !(\defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
/** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you
* to specify that large ints (like Steam Transaction IDs) should be treated as
* strings, rather than the PHP default behaviour of converting them to floats.
*/
- $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
+ $obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
} else {
/** Not all servers will support that, however, so for older versions we must
* manually detect large ints in the JSON string and quote them (thus converting
*them to strings) before decoding, hence the preg_replace() call.
*/
- $max_int_length = strlen((string) PHP_INT_MAX) - 1;
- $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
- $obj = json_decode($json_without_bigints);
+ $max_int_length = \strlen((string) PHP_INT_MAX) - 1;
+ $json_without_bigints = \preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
+ $obj = \json_decode($json_without_bigints);
}
- if (function_exists('json_last_error') && $errno = json_last_error()) {
+ if ($errno = \json_last_error()) {
static::handleJsonError($errno);
} elseif ($obj === null && $input !== 'null') {
throw new DomainException('Null result with non-null input');
@@ -301,8 +314,8 @@ class JWT
*/
public static function jsonEncode($input)
{
- $json = json_encode($input);
- if (function_exists('json_last_error') && $errno = json_last_error()) {
+ $json = \json_encode($input);
+ if ($errno = \json_last_error()) {
static::handleJsonError($errno);
} elseif ($json === 'null' && $input !== null) {
throw new DomainException('Null result with non-null input');
@@ -319,12 +332,12 @@ class JWT
*/
public static function urlsafeB64Decode($input)
{
- $remainder = strlen($input) % 4;
+ $remainder = \strlen($input) % 4;
if ($remainder) {
$padlen = 4 - $remainder;
- $input .= str_repeat('=', $padlen);
+ $input .= \str_repeat('=', $padlen);
}
- return base64_decode(strtr($input, '-_', '+/'));
+ return \base64_decode(\strtr($input, '-_', '+/'));
}
/**
@@ -336,7 +349,7 @@ class JWT
*/
public static function urlsafeB64Encode($input)
{
- return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
+ return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_'));
}
/**
@@ -365,15 +378,135 @@ class JWT
/**
* Get the number of bytes in cryptographic strings.
*
- * @param string
+ * @param string $str
*
* @return int
*/
private static function safeStrlen($str)
{
- if (function_exists('mb_strlen')) {
- return mb_strlen($str, '8bit');
+ if (\function_exists('mb_strlen')) {
+ return \mb_strlen($str, '8bit');
}
- return strlen($str);
+ return \strlen($str);
+ }
+
+ /**
+ * Convert an ECDSA signature to an ASN.1 DER sequence
+ *
+ * @param string $sig The ECDSA signature to convert
+ * @return string The encoded DER object
+ */
+ private static function signatureToDER($sig)
+ {
+ // Separate the signature into r-value and s-value
+ list($r, $s) = \str_split($sig, (int) (\strlen($sig) / 2));
+
+ // Trim leading zeros
+ $r = \ltrim($r, "\x00");
+ $s = \ltrim($s, "\x00");
+
+ // Convert r-value and s-value from unsigned big-endian integers to
+ // signed two's complement
+ if (\ord($r[0]) > 0x7f) {
+ $r = "\x00" . $r;
+ }
+ if (\ord($s[0]) > 0x7f) {
+ $s = "\x00" . $s;
+ }
+
+ return self::encodeDER(
+ self::ASN1_SEQUENCE,
+ self::encodeDER(self::ASN1_INTEGER, $r) .
+ self::encodeDER(self::ASN1_INTEGER, $s)
+ );
+ }
+
+ /**
+ * Encodes a value into a DER object.
+ *
+ * @param int $type DER tag
+ * @param string $value the value to encode
+ * @return string the encoded object
+ */
+ private static function encodeDER($type, $value)
+ {
+ $tag_header = 0;
+ if ($type === self::ASN1_SEQUENCE) {
+ $tag_header |= 0x20;
+ }
+
+ // Type
+ $der = \chr($tag_header | $type);
+
+ // Length
+ $der .= \chr(\strlen($value));
+
+ return $der . $value;
+ }
+
+ /**
+ * Encodes signature from a DER object.
+ *
+ * @param string $der binary signature in DER format
+ * @param int $keySize the number of bits in the key
+ * @return string the signature
+ */
+ private static function signatureFromDER($der, $keySize)
+ {
+ // OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE
+ list($offset, $_) = self::readDER($der);
+ list($offset, $r) = self::readDER($der, $offset);
+ list($offset, $s) = self::readDER($der, $offset);
+
+ // Convert r-value and s-value from signed two's compliment to unsigned
+ // big-endian integers
+ $r = \ltrim($r, "\x00");
+ $s = \ltrim($s, "\x00");
+
+ // Pad out r and s so that they are $keySize bits long
+ $r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT);
+ $s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT);
+
+ return $r . $s;
+ }
+
+ /**
+ * Reads binary DER-encoded data and decodes into a single object
+ *
+ * @param string $der the binary data in DER format
+ * @param int $offset the offset of the data stream containing the object
+ * to decode
+ * @return array [$offset, $data] the new offset and the decoded object
+ */
+ private static function readDER($der, $offset = 0)
+ {
+ $pos = $offset;
+ $size = \strlen($der);
+ $constructed = (\ord($der[$pos]) >> 5) & 0x01;
+ $type = \ord($der[$pos++]) & 0x1f;
+
+ // Length
+ $len = \ord($der[$pos++]);
+ if ($len & 0x80) {
+ $n = $len & 0x1f;
+ $len = 0;
+ while ($n-- && $pos < $size) {
+ $len = ($len << 8) | \ord($der[$pos++]);
+ }
+ }
+
+ // Value
+ if ($type == self::ASN1_BIT_STRING) {
+ $pos++; // Skip the first contents octet (padding indicator)
+ $data = \substr($der, $pos, $len - 1);
+ $pos += $len - 1;
+ } elseif (!$constructed) {
+ $data = \substr($der, $pos, $len);
+ $pos += $len;
+ } else {
+ $data = null;
+ }
+
+ return array($pos, $data);
}
}
diff --git a/lib/php-jwt/src/SignatureInvalidException.php b/lib/php-jwt/src/SignatureInvalidException.php
index 27332b21bea..87cb34df79b 100644
--- a/lib/php-jwt/src/SignatureInvalidException.php
+++ b/lib/php-jwt/src/SignatureInvalidException.php
@@ -3,5 +3,4 @@ namespace Firebase\JWT;
class SignatureInvalidException extends \UnexpectedValueException
{
-
}
diff --git a/lib/thirdpartylibs.xml b/lib/thirdpartylibs.xml
index 9c01c712051..f90da3dd580 100644
--- a/lib/thirdpartylibs.xml
+++ b/lib/thirdpartylibs.xml
@@ -299,7 +299,7 @@
php-jwt
A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to RFC 7519
BSD
- 5.0.0
+ 5.2.0
3-Clause
diff --git a/mod/lti/db/caches.php b/mod/lti/db/caches.php
new file mode 100644
index 00000000000..9d4f4e75d5c
--- /dev/null
+++ b/mod/lti/db/caches.php
@@ -0,0 +1,32 @@
+.
+
+/**
+ * This file contains the cache definitions for the lti plugin
+ *
+ * @package mod_lti
+ * @copyright 2020 Carlos VinÃcius Monteiro Costa
+ * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
+ */
+
+defined('MOODLE_INTERNAL') || die();
+
+// Added definition for keyset cache.
+$definitions = [
+ 'keyset' => [
+ 'mode' => cache_store::MODE_APPLICATION
+ ]
+];
\ No newline at end of file
diff --git a/mod/lti/edit_form.php b/mod/lti/edit_form.php
index 85507c0bcab..83361f5a407 100644
--- a/mod/lti/edit_form.php
+++ b/mod/lti/edit_form.php
@@ -129,12 +129,30 @@ class mod_lti_edit_types_form extends moodleform {
$mform->setType('lti_clientid', PARAM_TEXT);
}
- $mform->addElement('textarea', 'lti_publickey', get_string('publickey', 'lti'), array('rows' => 8, 'cols' => 60));
+ $keyoptions = [
+ LTI_RSA_KEY => get_string('keytype_rsa', 'lti'),
+ LTI_JWK_KEYSET => get_string('keytype_keyset', 'lti'),
+ ];
+ $mform->addElement('select', 'lti_keytype', get_string('keytype', 'lti'), $keyoptions);
+ $mform->setType('lti_keytype', PARAM_TEXT);
+ $mform->addHelpButton('lti_keytype', 'keytype', 'lti');
+ $mform->setDefault('lti_keytype', LTI_JWK_KEYSET);
+ $mform->hideIf('lti_keytype', 'lti_ltiversion', 'neq', LTI_VERSION_1P3);
+
+ $mform->addElement('textarea', 'lti_publickey', get_string('publickey', 'lti'), ['rows' => 8, 'cols' => 60]);
$mform->setType('lti_publickey', PARAM_TEXT);
$mform->addHelpButton('lti_publickey', 'publickey', 'lti');
+ $mform->hideIf('lti_publickey', 'lti_keytype', 'neq', LTI_RSA_KEY);
$mform->hideIf('lti_publickey', 'lti_ltiversion', 'neq', LTI_VERSION_1P3);
$mform->setForceLtr('lti_publickey');
+ $mform->addElement('text', 'lti_publickeyset', get_string('publickeyset', 'lti'), ['size' => '64']);
+ $mform->setType('lti_publickeyset', PARAM_TEXT);
+ $mform->addHelpButton('lti_publickeyset', 'publickeyset', 'lti');
+ $mform->hideIf('lti_publickeyset', 'lti_keytype', 'neq', LTI_JWK_KEYSET);
+ $mform->hideIf('lti_publickeyset', 'lti_ltiversion', 'neq', LTI_VERSION_1P3);
+ $mform->setForceLtr('lti_publickeyset');
+
$mform->addElement('text', 'lti_initiatelogin', get_string('initiatelogin', 'lti'), array('size' => '64'));
$mform->setType('lti_initiatelogin', PARAM_URL);
$mform->addHelpButton('lti_initiatelogin', 'initiatelogin', 'lti');
diff --git a/mod/lti/lang/en/lti.php b/mod/lti/lang/en/lti.php
index 4995d5cd9cc..1d1284be1df 100644
--- a/mod/lti/lang/en/lti.php
+++ b/mod/lti/lang/en/lti.php
@@ -86,6 +86,7 @@ $string['basicltifieldset'] = 'Custom example fieldset';
$string['basicltiintro'] = 'Activity description';
$string['basicltiname'] = 'Activity name';
$string['basicltisettings'] = 'Basic Learning Tool Interoperability (LTI) settings';
+$string['cachedef_keyset'] = 'Caches the keyset information of tools';
$string['cancel'] = 'Cancel';
$string['cancelled'] = 'Cancelled';
$string['cannot_delete'] = 'You may not delete this tool configuration.';
@@ -230,6 +231,10 @@ $string['initiatelogin'] = 'Initiate login URL';
$string['initiatelogin_help'] = 'The tool URL to which requests for initiating a login are to be sent. This URL is required before a message can be successfully sent to the tool.';
$string['invalidid'] = 'LTI ID was incorrect';
$string['jwtsecurity'] = 'LTI 1.3';
+$string['keytype'] = 'Public key type';
+$string['keytype_help'] = 'The authentication method used to validate the tool.';
+$string['keytype_keyset'] = 'Keyset Url';
+$string['keytype_rsa'] = 'RSA Key';
$string['launch_in_moodle'] = 'Launch tool in Moodle';
$string['launch_in_popup'] = 'Launch tool in a pop-up';
$string['launch_url'] = 'Tool URL';
@@ -398,6 +403,8 @@ $string['privacy:metadata:userid'] = 'The ID of the user accessing the LTI Consu
$string['privacy:metadata:useridnumber'] = 'The ID number of the user accessing the LTI Consumer';
$string['privacy:metadata:username'] = 'The username of the user accessing the LTI Consumer';
$string['publickey'] = 'Public key';
+$string['publickeyset'] = 'Public keyset';
+$string['publickeyset_help'] = 'Public keyset from where moodle will retrieve the tool\'s public key to allow signatures of incoming messages and service requests to be verified.';
$string['publickey_help'] = 'The public key (in PEM format) provided by the tool to allow signatures of incoming messages and service requests to be verified.';
$string['quickgrade'] = 'Allow quick grading';
$string['quickgrade_help'] = 'If enabled, multiple tools can be graded on one page. Add grades and comments then click the "Save all my feedback" button to save all changes for that page.';
diff --git a/mod/lti/locallib.php b/mod/lti/locallib.php
index 7632f47c07a..da61f6eacf3 100644
--- a/mod/lti/locallib.php
+++ b/mod/lti/locallib.php
@@ -52,7 +52,8 @@ defined('MOODLE_INTERNAL') || die;
// TODO: Switch to core oauthlib once implemented - MDL-30149.
use moodle\mod\lti as lti;
-use Firebase\JWT\JWT as JWT;
+use Firebase\JWT\JWT;
+use Firebase\JWT\JWK;
global $CFG;
require_once($CFG->dirroot.'/mod/lti/OAuth.php');
@@ -90,6 +91,8 @@ define('LTI_COURSEVISIBLE_ACTIVITYCHOOSER', 2);
define('LTI_VERSION_1', 'LTI-1p0');
define('LTI_VERSION_2', 'LTI-2p0');
define('LTI_VERSION_1P3', '1.3.0');
+define('LTI_RSA_KEY', 'RSA_KEY');
+define('LTI_JWK_KEYSET', 'JWK_KEYSET');
define('LTI_DEFAULT_ORGID_SITEID', 'SITEID');
define('LTI_DEFAULT_ORGID_SITEHOST', 'SITEHOST');
@@ -1319,6 +1322,45 @@ function lti_verify_oauth_signature($typeid, $consumerkey) {
return $tool;
}
+/**
+ * Verifies the JWT signature using a JWK keyset.
+ *
+ * @param string $jwtparam JWT parameter value.
+ * @param string $keyseturl The tool keyseturl.
+ * @param string $clientid The tool client id.
+ *
+ * @return object The JWT's payload as a PHP object
+ * @throws moodle_exception
+ * @throws UnexpectedValueException Provided JWT was invalid
+ * @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
+ * @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
+ * @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
+ * @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
+ */
+function lti_verify_with_keyset($jwtparam, $keyseturl, $clientid) {
+ // Attempts to retrieve cached keyset.
+ $cache = cache::make('mod_lti', 'keyset');
+ $keyset = $cache->get($clientid);
+
+ try {
+ if (empty($keyset)) {
+ throw new moodle_exception('errornocachedkeysetfound', 'mod_lti');
+ }
+ $keysetarr = json_decode($keyset, true);
+ $keys = JWK::parseKeySet($keysetarr);
+ $jwt = JWT::decode($jwtparam, $keys, ['RS256']);
+ } catch (Exception $e) {
+ // Something went wrong, so attempt to update cached keyset and then try again.
+ $keyset = file_get_contents($keyseturl);
+ $keysetarr = json_decode($keyset, true);
+ $keys = JWK::parseKeySet($keysetarr);
+ $jwt = JWT::decode($jwtparam, $keys, ['RS256']);
+ // If sucessful, updates the cached keyset.
+ $cache->set($clientid, $keyset);
+ }
+ return $jwt;
+}
+
/**
* Verifies the JWT signature of an incoming message.
*
@@ -1336,6 +1378,7 @@ function lti_verify_oauth_signature($typeid, $consumerkey) {
*/
function lti_verify_jwt_signature($typeid, $consumerkey, $jwtparam) {
$tool = lti_get_type($typeid);
+
// Validate parameters.
if (!$tool) {
throw new moodle_exception('errortooltypenotfound', 'mod_lti');
@@ -1347,16 +1390,28 @@ function lti_verify_jwt_signature($typeid, $consumerkey, $jwtparam) {
$typeconfig = lti_get_type_config($typeid);
$key = $tool->clientid ?? '';
- $publickey = $typeconfig['publickey'] ?? '';
if ($consumerkey !== $key) {
throw new moodle_exception('errorincorrectconsumerkey', 'mod_lti');
}
- if (empty($publickey)) {
- throw new moodle_exception('No public key configured');
- }
- JWT::decode($jwtparam, $publickey, array('RS256'));
+ if (empty($typeconfig['keytype']) || $typeconfig['keytype'] === LTI_RSA_KEY) {
+ $publickey = $typeconfig['publickey'] ?? '';
+ if (empty($publickey)) {
+ throw new moodle_exception('No public key configured');
+ }
+ // Attemps to verify jwt with RSA key.
+ JWT::decode($jwtparam, $publickey, ['RS256']);
+ } else if ($typeconfig['keytype'] === LTI_JWK_KEYSET) {
+ $keyseturl = $typeconfig['publickeyset'] ?? '';
+ if (empty($keyseturl)) {
+ throw new moodle_exception('No public keyset configured');
+ }
+ // Attempts to verify jwt with jwk keyset.
+ lti_verify_with_keyset($jwtparam, $keyseturl, $tool->clientid);
+ } else {
+ throw new moodle_exception('Invalid public key type');
+ }
return $tool;
}
@@ -2476,6 +2531,12 @@ function lti_get_type_type_config($id) {
if (isset($config['publickey'])) {
$type->lti_publickey = $config['publickey'];
}
+ if (isset($config['publickeyset'])) {
+ $type->lti_publickeyset = $config['publickeyset'];
+ }
+ if (isset($config['keytype'])) {
+ $type->lti_keytype = $config['keytype'];
+ }
if (isset($config['initiatelogin'])) {
$type->lti_initiatelogin = $config['initiatelogin'];
}
diff --git a/mod/lti/tests/fixtures/test_keyset b/mod/lti/tests/fixtures/test_keyset
new file mode 100644
index 00000000000..6d8f60eb50a
--- /dev/null
+++ b/mod/lti/tests/fixtures/test_keyset
@@ -0,0 +1 @@
+{"keys":[{"kty":"RSA","kid":"701feb7a2901164add6576bfced23510","n":"tFqL_TBjryeXRp4SMLxpW7cDWuw9nag1tN8m3aLRnHj9SECzavBdOQIlXiPeKIV2i95TCTdFAxdjIoDXGqy_MUX0BRdQrWHA4pF-4bj3WgciwieJ9AVV1QH8dEgkV8vlSWQ9vuD0qYsr24ZfznMtKXXdToLtwN6Za1c0RtIJC1s8rSFIaFEQ8EZW0IgJYvYn-HJvbBL0ZZXBetTb-kKHAdhqWJs8MooehG9OjB7bvur25uc_Q32NfMvMYEA-oWcs9n5PuxgmCAgQHAHzQH4l0oWwF7nnCddhNGskIUGT4VqtbZU-ZSr3jqXg5eHhcKowP-Yl32ugUm1kKzf5RDZQG7Ci4bkhaCzliBFUpiaSezXOqeVe2rgq0pBBJZFjL6ECCWLDQMzYzUtZrAIt3qQeTcVnEgmbXQmXjPbpF5rj7xYeyZoMKY5Qe1NUZNEdFFuODIA6PZFUmOO3tUwZs9Zmk0OUX9dZzlJIa-cyyez0kben_MLnZ64T4Z3dPDzI2rmCJGoexzDXDFb-_bAZTVdGbohDBkkBEnBG2jjBnWlZdjzuRGENDkSKw8lVm2g-uc4cGIkdLfW8BpGeIOZsT3A7-o5R3D0U7hlykd-weF99QF_ZcflE71iZN80u_J-xB7DA2pdTi7TF6yDjEFaG9kYYgmvabx2qTKIcfAkOKVP4YvU","e":"AQAB","alg":"RS256","use":"sig"},{"kty":"RSA","kid":"57c1177d2d53a021c73756491c137b17","n":"tkeuoQIsfQzW8_wrmI4qCLPYccqNc9iMD5_uwy6JTVx6PQAIwlSGeAPkWpxV9RJmXKWhZ6dMxZ-vCEPqDSMI3IIvYPdVOuu-jdlxFtGfodIu0R1Nk38Q4TPnBQ3WXKaBvwpsBLdoURiHxAprFIyLy4m95-e5qB3dW0kFYbtbSHz3rz28byJ3t0SQBlSO36f2uBbn3jWC3-IMkIFiST6Ndvdj0Z7Q08qALXWG3k6R5y8oEJpNrxhyUgJypeCKsMt938tNBPDGXNVyo0dUK6DL2jJX7UpNCmv62mblfDiGrh4LCJJEcY-Mn2EtGhYczRGYVOhq8-7_GfYa7Dor7fzi-57M0cJ-ROB99YwQ415XcE-wnhSKy8Wr_K8CEPK04o8l5mUraBwRIm7N3hfMC8kez7Pu7mcA9u5Z1V5wtj6ltztZhTKjJVe-azurLjVpz8zbKl_tc6rD-mkhaXpyFTStk0jf9uYVf6fsEq3btPoxmNZgpNW1FeB5ied5ndhydDVtj8cSl4vVc4PzTKwHb99EcVC7ka_327dp7wE3ewMkPinxdWVUrtilWglVUOO6O9K6iOr5e0zHFw7l7-LMOod6mqj4RfWqvvZRaUsB89WMTvT0i5Y-Wx0ysidIEKNfFekBLOb57eb160ysoEdPfVNQ7nCJHlLjVxwO0Ez1OOwnnIE","e":"AQAB","alg":"RS256","use":"sig"}]}
\ No newline at end of file
diff --git a/mod/lti/tests/locallib_test.php b/mod/lti/tests/locallib_test.php
index 2b2f59e6a9d..1a9800ae803 100644
--- a/mod/lti/tests/locallib_test.php
+++ b/mod/lti/tests/locallib_test.php
@@ -1078,6 +1078,8 @@ V6L11BWkpzGXSW4Hv43qa+GSYOD2QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9
MwIDAQAB
-----END PUBLIC KEY-----';
+ $config->lti_keytype = LTI_RSA_KEY;
+
$typeid = lti_add_type($type, $config);
lti_verify_jwt_signature($typeid, '', 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4g' .
@@ -1087,6 +1089,46 @@ MwIDAQAB
'v7tuPWBFfEbLxtF2pZS6YC1aSfLQxeNe8djT9YjpvRZA');
}
+ /**
+ * Test lti_verify_jwt_signature_jwk().
+ */
+ public function test_lti_verify_jwt_signature_jwk() {
+ $this->resetAfterTest();
+
+ $this->setAdminUser();
+
+ // Create a tool type, associated with that proxy.
+ $type = new stdClass();
+ $type->state = LTI_TOOL_STATE_CONFIGURED;
+ $type->name = "Test tool";
+ $type->description = "Example description";
+ $type->baseurl = $this->getExternalTestFileUrl('/test.html');
+
+ $config = new stdClass();
+ $config->lti_publickeyset = dirname(__FILE__) . '/fixtures/test_keyset';
+
+ $config->lti_keytype = LTI_JWK_KEYSET;
+
+ $typeid = lti_add_type($type, $config);
+
+ $jwt = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IjU3YzExNzdkMmQ1M2EwMjFjNzM';
+ $jwt .= '3NTY0OTFjMTM3YjE3In0.eyJpc3MiOiJnclJvbkd3RTd1WjRwZ28iLCJzdWIiOiJnclJvb';
+ $jwt .= 'kd3RTd1WjRwZ28iLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0L21vb2RsZS9tb2QvbHRpL3R';
+ $jwt .= 'va2VuLnBocCIsImp0aSI6IjFlMUJPVEczVFJjbFdUem00dERsMGc9PSIsImlhdCI6MTU4M';
+ $jwt .= 'Dg1NTUwNX0.Lowhc9ovNAXRb2rkAnv1oozDXlRD54Mz2JS1i8Zx4yGWQzmXzam-La19_g0';
+ $jwt .= 'CTnwlKM6gxaInnRKFRAcwhJVcWec389liLAjMbna6d6iTWYTZr7q_4BIe3CT_oTMWASGta';
+ $jwt .= 'Paaq53ch1rO4YdueEtmtd1K47ibo4Lhu1jmP_icc3lxjfnqiv4vIYdy7W2JQEzpk1ImuQr';
+ $jwt .= 'AlO1xR3fZ6bgcJhVIaw5xoaZD3ZgEjuZOQXMkywv1bL-mL17RX336CzHd8rYZg82QXrBzb';
+ $jwt .= 'NWzAlaZxv9VSug8t6mORvM6TkYYWjqEBKemgkD5rNh1BHrPcjWP7vy2Jz7YMjLsmuvDuLK';
+ $jwt .= '_PHYIKL--s4gcXWoYmOu1vj-SgoPczTJPoiBD35hAKqVHy5ggHaYHBy95_bbcFd8H1smHw';
+ $jwt .= 'pejrAFj1QAwGyTISLzUm08oq7Ak0tSxRKKXw4lpZAka1MmYxO3tJ_3-MXw6Bwz12bNgitJ';
+ $jwt .= 'lQd6n3kkGLCJAmANeRkPsH6eZVwF0n2cjh2O1JAwyNcMD2vs4I8ftM1EqqoE2M3r6kt3AC';
+ $jwt .= 'EscmqzizI3j80USBCLUUb1UTsfJb2g7oyApJAp-13Q3InR3QyvWO8unG5VraFE7IL5I28h';
+ $jwt .= 'MkQAHuCI90DFmXB4leflAu7wNlIK_U8xkGl8X8Mnv6MWgg94Ki8jgIq_kA85JAqI';
+
+ lti_verify_jwt_signature($typeid, '', $jwt);
+ }
+
/**
* Test lti_verify_jwt_signature().
*/
@@ -1155,6 +1197,7 @@ MwIDAQAB
$type->baseurl = $this->getExternalTestFileUrl('/test.html');
$config = new stdClass();
+ $config->lti_keytype = LTI_RSA_KEY;
$typeid = lti_add_type($type, $config);
$this->expectExceptionMessage('No public key configured');
@@ -1272,6 +1315,7 @@ e+lf4s4OxQawWD79J9/5d3Ry0vbV3Am1FtGJiJvOwRsIfVChDpYStTcHTCMqtvWb
V6L11BWkpzGXSW4Hv43qa+GSYOD2QU68Mb59oSk2OB+BtOLpJofmbGEGgvmwyCI9
MwIDAQAB
-----END PUBLIC KEY-----';
+ $config->lti_keytype = LTI_RSA_KEY;
$typeid = lti_add_type($type, $config);
diff --git a/mod/lti/token.php b/mod/lti/token.php
index 3d90ca8a385..1dc2abbb1db 100644
--- a/mod/lti/token.php
+++ b/mod/lti/token.php
@@ -25,12 +25,11 @@
define('NO_DEBUG_DISPLAY', true);
define('NO_MOODLE_COOKIES', true);
-use Firebase\JWT\JWT as JWT;
+use Firebase\JWT\JWT;
require_once(__DIR__ . '/../../config.php');
require_once($CFG->dirroot . '/mod/lti/locallib.php');
-
$response = new \mod_lti\local\ltiservice\response();
$contenttype = isset($_SERVER['CONTENT_TYPE']) ? explode(';', $_SERVER['CONTENT_TYPE'], 2)[0] : '';
@@ -66,19 +65,17 @@ if ($ok) {
}
if ($ok) {
- $error = 'invalid_client';
$tool = $DB->get_record('lti_types', array('clientid' => $claims['sub']));
if ($tool) {
- $typeconfig = lti_get_type_config($tool->id);
- if (!empty($typeconfig['publickey'])) {
- try {
- $jwt = JWT::decode($clientassertion, $typeconfig['publickey'], array('RS256'));
- $ok = true;
- } catch (Exception $e) {
- $ok = false;
- }
+ try {
+ lti_verify_jwt_signature($tool->id, $claims['sub'], $clientassertion);
+ $ok = true;
+ } catch (Exception $e) {
+ $error = $e->getMessage();
+ $ok = false;
}
} else {
+ $error = 'invalid_client';
$ok = false;
}
}
@@ -86,6 +83,7 @@ if ($ok) {
if ($ok) {
$scopes = array();
$requestedscopes = explode(' ', $scope);
+ $typeconfig = lti_get_type_config($tool->id);
$permittedscopes = lti_get_permitted_service_scopes($tool, $typeconfig);
$scopes = array_intersect($requestedscopes, $permittedscopes);
$ok = !empty($scopes);
@@ -115,4 +113,4 @@ EOD;
$response->set_body($body);
-$response->send();
+$response->send();
\ No newline at end of file
diff --git a/mod/lti/version.php b/mod/lti/version.php
index 42ae63789d9..e26af0d5dd2 100644
--- a/mod/lti/version.php
+++ b/mod/lti/version.php
@@ -48,7 +48,7 @@
defined('MOODLE_INTERNAL') || die;
-$plugin->version = 2020010800; // The current module version (Date: YYYYMMDDXX).
+$plugin->version = 2020022200; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2019111200; // Requires this Moodle version.
$plugin->component = 'mod_lti'; // Full name of the plugin (used for diagnostics).
$plugin->cron = 0;