Securely creating and destroying login sessions in PHP

后端 未结 5 983
别跟我提以往
别跟我提以往 2020-12-13 00:58

This is my code to control authentication on a website. I\'m not sure if my logic is correct. If the username and password are correct the following happen:

         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-13 01:48

    First of all you should read the Mozilla WebAppSec Security Coding Guideline - Session Management and OWASP A3-Broken Authentication and Session Management. You can configure PHP's session handler to meet these requirements.

    The first flaw you should prevent is A9-Insufficient Transport Layer Protection. In short you do not want someone to hijack a session using a tool like Firesheep. This attack can be prevented by forcing the browser to only send the session id over https:

    session.cookie_secure=1
    

    You can prevent an attacker from obtaining the session id using XSS by setting the httponly flag:

    session.cookie_httponly=1
    

    You always want to use a cookie to store your session id. If the session id can be passed using a GET or POST variable then an attacker could use Session Fixation attack to hijack a session. Another way of thinking about this attack is that you don't want an attacker to create a session for another user:

    session.use_cookies=1
    session.use_only_cookies=1
    

    Next you want to make sure you have atleast 128 bits of entropy from a CSPRNG. Under *nix systems you can use /dev/urandom:

    session.entropy_file="/dev/urandom"
    session.entropy_length=16
    

    The session handler isn't everything. You still need to worry about Cross-Site Request Forgery attacks (aka CSRF or "Session Riding"), and Cross-Site Scripting (XSS). XSS can be used to defeat CSRF protection (even with http_only cookies!). Clickjacking can also be used by an attacker to perform unauthorized actions.

    After you set these configuration options, just call session_start(). As for destroying the session call session_destroy() when the user logs out, its that simple!

提交回复
热议问题