简体   繁体   中英

is this methods enough for secure my host (php)?

i wanna make my host high Secure ( prevent attacks xss & CSRF... )

  • first defense (token)
if ( time() >= $_SESSION['token']['expire'] ) {
    $length = rand(31,50);
    try {
      $_SESSION['token']['code'] =  bin2hex(random_bytes($length));
      $_SESSION['token']['input'] =  bin2hex(random_bytes($length));
    } catch (\Exception $e) {
      $_SESSION['token']['code'] = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $length);
      $_SESSION['token']['input'] = substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $length);
   }
   $_SESSION['token']['expire'] = time() + 3600;
   die(JSON_TIME_OUT);
}
  • second defense (check all queries)
$value = trim(strip_tags(htmlspecialchars(stripslashes($POST['query']))));
  • third defense (just allow post REQUEST )
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || sizeof($_GET)) {
    http_response_code(405);
    exit;
}
  • forth defense ( for save password in db )
$pass = password_hash("password", PASSWORD_DEFAULT);

Is there anything else I missed?

You missed SQL injection.

You can use prepared statements to avoid SQL injections.

Here is an example:

$conn = mysqli_connect("localhost", "username", "password", "database");

$username = "someone";
$comments = "something like ); SELECT * FROM table;"; #some kind of sql injection
$current_date = date("h:i:s a d-m-Y");
        $sql = "INSERT INTO comments (name, comments, date_publish) VALUES (?, ?, ?);";
        $stmt = mysqli_stmt_init($conn);
        if (!mysqli_stmt_prepare($stmt, $sql)) {
            echo "An error occured!";
        } else {
            mysqli_stmt_bind_param($stmt, "sss", $username, $comment, $current_date);
            mysqli_stmt_execute($stmt);
            mysqli_stmt_get_result($stmt);
            echo "Done!";
        }

Even though you have included (php) in your title, I want to share some security headers:

Add the following to Apache, if using Apache:

<IfModule headers_module>
Header always set Expires "-1"
Header always set Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
Header always set Pragma "no-cache"

<FilesMatch "\.(gif|jpe?g|png|webp|ico|mp4|mp3)$">
Header always unset Expires
Header always set Cache-Control "must-revalidate, max-age=3600"
Header always unset Pragma
</FilesMatch>
Header always set Content-Security-Policy "default-src 'none'; img-src data: https: 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none'; style-src 'self'; base-uri 'none'; form-action 'self'; media-src https: 'self'; frame-src 'none'; child-src 'none'; connect-src 'self'"
Header always set X-Frame-Options "DENY"
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Content-Type-Options nosniff
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" "expr=%{HTTPS} == 'on'"
#Header always set Referrer-Policy "no-referrer"
Header always set Permissions-Policy "geolocation=();midi=();notifications=();push=();sync-xhr=(self);microphone=();camera=();magnetometer=();gyroscope=();speaker=(self);vibrate=();fullscreen=(self);payment=();"
Header always set X-Permitted-Cross-Domain-Policies "none"
</IfModule>

Here are the plain headers:

set-cookie: __Secure-YOURSESSID=abcdefghijklmnopqrstuvwxyz123456789; path=/; secure; HttpOnly; SameSite=Lax
expires: -1
cache-control: no-store, no-cache, must-revalidate, max-age=0
pragma: no-cache
content-security-policy: default-src 'none'; img-src data: https: 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none'; style-src 'self'; base-uri 'none'; form-action 'self'; media-src https: 'self'; frame-src 'none'; child-src 'none'; connect-src 'self'
x-frame-options: DENY
x-xss-protection: 1; mode=block
x-content-type-options: nosniff
strict-transport-security: max-age=63072000; includeSubDomains; preload
permissions-policy: geolocation=();midi=();notifications=();push=();sync-xhr=(self);microphone=();camera=();magnetometer=();gyroscope=();speaker=(self);vibrate=();fullscreen=(self);payment=();
x-permitted-cross-domain-policies: none
content-type: text/html; charset=UTF-8

You can alter them to your needs. The Content-Security-Policy header is the most important one. It might break your site, but, it will help a lot.

Use SSLLabs to test your site's security.

Here is an Apache configuration for most secure SSLLabs score:

SSLCipherSuite TLSv1.3 TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384
SSLOpenSSLConfCmd ECDHParameters secp384r1

#generate DH param using: openssl dhparam -out dhparam.pem 4096
SSLOpenSSLConfCmd DHParameters "/path/to/ssl/dh4096.pem"

SSLHonorCipherOrder On
SSLProtocol -all +TLSv1.2 +TLSv1.3
SSLPassPhraseDialog builtin
SSLSessionCache "shmcb:/usr/local/apache2/logs/ssl_scache(512000)"
SSLSessionCacheTimeout 300
SSLUseStapling On
SSLStaplingCache "shmcb:ssl_stapling(32768)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM