user_guide_src/source/concepts/security.rst
################### Security Guidelines ###################
We take security seriously. CodeIgniter incorporates a number of features and techniques to either enforce good security practices, or to enable you to do so easily.
We respect the Open Web Application Security Project (OWASP) <https://owasp.org>_
and follow their recommendations as much as possible.
The following comes from
OWASP Top Ten <https://owasp.org/www-project-top-ten/>_ and
OWASP API Security Top 10 <https://owasp.org/API-Security/editions/2023/en/0x11-t10/>_
identifying the top vulnerabilities for web applications and apis.
For each, we provide a brief description, the OWASP recommendations, and then
the CodeIgniter provisions to address the problem.
.. contents:: :local: :depth: 2
OWASP Top 10 2021
Access control enforces policy such that users cannot act outside of their intended permissions. Failures typically lead to unauthorized information disclosure, modification, or destruction of all data or performing a business function outside the user's limits.
Common access control vulnerabilities include:
Access control is only effective in trusted server-side code or server-less API, where the attacker cannot modify the access control check or metadata.
Public <application-structure-public> folder, with application and system
outside../libraries/validation librarySecurity </libraries/security> library provides for
:ref:CSRF protection <cross-site-request-forgery>../libraries/sessions library../libraries/throttler for rate limit../libraries/cors filterlog_message() function for loggingCodeIgniter Shield <shield>The first thing is to determine the protection needs of data in transit and at rest. For example, passwords, credit card numbers, health records, personal information, and business secrets require extra protection, mainly if that data falls under privacy laws, e.g., EU's General Data Protection Regulation (GDPR), or regulations, e.g., financial data protection such as PCI Data Security Standard (PCI DSS). For all such data:
Do the following, at a minimum, and consult the references:
Config\App::$forceGlobalSecureRequests)force_https() function../libraries/encryptiondatabase config <database-config-explanation-of-values> (encrypt)CodeIgniter Shield <shield>An application is vulnerable to attack when:
Some of the more common injections are SQL, NoSQL, OS command, Object Relational Mapping (ORM), LDAP, and Expression Language (EL) or Object Graph Navigation Library (OGNL) injection. The concept is identical among all interpreters. Source code review is the best method of detecting if applications are vulnerable to injections. Automated testing of all parameters, headers, URL, cookies, JSON, SOAP, and XML data inputs is strongly encouraged. Organizations can include static (SAST), dynamic (DAST), and interactive (IAST) application security testing tools into the CI/CD pipeline to identify introduced injection flaws before production deployment.
Preventing injection requires keeping data separate from commands and queries:
The preferred option is to use a safe API, which avoids using the interpreter entirely, provides a parameterized interface, or migrates to Object Relational Mapping Tools (ORMs).
Use positive server-side input validation. This is not a complete defense as many applications require special characters, such as text areas or APIs for mobile applications.
For any residual dynamic queries, escape special characters using the specific escape syntax for that interpreter.
Use LIMIT and other SQL controls within queries to prevent mass disclosure of records in case of SQL injection.
urls-uri-securityinvalidchars filter../libraries/validation libraryesc() functionHTTP library <../incoming/incomingrequest> provides for
:ref:input field filtering <incomingrequest-filtering-input-data>content-security-policy../database/query_builderDatabase escape methods <database-queries-escaping>database-queries-query-bindingsInsecure design is a broad category representing different weaknesses, expressed as “missing or ineffective control design.” Insecure design is not the source for all other Top 10 risk categories. There is a difference between insecure design and insecure implementation. We differentiate between design flaws and implementation defects for a reason, they have different root causes and remediation.
A secure design can still have implementation defects leading to vulnerabilities that may be exploited. An insecure design cannot be fixed by a perfect implementation as by definition, needed security controls were never created to defend against specific attacks. One of the factors that contribute to insecure design is the lack of business risk profiling inherent in the software or system being developed, and thus the failure to determine what level of security design is required.
PHPUnit testing <../testing/overview>../libraries/throttler for rate limitCodeIgniter Shield <shield>The application might be vulnerable if the application is:
Without a concerted, repeatable application security configuration process, systems are at a higher risk.
Secure installation processes should be implemented, including:
spark config:check <confirming-config-values> commandspark phpini:check <spark-phpini-check> commandProduction mode <environment-constant> by defaultsecureheaders filterYou are likely vulnerable:
There should be a patch management process in place to:
Every organization must ensure an ongoing plan for monitoring, triaging, and applying updates or configuration changes for the lifetime of the application or portfolio.
app-starter-upgrading by ComposerConfirmation of the user's identity, authentication, and session management is critical to protect against authentication-related attacks. There may be authentication weaknesses if the application:
Session <../libraries/sessions> libraryCodeIgniter Shield <shield>Software and data integrity failures relate to code and infrastructure that does not protect against integrity violations. An example of this is where an application relies upon plugins, libraries, or modules from untrusted sources, repositories, and content delivery networks (CDNs). An insecure CI/CD pipeline can introduce the potential for unauthorized access, malicious code, or system compromise.
Lastly, many applications now include auto-update functionality, where updates are downloaded without sufficient integrity verification and applied to the previously trusted application. Attackers could potentially upload their own updates to be distributed and run on all installations.
Another example is where objects or data are encoded or serialized into a structure that an attacker can see and modify is vulnerable to insecure deserialization.
This category is to help detect, escalate, and respond to active breaches. Without logging and monitoring, breaches cannot be detected. Insufficient logging, detection, monitoring, and active response occurs any time:
You are vulnerable to information leakage by making logging and alerting events visible to a user or an attacker (see A01:2021-Broken Access Control).
Developers should implement some or all the following controls, depending on the risk of the application:
There are commercial and open-source application protection frameworks such as the OWASP ModSecurity Core Rule Set, and open-source log correlation software, such as the Elasticsearch, Logstash, Kibana (ELK) stack, that feature custom dashboards and alerting.
Logging <../general/logging> libraryCodeIgniter Shield <shield>SSRF flaws occur whenever a web application is fetching a remote resource without validating the user-supplied URL. It allows an attacker to coerce the application to send a crafted request to an unexpected destination, even when protected by a firewall, VPN, or another type of network access control list (ACL).
As modern web applications provide end-users with convenient features, fetching a URL becomes a common scenario. As a result, the incidence of SSRF is increasing. Also, the severity of SSRF is becoming higher due to cloud services and the complexity of architectures.
Developers can prevent SSRF by implementing some or all the following defense in depth controls:
From Network layer:
Segment remote resource access functionality in separate networks to reduce the impact of SSRF
Enforce “deny by default” firewall policies or network access control rules to block all but essential intranet traffic.
Hints:
From Application layer:
Do not mitigate SSRF via the use of a deny list or regular expression. Attackers have payload lists, tools, and skills to bypass deny lists.
../libraries/validation libraryHTTP library <../incoming/incomingrequest> provides for
:ref:input field filtering <incomingrequest-filtering-input-data>OWASP API Security Top 10 2023
APIs tend to expose endpoints that handle object identifiers, creating a wide attack surface of Object Level Access Control issues. Object level authorization checks should be considered in every function that accesses a data source using an ID from the user.
CodeIgniter Shield <shield>PHPUnit testing <../testing/overview>Authentication mechanisms are often implemented incorrectly, allowing attackers to compromise authentication tokens or to exploit implementation flaws to assume other user's identities temporarily or permanently. Compromising a system's ability to identify the client/user, compromises API security overall.
../incoming/filtersrouting-spark-routes commandCodeIgniter Shield <shield>../libraries/throttler for rate limitThis category combines API3:2019 Excessive Data Exposure and API6:2019 - Mass Assignment, focusing on the root cause: the lack of or improper authorization validation at the object property level. This leads to information exposure or manipulation by unauthorized parties.
model-allowed-fieldsCodeIgniter Shield <shield>Satisfying API requests requires resources such as network bandwidth, CPU, memory, and storage. Other resources such as emails/SMS/phone calls or biometrics validation are made available by service providers via API integrations, and paid for per request. Successful attacks can lead to Denial of Service or an increase of operational costs.
../libraries/validation library../libraries/throttler for rate limitComplex access control policies with different hierarchies, groups, and roles, and an unclear separation between administrative and regular functions, tend to lead to authorization flaws. By exploiting these issues, attackers can gain access to other users’ resources and/or administrative functions.
Your application should have a consistent and easy-to-analyze authorization module that is invoked from all your business functions. Frequently, such protection is provided by one or more components external to the application code.
../incoming/filtersCodeIgniter Shield <shield>APIs vulnerable to this risk expose a business flow - such as buying a ticket, or posting a comment - without compensating for how the functionality could harm the business if used excessively in an automated manner. This doesn't necessarily come from implementation bugs.
The mitigation planning should be done in two layers:
Some of the protection mechanisms are more simple while others are more difficult to implement. The following methods are used to slow down automated threats:
Secure and limit access to APIs that are consumed directly by machines (such as developer and B2B APIs). They tend to be an easy target for attackers because they often don't implement all the required protection mechanisms.
Server-Side Request Forgery (SSRF) flaws can occur when an API is fetching a remote resource without validating the user-supplied URI. This enables an attacker to coerce the application to send a crafted request to an unexpected destination, even when protected by a firewall or a VPN.
Isolate the resource fetching mechanism in your network: usually these features are aimed to retrieve remote resources and not internal ones.
Whenever possible, use allow lists of:
Disable HTTP redirections.
Use a well-tested and maintained URL parser to avoid issues caused by URL parsing inconsistencies.
Validate and sanitize all client-supplied input data.
Do not send raw responses to clients.
../libraries/validation libraryHTTP library <../incoming/incomingrequest> provides for
:ref:input field filtering <incomingrequest-filtering-input-data>CURLRequest <../libraries/curlrequest> classURI <../libraries/uri> classAPIs and the systems supporting them typically contain complex configurations, meant to make the APIs more customizable. Software and DevOps engineers can miss these configurations, or don't follow security best practices when it comes to configuration, opening the door for different types of attacks.
The API life cycle should include:
Furthermore:
Ensure that all API communications from the client to the API server and any downstream/upstream components happen over an encrypted communication channel (TLS), regardless of whether it is an internal or public-facing API.
Be specific about which HTTP verbs each API can be accessed by: all other HTTP verbs should be disabled (e.g. HEAD).
APIs expecting to be accessed from browser-based clients (e.g., WebApp front-end) should, at least:
Restrict incoming content types/data formats to those that meet the business/ functional requirements.
Ensure all servers in the HTTP server chain (e.g. load balancers, reverse and forward proxies, and back-end servers) process incoming requests in a uniform manner to avoid desync issues.
Where applicable, define and enforce all API response payload schemas, including error responses, to prevent exception traces and other valuable information from being sent back to attackers.
Config\App::$forceGlobalSecureRequests)force_https() functionDefined Route Routing <defined-route-routing>auto-routing-improved../libraries/cors filterAPIs tend to expose more endpoints than traditional web applications, making proper and updated documentation highly important. A proper inventory of hosts and deployed API versions also are important to mitigate issues such as deprecated API versions and exposed debug endpoints.
routing-spark-routes commandDevelopers tend to trust data received from third-party APIs more than user input, and so tend to adopt weaker security standards. In order to compromise APIs, attackers go after integrated third-party services instead of trying to compromise the target API directly.
CURLRequest <../libraries/curlrequest> class../libraries/validation library