Games General PHP Security

Definitive PHP security checklist – sk89q.com

I’ve ready a reasonably complete PHP safety guidelines that’s a superb scan via.

Replace: This listing was written in 2009 and now it’s outdated, incomplete, and you will discover extra trendy sources, comparable to OWASP.

If in case you have any questions, be happy to go away a remark. The next can also be now in a really concise printable type.

  • Primary:
    • Have robust passwords make certain that your “password restoration questions” will not be too apparent.
      • When you write down your passwords, be sure that you set it in a protected place.
    • Ensure that register_globals is disabled, as a result of that permits arbitrary variables to be injected into your script’s setting (!).
    • Disable magic quotes. It has no impact on safety, however it leads individuals to assume that it truly helps safe purposes towards SQL injection, and so individuals depend on it for escaping (extremely improper!). The 2 related PHP settings are magic_quotes_gpc and magic_quotes_runtime.
    • Disable display_errors in your manufacturing surroundings to make it harder to study particulars about your setting. You need to proceed to log errors, nevertheless.
    • Don’t overlook concerning the bodily safety of your server(s). Ensure you’re in a safe knowledge middle (trace: some are grossly insecure).
  • Consumer enter and non-uploaded content material:
    • Remember which you can provoke a request from one thing so simple as telnet, in order that signifies that all incoming knowledge could be cast.
      • Because of this every thing in $_GET, $_POST, $_COOKIE, and $_REQUEST can all include any worth.
      • $_SERVER and $_ENV are a bit totally different: some values come from the online server, whereas others come from the shopper.
        • $_SERVER[‘PHP_SELF’] shouldn’t be completely protected, as URLs could be, relying in your configuration, cleverly constructed to include arbitrary knowledge and but nonetheless work.
    • Filter and validate knowledge to make it possible for it’s protected for the surroundings that you’re utilizing the info in.
      • Remember that incoming knowledge can include management characters akin to null. Null signifies the top of a string in C/C++, so you possibly can think about what might occur in case you are passing a PHP string to a different program or the system API.
      • Verify the size of inputted knowledge to be sure that it isn’t too lengthy.
      • Be sure to validate e mail addresses, as a result of it’s potential to inject e-mail headers by crafting specifically constructed e mail addresses.
      • Don’t overlook that inputted numbers could be very giant, very small, zero, or unfavorable. You don’t need to deposit a damaging variety of credit!
      • Remember that some character units (specifically Unicode) have “invisible” characters, characters that look alike, or alternative ways of mixing characters (for diacritics, specifically). This might be used to impersonate one other consumer.
        • Some character units additionally include format management characters (specifically Unicode), which might be used to switch the format of the web page barely.
    • Earlier than outputting knowledge to the browser, be sure that to correctly escape it to stop cross-site scripting (XSS). As a common rule, use a white listing, by no means a black record.
      • In case you are permitting the consumer to make use of (some) HTML, it is vital that you simply use a really safe HTML sanitizer (HTML Air purifier is advisable).
        • There are numerous some ways to realize the identical end in HTML, so don’t attempt to do HTML sanitizing your self (significantly, simply overlook it).
      • If CSS is allowed, then that have to be sanitized as nicely.
        • Remember that sure CSS properties akin to “place” could possibly be used maliciously (parts overlaying login types, etcetera).
        • CSS also can include escape sequences each inside and out of doors strings (34).
        • CSS information can include JavaScript. This manifests itself within the type of “CSS expressions” and “behaviors” (Web Explorer options) or Gecko “bindings.”
      • Verify to be sure that any user-supplied URLs are legitimate and protected. URLs to web sites, URLs to pictures, and so on.
        • Concentrate on the totally different protocols: http:, https:, ftp:, ftps:, gopher:, Third-party ones resembling purpose:, and knowledge:.
      • For those who permit customers to embed plugins (i.e. Flash films), ensure you embed it in a means the place a unique plugin can’t be loaded (based mostly on file sort).
      • Included Java applets, Flash films, or different plugin content material could possibly entry the web page by executing JavaScript, relying on the best way that the content material was embedded into the web page.
    • Use a “protected” encoding on your web page (comparable to ISO-8859-1) or in any other case confirm that the content material of inputted knowledge to see if it legitimate (together with should you use UTF-Eight). It’s because sure invalid character sequences may cause the subsequent character (the subsequent character probably being an essential < or “) to be ignored in some encodings.
      • You will need to specify the encoding, in any other case you permit the online browser to guess on the encoding, and leaving the likelihood that it might change to a “harmful” encoding.
      • Specify the encoding in an HTTP header and never within the HTML.
  • Uploaded information:
    • Confirm that the kind of the file is what you anticipated.
      • The mime sort/file sort within the $_FILES array is offered by the consumer and may include any worth. Not solely can the offered mime sort be spoofed, it might additionally simply be improper or be overly generic.
        (Conclusion: The sector is ineffective.)
      • The easiest way to examine whether or not the file is of the format you anticipated is to research the contents of the file.
        • A easy file sort examine algorithm could be simply fooled by placing the minimal needed elements of the file format to cross that verify. For instance, you might take the primary 20 bytes of a PNG file after which append the contents of badvirus.vbs to the top, supplying you with a file that may simply cross by way of many filters. A extra difficult filter is extra computationally intensive to make use of, nevertheless, and the few advantages are often not value it.
        • An alternate technique to confirm the format of the file is to re-save it. A PNG picture might be re-saved utilizing the GD library, for instance. Nevertheless, this will degrade the standard of the file, particularly if JPEG is worried.
      • Remember that some codecs can include arbitrary knowledge and nonetheless be legitimate (assume “remark fields” in some file varieties).
    • Confirm that the dimensions of the file just isn’t too giant.
      • In case you are utilizing MAX_FILE_SIZE, you continue to have to carry out the examine. Don’t use the worth of MAX_FILE_SIZE to verify once more, as this may be spoofed (keep in mind that all enter knowledge is suspect).
      • Just remember to don’t permit uploaded information to utterly take up all of the area in your system, probably inflicting grave penalties.
    • Remember that uploaded information, even when legitimate, can nonetheless include malicious content material.
      • Uploaded information could also be or include viruses. You’ll be able to scan for viruses if you want, though it does burn up (probably costly) assets to take action.
      • Uploaded HTML information can include malicious JavaScript.
    • Don’t transfer uploaded information to web-accessible directories, as your net server might parse some information as executable code (i.e. an uploaded .php file). It additionally hampers your potential to limit entry to the information (as famous earlier than about hiding information).
    • Do in depth path checks to ensure you don’t serve a non-uploaded file.
    • Don’t execute/serve uploaded information with embrace(). This executes PHP code, as beforehand talked about. Use readfile().
    • Serve all uploaded information as an attachment and by no means inline (it’s a HTTP header referred to as “Content material-Disposition”). It’s because Web Explorer will override the content material sort you inform it and guess by itself. PNG picture? No! Web Explorer says it’s a HTML file with JavaScript code.
      • Ship the “X-Content material-Sort-Choices: nosniff” header. This solely alleviates the issue for IE8 and above, however IE7 and under would nonetheless have the difficulty (so you continue to have to ship information as attachments).
    • Keep away from serving information with content material varieties of “software/octet-stream,” “software/unknown,” or “textual content/plain” until needed.
  • Database:
    • When inserting inputted knowledge into an SQL question, escape the info or use parameterized/ready statements. The difficulty at hand is known as SQL injection.
      • Don’t use addslashes() to flee knowledge; use the perform on your specific DBMS to flee knowledge, as a result of totally different databases escape in another way.
      • A great way to stop SQL injection is to make use of ready statements. PDO helps ready statements, amongst different libraries.
    • Lock down entry permissions in order that your software doesn’t have extra privileges to the database (pointless write privileges, and so forth.).
    • Remember that your DBMS might permit distant connections (by default), so disable that function as crucial.
  • Together with and serving information:
    • By no means use consumer enter immediately in a pathname.
      • Examine for listing traversal.
      • Verify for null poison bytes.
      • Concentrate on the “:” character, which is used on NTFS and Home windows to entry alternate knowledge streams.
      • Concentrate on PHP streams, which permits you (and attackers) to entry non-file-based assets with URIs like http://example.com/badcode.txt.
        • Examine to make it possible for attackers can’t embrace a distant file containing PHP code.
    • You shouldn’t be merely hiding information in a web-accessible listing as a result of individuals might guess URLs.
      • This is applicable to hiding issues based mostly on the content material of a GET or POST variable. Truly verifying the id of the consumer and his or her authorization degree is a a lot better strategy.
    • When it’s essential get a distant file, don’t use embrace(), as that may even execute any PHP code on the web page. Use one thing reminiscent of file_get_contents().
  • Authentication and authorization:
    • Set up a nasty password throttling system to stop brute drive assaults.
      • You need to contemplate throwing up a CAPTCHA check earlier than outright denying any additional login makes an attempt. Do this not for safety causes, however relatively to make it much less annoying on your extra forgetful customers.
    • Remember that a malicious consumer can sniff for packets to get a consumer’s password. The one actual answer to this drawback is to make use of SSL. It’s attainable to setup your personal problem and response system, nevertheless it gained’t shield customers if they’re additionally vulnerable to a man-in-the-middle assault.
    • Don’t retailer a consumer’s password in a cookie when logging in, for apparent causes. This will likely look like a simple approach to implement “keep in mind me,” however it’s a dangerous concept.
    • Hash saved passwords to make it more durable for an attacker who has gained entry to your database to get the uncooked password of customers.
      • Use salts to make rainbow tables ineffective. It’s extremely advisable that you simply use a special salt per consumer to make intrusion harder (you’ll have to retailer the person salts). Salts ought to be sufficiently lengthy and sophisticated to be robust.
      • Use the PHP crypt() perform if potential, because it generates excellent hashes. You need to use Blowfish or SHA and use an excellent variety of rounds. Growing the variety of rounds causes the hash calculation to be extra computationally costly, making the hashes a lot more durable to brute pressure. Since you don’t continually generate hashes, the additional CPU required shouldn’t have a serious influence.
      • Don’t use MD5.
    • In the event you permit your customers to enter password restoration questions, make certain to remind customers to not use questions with solutions that may be simply guessed by another person. Individuals’s accounts have been misplaced as a result of this very purpose.
    • Watch out with account restoration types to not permit malicious customers from discovering whether or not an e mail tackle is registered in your database. The one answer to this drawback is to not let the consumer know whether or not the e-mail handle exists within the database once they use the password restoration type. An e-mail all the time needs to be despatched in that state of affairs.
    • Keep in mind to throttle any web page that sends emails to stop a malicious consumer from utilizing your script to abuse your software.
  • Periods and cookies:
    • Use solely cookies for periods, to stop session fixation (i.e. a malicious consumer sending a goal consumer a hyperlink to make use of an present session already underneath the management of the attacker) and session hijacking (i.e. leaking a session ID positioned within the URL) assaults. In case you are utilizing the PHP periods, there’s a PHP setting named session.use_only_cookies that determines this conduct.
    • After a session is full (“logout”), destroy its knowledge and don’t simply clear the cookie (a malicious consumer might in any other case simply re-instate the cookie and use the session once more).
    • When altering a consumer’s authorization degree (i.e. from visitor to a logged in consumer), destroy the previous session and create a brand new session to make session fixation more durable. It’s because if the attacker has entry to the session (for some purpose), the previous session will now turn out to be ineffective relatively than get additional privileges.
    • Even in case you are not in a shared internet hosting surroundings, in case you use the identical listing to retailer session information for 2 or extra of your websites, then a session created on one web site shall be a legitimate session on one other.
  • Distant web sites:
    • Remember that different websites can conduct cross-site request forgeries, and cross off as a logged in consumer (each GET and POST requests could be cast).
      • Don’t depend on referrers to guard towards CSRFs, as a result of many Web safety packages block the referrer subject or give it some doubtful worth (like “—“).
      • Use tokens/keys together with your types to stop CSRFs. Do that for necessary pages.
      • Utilizing POST for pages that carry out actions helps mitigate the difficulty, though it’s nonetheless attainable to submit a POST request from a type routinely.
      • Remember that even materials you host in your web site can be utilized towards you, as a result of the content material is already in your web site, and thus there are not any cross-domain sanctions.
        Instance: An avatar URL that masses your logout web page.
    • Remember that, whereas different web sites can’t simply learn content material off your pages, some information may be learn remotely (corresponding to .js information) by their nature (together with them by way of SCRIPT tags, etcetera).
      • Information that appear to be JavaScript information might probably be learn remotely.
      • Don’t overlook about your information that include JSON.
    • Older variations (and probably present) of Flash might play media information remotely and bypass referrer checks, as a result of Flash Participant didn’t ship a referrer.
    • Remember that info might be probed utilizing the inclusion of a file in your server on a distant website.
      • Remember that the existence of a file might be detected utilizing the “onerror” occasion of a picture aspect.
      • Pages that conditionally take an extended time to load might be detected on a distant web site.
        • Cached information will take a shorter time to load.
      • The size of pictures on you server may be detected on a distant web site.
      • CSS information may be included remotely, and though not learn, if the CSS information are conditional, info might be garnered from how the assault website is modified with the inclusion of the CSS file. Relatively than together with a CSS file, an attacker might try to incorporate an HTML file instantly as properly, as a result of the CSS parsers in net browsers are pretty lax and can attempt their greatest.
      • Some browsers permit a distant website to detect the frames inside one other website.
      • Some browsers might throw a unique error when you try and delete a non-existent variable in a body include a distant web site than should you have been to delete an present variable.
      • It’s potential to detect whether or not a consumer has visited a URL by checking how the browser has styled the hyperlink (visited vs. unvisited types).
    • Remember that Web Explorer permits a distant web site to incorporate one other web site in an inline body however disable JavaScript and cookies to perform contained in the inline body. This breaks body break-out makes an attempt.
    • Set up body busting code and ship the X-Body-Choices header to guard towards UI redressing/clickjacking. Body bursting code gained’t work in IE if the attacker’s web site disabled JavaScript in an inline body (see above), however that’s what the header is for. Older variations of IE are nonetheless left weak.
  • Miscellaneous:
    • In case you are utilizing random numbers for safety, remember that it’s essential to be utilizing a cryptographically safe random quantity generator in any other case it’s attainable to guess the sample of random numbers.
      • Issues reminiscent of account activation hyperlinks and randomly generated secret IDs have to be generated utilizing a cryptographically safe random generator. Principally something that’s random that must be stored secret must be generated utilizing a safe PRNG.
      • PHP doesn’t present a cryptographically safe random quantity generator. Nevertheless, you possibly can entry /dev/urandom (*nix) or CAPICOM.Utilities.1 (Home windows). For an instance, see this remark. You may as well set up the Suhosin patch as an alternative.
    • Something that consumes loads of assets must be throttled and restricted.
      • Pages that conduct lengthy or useful resource intensive operations ought to be throttled, in order that performing a denial-of-service assault towards you isn’t so simple as leaving 10 browser home windows on auto-refresh.
      • Examine to make it possible for pages that entry distant assets (i.e. APIs, and so forth.) can’t be used to launch denial of service assaults towards these distant assets through the use of your website as a proxy.
    • Don’t attempt to create your personal encryption algorithm.
    • In case you are calling exterior packages (i.e. exec()), just remember to escape the arguments.
    • When you utilizing a web page to redirect to different pages (or different websites), be sure that this can’t be abused.
    • Remember that one thing might go flawed, and your PHP information might all of a sudden be uncovered (it has occurred to massive identify websites, similar to Fb and others). Take precautions to stop this.
    • Don’t put configuration information or any essential information in an internet accessible listing, particularly if their content material may be learn by way of the browser.
    • If that you must shield information (for instance, towards a login), put the information right into a non-web-accessible listing and route all information via a PHP script. (This has been touched on beforehand.)
    • Web Explorer has an XSS filter that would probably be exploited to stop a bit of code in a web page to be executed by passing that piece of code as a question parameter within the URL.
  • Shared host safety:
    • Remember that on many shared hosts, customers can entry the information of different customers. It will not be doable by way of PHP, however it might be doable by way of PHP by way of CGI (or Perl, and so forth. by way of CGI).
      • In shared hosts the place safety is barely higher, you need to chmod your information in order that customers of different teams can’t entry your information.
      • Somebody famous that I glossed over this challenge. Okay, learn that once more: customers can entry the information of different customers. That ought to be a serious fear, and one of the best half is that the majority PHP shared net hosts don’t safe their servers towards this. It is best to confirm that the online host that you’re working with has correctly secured their setting, and if it hasn’t, you need to transfer.
    • Remember that IE6 permits header spoofing with XMLHttpRequest, together with the spoofing of Host and Referer. In case you are on a digital host setup (which you possible are in case you are on a shared host), then one other website can spoof the Host header and thus ship arbritrary requests to your web site from one other web site on the identical server. (IE6 doesn’t permit cross-domain requests. It’s the truth that the Host header tells the online server which website to host if a number of websites are all on the identical IP handle.)
    • Remember that different customers on the identical server might have the identical IP handle as your web site or can entry your web site from 127.zero.zero.1.
    • Remember that different customers on the identical server could possibly run a server on the identical IP as your web site however on a unique port.
    • Remember that different customers are “not” distant so far as your database could also be involved.
    • Remember that one other consumer on the identical server could possibly create a false session to be used by yourself website (as a result of in lots of configurations, all session short-term information are saved in the identical listing for all customers).
      • Consequently, that signifies that different customers can also be capable of learn your session knowledge.
      • A session created on one website can be utilized on one other as nicely.
    • File uploads on one website may be accessible on one other website as a result of websites typically share a single world-readable /tmp listing.

And don’t overlook: this listing can also be out there as a printable cheat sheet.

Obtain: phpsec_cheatsheet.pdf

PHP Application Security Checklist