The 2018 Guide to Building Secure PHP Software!

directory

  • preface
  • PHP Versions/PHP Versions
  • Composer Dependency Management/Dependency Management with Composer
    • Recommended extensions/Recommended Packages
  • HTTPS and Browser Security/HTTPS and Browser Security
    • Security Headers/Security Headers
    • Subresource Integrity/Subresource Integrity
    • Document Relationships/Document Relationships
  • Developing Secure PHP Software
    • Database injection/Database Interaction
    • Uploads/File Uploads
    • Cross-site Scripting (XSS)
    • Cross-site Request Forgery (CSRF)
    • XML Attacks/XML Attacks (XXE, XPath Injection)
    • / Deserialization and PHP Object Injection
    • Password Hashing/Password Hashing
    • General-purpose Cryptography
    • Randomness/Randomness
    • Server Side HTTPS Requests/Server Side HTTPS Requests
    • Things to Avoid
  • Specialized Use/Specialized Use-Cases
    • Searchable Encryption/Searchable Encryption
    • Token-based Authentication/token-based Authentication without Side-channels
    • Developing Secure APIs
    • Security Event Logging with Chronicle
  • A Word From the Author
  • Resources/Resources

preface

As 2018 approaches, programmers in general (and Web developers in particular) should shed many of the bad habits and beliefs of the past when developing PHP programs. Some people don’t think it is, but it is true.

This guide should complement The focus section of The PHP: The Right Way security chapter, rather than general PHP programming topics.

The body of the

PHP version

Use PHP 7.2 in 2018, and plan to switch to PHP 7.3 in early 2019.

PHP 7.2 was released on November 30, 2017.

At the time of this writing, only versions 7.1 and 7.2 are officially actively maintained by PHP, while 5.6 and 7.0 have only been updated with security patches for about a year.

For other versions of PHP that are not officially maintained, although some operating systems provide long-term support and maintenance, this is often detrimental. In particular, they provide security support patches without a version number, which makes it difficult to explain the security of the system (just knowing the PHP version).

So, no matter what promises other vendors make, you should always stick to the officially supported version of PHP if you can. This way, even if it ends up being a short-lived security release, a release that is constantly working on upgrades will always give you some unexpected surprises.

Dependency management

Life is short, I use Composer

Composer is the most advanced dependency management solution in the PHP ecosystem. We recommend The full chapter on dependency management in PHP: The Right Way.

If you don’t use Composer to manage your app’s dependencies, eventually (hopefully later but most likely sooner) a dependency in your app will become seriously obsolete, and vulnerabilities in older versions will be exploited for computer crime.

Important: Always remember to keep dependent updates when developing software. Fortunately, this is all a single command:

composer update
Copy the code

If you are using some professional PHP extensions (written in C), you cannot use Composer management, but PECL.

Recommended extending

No matter what you are writing, you will always benefit from these dependencies. This is in addition to what most PHP programmers recommend (PHPUnit, php-cs-fixer,…) External supplement.

roave/security-advisories

Roave’s Security-Advisories uses Friends of PHP Repository to make sure your project doesn’t rely on dependencies that are known to be vulnerable.

composer require roave/security-advisories:dev-master    
Copy the code

Alternatively, you can upload your composer. Lock file to Sensio Labs as part of a routine automated vulnerability assessment workflow to alert to the discovery of any outdated software packages.

vimeo/psalm

Psalm is a static analysis tool that helps you identify potential bugs in your code. There are other good static analysis tools out there (Phan and PHPStan are great, for example), but WHEN you find that you need to support PHP 5, Psalm will be the first choice for PHP 5.4+.

Using Psalm is simple:

# Version 1 doesn't exist yet, but it will one day:
composer require --dev vimeo/psalm:^0

# Only do this once:
vendor/bin/psalm --init

# Do this as often as you need:
vendor/bin/psalm
Copy the code

If you’re running it for the first time in an existing code base, you’ll probably see a lot of red errors. But unless you’re building something the size of WordPress, trying to pass all the tests is anything but daunting.

Regardless of which static analysis tool you use, we recommend that you include it in your Continuous Integration Workflow to run with every change in code.

HTTPS and browser security

HTTPS, which should be tested, and security headers .

In 2018, insecure HTTP sites will no longer be accepted. Fortunately, thanks to the ACME protocol and the Let’s Encrypt Certificate Authority, free TLS certificates are possible.

Integrating ACME into your server is a piece of cake.

  • Caddy: Auto join.
  • ApacheAs soon asmod_mdCan be used. And before we do that,There are many high quality tutorials online.
  • Nginx: Relatively simple.

You might be thinking, “Ok, I already have A TLS certificate, so I’m going to spend some time fiddling with configuration information to make the site secure and fast.”

No! Mozilla has done a good job! . You can use a configuration generator to generate a suite of recommendations based on your site’s target audience.

If you want your website to be secure, HTTPS (HTTP over TLS) is not a compromise. Using HTTPS instantly eliminates many attacks (man-in-the-middle attacks, eavesdropping, replay attacks, and several session-style attacks that allow users to impersonate).

Safety first

Using HTTPS on the server does provide many security and performance benefits for users, but you can further enhance security by taking advantage of certain browser security features. Much of this involves the security header of the response content.

  • Content-Security-Policy
    • You need this Header because it provides granular control over whether the browser allows internal and external resources to be loaded, thus providing an effective layer of defense against cross-domain scripting vulnerabilities.
    • See CSP-Builder for quick and easy deployment/administration of Content Security Policies.
    • For further analysis, Scott Helme’s introduction to Content-Security-Policy Headers is a good guide.
  • Expect-CT
    • You need this Header because it adds a layer of protection against rogue/compromised certification authorities by forcing some bad actor to issue evidence of their faulty certificates to publicly verifiable appending only data structures.
    • Priority set toenforce,max-age=30. As long as you are confident that the Header will not cause service interruptions, addmax-age.
  • Referrer-Policy
    • You need this Header because it allows you to control whether information about a user’s behavior is disclosed to third parties.
    • Similarly, Scott Helme has provided an excellent introduction to the Referreer-Policy Header.
    • Set to unless there is a reason to allow a looser settingsame-originorno-referrer.
  • Strict-Transport-Security
    • You need this Header because it tells the browser to set Future Requests to same-origin over HTTPS instead of insecure HTTP.
    • On the first deployment, set it tomax-age = 30Then, when you are sure that nothing will break, increase this value to some larger value (for example, 31536000).
  • X-Content-Type-Options
    • You need this Header because miME-type confusion can lead to unpredictable results, including strange edge cases that allow XSS vulnerabilities. This is best accompanied by a standard Content-Type Header.
    • Unless default behavior (such as file downloads) is required, set it tonosniff.
  • X-Frame-Options
    • You need this Header because it allows you to prevent click hijacking.
    • Set toDENY(orSAMEORIGINBut only when you use<frame>Element of time).
  • X-XSS-Protection
    • You need this Header because it enables some browser anti-XSS features that are not enabled by default.
    • Set to1; mode=block.

Also, if you use PHP’s built-in session management feature (recommended), you might want to call session_start() like this:

<? php session_start(['cookie_httponly'= >true.'cookie_secure'= >true
]);
Copy the code

This forces your application to use http-only and Secure flags when sending session identifiers to prevent XSS attacks from stealing users’ cookies and forces them to be sent separately over HTTPS. We previously covered secure PHP sessions in a 2015 blog post.

Subresource integrity

At some point in the future, you might use CDN to load your site’s public JavaScript/CSS library. Security engineers have seen an obvious risk that hacking and replacing CDN (gaining control of the CDN) could inject code into thousands of sites if many use CDN to provide content.

Check out subresource integrity.

SRI (Subresource Integrity) allows you to hash the contents of the files you want CDN to serve. Currently practiced SRI only allows the use of secure cryptographic hashing functions, meaning that it is impossible for an attacker to generate malicious version resources that are identical to the original file hash.

A real example: Bootstrap V4-alpha uses SRI in their CDN example snippet

<link
    rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"
    integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ"
    crossorigin="anonymous"
/>
<script
    src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
    integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn"
    crossorigin="anonymous"
></script>
Copy the code

Document relationship

Web developers often set target properties on hyperlinks (for example, target =”_ blank” opens the link in a new window). However, if you don’t pass the rel =”noopener” tag, you can allow the target page to control the current page.

Don’t do this:

<a href="http://example.com" target="_blank">Click here</a>
Copy the code

This allows the http://example.com page to control the current page.

Instead, do this:

<a href="https://example.com" target="_blank" rel="noopener noreferrer">Click here</a>
Copy the code

By thus opening https://example.com in a new window, control of the current window is also not granted to a potentially malicious third party.

You can go further.

Develop secure PHP programs

If application security is a new topic for you, start with an introduction to application security.

Most security experts point out that developers can use resources like OWASP Top 10 to get started.

However, most common vulnerabilities can be the same high-level security issues (such as incomplete separation of code and data, loose and sound logic, insecure operating environments, or decipherable cryptographic protocols).

Our hypothesis is that security novices should be granted access to some simpler, basic security knowledge and problems, and how to solve them, and should be a better, long-term security project.

Therefore, we avoid recommending the top 10 or 20 safety lists.

Database injection

Avoid SQL injection in PHP programs.

If you are writing your own SQL code, make sure to use prepared and that any information supplied from the network or file system is passed as arguments, not as string concatenation. Also, make sure you don’t use the simulated Prepared statement.

For good results, use EasyDB.

Don’t do this:

<? php /* Insecure code: */$query = $pdo->query("SELECT * FROM users WHERE username = '" . $_GET['username']."'");
Copy the code

Do this:

<? php /* Secure against SQL injection: */$results = $easydb->row("SELECT * FROM users WHERE username = ?".$_GET['username']);
Copy the code

There are other database abstraction layers that provide the same security (EasyDB is actually using PDO, but avoids prepared before the actual PREPARE statement). As long as user input does not affect the structure of the query, it is safe (including stored procedures).

File upload

How to safely allow users to upload files?

Accepting file uploads is a risky proposition, but security can be ensured by taking some basic precautions. That is, by allowing files to be uploaded directly, they may be accidentally allowed to be executed or interpreted. Uploaded files should be read-only or read-write and should never be executable.

If your web root directory is/var/www/example.com, please don’t save uploaded files in the/var/www/example.com/uploaded_files.

Save to a non-accessible directory (e.g. /var/www/example.com- matches /) so that it is not accidentally executed as a server-side script and has a back door to execute the remote code.

A more simple method is to site root move down a level (i.e., / var/www/example.com/public).

How to securely download these uploaded files is also a problem.

  • When an SVG image type is accessed directly, JavaScript code is executed in the user’s browser. Although the image/ prefix in its MIME type is misleading, it is correct.
  • As mentioned earlier, MIME type sniffing can lead to type obfuscation attacks. See x-Content-type-options.
  • If you drop the previous advice on how to store uploaded files securely, an attacker can take full control of the server by uploading.php or.phtml files and accessing the files directly from the browser to execute arbitrary code.

Cross site scripting

Everything you want to know about cross-site scripting attacks in PHP is here

Likewise, preventing XSS is as simple as SQL injection. We have a simple and easy-to-use API to separate the structure of a document from the populated data.

In practice, however, many Web developers still develop by generating a long string of HTML code as a response. And this is not a reality unique to PHP; it is something that all Web developers should take seriously.

Reducing XSS vulnerabilities is a good idea. All in all, the previous section on browser security is quite relevant. In short:

  • Try to avoid outputs and inputs (Always escape on output, never on input). If you save sanitized data in a database and find SQL injection vulnerabilities elsewhere, an attacker will contaminate the trusted to be Sanitized records with malicious programs. To bypass XSS protection.
  • If your framework has a template engine that provides automatic context filtering, use it. This can be done safely by the framework.
  • Echo htmlentities ($string, ENT_QUOTES | ENT_HTML5, 'utf-8)Is a secure and effective way to prevent all XSS attacks on UTF-8-encoded web pages, but not any HTML.
  • If your environment requires you to use Markdown instead of HTML, don’t use HTML.
  • If you need to use native HTML (without a template engine), refer to # 1 and use HTML Purifier. HTML Purifier is not suitable for escaping as HTML attribute context.

Cross-site request forgery

Cross-site request forgery (CSRF) is an obfuscated proxy attack that induces a user’s browser to perform a malicious HTTP request (using that user’s permissions) on behalf of the attacker.

This is generally easy to solve in two steps:

  • Using HTTPS. This is a prerequisite. Without HTTPS, any protection is vulnerable, although HTTPS itself does not protect against CSRF.
  • Add basic challenge-Response authentication.
    • Add a hidden form attribute for each form.
    • Fill in a password-safe random value (called a token).
    • Verify that hidden form attributes are provided and match the expected value.

We wrote a library called anti-csrf and:

  • You can limit each token to one use to prevent replay attacks.
    • Multiple tokens are stored at the back end.
    • Once the token is acquired, the token is recycled.
  • Each token can be bound to a specific URL.
    • If a token is compromised, it cannot be used in a different context.
  • Tokens can be bound to specific IP addresses.
  • After V2.1, tokens can be reused (for example, for Ajax use).

If you don’t use a framework to prevent CSRF vulnerabilities, put anti-CSRF aside. In the near future, SameSite cookies will allow us to more easily avoid CSRF attacks.

XML attack (XXE, XPath Injection)

There are two major vulnerabilities in applications that process large amounts of XML:

  • XML External Entities (XXE)
  • XPath injection

In addition, XXE attacks can be used as an initiator for local/remote files that contain the attack code.

Early versions of Google Docs were known as XXE, but were largely unheard of outside of business applications that used XML to a large extent.

Key mitigation measures against XXE attacks:

<? php libxml_disable_entity_loader(true);
Copy the code

XPath injection is very similar to SQL injection, except for XML documents.

Fortunately, passing user input to XPath queries is very rare in the PHP ecosystem.

Unfortunately, this also means that there are no best avoidance measures (precompiled and parameterized XPath queries) available in the PHP ecosystem. The best way to do this is to set a whitelist of allowed characters on any data that involves aN XPath query.

<? phpdeclare(strict_types=1);

class SafeXPathEscaper
{
    /**
     * @param string $input
     * @return string
     */
    public static function allowAlphaNumeric(string $input): string
    {
        return \preg_replace('#[^A-Za-z0-9]#'.' '.$input);
    }

    /**
     * @param string $input
     * @return string
     */
    public static function allowNumeric(string $input): string
    {
        return \preg_replace([^ 0-9] '# #'.' '.$input);
    }
}

// Usage:
$selected = $xml->xpath(
    "/user/username/" . SafeXPathEscaper::allowAlphaNumeric(
        $_GET['username']));Copy the code

Whitelists are always safer than blacklists.

Deserialization and PHP object injection

In depth: Implement (de) serialization safely in PHP

If you pass unserialize() untrusted data, it usually results in one of two things:

  • PHP object injection, which can be used to start a POP chain and trigger other vulnerabilities that misuse objects.
  • Memory corruption in the PHP interpreter itself.

Most developers prefer to use JSON serialization, which is a significant improvement over their software security. But keep in mind that json_decode() is vulnerable to hashing denial-of-service (Hash-DOS) attacks. Unfortunately, PHP’s Hash-DOS problem has not been completely resolved.

Migrating from DJb33 to Siphash with the highest bit of hash output set to 1 for string input and 0 for integer input, using the request key provided by CSPRNG, will fully resolve these attacks.

Unfortunately, the PHP team isn’t ready to give up the performance improvements they’ve already achieved with the PHP 7 series, so it’s hard to convince them to abandon DJB33 (which is very fast but not as secure) in favor of SipHash (which is also fast, but not as fast, but more secure). If performance is significantly affected, it may hinder adoption of future versions, but it also affects security.

Therefore, the best approach is:

  • useJSONBecause it is better thanunserialize()More secure.
  • Wherever possible, ensure that input is authenticated before deserialization.
    • The data provided to the user is used through a secret key known only to the serversodium_crypto_auth()andsodium_crypto_auth_verify()Validation.
    • For data provided by third parties, let them use itsodium_crypto_sign()Sign their JSON messages and usesodium_crypto_sign_open()And a third-party public key to validate the message.
    • If you need to encode the transmitted signature in hexadecimal or Base64 bits, you can also use a separate signing API.
  • If you can’t validate JSON strings, strictly limit speed and block IP addresses to mitigate repeat offenders.

A cryptographic hash

In 2016, how to save your password safely

Secure password storage was once a hotly debated topic, but is now fairly trivial to implement, especially in PHP:

<? php$hash = \password_hash($password, PASSWORD_DEFAULT);

if (\password_verify($password.$hash)) {
    // Authenticated.
    if (\password_needs_rehash($hash, PASSWORD_DEFAULT)) {
        // Rehash, update database.
    }
}
Copy the code

You don’t even need to know what algorithm to use in the background, because if you’re using the latest version of PHP, you’ll also be using the latest technology, and the user’s password will be automatically updated (as soon as a new default algorithm is available).

Whatever you do, don’t do what WordPress does.

From PHP 5.5 through 7.2, the default algorithm is Bcrypt. In the future, it may switch to Argon2, which won the password hash contest.

If you haven’t used the Password_ * API before and need to migrate legacy hashes, make sure you do so. Many companies got it wrong, most notably Yahoo. Recently, incorrectly implementing traditional hash upgrades seems to have led to Apple’s iamroot error.

General encryption

Here are some of the topics we’ve written about in detail:

  • Using Encryption and Authentication Correctly (2015)
  • Recommended: Choosing the Right Cryptography Library for your PHP Project: A Guide (2015)
  • Recommended: You Wouldn’t Base64 a Password – Cryptography Decoded (2015)
  • Cryptographically Secure PHP Development (2017)
  • Recommended: Libsodium Quick Reference: Similarly-Named Functions and Their Use-Cases (2017)

In general, you’ll always want to use the Sodium Cryptography Library (libsodium) for application layer encryption. If you need to support PHP versions older than 7.2 (like 5.2.4), you can use sodium_compat, basically assuming that your users are also 7.2.

In certain cases, due to strict algorithm selection and interoperability, you may need different libraries. If in doubt, consult a password expert and password engineer to find out if your password choice is secure (this is one of the services we offer).

randomness

In depth: How to generate safe integers and strings in PHP?

If you need random numbers, use random_int(). If you need a random byte string, use random_bytes(). Do not use mt_rand(), rand(), or uniqid().

If you need to generate a pseudorandom from a secret seed, use SeedSpring instead of srand() or mt_srand().

<? php use ParagonIE\SeedSpring\SeedSpring;$seed = random_bytes(16);
$rng = new SeedSpring($seed);

$data = $rng->getBytes(1024);
$int = $rng->getInt(1, 100);
Copy the code

HTTPS request on the server

Ensure that TLS certificate validation is not disabled

Feel free to use any PSR-7-compatible HTTP client you’re already familiar with. We like Guzzle, some people like to use cURL directly.

Whatever you end up using, be sure to use certainty to ensure you always have the latest CACert package available, allowing for the strictest TLS certificate validation Settings and protecting your server from outbound HTTPS requests.

Installation of Certainty is simple:

composer require paragonie/certainty:^1
Copy the code

Using Certainty is also simple:

<? php use ParagonIE\Certainty\RemoteFetch;$latestCACertBundle = (new RemoteFetch())->getLatestBundle();

    # cURL users:
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_CAINFO, $latestCACertBundle->getFilePath());

    # Guzzle users:
    /** @var \GuzzleHttp\Client $http* /$repsonse = $http->get(
        'https://example.com'['verify'= >$latestCACertBundle->getFilePath()
        ]
    );
Copy the code

This protects you from man-in-the-middle attacks between the web server and any third-party apis that are integrated.

Do we really need Certainty?

Certainty is not a requirement to protect your system. The lack of it is not a bug. But without Certainty, open source software must guess where the operating system’s CACert package exists, and if it guesses incorrectly, it often fails and causes usability problems. Historically, this has inspired many developers to simply disable certificate validation so that their code “works”, not realizing that they are just turning the application into an active attack. Mr Certainty eliminated this incentive by tying CACert to the latest predictable location. Mr Certainty also provides companies with a number of tools for running their own internal CAS.

Who disabled certificate validation?

Plugin/extension developer for popular content management systems (WordPress, Magento, etc. CMS)! This is a huge problem that we’re trying to solve at the ecosystem level. It is not isolated to any particular CMS, you will find that these unsafe plug-ins etc are similar.

If you are using a similar CMS, search the plug-in for CURLOPT_SSL_VERIFYPEER and CURLOPT_SSL_VERIFYHOST, and you may find several that set these values to FALSE.

Things to avoid

  • Don’t usemcrypt. This is a cryptographic library that has not been developed in over a decade. If you follow our PHP version recommendations, this should be an easy mistake to avoid becausemcryptNo longer supported by PHP 7.2 and later.
  • Configure security suggestions for driversShould be largely ignored. If you’re reading PHP security guidelines that tell you to change your php.ini Settings instead of writing better code, you’re probably reading outdated advice. Close the window and go to some andregister_globalsFor an unrelated article.
  • Don’t use JOSE (JWT, JWS, JWE), a set of Internet standards that codifies a series of error-prone password designs. Although, for some reason, it was written into the standard and attracted a lot of preachers.
  • Encrypting URL parameters is a common anti-pattern used by companies to obscure metadata (for example, how many users do we have?). . It creates a high risk of error and a false sense of security. We suggest a safer option in the linked article.
  • Don’t offer the “I forgot my password” feature unless you absolutely have to. Make no bones about it: password reset is a backdoor. There are methods that can be implemented to defend against legitimate threat models, but high-risk users should not be considered.
  • Avoid RSA and use libsodium instead. If you must use RSA, be sure to specify OAEP padding.
<? php openssl_private_decrypt($ciphertext.$decrypted, // Plaintext gets written to this variable upon success,
    $privateKey, OPENSSL_PKCS1_OAEP_PADDING // Important: DO NOT OMIT THIS! ) ;Copy the code

If you have to fill with PKCS# 1 v1.5, then whichever you integrate with will almost certainly be affected by ROBOT, please report it to the appropriate vendor (or us-cert) with a vulnerability that allows plaintext leakage and signature forgery.

Professional use

Now that you have the basics of building secure PHP applications in 2018 and beyond, let’s look at some more professional uses.

Searchable encryption

In depth: Build a searchable encrypted database using PHP and SQL

A searchable encrypted database would be desirable, but widely considered unlikely. The blog post linked above attempts to do this by improving our solution, but essentially looks like this:

  • Design your schema so that the Database Compromise does not give attackers access to your encryption keys.
  • Encrypt data with a key.
  • Create multiple indexes (with their own unique keys) based on HMAC or Secure KDF with a Static salt
  • Optional: Truncate the output of Step 3 and use it as a Bloom filter
  • Use the output of steps 3 or 4 in the SELECT query
  • Decrypt the results.

At any step in the process, you can make different trade-offs based on actual usage.

No side-channels token-based authentication

Split Tokens: Token-based Authentication Protocols without Side-channels

Speaking of databases (in the previous section), did you know that SELECT queries could theoretically be a source of timed information leaks?

Simple mitigation measures:

  • Split your authentication token in half
  • Half are used in SELECT queries
  • The latter half is validated at constant-time
    • Optionally, the second half of the hash is stored in the database. This makes sense for tokens that can only be used once, such as a password reset or a “remember me on this computer” token

Even if half of the tokens could be stolen using timed leaks, the rest would require brute force to succeed.

Develop secure apis

Rolling Your PHP-powered APIs with Sapient

We wrote SAPIENT (The Secure API ENgineering Toolkit) to make messaging for server-to-server authentication easy. In addition to the security provided by HTTPS, Sapient allows you to encrypt and authenticate messages using shared or public keys. This allows you to use Ed25519 to authenticate API requests and responses, or to encrypt messages to a target server that can only be decrypted by the recipient server’s key, even if there is an intermediate attacker and a rogue certificate authority. Since every HTTP message body is authenticated by a secure password, it can safely be used as a substitute for Stateful Token juggling protocols (such as OAuth). However, in cryptography, before doing anything irregular, always make sure that their implementation is studied by experts.

All cryptography algorithms used by Sapient are provided by the Sodium Cryptography Library.

Further reading:

  • Sapient Documentation
  • Sapient Tutorial
  • Sapient Specification

Paragon Initiative Enterprises has used Sapient in many of its products, including many open source software projects, and will continue to add software projects to the Sapient user base.

Use Chronicle to document security events

Chronicle Will Make You Question the Need for Blockchain Technology

Chronicle, an app-only Cryptographic Ledger based on a hash chain data structure, has many of the attributes that appeal to corporate “blockchain” technology without overdoing it.

In addition to the creative use case of append only cryptographic ledger, Chronicle can be very interesting when integrated into SIEM because you can send security-critical events to a private Chronicle, And they can’t be changed.

If your Chronicle is set up to cross-sign its digest hashes to other Chronicle instances, or if other instances are configured to copy your Chronicle content, it will be difficult for an attacker to tamper with your security event log.

With Chronicle’s help, you can achieve the resilience that blockchain promises without any privacy, performance or scalability issues.

To publish data to the local Chronicle, you can use any of the Sapient-Compatible apis, but the simplest solution is called Quill.

Some words from the author

Some smart readers may have noticed that we cite a lot of our own work, including blog posts and open source software. (and not just citing our own work, of course)

This is no accident.

Since we launched in early 2015, we have been writing security libraries and participating in efforts to improve the security of the PHP ecosystem. We’ve covered a lot of ground, and our security engineers (who recently pushed for more secure encryption to be added to PHP’s core, as recently as PHP 7.2) vouch for not being good at self-hype or staying enthusiastic about what they’ve done. But you probably haven’t heard about the tools or libraries we’ve been developing over the years. I’m sorry about that.

We can’t be pioneers anyway, so we try to work with industry experts who value the common good over the small profits. This is why many of the sections on browser security refer to the work of Scott Helme and his company in making these new security features accessible and understandable to developers.

This guide is certainly not exhaustive. There are almost as many ways to write unsafe code as there are ways to write code. Security is a state of mind, not a destination. With all that has been written above, and the resources that follow, we hope this will help developers around the world start writing secure software in PHP today.

resources

If you’ve followed everything on this page and need more, you might be interested in our curated reading list to learn about application security.

If you think your code is secure enough and you want us to judge it as a security engineer, that’s what we do for our customers.

If you work for a company that does compliance testing (PCI-DSS, ISO 27001, etc.), you may also want to hire our company to audit your source code. Our process is better suited to developers than other security consulting firms.

What follows is a list of resources provided by PHP and the information security community to help make the Internet more secure.

  • PHP: The Right Way: A practical guide to modern PHP development, free online.

  • Mozilla’s SSL Config Generator

  • Let’s Encrypt: Certificate authorities that have done a lot to create a more secure Internet by providing free TLS certificates.

  • Qualys SSL Labs: Provides a quick and easy test suite for TLS configurations. Almost everyone uses this to solve their password set and certificate problems, and for good reason: It does its job well.

  • Security Headers: Verifies how well your site is protecting users with browser Security features.

  • Report-uri: a great free resource that provides real-time security reporting services that monitor security policies such as CSP/HPKP. They give you a report-URI that you can pass to your user’s browser, and if something happens or someone finds an XSS attack medium, they’ll complain about the report-URI. The report-URI summarizes these errors and allows you to better troubleshoot and categorize these reports.

  • PHP Security Advent Calenda: The team under RIPSTech is responsible.

  • Snuffleupagus: a security-oriented PHP module (spiritual successor to Suhosin, which seems likely to be largely abandoned)

  • PHP Delusions: a site dedicated to making better use of PHP. Most of the tone is very insightful, and the author’s dedication to technical accuracy and clarity makes it worth reading, especially for those who aren’t too keen on PDO features.

  • Have I Been Pwned? : Helps users find out if their data is an outdated data breach.

At the end

The 2018 Guide to Building Secure PHP Software – P.I.E. Staff


Original text: laravel-china.org/articles/72…