Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 400 and 401]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * This files exposes functions for LTI 1.3 Key Management.
  19   *
  20   * @package    mod_lti
  21   * @copyright  2020 Claude Vervoort (Cengage)
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  namespace mod_lti\local\ltiopenid;
  25  
  26  use Firebase\JWT\JWT;
  27  
  28  /**
  29   * This class exposes functions for LTI 1.3 Key Management.
  30   *
  31   * @package    mod_lti
  32   * @copyright  2020 Claude Vervoort (Cengage)
  33   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  34   */
  35  class jwks_helper {
  36  
  37      /**
  38       *
  39       * See https://www.imsglobal.org/spec/security/v1p1#approved-jwt-signing-algorithms.
  40       * @var string[]
  41       */
  42      private static $ltisupportedalgs = [
  43          'RS256' => 'RSA',
  44          'RS384' => 'RSA',
  45          'RS512' => 'RSA',
  46          'ES256' => 'EC',
  47          'ES384' => 'EC',
  48          'ES512' => 'EC'
  49      ];
  50  
  51      /**
  52       * Returns the private key to use to sign outgoing JWT.
  53       *
  54       * @return array keys are kid and key in PEM format.
  55       */
  56      public static function get_private_key() {
  57          $privatekey = get_config('mod_lti', 'privatekey');
  58          $kid = get_config('mod_lti', 'kid');
  59          return [
  60              "key" => $privatekey,
  61              "kid" => $kid
  62          ];
  63      }
  64  
  65      /**
  66       * Returns the JWK Key Set for this site.
  67       * @return array keyset exposting the site public key.
  68       */
  69      public static function get_jwks() {
  70          $jwks = array('keys' => array());
  71  
  72          $privatekey = self::get_private_key();
  73          $res = openssl_pkey_get_private($privatekey['key']);
  74          $details = openssl_pkey_get_details($res);
  75  
  76          // Avoid passing null values to base64_encode.
  77          if (!isset($details['rsa']['e']) || !isset($details['rsa']['n'])) {
  78              throw new \moodle_exception('Error: essential openssl keys not set');
  79          }
  80  
  81          $jwk = array();
  82          $jwk['kty'] = 'RSA';
  83          $jwk['alg'] = 'RS256';
  84          $jwk['kid'] = $privatekey['kid'];
  85          $jwk['e'] = rtrim(strtr(base64_encode($details['rsa']['e']), '+/', '-_'), '=');
  86          $jwk['n'] = rtrim(strtr(base64_encode($details['rsa']['n']), '+/', '-_'), '=');
  87          $jwk['use'] = 'sig';
  88  
  89          $jwks['keys'][] = $jwk;
  90          return $jwks;
  91      }
  92  
  93      /**
  94       * Take an array of JWKS keys and infer the 'alg' property for a single key, if missing, based on an input JWT.
  95       *
  96       * This only sets the 'alg' property for a single key when all the following conditions are met:
  97       * - The key's 'kid' matches the 'kid' provided in the JWT's header.
  98       * - The key's 'alg' is missing.
  99       * - The JWT's header 'alg' matches the algorithm family of the key (the key's kty).
 100       * - The JWT's header 'alg' matches one of the approved LTI asymmetric algorithms.
 101       *
 102       * Keys not matching the above are left unchanged.
 103       *
 104       * @param array $jwks the keyset array.
 105       * @param string $jwt the JWT string.
 106       * @return array the fixed keyset array.
 107       */
 108      public static function fix_jwks_alg(array $jwks, string $jwt): array {
 109          $jwtparts = explode('.', $jwt);
 110          $jwtheader = json_decode(JWT::urlsafeB64Decode($jwtparts[0]), true);
 111          if (!isset($jwtheader['kid'])) {
 112              throw new \moodle_exception('Error: kid must be provided in JWT header.');
 113          }
 114  
 115          foreach ($jwks['keys'] as $index => $key) {
 116              // Only fix the key being referred to in the JWT.
 117              if ($jwtheader['kid'] != $key['kid']) {
 118                  continue;
 119              }
 120  
 121              // Only fix the key if the alg is missing.
 122              if (!empty($key['alg'])) {
 123                  continue;
 124              }
 125  
 126              // The header alg must match the key type (family) specified in the JWK's kty.
 127              if (!isset(static::$ltisupportedalgs[$jwtheader['alg']]) ||
 128                      static::$ltisupportedalgs[$jwtheader['alg']] != $key['kty']) {
 129                  throw new \moodle_exception('Error: Alg specified in the JWT header is incompatible with the JWK key type');
 130              }
 131  
 132              $jwks['keys'][$index]['alg'] = $jwtheader['alg'];
 133          }
 134  
 135          return $jwks;
 136      }
 137  
 138  }