示例#1
0
 public static final function DownloadsHandler($encrypted_download_pack, $controller_key)
 {
     //--
     $encrypted_download_pack = (string) $encrypted_download_pack;
     $controller_key = (string) $controller_key;
     //--
     $client_signature = SmartUtils::get_visitor_signature();
     //--
     if ((string) SMART_APP_VISITOR_COOKIE == '') {
         Smart::log_info('File Download', 'Failed: 400 / Invalid Visitor Cookie' . ' on Client: ' . $client_signature);
         self::Raise400Error('ERROR: Invalid Visitor UUID. Cookies must be enabled to enable this feature !');
         return '';
     }
     //end if
     //--
     $downloaded_file = '';
     // init
     //--
     $decoded_download_packet = (string) trim((string) SmartUtils::crypto_decrypt((string) $encrypted_download_pack, 'SmartFramework//DownloadLink' . SMART_FRAMEWORK_SECURITY_KEY));
     //--
     if ((string) $decoded_download_packet != '') {
         // if data is corrupted, decrypt checksum does not match, will return an empty string
         //--
         if (SMART_FRAMEWORK_ADMIN_AREA === true) {
             // {{{SYNC-DWN-CTRL-PREFIX}}}
             $controller_key = (string) 'AdminArea/' . $controller_key;
         } else {
             $controller_key = (string) 'IndexArea/' . $controller_key;
         }
         //end if
         //-- {{{SYNC-DOWNLOAD-ENCRYPT-ARR}}}
         $arr_metadata = explode("\n", (string) $decoded_download_packet, 6);
         // only need first 5 parts
         //print_r($arr_metadata);
         // #PACKET-STRUCTURE# [we will have an array like below, according with the: SmartUtils::create_download_link()]
         // [TimedAccess]\n
         // [FilePath]\n
         // [AccessKey]\n
         // [UniqueKey]\n
         // [SFR.UA]\n
         // #END#
         //--
         $crrtime = (string) trim((string) $arr_metadata[0]);
         $filepath = (string) trim((string) $arr_metadata[1]);
         $access_key = (string) trim((string) $arr_metadata[2]);
         $unique_key = (string) trim((string) $arr_metadata[3]);
         //--
         unset($arr_metadata);
         //--
         $timed_hours = 1;
         // default expire in 1 hour
         if (defined('SMART_FRAMEWORK_DOWNLOAD_EXPIRE')) {
             if ((int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE > 0) {
                 if ((int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE <= 24) {
                     // max is 24 hours (since download link is bind to unique browser signature + unique cookie ... make non-sense to keep more)
                     $timed_hours = (int) SMART_FRAMEWORK_DOWNLOAD_EXPIRE;
                 }
                 //end if
             }
             //end if
         }
         //end if
         //--
         if ((int) $timed_hours > 0) {
             if ((int) $crrtime < (int) (time() - 60 * 60 * $timed_hours)) {
                 Smart::log_info('File Download', 'Failed: 403 / Download expired at: ' . date('Y-m-d H:i:s O', (int) $crrtime) . ' for: ' . $filepath . ' on Client: ' . $client_signature);
                 self::Raise403Error('ERROR: The Access Key for this Download is Expired !');
                 return '';
             }
             //end if
         }
         //end if
         //--
         if ((string) $access_key != (string) sha1('DownloadLink:' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . SMART_APP_VISITOR_COOKIE . ':' . $filepath . '^' . $controller_key)) {
             Smart::log_info('File Download', 'Failed: 403 / Invalid Access Key for: ' . $filepath . ' on Client: ' . $client_signature);
             self::Raise403Error('ERROR: Invalid Access Key for this Download !');
             return '';
         }
         //end if
         //--
         if ((string) $unique_key != (string) SmartHashCrypto::sha1('Time=' . $crrtime . '#' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . $access_key . '-' . SmartUtils::unique_auth_client_private_key() . ':' . $filepath . '+' . $controller_key)) {
             Smart::log_info('File Download', 'Failed: 403 / Invalid Client (Unique) Key for: ' . $filepath . ' on Client: ' . $client_signature);
             self::Raise403Error('ERROR: Invalid Client Key to Access this Download !');
             return '';
         }
         //end if
         //--
         if (SmartFileSysUtils::check_file_or_dir_name($filepath)) {
             //--
             $skip_log = 'no';
             // default log
             if (defined('SMART_FRAMEWORK_DOWNLOAD_SKIP_LOG')) {
                 $skip_log = 'yes';
                 // do not log if accessed via admin area and user is authenticated
             }
             //end if
             //--
             $tmp_file_ext = (string) strtolower(SmartFileSysUtils::get_file_extension_from_path($filepath));
             // [OK]
             $tmp_file_name = (string) strtolower(SmartFileSysUtils::get_file_name_from_path($filepath));
             //--
             $tmp_eval = SmartFileSysUtils::mime_eval($tmp_file_name);
             $mime_type = (string) $tmp_eval[0];
             $mime_disp = (string) $tmp_eval[1];
             //-- the path must not start with / but this is tested below
             $tmp_arr_paths = (array) explode('/', $filepath, 2);
             // only need 1st part for testing
             //-- allow file downloads just from specific folders like wpub/ or wsys/ (this is a very important security fix to dissalow any downloads that are not in the specific folders)
             if (substr((string) $filepath, 0, 1) != '/' and strpos((string) SMART_FRAMEWORK_DOWNLOAD_FOLDERS, '<' . trim((string) $tmp_arr_paths[0]) . '>') !== false and stripos((string) SMART_FRAMEWORK_DENY_UPLOAD_EXTENSIONS, '<' . $tmp_file_ext . '>') === false) {
                 //--
                 SmartFileSysUtils::raise_error_if_unsafe_path($filepath);
                 // re-test finally
                 //--
                 @clearstatcache();
                 //--
                 if (is_file($filepath)) {
                     //--
                     if (!headers_sent()) {
                         //--
                         $fp = @fopen($filepath, 'rb');
                         $fsize = @filesize($filepath);
                         //--
                         if (!$fp || $fsize <= 0) {
                             //--
                             Smart::log_info('File Download', 'Failed: 404 / The requested File is Empty or Not Readable: ' . $filepath . ' on Client: ' . $client_signature);
                             self::Raise404Error('WARNING: The requested File is Empty or Not Readable !');
                             return '';
                             //--
                         }
                         //end if
                         //-- set max execution time to zero
                         ini_set('max_execution_time', 0);
                         // we can expect a long time if file is big, but this will be anyway overriden by the WebServer Timeout Directive
                         //--
                         // cache headers are presumed to be sent by runtime before of this step
                         //--
                         header('Content-Type: ' . $mime_type);
                         header('Content-Disposition: ' . $mime_disp);
                         header('Content-Length: ' . $fsize);
                         //--
                         @fpassthru($fp);
                         // output without reading all in memory
                         //--
                         @fclose($fp);
                         //--
                     } else {
                         //--
                         Smart::log_info('File Download', 'Failed: 500 / Headers Already Sent: ' . $filepath . ' on Client: ' . $client_signature);
                         self::Raise500Error('ERROR: Download Failed, Headers Already Sent !');
                         return '';
                         //--
                     }
                     //end if else
                     //--
                     if ((string) $skip_log != 'yes') {
                         //--
                         $downloaded_file = (string) $filepath;
                         // return the file name to be logged
                         //--
                     }
                     //end if
                     //--
                 } else {
                     //--
                     Smart::log_info('File Download', 'Failed: 404 / The requested File does not Exists: ' . $filepath . ' on Client: ' . $client_signature);
                     self::Raise404Error('WARNING: The requested File for Download does not Exists !');
                     return '';
                     //--
                 }
                 //end if else
             } else {
                 //--
                 Smart::log_info('File Download', 'Failed: 403 / Access to this File is Denied: ' . $filepath . ' on Client: ' . $client_signature);
                 self::Raise403Error('ERROR: Download Access to this File is Denied !');
                 return '';
                 //--
             }
             //end if else
             //--
         } else {
             //--
             Smart::log_info('File Download', 'Failed: 400 / Unsafe File Path: ' . $filepath . ' on Client: ' . $client_signature);
             self::Raise400Error('ERROR: Unsafe Download File Path !');
             return '';
             //--
         }
         //end if else
         //--
     } else {
         //--
         Smart::log_info('File Download', 'Failed: 400 / Invalid Data Packet' . ' on Client: ' . $client_signature);
         self::Raise400Error('ERROR: Invalid Download Data Packet !');
         return '';
         //--
     }
     //end if else
     //--
     return (string) $downloaded_file;
     //--
 }
 public static function test_crypto()
 {
     //--
     $time = microtime(true);
     //--
     //--
     $unicode_text = "Unicode String [ " . time() . " ]: @ Smart スマート // Cloud Application Platform クラウドアプリケーションプラットフォーム '" . implode('', array_keys(SmartUnicode::accented_chars())) . " \" <p></p>\n\t? & * ^ \$ @ ! ` ~ % () [] {} | \\ / + - _ : ; , . #'" . microtime() . '#';
     //--
     //--
     $b64enc = base64_encode($unicode_text);
     $b64dec = base64_decode($b64enc);
     //--
     //--
     $bin2hex = strtoupper(bin2hex((string) $unicode_text));
     $hex2bin = hex2bin(strtolower(trim((string) $bin2hex)));
     //--
     //--
     $hkey = 'TestUnit // This is a test key for Crypto Cipher ...' . time() . $unicode_text;
     //--
     $he_enc = SmartUtils::crypto_encrypt($unicode_text, $hkey);
     $he_dec = SmartUtils::crypto_decrypt($he_enc, $hkey);
     //--
     if ((string) $he_dec != (string) $unicode_text or sha1($he_dec) != sha1($unicode_text)) {
         Smart::raise_error('TestUnit FAILED in ' . __FUNCTION__ . '() :: Crypto Cipher test', 'TestUnit: Crypto Cipher test failed ...');
         return;
     }
     //end if
     //--
     //--
     $bf_key = SmartHashCrypto::sha512('TestUnit // This is a test key for Blowfish ...' . time() . $unicode_text);
     $bf_enc = SmartUtils::crypto_blowfish_encrypt($unicode_text, $bf_key);
     $bf_dec = SmartUtils::crypto_blowfish_decrypt($bf_enc, $bf_key);
     if ((string) $bf_dec != (string) $unicode_text or sha1($bf_dec) != sha1($unicode_text)) {
         Smart::raise_error('TestUnit FAILED in ' . __FUNCTION__ . '() :: Crypto Blowfish test', 'TestUnit: Blowfish test failed ...');
         return;
     }
     //end if
     //--
     //--
     $arch_lzs = SmartArchiverLZS::compressToBase64($unicode_text);
     $unarch_lzs = SmartArchiverLZS::decompressFromBase64($arch_lzs);
     if ((string) $unarch_lzs != (string) $unicode_text or sha1($unarch_lzs) != sha1($unicode_text)) {
         Smart::raise_error('TestUnit FAILED in ' . __FUNCTION__ . '() :: Crypto Arch-LZS test', 'TestUnit: Arch-LZS test failed ...');
         return;
     }
     //end if
     //--
     //--
     $arch_bf_lzs = SmartArchiverLZS::compressToBase64($bf_enc);
     $unarch_bf_lzs = SmartArchiverLZS::decompressFromBase64($arch_bf_lzs);
     if ((string) $unarch_bf_lzs != (string) $bf_enc or sha1($unarch_bf_lzs) != sha1($bf_enc)) {
         Smart::raise_error('TestUnit FAILED in ' . __FUNCTION__ . '() :: Crypto Blowfish-Arch-LZS test', 'TestUnit: Blowfish-Arch-LZS test failed ...');
         return;
     }
     //end if
     //--
     //--
     $time = 'TOTAL TIME was: ' . (microtime(true) - $time);
     //--
     //--
     return SmartMarkersTemplating::render_file_template('lib/core/templates/testunit/crypto-test.inc.htm', array('EXE-TIME' => Smart::escape_html($time), 'UNICODE-TEXT' => Smart::escape_html($unicode_text), 'JS-ESCAPED' => $unicode_text, 'HASH-SHA512' => Smart::escape_html(SmartHashCrypto::sha512($unicode_text)), 'HASH-SHA1' => Smart::escape_html(sha1($unicode_text)), 'HASH-MD5' => Smart::escape_html(md5($unicode_text)), 'BASE64-ENCODED' => Smart::escape_html($b64enc), 'BASE64-DECODED' => Smart::escape_html($b64dec), 'BIN2HEX-ENCODED' => Smart::escape_html($bin2hex), 'HEX2BIN-DECODED' => Smart::escape_html($hex2bin), 'LZS-ARCHIVED' => Smart::escape_html($arch_lzs), 'LZS-UNARCHIVED' => Smart::escape_html($unarch_lzs), 'BLOWFISH-ENCRYPTED' => Smart::escape_html($bf_enc), 'BLOWFISH-LZS-ENCRYPTED' => Smart::escape_html($arch_bf_lzs), 'BLOWFISH-DECRYPTED' => Smart::escape_html($bf_dec), 'BLOWFISH-KEY' => Smart::escape_html($bf_key), 'BLOWFISH-OPTIONS' => Smart::escape_html(SmartCipherCrypto::crypto_options('blowfish')), 'HASHCRYPT-ENC' => Smart::escape_html($he_enc), 'HASHCRYPT-DEC' => Smart::escape_html($he_dec), 'HASHCRYPT-OPTIONS' => Smart::escape_html(SmartCipherCrypto::crypto_options('custom'))));
     //--
 }
 public static function decode_mime_fileurl($y_enc_msg_file, $y_ctrl_key)
 {
     //--
     $y_enc_msg_file = (string) trim((string) $y_enc_msg_file);
     if ((string) $y_enc_msg_file == '') {
         Smart::log_warning('Mail-Utils / Decode Mime File URL: Empty Message File Path has been provided. This means the URL link will be unavaliable (empty) to assure security protection.');
         return '';
     }
     //end if
     if (!SmartFileSysUtils::check_file_or_dir_name($y_enc_msg_file)) {
         Smart::log_warning('Mail-Utils / Decode Mime File URL: Invalid Message File Path has been provided. This means the URL link will be unavaliable (empty) to assure security protection. Message File: ' . $y_enc_msg_file);
         return '';
     }
     //end if
     //--
     $y_ctrl_key = (string) trim((string) $y_ctrl_key);
     if ((string) $y_ctrl_key == '') {
         Smart::log_warning('Mail-Utils / Decode Mime File URL: Empty Controller Key has been provided. This means the URL link will be unavaliable (empty) to assure security protection.');
         return '';
     }
     //end if
     if (SMART_FRAMEWORK_ADMIN_AREA === true) {
         // {{{SYNC-ENCMIMEURL-CTRL-PREFIX}}}
         $y_ctrl_key = (string) 'AdminMailUtilArea/' . $y_ctrl_key;
     } else {
         $y_ctrl_key = (string) 'IndexMailUtilArea/' . $y_ctrl_key;
     }
     //end if
     //--
     $the_sep_arr = (array) self::mime_separe_part_link($y_enc_msg_file);
     $y_enc_msg_file = (string) $the_sep_arr['msg'];
     $the_msg_part = (string) $the_sep_arr['part'];
     unset($the_sep_arr);
     //--
     $arr = array();
     // {{{SYNC-MIME-ENCRYPT-ARR}}}
     $arr['error'] = '';
     // by default, no error
     //--
     if ((string) SMART_APP_VISITOR_COOKIE == '') {
         $arr['error'] = 'WARNING: Access Forbidden ... No Visitor ID set ...!';
         return (array) $arr;
     }
     //end if
     //--
     if ((string) $the_msg_part != '') {
         $the_msg_part = strtolower(trim((string) SmartUtils::url_hex_decode((string) $the_msg_part)));
     }
     //end if
     //--
     $decoded_link = trim((string) SmartUtils::crypto_decrypt((string) $y_enc_msg_file, 'SmartFramework//MimeLink' . SMART_FRAMEWORK_SECURITY_KEY));
     $dec_arr = (array) explode("\n", trim((string) $decoded_link));
     //print_r($dec_arr);
     //--
     $arr['creation-time'] = trim((string) $dec_arr[0]);
     $arr['message-file'] = trim((string) $dec_arr[1]);
     $arr['message-part'] = trim((string) $the_msg_part);
     $arr['access-key'] = trim((string) $dec_arr[2]);
     $arr['bw-unique-key'] = trim((string) $dec_arr[3]);
     $arr['sf-robot-key'] = trim((string) $dec_arr[4]);
     //-- check if file path is valid
     if ((string) $arr['message-file'] == '') {
         $arr = array();
         $arr['error'] = 'ERROR: Empty Message Path ...';
         return (array) $arr;
     }
     //end if
     if (!SmartFileSysUtils::check_file_or_dir_name($arr['message-file'])) {
         $arr = array();
         $arr['error'] = 'ERROR: Unsafe Message Path Access ...';
         return (array) $arr;
     }
     //end if
     //--
     $browser_os_ip_identification = SmartUtils::get_os_browser_ip();
     // get browser and os identification
     //-- re-compose the access key
     $crrtime = (int) $arr['creation-time'];
     $access_key = sha1('MimeLink:' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . SMART_APP_VISITOR_COOKIE . ':' . $arr['message-file'] . '>' . $y_ctrl_key);
     $uniq_key = sha1('Time=' . $crrtime . '#' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . $access_key . '-' . SmartUtils::unique_auth_client_private_key() . ':' . $arr['message-file'] . '>' . $y_ctrl_key);
     $self_robot_key = sha1('Time=' . $crrtime . '#' . SmartAuth::get_login_id() . '*' . SMART_SOFTWARE_NAMESPACE . '-' . SMART_FRAMEWORK_SECURITY_KEY . '-' . trim($browser_os_ip_identification['signature']) . '$' . $access_key . ':' . $arr['message-file'] . '>' . $y_ctrl_key);
     //-- check access key
     if ((string) $arr['error'] == '') {
         if ((string) $access_key != (string) $arr['access-key']) {
             $arr = array();
             $arr['error'] = 'ERROR: Access Forbidden ... Invalid ACCESS KEY ...';
         }
         //end if
     }
     //end if
     //-- check the client key
     if ((string) $arr['error'] == '') {
         //--
         $ok_client_key = false;
         //--
         if ((string) $the_msg_part == '' and (string) $arr['bw-unique-key'] == (string) $uniq_key) {
             // no message part, allow only client browser
             $ok_client_key = true;
         } elseif ((string) $the_msg_part != '' and ((string) $arr['bw-unique-key'] == (string) $uniq_key or (string) $browser_os_ip_identification['bw'] == '@s#' and (string) $arr['sf-robot-key'] == (string) $self_robot_key)) {
             $ok_client_key = true;
         } else {
             $ok_client_key = false;
         }
         //end if else
         //--
         if ($ok_client_key != true) {
             $arr = array();
             $arr['error'] = 'ERROR: Access Forbidden ... Invalid CLIENT KEY ...';
         }
         //end if
         //--
     }
     //end if
     //--
     return (array) $arr;
     //--
 }