From 7d66104eca69a9b34239bf88c3bab1dd7f791073 Mon Sep 17 00:00:00 2001 From: nilsteampassnet Date: Sun, 24 Nov 2024 06:57:15 +0100 Subject: [PATCH 1/3] Some servers cannot be customized in depth. This PR restores standard upload parameters. It fixes also the backup restore process providing more feedback (%). --- includes/config/include.php | 2 +- pages/backups.js.php | 12 ++++---- sources/admin.queries.php | 10 ++----- sources/backups.queries.php | 60 ++++++++++++++++++++++++------------- sources/logs.datatables.php | 26 ++++++++-------- sources/main.functions.php | 15 ++++------ sources/main.queries.php | 1 - sources/upload.files.php | 8 +++++ 8 files changed, 77 insertions(+), 57 deletions(-) diff --git a/includes/config/include.php b/includes/config/include.php index 7bb2d84a7..f22b8c133 100755 --- a/includes/config/include.php +++ b/includes/config/include.php @@ -28,7 +28,7 @@ define('TP_VERSION', '3.1.2'); define("UPGRADE_MIN_DATE", "1732264740"); -define('TP_VERSION_MINOR', '167'); +define('TP_VERSION_MINOR', '168'); define('TP_TOOL_NAME', 'Teampass'); define('TP_ONE_DAY_SECONDS', 86400); define('TP_ONE_WEEK_SECONDS', 604800); diff --git a/pages/backups.js.php b/pages/backups.js.php index 867da1f0f..053f22c5b 100755 --- a/pages/backups.js.php +++ b/pages/backups.js.php @@ -294,8 +294,6 @@ function(response) { function updateProgressBar(offset, totalSize) { // Show progress to user var percentage = Math.round((offset / totalSize) * 100); - //var message = 'get('restore_in_progress');?> ' + percentage + '%'; - //console.log(message) $('#onthefly-restore-progress-text').text(percentage); } @@ -314,13 +312,14 @@ function updateProgressBar(offset, totalSize) { : $SETTINGS['upload_maxfilesize']; ?> + let toastrElement; var restoreOperationId = '', uploader_restoreDB = new plupload.Uploader({ runtimes: "gears,html5,flash,silverlight,browserplus", browse_button: "onthefly-restore-file-select", container: "onthefly-restore-file", max_file_size: "", - chunk_size: "5mb", + chunk_size: "2mb", // adapted to standard PHP configuration unique_names: true, dragdrop: true, multiple_queues: false, @@ -364,8 +363,7 @@ function(teampassUser) { BeforeUpload: function(up, file) { // Show cog toastr.remove(); - toastr.info('get('loading_item'); ?> ... '); - console.log("Upload token: "+store.get('teampassUser').uploadToken); + toastrElement = toastr.info('get('loading_item'); ?> ... 0%'); up.setOption('multipart_params', { PHPSESSID: 'get('user-id'); ?>', @@ -374,6 +372,10 @@ function(teampassUser) { user_token: store.get('teampassUser').uploadToken }); }, + UploadProgress: function(up, file) { + // Update only the percentage inside the Toastr message + $('#plupload-progress').text(file.percent + '%'); + }, UploadComplete: function(up, files) { store.update( 'teampassUser', diff --git a/sources/admin.queries.php b/sources/admin.queries.php index b348ccf39..ff8e5840a 100755 --- a/sources/admin.queries.php +++ b/sources/admin.queries.php @@ -206,7 +206,6 @@ 'encrypt', $SETTINGS['path_to_files_folder'] . '/' . $filename, $SETTINGS['path_to_files_folder'] . '/defuse_temp_' . $filename, - $SETTINGS, $post_option ); @@ -283,7 +282,6 @@ 'decrypt', $SETTINGS['path_to_files_folder'] . '/' . $file, $SETTINGS['path_to_files_folder'] . '/defuse_temp_' . $file, - $SETTINGS, $key ); @@ -890,8 +888,7 @@ prepareFileWithDefuse( 'decrypt', $SETTINGS['path_to_upload_folder'] . '/' . $record['file'], - $SETTINGS['path_to_upload_folder'] . '/' . $record['file'] . '_encrypted', - $SETTINGS + $SETTINGS['path_to_upload_folder'] . '/' . $record['file'] . '_encrypted' ); // Do cleanup of files @@ -901,8 +898,7 @@ prepareFileWithDefuse( 'encryp', $SETTINGS['path_to_upload_folder'] . '/' . $record['file'] . '_encrypted', - $SETTINGS['path_to_upload_folder'] . '/' . $record['file'], - $SETTINGS + $SETTINGS['path_to_upload_folder'] . '/' . $record['file'] ); // Do cleanup of files @@ -1476,7 +1472,6 @@ 'decrypt', $SETTINGS['path_to_upload_folder'] . '/' . $file_info['file'], $SETTINGS['path_to_upload_folder'] . '/defuse_temp_' . $file_info['file'], - $SETTINGS ); // Case where we want to encrypt } elseif ($post_option === 'encrypt') { @@ -1484,7 +1479,6 @@ 'encrypt', $SETTINGS['path_to_upload_folder'] . '/' . $file_info['file'], $SETTINGS['path_to_upload_folder'] . '/defuse_temp_' . $file_info['file'], - $SETTINGS ); } // Do file cleanup diff --git a/sources/backups.queries.php b/sources/backups.queries.php index 12e118f16..02208a96d 100755 --- a/sources/backups.queries.php +++ b/sources/backups.queries.php @@ -173,7 +173,7 @@ while ($row = $result->fetch_row()) { $return .= 'INSERT INTO ' . $table . ' VALUES('; for ($j = 0; $j < $numFields; ++$j) { - // Gestion des valeurs NULL + // Manage NULL values $value = $row[$j] === null ? 'NULL' : '"' . addslashes(preg_replace("/\n/", '\\n', $row[$j])) . '"'; $return .= $value; if ($j < ($numFields - 1)) { @@ -199,7 +199,7 @@ fwrite($handle, $return); fclose($handle); } - + // Encrypt the file if (empty($post_key) === false) { // Encrypt the file @@ -207,7 +207,6 @@ 'encrypt', $SETTINGS['path_to_files_folder'] . '/' . $filename, $SETTINGS['path_to_files_folder'] . '/defuse_temp_' . $filename, - $SETTINGS, $post_key ); @@ -287,10 +286,22 @@ $post_backupFile = filter_var($dataReceived['backupFile'], FILTER_SANITIZE_FULL_SPECIAL_CHARS); $post_clearFilename = filter_var($dataReceived['clearFilename'], FILTER_SANITIZE_FULL_SPECIAL_CHARS); $post_offset = (int) filter_var($dataReceived['offset'], FILTER_SANITIZE_NUMBER_INT); - $post_totalSize = (int) filter_var($dataReceived['post_totalSize'], FILTER_SANITIZE_NUMBER_INT); + $post_totalSize = (int) filter_var($dataReceived['totalSize'], FILTER_SANITIZE_NUMBER_INT); $batchSize = 500; - if (WIP === true) error_log('DEBUG: Offset -> '.$post_offset.' | File -> '.$post_clearFilename.' | key -> '.$post_key); + // Check if the offset is greater than the total size + if (empty($post_offset) === false && $post_offset >= $post_totalSize) { + echo prepareExchangedData( + array( + 'error' => false, + 'message' => 'operation_finished', + ), + 'encode' + ); + break; + } + + if (WIP === true) error_log('DEBUG: Offset -> '.$post_offset.'/'.$post_totalSize.' | File -> '.$post_clearFilename.' | key -> '.$post_key); include_once $SETTINGS['cpassman_dir'] . '/sources/main.functions.php'; @@ -311,19 +322,19 @@ ); $post_backupFile = $data['valeur']; - - // Uncrypt the file + + // Decrypt the file if (empty($post_key) === false) { // Decrypt the file + $ret = prepareFileWithDefuse( 'decrypt', $SETTINGS['path_to_files_folder'] . '/' . $post_backupFile, $SETTINGS['path_to_files_folder'] . '/defuse_temp_' . $post_backupFile, - $SETTINGS, $post_key ); - - if (empty($ret) === false) { + + if (empty($ret) === false && $ret !== true) { echo prepareExchangedData( array( 'error' => true, @@ -338,11 +349,19 @@ fileDelete($SETTINGS['path_to_files_folder'] . '/' . $post_backupFile, $SETTINGS); $post_backupFile = $SETTINGS['path_to_files_folder'] . '/defuse_temp_' . $post_backupFile; } else { - $post_backupFile = $SETTINGS['path_to_files_folder'] . '/' . $post_backupFile; + echo prepareExchangedData( + array( + 'error' => true, + 'message' => 'An error occurred. No encryption key provided.', + ), + 'encode' + ); + break; } } else { $post_backupFile = $post_clearFilename; } + //read sql file $handle = fopen($post_backupFile, 'r'); @@ -353,20 +372,19 @@ } if ($handle !== false) { - // Déplacer le pointeur de fichier à l'offset actuel + // Move the file pointer to the current offset fseek($handle, $post_offset); - $query = ''; $executedQueries = 0; while (!feof($handle) && $executedQueries < $batchSize) { $line = fgets($handle); // Check if not false if ($line !== false) { - // Vérifier si la ligne est une partie d'une instruction SQL + // Check if the line is part of an SQL statement if (substr(trim($line), -1) != ';') { $query .= $line; } else { - // Exécuter l'instruction SQL complète + // Execute the complete SQL statement $query .= $line; DB::queryRaw($query); $query = ''; @@ -375,14 +393,14 @@ } } - // Calculer le nouvel offset + // Calculate the new offset $newOffset = ftell($handle); - // Vérifier si la fin du fichier a été atteinte + // Check if the end of the file has been reached $isEndOfFile = feof($handle); fclose($handle); - // Répondre avec le nouvel offset + // Respond with the new offset echo prepareExchangedData( array( 'error' => false, @@ -393,12 +411,13 @@ 'encode' ); - // Vérifier si la fin du fichier a été atteinte pour supprimer le fichier + // Check if the end of the file has been reached to delete the file if ($isEndOfFile) { + error_log('DEBUG: End of file reached. Deleting file '.$post_backupFile); unlink($post_backupFile); } } else { - // Gérer l'erreur d'ouverture du fichier + // Handle file opening error echo prepareExchangedData( array( 'error' => true, @@ -410,3 +429,4 @@ break; } } + diff --git a/sources/logs.datatables.php b/sources/logs.datatables.php index 727cb3931..9b6376dcf 100755 --- a/sources/logs.datatables.php +++ b/sources/logs.datatables.php @@ -148,7 +148,7 @@ 'SELECT COUNT(*) FROM '.prefixTable('log_system').' as l INNER JOIN '.prefixTable('users').' as u ON (l.qui=u.id) - WHERE %l ORDER BY %s %s', + WHERE %l ORDER BY %l %l', $sWhere, $orderColumn, $orderDirection @@ -221,7 +221,7 @@ FROM '.prefixTable('log_items').' as l INNER JOIN '.prefixTable('items').' as i ON (l.id_item=i.id) INNER JOIN '.prefixTable('users').' as u ON (l.id_user=u.id) - WHERE %l ORDER BY %s %s', + WHERE %l ORDER BY %l %l', $sWhere, $orderColumn, $orderDirection @@ -294,7 +294,7 @@ FROM '.prefixTable('log_items').' as l INNER JOIN '.prefixTable('items').' as i ON (l.id_item=i.id) INNER JOIN '.prefixTable('users').' as u ON (l.id_user=u.id) - WHERE %l ORDER BY %s %s', + WHERE %l ORDER BY %l %l', $sWhere, $orderColumn, $orderDirection @@ -368,7 +368,7 @@ 'SELECT COUNT(*) FROM '.prefixTable('log_system').' as l INNER JOIN '.prefixTable('users').' as u ON (l.qui=u.id) - WHERE %l ORDER BY %s %s', + WHERE %l ORDER BY %l %l', $sWhere, $orderColumn, $orderDirection @@ -468,7 +468,7 @@ INNER JOIN '.prefixTable('items').' AS i ON (l.id_item=i.id) INNER JOIN '.prefixTable('users').' AS u ON (l.id_user=u.id) INNER JOIN '.prefixTable('nested_tree').' AS t ON (i.id_tree=t.id) - WHERE %l ORDER BY %s %s', + WHERE %l ORDER BY %l %l', $sWhere, $orderColumn, $orderDirection @@ -551,7 +551,7 @@ $iTotal = DB::queryFirstField( 'SELECT COUNT(*) FROM '.prefixTable('log_system').' as l - WHERE %l ORDER BY %s %s', + WHERE %l ORDER BY %l %l', $sWhere, $orderColumn, $orderDirection @@ -627,7 +627,7 @@ 'SELECT COUNT(*) FROM '.prefixTable('log_system').' as l INNER JOIN '.prefixTable('users').' as u ON (l.qui=u.id) - WHERE %l ORDER BY %s %s', + WHERE %l ORDER BY %l %l', $sWhere, $orderColumn, $orderDirection @@ -697,7 +697,7 @@ FROM '.prefixTable('items_edition').' AS e INNER JOIN '.prefixTable('items').' as i ON (e.item_id=i.id) INNER JOIN '.prefixTable('users').' as u ON (e.user_id=u.id) - WHERE %l ORDER BY %s %s', + WHERE %l ORDER BY %l %l', $sWhere, $orderColumn, $orderDirection @@ -773,7 +773,7 @@ $iTotal = DB::queryFirstField( 'SELECT COUNT(*) FROM '.prefixTable('users').' - WHERE %l ORDER BY %s %s', + WHERE %l ORDER BY %l %l', $sWhere, $orderColumn, $orderDirection @@ -855,7 +855,7 @@ 'SELECT COUNT(*) FROM '.prefixTable('background_tasks').' AS p LEFT JOIN '.prefixTable('users').' AS u ON %l - WHERE %l ORDER BY %s %s', + WHERE %l ORDER BY %l %l', 'u.id = json_extract(p.arguments, "$[0]")', $sWhere, $orderColumn, @@ -866,7 +866,7 @@ $sql = 'SELECT p.increment_id, p.created_at, p.updated_at, p.process_type, p.is_in_progress FROM '.prefixTable('background_tasks').' AS p LEFT JOIN '.prefixTable('users').' AS u ON %l - WHERE %l ORDER BY %s %s LIMIT %i, %i'; + WHERE %l ORDER BY %l %l LIMIT %i, %i'; $params = ['u.id = json_extract(p.arguments, "$[0]")',$sWhere, $orderColumn, $orderDirection, $sLimitStart, $sLimitLength]; // Get the records @@ -945,7 +945,7 @@ 'SELECT COUNT(*) FROM '.prefixTable('background_tasks').' AS p LEFT JOIN '.prefixTable('users').' AS u ON u.id = json_extract(p.arguments, "$[0]") - WHERE %l ORDER BY %s %s', + WHERE %l ORDER BY %l %l', $sWhere, $orderColumn, $orderDirection @@ -955,7 +955,7 @@ $sql = 'SELECT p.* FROM '.prefixTable('background_tasks').' AS p LEFT JOIN '.prefixTable('users').' AS u ON %l - WHERE %l ORDER BY %s %s LIMIT %i, %i'; + WHERE %l ORDER BY %l %l LIMIT %i, %i'; $params = ['u.id = json_extract(p.arguments, "$[0]")',$sWhere, $orderColumn, $orderDirection, $sLimitStart, $sLimitLength]; // Get the records diff --git a/sources/main.functions.php b/sources/main.functions.php index 4665b89f1..aaf3e868f 100755 --- a/sources/main.functions.php +++ b/sources/main.functions.php @@ -1865,7 +1865,6 @@ function prepareFileWithDefuse( string $type, string $source_file, string $target_file, - array $SETTINGS, string $password = null ) { // Load AntiXSS @@ -1890,7 +1889,6 @@ function prepareFileWithDefuse( $err = defuseFileDecrypt( $source_file, $target_file, - $SETTINGS, /** @scrutinizer ignore-type */ $password ); } elseif ($type === 'encrypt') { @@ -1898,7 +1896,6 @@ function prepareFileWithDefuse( $err = defuseFileEncrypt( $source_file, $target_file, - $SETTINGS, /** @scrutinizer ignore-type */ $password ); } @@ -1920,9 +1917,9 @@ function prepareFileWithDefuse( function defuseFileEncrypt( string $source_file, string $target_file, - array $SETTINGS, string $password = null ) { + $err = ''; try { CryptoFile::encryptFileWithPassword( $source_file, @@ -1932,9 +1929,9 @@ function defuseFileEncrypt( } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) { $err = 'wrong_key'; } catch (CryptoException\EnvironmentIsBrokenException $ex) { - $err = $ex; + $err = print_r($ex, true); } catch (CryptoException\IOException $ex) { - $err = $ex; + $err = print_r($ex, true); } // return error @@ -1954,9 +1951,9 @@ function defuseFileEncrypt( function defuseFileDecrypt( string $source_file, string $target_file, - array $SETTINGS, string $password = null ) { + $err = ''; try { CryptoFile::decryptFileWithPassword( $source_file, @@ -1966,9 +1963,9 @@ function defuseFileDecrypt( } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) { $err = 'wrong_key'; } catch (CryptoException\EnvironmentIsBrokenException $ex) { - $err = $ex; + $err = print_r($ex, true); } catch (CryptoException\IOException $ex) { - $err = $ex; + $err = print_r($ex, true); } // return error diff --git a/sources/main.queries.php b/sources/main.queries.php index 0d5f35d45..7b804ff57 100755 --- a/sources/main.queries.php +++ b/sources/main.queries.php @@ -2968,7 +2968,6 @@ function migrateTo3_DoUserPersonalItemsEncryption( 'decrypt', $SETTINGS['path_to_upload_folder'] . '/' . $record2['file'], $SETTINGS['path_to_upload_folder'] . '/' . $record2['file'] . '.delete', - $SETTINGS, $post_user_psk ); diff --git a/sources/upload.files.php b/sources/upload.files.php index f441761e0..2e35d7b87 100755 --- a/sources/upload.files.php +++ b/sources/upload.files.php @@ -422,6 +422,14 @@ rename("{$filePath}.part", $filePath); } else { // continue uploading other chunks + echo prepareExchangedData( + array( + 'error' => false, + 'chunk' => (int) $chunk + 1, + 'chunks' => $chunks, + ), + 'encode' + ); die(); } From 2a07e22d2b9c08f6db314bba09086535cea8bff0 Mon Sep 17 00:00:00 2001 From: nilsteampassnet Date: Sun, 24 Nov 2024 09:49:57 +0100 Subject: [PATCH 2/3] Added some few improvements in file size management --- includes/config/include.php | 2 +- pages/import.js.php | 13 ------- pages/items.js.php | 69 ++++++++++++++++++++++++---------- sources/upload.attachments.php | 36 +++++++++++++----- 4 files changed, 78 insertions(+), 42 deletions(-) diff --git a/includes/config/include.php b/includes/config/include.php index f22b8c133..4a4d6ce69 100755 --- a/includes/config/include.php +++ b/includes/config/include.php @@ -28,7 +28,7 @@ define('TP_VERSION', '3.1.2'); define("UPGRADE_MIN_DATE", "1732264740"); -define('TP_VERSION_MINOR', '168'); +define('TP_VERSION_MINOR', '169'); define('TP_TOOL_NAME', 'Teampass'); define('TP_ONE_DAY_SECONDS', 86400); define('TP_ONE_WEEK_SECONDS', 604800); diff --git a/pages/import.js.php b/pages/import.js.php index 0ea5af7af..f1e76c725 100755 --- a/pages/import.js.php +++ b/pages/import.js.php @@ -142,21 +142,8 @@ function(teampassApplication) { PHPSESSID: 'get('key'); ?>', type_upload: "import_items_from_csv", user_token: data[0].token - /*itemId: store.get('teampassItem').id, - type_upload: 'item_attachments', - isNewItem: store.get('teampassItem').isNewItem, - isPersonal: store.get('teampassItem').folderIsPersonal, - edit_item: false, - user_upload_token: store.get('teampassApplication').attachmentToken, - randomId: store.get('teampassApplication').uploadedFileId, - files_number: $('#form-item-hidden-pickFilesNumber').val(), - file_size: file.size*/ }); - /*up.settings.multipart_params.PHPSESSID = ""; - up.settings.multipart_params.type_upload = "import_items_from_csv"; - up.settings.multipart_params.user_token = data[0].token;*/ - up.start(); }, "json" diff --git a/pages/items.js.php b/pages/items.js.php index df9d52cc8..77fc2df53 100755 --- a/pages/items.js.php +++ b/pages/items.js.php @@ -2760,6 +2760,8 @@ function(ret) { var mime_types = ; var prevent_empty = ; var resize = ; + let toastrElement; + let fileId; var uploader_attachments = new plupload.Uploader({ runtimes: 'html5,flash,silverlight,html4', @@ -2778,12 +2780,11 @@ function(ret) { resize: resize, init: { BeforeUpload: function(up, file) { - toastr.info( - 'get('uploading'); ?>', - '', { - timeOut: 0 - } - ); + fileId = file.id; + toastr.remove(); + toastrElement = toastr.info('get('loading_item'); ?> ... 0%'); + // Show file name + $('#upload-file_' + file.id).html('' + htmlEncode(file.name) + ''); // Get random number if (store.get('teampassApplication').uploadedFileId === '') { @@ -2807,17 +2808,23 @@ function(teampassApplication) { files_number: $('#form-item-hidden-pickFilesNumber').val(), file_size: file.size }); + }, + UploadProgress: function(up, file) { + // Update only the percentage inside the Toastr message + $('#plupload-progress').text(file.percent + '%'); + }, + UploadComplete: function(up, files) { + // Inform user + toastr.remove(); + }, + Error: function(up, args) { + console.log("ERROR arguments:"); + console.log(args); } } }); - // Uploader options - uploader_attachments.bind('UploadProgress', function(up, file) { - //console.log('uploader_attachments.bind') - $('#upload-file_' + file.id).html('' + htmlEncode(file.name) + ''); - }); uploader_attachments.bind('FileUploaded', function(up, file) { - //console.log('File '+file.name+' uploaded'); $('#fileStatus_'+file.id).html(''); userUploadedFile = true; userDidAChange = true; @@ -2825,15 +2832,39 @@ function(teampassApplication) { }); uploader_attachments.bind('Error', function(up, err) { toastr.remove(); - toastr.error( - err.message + (err.file ? ', File: ' + err.file.name : ''), - '', { - timeOut: 5000, - progressBar: true + // Extraire le message d'erreur + let errorMessage = 'An unknown error occurred.'; + if (err.response) { + try { + const response = JSON.parse(err.response); + if (response.error && response.error.message) { + errorMessage = response.error.message; + } + } catch (e) { + errorMessage = err.response; // Si la réponse n'est pas JSON } - ); + } - up.refresh(); // Reposition Flash/Silverlight + // Vérifie si l'erreur est due à un dépassement de taille ou une autre erreur critique + if (err.code === -200 || err.status === 413) { + // Arrêter l'upload des chunks + up.stop(); + errorMessage += ' - Upload stopped.'; + + // Affiche l'erreur dans l'interface utilisateur + toastr.error( + errorMessage + (err.file ? ', File: ' + err.file.name : ''), + '', { + timeOut: 10000, + progressBar: true + } + ); + + $('#fileStatus_'+fileId).html(''); + return false; + } else { + up.refresh(); // Reposition Flash/Silverlight + } }); $("#form-item-upload-pickfiles").click(function(e) { diff --git a/sources/upload.attachments.php b/sources/upload.attachments.php index 82c0bb0f7..eca91bba5 100755 --- a/sources/upload.attachments.php +++ b/sources/upload.attachments.php @@ -117,6 +117,25 @@ handleAttachmentError('No user token found.', 110); exit(); } else { + // Check post_max_size + $POST_MAX_SIZE = ini_get('post_max_size'); + $unit = strtoupper(substr(trim($POST_MAX_SIZE), -1)); // Assurez-vous de bien gérer les espaces éventuels + $units = ['G' => 1073741824, 'M' => 1048576, 'K' => 1024]; + $multiplier = $units[$unit] ?? 1; // Vérifie si l'unité est dans le tableau, sinon 1 + $maxSize = (int)$POST_MAX_SIZE * $multiplier; + + // CHeck if the POST is too big + if (!empty($_SERVER['CONTENT_LENGTH']) && (int)$_SERVER['CONTENT_LENGTH'] > $maxSize && $maxSize > 0) { + handleAttachmentError('POST exceeded maximum allowed size.', 111, 413); + } + + // CHeck if file size is too big + if ($post_fileSize > $maxSize && $maxSize > 0) { + handleAttachmentError('File exceeds the maximum allowed size', 120, 413); + die(); + } + error_log('POST_MAX_SIZE: ' . $POST_MAX_SIZE." - CONTENT_LENGTH: ".$_SERVER['CONTENT_LENGTH']." - UNIT: ".$unit." - MAX: ".$maxSize." - MULTIPLIER: ".$multiplier." - FILE_SIZE: ".$post_fileSize); + // delete expired tokens DB::delete(prefixTable('tokens'), 'end_timestamp < %i', time()); @@ -214,14 +233,6 @@ date_default_timezone_set($post_timezone); } -// Check post_max_size -$POST_MAX_SIZE = ini_get('post_max_size'); -$unit = strtoupper(substr($POST_MAX_SIZE, -1)); -$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1))); -if ((int) $_SERVER['CONTENT_LENGTH'] > $multiplier * (int) $POST_MAX_SIZE && $POST_MAX_SIZE) { - handleAttachmentError('POST exceeded maximum allowed size.', 111, 413); -} - // Validate the file size (Warning: the largest files supported by this code is 2GB) $file_size = @filesize($_FILES['file']['tmp_name']); if ($file_size === false || (int) $file_size > (int) $max_file_size_in_bytes) { @@ -483,7 +494,14 @@ function handleAttachmentError($message, $code, $http_code = 400) http_response_code($http_code); // json error message - echo '{"jsonrpc" : "2.0", "error" : {"code": ' . htmlentities((string) $code, ENT_QUOTES) . ', "message": "' . htmlentities((string) $message, ENT_QUOTES) . '"}, "id" : "id"}'; + echo json_encode([ + 'jsonrpc' => '2.0', + 'error' => [ + 'code' => $code, + 'message' => $message + ], + 'id' => 'id' + ]); // Force exit to avoid bypass filters. exit; From 792b10b4d87e9a50f1a3019fcb5d9db82e445bbe Mon Sep 17 00:00:00 2001 From: nilsteampassnet Date: Mon, 25 Nov 2024 18:46:42 +0100 Subject: [PATCH 3/3] Improvement based upon review comment --- includes/config/include.php | 2 +- sources/main.functions.php | 29 +++++++++++++++++++---------- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/includes/config/include.php b/includes/config/include.php index 4a4d6ce69..a6c039116 100755 --- a/includes/config/include.php +++ b/includes/config/include.php @@ -28,7 +28,7 @@ define('TP_VERSION', '3.1.2'); define("UPGRADE_MIN_DATE", "1732264740"); -define('TP_VERSION_MINOR', '169'); +define('TP_VERSION_MINOR', '170'); define('TP_TOOL_NAME', 'Teampass'); define('TP_ONE_DAY_SECONDS', 86400); define('TP_ONE_WEEK_SECONDS', 604800); diff --git a/sources/main.functions.php b/sources/main.functions.php index aaf3e868f..2e137afbb 100755 --- a/sources/main.functions.php +++ b/sources/main.functions.php @@ -134,15 +134,20 @@ function cryption(string $message, string $ascii_key, string $type, ?array $SETT $text = Crypto::decrypt($message, $key); } } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) { - $err = 'an attack! either the wrong key was loaded, or the ciphertext has changed since it was created either corrupted in the database or intentionally modified by someone trying to carry out an attack.'; + error_log('TEAMPASS-Error-Wrong key or modified ciphertext: ' . $ex->getMessage()); + $err = 'wrong_key_or_modified_ciphertext'; } catch (CryptoException\BadFormatException $ex) { - $err = $ex; + error_log('TEAMPASS-Error-Bad format exception: ' . $ex->getMessage()); + $err = 'bad_format'; } catch (CryptoException\EnvironmentIsBrokenException $ex) { - $err = $ex; - } catch (CryptoException\CryptoException $ex) { - $err = $ex; + error_log('TEAMPASS-Error-Environment: ' . $ex->getMessage()); + $err = 'environment_error'; } catch (CryptoException\IOException $ex) { - $err = $ex; + error_log('TEAMPASS-Error-IO: ' . $ex->getMessage()); + $err = 'io_error'; + } catch (Exception $ex) { + error_log('TEAMPASS-Error-Unexpected exception: ' . $ex->getMessage()); + $err = 'unexpected_error'; } return [ @@ -1929,9 +1934,11 @@ function defuseFileEncrypt( } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) { $err = 'wrong_key'; } catch (CryptoException\EnvironmentIsBrokenException $ex) { - $err = print_r($ex, true); + error_log('TEAMPASS-Error-Environment: ' . $ex->getMessage()); + $err = 'environment_error'; } catch (CryptoException\IOException $ex) { - $err = print_r($ex, true); + error_log('TEAMPASS-Error-General: ' . $ex->getMessage()); + $err = 'general_error'; } // return error @@ -1963,9 +1970,11 @@ function defuseFileDecrypt( } catch (CryptoException\WrongKeyOrModifiedCiphertextException $ex) { $err = 'wrong_key'; } catch (CryptoException\EnvironmentIsBrokenException $ex) { - $err = print_r($ex, true); + error_log('TEAMPASS-Error-Environment: ' . $ex->getMessage()); + $err = 'environment_error'; } catch (CryptoException\IOException $ex) { - $err = print_r($ex, true); + error_log('TEAMPASS-Error-General: ' . $ex->getMessage()); + $err = 'general_error'; } // return error