diff --git a/web/documentserver-example/php/3rd-Party.license b/web/documentserver-example/php/3rd-Party.license index 7bb4393a..a893eafb 100644 --- a/web/documentserver-example/php/3rd-Party.license +++ b/web/documentserver-example/php/3rd-Party.license @@ -19,3 +19,7 @@ License File: jQuery.iframe-transport.license jQuery.UI - jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according to jQuery's event-driven architecture (find something, manipulate it) and is themeable, making it easy for developers of any skill level to integrate and extend into their own code. (https://jquery.org/license/) License: MIT License File: jQuery.UI.license + +JWT - JSON Web Token implementation (https://github.com/firebase/php-jwt/blob/master/LICENSE) +License: BSD +License File: jwt.license diff --git a/web/documentserver-example/php/jwtmanager.php b/web/documentserver-example/php/jwtmanager.php index 5ac3840f..6ae02724 100644 --- a/web/documentserver-example/php/jwtmanager.php +++ b/web/documentserver-example/php/jwtmanager.php @@ -17,6 +17,10 @@ * */ +require_once( dirname(__FILE__) . '/lib/jwt/BeforeValidException.php' ); +require_once( dirname(__FILE__) . '/lib/jwt/ExpiredException.php' ); +require_once( dirname(__FILE__) . '/lib/jwt/SignatureInvalidException.php' ); +require_once( dirname(__FILE__) . '/lib/jwt/JWT.php' ); require_once( dirname(__FILE__) . '/config.php' ); // check if a secret key to generate token exists or not @@ -26,51 +30,17 @@ function isJwtEnabled() { // encode a payload object into a token using a secret key function jwtEncode($payload) { - $header = [ - "alg" => "HS256", // the hashing algorithm - "typ" => "JWT" // the token type - ]; - // three parts of token - $encHeader = base64UrlEncode(json_encode($header)); // header - $encPayload = base64UrlEncode(json_encode($payload)); // payload - $hash = base64UrlEncode(calculateHash($encHeader, $encPayload)); // signature - - return "$encHeader.$encPayload.$hash"; + return \Firebase\JWT\JWT::encode($payload, $GLOBALS["DOC_SERV_JWT_SECRET"]); } // decode a token into a payload object using a secret key function jwtDecode($token) { - if (!isJwtEnabled()) return ""; - - $split = explode(".", $token); - if (count($split) != 3) return ""; - - $hash = base64UrlEncode(calculateHash($split[0], $split[1])); - - if (strcmp($hash, $split[2]) != 0) return ""; - return base64UrlDecode($split[1]); -} - -// generate a hash code based on a key using the HMAC method -function calculateHash($encHeader, $encPayload) { - return hash_hmac("sha256", "$encHeader.$encPayload", $GLOBALS['DOC_SERV_JWT_SECRET'], true); -} - -// encode a string into the base64 value -function base64UrlEncode($str) { - return str_replace("/", "_", str_replace("+", "-", trim(base64_encode($str), "="))); -} - -// decode a base64 value into the string -function base64UrlDecode($payload) { - $b64 = str_replace("_", "/", str_replace("-", "+", $payload)); - switch (strlen($b64) % 4) { - case 2: - $b64 = $b64 . "=="; break; - case 3: - $b64 = $b64 . "="; break; + try { + $payload = \Firebase\JWT\JWT::decode($token, $GLOBALS["DOC_SERV_JWT_SECRET"], array("HS256")); + } catch (\UnexpectedValueException $e) { + $payload = ""; } - return base64_decode($b64); -} + return $payload; +} ?> \ No newline at end of file diff --git a/web/documentserver-example/php/lib/jwt/BeforeValidException.php b/web/documentserver-example/php/lib/jwt/BeforeValidException.php new file mode 100644 index 00000000..a6ee2f7c --- /dev/null +++ b/web/documentserver-example/php/lib/jwt/BeforeValidException.php @@ -0,0 +1,7 @@ + + * @author Anant Narayanan + * @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD + * @link https://github.com/firebase/php-jwt + */ +class JWT +{ + + /** + * When checking nbf, iat or expiration times, + * we want to provide some extra leeway time to + * account for clock skew. + */ + public static $leeway = 0; + + /** + * Allow the current timestamp to be specified. + * Useful for fixing a value within unit testing. + * + * Will default to PHP time() value if null. + */ + public static $timestamp = null; + + public static $supported_algs = array( + 'HS256' => array('hash_hmac', 'SHA256'), + 'HS512' => array('hash_hmac', 'SHA512'), + 'HS384' => array('hash_hmac', 'SHA384'), + 'RS256' => array('openssl', 'SHA256'), + ); + + /** + * 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' + * + * @return object The JWT's payload as a PHP object + * + * @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 + * + * @uses jsonDecode + * @uses urlsafeB64Decode + */ + public static function decode($jwt, $key, $allowed_algs = array()) + { + $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp; + + if (empty($key)) { + throw new InvalidArgumentException('Key may not be empty'); + } + if (!is_array($allowed_algs)) { + throw new InvalidArgumentException('Algorithm not allowed'); + } + $tks = explode('.', $jwt); + if (count($tks) != 3) { + throw new UnexpectedValueException('Wrong number of segments'); + } + list($headb64, $bodyb64, $cryptob64) = $tks; + if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) { + throw new UnexpectedValueException('Invalid header encoding'); + } + if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) { + throw new UnexpectedValueException('Invalid claims encoding'); + } + $sig = static::urlsafeB64Decode($cryptob64); + + if (empty($header->alg)) { + throw new UnexpectedValueException('Empty algorithm'); + } + if (empty(static::$supported_algs[$header->alg])) { + throw new UnexpectedValueException('Algorithm not supported'); + } + if (!in_array($header->alg, $allowed_algs)) { + throw new UnexpectedValueException('Algorithm not allowed'); + } + if (is_array($key) || $key instanceof \ArrayAccess) { + if (isset($header->kid)) { + $key = $key[$header->kid]; + } else { + throw new UnexpectedValueException('"kid" empty, unable to lookup correct key'); + } + } + + // Check the signature + if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) { + throw new SignatureInvalidException('Signature verification failed'); + } + + // Check if 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) + ); + } + + // Check that this token has been created before 'now'. This prevents + // using tokens that have been created for later use (and haven't + // 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) + ); + } + + // Check if this token has expired. + if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) { + throw new ExpiredException('Expired token'); + } + + return $payload; + } + + /** + * Converts and signs a PHP object or array into a JWT string. + * + * @param object|array $payload PHP object or array + * @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' + * @param mixed $keyId + * @param array $head An array with header elements to attach + * + * @return string A signed JWT + * + * @uses jsonEncode + * @uses urlsafeB64Encode + */ + public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null) + { + $header = array('typ' => 'JWT', 'alg' => $alg); + if ($keyId !== null) { + $header['kid'] = $keyId; + } + 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); + + $signature = static::sign($signing_input, $key, $alg); + $segments[] = static::urlsafeB64Encode($signature); + + return implode('.', $segments); + } + + /** + * Sign a string with a given key and algorithm. + * + * @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' + * + * @return string An encrypted message + * + * @throws DomainException Unsupported algorithm was specified + */ + public static function sign($msg, $key, $alg = 'HS256') + { + if (empty(static::$supported_algs[$alg])) { + throw new DomainException('Algorithm not supported'); + } + list($function, $algorithm) = static::$supported_algs[$alg]; + switch($function) { + case 'hash_hmac': + return hash_hmac($algorithm, $msg, $key, true); + case 'openssl': + $signature = ''; + $success = openssl_sign($msg, $signature, $key, $algorithm); + if (!$success) { + throw new DomainException("OpenSSL unable to sign data"); + } else { + return $signature; + } + } + } + + /** + * Verify a signature with the message, key and method. Not all methods + * are symmetric, so we must have a separate verify and sign method. + * + * @param string $msg The original message (header and body) + * @param string $signature The original signature + * @param string|resource $key For HS*, a string key works. for RS*, must be a resource of an openssl public key + * @param string $alg The algorithm + * + * @return bool + * + * @throws DomainException Invalid Algorithm or OpenSSL failure + */ + private static function verify($msg, $signature, $key, $alg) + { + if (empty(static::$supported_algs[$alg])) { + throw new DomainException('Algorithm not supported'); + } + + list($function, $algorithm) = static::$supported_algs[$alg]; + switch($function) { + case 'openssl': + $success = openssl_verify($msg, $signature, $key, $algorithm); + if (!$success) { + throw new DomainException("OpenSSL unable to verify data: " . openssl_error_string()); + } else { + return $signature; + } + case 'hash_hmac': + default: + $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)); + + $status = 0; + for ($i = 0; $i < $len; $i++) { + $status |= (ord($signature[$i]) ^ ord($hash[$i])); + } + $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash)); + + return ($status === 0); + } + } + + /** + * Decode a JSON string into a PHP object. + * + * @param string $input JSON string + * + * @return object Object representation of JSON string + * + * @throws DomainException Provided string was invalid JSON + */ + public static function jsonDecode($input) + { + 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); + } 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); + } + + if (function_exists('json_last_error') && $errno = json_last_error()) { + static::handleJsonError($errno); + } elseif ($obj === null && $input !== 'null') { + throw new DomainException('Null result with non-null input'); + } + return $obj; + } + + /** + * Encode a PHP object into a JSON string. + * + * @param object|array $input A PHP object or array + * + * @return string JSON representation of the PHP object or array + * + * @throws DomainException Provided object could not be encoded to valid JSON + */ + public static function jsonEncode($input) + { + $json = json_encode($input); + if (function_exists('json_last_error') && $errno = json_last_error()) { + static::handleJsonError($errno); + } elseif ($json === 'null' && $input !== null) { + throw new DomainException('Null result with non-null input'); + } + return $json; + } + + /** + * Decode a string with URL-safe Base64. + * + * @param string $input A Base64 encoded string + * + * @return string A decoded string + */ + public static function urlsafeB64Decode($input) + { + $remainder = strlen($input) % 4; + if ($remainder) { + $padlen = 4 - $remainder; + $input .= str_repeat('=', $padlen); + } + return base64_decode(strtr($input, '-_', '+/')); + } + + /** + * Encode a string with URL-safe Base64. + * + * @param string $input The string you want encoded + * + * @return string The base64 encode of what you passed in + */ + public static function urlsafeB64Encode($input) + { + return str_replace('=', '', strtr(base64_encode($input), '+/', '-_')); + } + + /** + * Helper method to create a JSON error. + * + * @param int $errno An error number from json_last_error() + * + * @return void + */ + private static function handleJsonError($errno) + { + $messages = array( + JSON_ERROR_DEPTH => 'Maximum stack depth exceeded', + JSON_ERROR_CTRL_CHAR => 'Unexpected control character found', + JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON' + ); + throw new DomainException( + isset($messages[$errno]) + ? $messages[$errno] + : 'Unknown JSON error: ' . $errno + ); + } + + /** + * Get the number of bytes in cryptographic strings. + * + * @param string + * + * @return int + */ + private static function safeStrlen($str) + { + if (function_exists('mb_strlen')) { + return mb_strlen($str, '8bit'); + } + return strlen($str); + } +} diff --git a/web/documentserver-example/php/lib/jwt/LICENSE b/web/documentserver-example/php/lib/jwt/LICENSE new file mode 100644 index 00000000..cb0c49b3 --- /dev/null +++ b/web/documentserver-example/php/lib/jwt/LICENSE @@ -0,0 +1,30 @@ +Copyright (c) 2011, Neuman Vong + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of Neuman Vong nor the names of other + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/web/documentserver-example/php/lib/jwt/SignatureInvalidException.php b/web/documentserver-example/php/lib/jwt/SignatureInvalidException.php new file mode 100644 index 00000000..27332b21 --- /dev/null +++ b/web/documentserver-example/php/lib/jwt/SignatureInvalidException.php @@ -0,0 +1,7 @@ += 5.2.0 + $data = json_decode($body_stream, false); // check if the response is correct if ($data === NULL) { @@ -47,27 +47,29 @@ function readBody() { sendlog(" jwt enabled, checking tokens", "webedior-ajax.log"); $inHeader = false; - $token = ""; + $data = ""; $jwtHeader = $GLOBALS['DOC_SERV_JWT_HEADER'] == "" ? "Authorization" : $GLOBALS['DOC_SERV_JWT_HEADER']; if (!empty($data["token"])) { // if the document token is in the data - $token = jwtDecode($data["token"]); // decode it + $data = jwtDecode($data["token"]); // decode it + sendlog(" jwt in body", "webedior-ajax.log"); } elseif (!empty(apache_request_headers()[$jwtHeader])) { // if the Authorization header exists - $token = jwtDecode(substr(apache_request_headers()[$jwtHeader], strlen("Bearer "))); // decode its part after Authorization prefix + $data = jwtDecode(substr(apache_request_headers()[$jwtHeader], strlen("Bearer "))); // decode its part after Authorization prefix $inHeader = true; + sendlog(" jwt in header", "webedior-ajax.log"); } else { // otherwise, an error occurs sendlog(" jwt token wasn't found in body or headers", "webedior-ajax.log"); $result["error"] = "Expected JWT"; return $result; } - if (empty($token)) { // invalid signature error + + if ($data === "") { // invalid signature error sendlog(" token was found but signature is invalid", "webedior-ajax.log"); $result["error"] = "Invalid JWT signature"; return $result; } - $data = json_decode($token, true); - if ($inHeader) $data = $data["payload"]; + if ($inHeader) $data = $data->payload; } return $data; @@ -75,14 +77,14 @@ function readBody() { // file saving process function processSave($data, $fileName, $userAddress) { - $downloadUri = $data["url"]; + $downloadUri = $data->url; if ($downloadUri === null) { $result["error"] = 1; return $result; } $curExt = strtolower('.' . pathinfo($fileName, PATHINFO_EXTENSION)); // get current file extension - $downloadExt = strtolower('.' . $data["filetype"]); // get the extension of the downloaded file + $downloadExt = strtolower('.' . $data->filetype); // get the extension of the downloaded file // TODO [Delete in version 7.0 or higher] if (!$downloadExt) $downloadExt = strtolower('.' . pathinfo($downloadUri, PATHINFO_EXTENSION)); // Support for versions below 7.0 @@ -123,18 +125,18 @@ function processSave($data, $fileName, $userAddress) { rename(getStoragePath($fileName, $userAddress), $verDir . DIRECTORY_SEPARATOR . "prev" . $curExt); // get the path to the previous file version and rename the storage path with it file_put_contents($storagePath, $new_data, LOCK_EX); // save file to the storage directory - if ($changesData = file_get_contents($data["changesurl"])) { + if ($changesData = file_get_contents($data->changesurl)) { file_put_contents($verDir . DIRECTORY_SEPARATOR . "diff.zip", $changesData, LOCK_EX); // save file changes to the diff.zip archive } - $histData = empty($data["changeshistory"]) ? null : $data["changeshistory"]; + $histData = empty($data->changeshistory) ? null : $data->changeshistory; if (empty($histData)) { - $histData = json_encode($data["history"], JSON_PRETTY_PRINT); + $histData = json_encode($data->history, JSON_PRETTY_PRINT); } if (!empty($histData)) { file_put_contents($verDir . DIRECTORY_SEPARATOR . "changes.json", $histData, LOCK_EX); // write the history changes to the changes.json file } - file_put_contents($verDir . DIRECTORY_SEPARATOR . "key.txt", $data["key"], LOCK_EX); // write the key value to the key.txt file + file_put_contents($verDir . DIRECTORY_SEPARATOR . "key.txt", $data->key, LOCK_EX); // write the key value to the key.txt file $forcesavePath = getForcesavePath($newFileName, $userAddress, false); // get the path to the forcesaved file version if ($forcesavePath != "") { // if the forcesaved file version exists @@ -151,14 +153,14 @@ function processSave($data, $fileName, $userAddress) { // file force saving process function processForceSave($data, $fileName, $userAddress) { - $downloadUri = $data["url"]; + $downloadUri = $data->url; if ($downloadUri === null) { $result["error"] = 1; return $result; } $curExt = strtolower('.' . pathinfo($fileName, PATHINFO_EXTENSION)); // get current file extension - $downloadExt = strtolower('.' . $data["filetype"]); // get the extension of the downloaded file + $downloadExt = strtolower('.' . $data->filetype); // get the extension of the downloaded file // TODO [Delete in version 7.0 or higher] if (!$downloadExt) $downloadExt = strtolower('.' . pathinfo($downloadUri, PATHINFO_EXTENSION)); // Support for versions below 7.0 @@ -190,7 +192,7 @@ function processForceSave($data, $fileName, $userAddress) { if (!(($new_data = file_get_contents($downloadUri)) === FALSE)) { $baseNameWithoutExt = substr($fileName, 0, strlen($fileName) - strlen($curExt)); - $isSubmitForm = $data["forcesavetype"] == 3; // SubmitForm + $isSubmitForm = $data->forcesavetype == 3; // SubmitForm if ($isSubmitForm) { if ($newFileName){ @@ -213,7 +215,7 @@ function processForceSave($data, $fileName, $userAddress) { file_put_contents($forcesavePath, $new_data, LOCK_EX); if ($isSubmitForm) { - $uid = $data["actions"][0]["userid"]; // get the user id + $uid = $data->actions[0]->userid; // get the user id createMeta($fileName, $uid, "Filling Form", $userAddress); // create meta data for the forcesaved file } diff --git a/web/documentserver-example/php/webeditor-ajax.php b/web/documentserver-example/php/webeditor-ajax.php index 9444a600..e825ed47 100755 --- a/web/documentserver-example/php/webeditor-ajax.php +++ b/web/documentserver-example/php/webeditor-ajax.php @@ -215,22 +215,24 @@ function track() { // get the body of the post request and check if it is correct $data = readBody(); - if (!empty($data["error"])){ + + if (!empty($data->error)){ return $data; } global $_trackerStatus; - $status = $_trackerStatus[$data["status"]]; // get status from the request body + $status = $_trackerStatus[$data->status]; // get status from the request body $userAddress = $_GET["userAddress"]; $fileName = basename($_GET["fileName"]); + sendlog(" CommandRequest status: " . $data->status, "webedior-ajax.log"); switch ($status) { case "Editing": // status == 1 - if ($data["actions"] && $data["actions"][0]["type"] == 0) { // finished edit - $user = $data["actions"][0]["userid"]; // the user who finished editing - if (array_search($user, $data["users"]) === FALSE) { - $commandRequest = commandRequest("forcesave", $data["key"]); // create a command request with the forcasave method + if ($data->actions && $data->actions[0]->type == 0) { // finished edit + $user = $data->actions[0]->userid; // the user who finished editing + if (array_search($user, $data->users) === FALSE) { + $commandRequest = commandRequest("forcesave", $data->key); // create a command request with the forcasave method sendlog(" CommandRequest forcesave: " . serialize($commandRequest), "webedior-ajax.log"); } }