Skip to content

[Enhancement]: Security strategy for OSPOS #3965

Open

Description

@objecttothis

During the conversion to CI4 we need to make sure that our code security strategy is rock solid. This will lay the groundwork for 3rd-party integrations so that we can have a foundational set of code standards for security.

Escaping outputs:

  • Many of the built-in CodeIgniter 4 library functions automatically escape outputs. Examples of this are form_input(), form_password(), form_upload(), form_textarea(), form_dropdown(), form_multiselect(), form_checkbox() and form_radio(). anchor() also is automatically escaped, so no need to do anything with those.
  • Output outside of this should always be wrapped in esc() and using the correct context as a 2nd parameter.
  • Use bootstrap_tables built-in escaping of table data which allows passing of raw data through the JSON.

Validation of Inputs:

  • CodeIgniter has validation mechanisms that allow us to return errors to the user when invalid data is sent.
  • We need to be validating textboxes and other form input for correct data, and required data.

Query Security:

  • CodeIgniter4's Query Builder should be used when possible. This is because QueryBuilder has automatic escaping of queries and creates parameterized queries.
  • Any time queries are not written with QueryBuilder or QueryBuilder->rawSql() is used, $this->db->escape() should be wrapped around variables being inserted into the database and $this->db->protect_identifiers() should be wrapped around variables representing table or column names. protect_identifiers fails in many cases, so input must be validated using allow list.

Database Security:

  • Encryption of all information which can be used to identify an individual including names, addresses, phone numbers, email and addresses.
  • Passwords need to be hashed and salted.
  • Encryption of API keys used in API calls.

Now on to what I am less certain about:

  • CSRF is needed, but we need to do everything in such a way that it doesn't hinder APIs since those will be needed for third party integrations. If it's interfering, potentially using token authentication and APIKEYs in place of CSRF is warranted?
  • General best practice, I'm told, is to store html and tags in the database as they are entered (i.e., not encoded). Filtering inputs practices though seems to frequently suggestion wrapping $_POST (getPost() in CI4) in htmlspecialchars() since getPost($foo, FILTER_SANITIZE_STRING) is deprecated. Those functions encode special characters though before they get sent to the model for storing in the database. So the big question is what does Filtering Inputs need to look like?
  • One option is simply stripping unwanted data. For example with phone numbers we may wrap that in a preg_replace() that filters anything that is not '(', ')', ' ', '-', '+','[0-9]' and maybe 'x' or '/' for indicating extension numbers. We only have certain kinds of data, so it seems reasonable to have a handful of functions in the security_helper to properly filter these kinds of values without mangling the text. It also makes sense to use the 2nd parameter of getGet() and getPost() where it doesn't mangle text since those are already written. In places we want some HTML tags to be allowed (such as descriptions and attribute text) perhaps using something like https://github.com/ezyang/htmlpurifier rather than strip_tags() would be a good approach.

What's wrong? What's missing?
@jekkos , et. al. thoughts?

Activity

  1. added
    CodeIgniter4
    on Apr 2, 2024
  2. added this to the 3.4.0 milestone on Apr 2, 2024
  3. self-assigned this
    on Apr 2, 2024
  4. jekkos commented on Apr 10, 2024

    @jekkos
    Member

    Escaping output

    • I would also use bootstrap tables builtin escape functionality so that we can just echo the raw data in json objects

    Validation of inputs

    • Server side validation is mandatory. Clientside or javascript validation is optional and will make the UI more user friendly. The latter can trigger faster as we do not always need to do a full server roundtrip

    Query security

    • Recently I reviewed this ticket on blind SQL injection. I wonder if this issue is still present in CI4. The issue was that the sort in the builder accepts a field name that could be manipulated to run custom SQL. The fix was never merged but it should be revisited and could be a good sanity check on the CI4 protections

    Database security

    • Encrypting user data might be tricky, how will we query it if the database contains encrypted values? Then all query input needs to be encrypted as well

    CSRF

    • If your application is attaching the credentials via an Authorization header then the browser can't automatically authenticate the requests, and CSRF isn't possible. I believe I never saw CSRF mitigation and probably because browser do not send this header automatically

    • This point I agree and tried to explain already few times. In my opinion we should not try to do escaping on the input. We should escape the data right before rendering it instead. The reason is that wee do not know in what context an input will need to be shown. It can be HTML, XML, javascript, or something else. The way escaping is done is different in every context and it won't work when it the text that needs to be rendered was already escaped in some other way

    • This last comment is in my opinion a validation step. Basically we try to normalize certain fields before it goes to the database.

  5. objecttothis commented on Apr 15, 2024

    @objecttothis
    MemberAuthor

    @jekkos I looked into the vulnerability a little and here is what Github Copilot came back with.
    image

    It appears we are using QueryBuilder in most places, but we should search the code for places where we have sorting in the query but we aren't using QueryBuilder.
    image

    I had also added filters into the getGet() methods to filter the inputs and this should add to the protection provided by QueryBuilder.
    image

    It wouldn't hurt to also add some validation as well, but I'd be curious to see if the original attack vector was closed properly. Where is the original vulnerability report?

  6. jekkos commented on Apr 17, 2024

    @jekkos
    Member
  7. objecttothis commented on Apr 17, 2024

    @objecttothis
    MemberAuthor

    This was a concrete example https://huntr.com/bounties/eccf7762-efb4-4db6-a1de-1030331f34d7

    OK if someone else doesn't get to it then I'll try it on Monday when I'm working on this project again.

  8. objecttothis commented on Apr 17, 2024

    @objecttothis
    MemberAuthor

    @jekkos it doesn't give me access to your dashboard. Are you able to either email it to me or send the report and example to the devroom in glitter? I'm not sure if that site allows sharing of a dashboard with multiple maintainers but that could be an option as well.

  9. objecttothis commented on Apr 17, 2024

    @objecttothis
    MemberAuthor

    @jekkos I think I'm just too much of a sucker for a good vulnerability hunt. I couldn't wait until Monday. Unfortunately here is the SQL being generated:

    SELECT *
    FROM `ospos_giftcards`
    LEFT JOIN `ospos_people` AS `person` ON `ospos_giftcards`.`person_id` = `person`.`person_id`
    WHERE   (
    `person`.`first_name` LIKE '%%' ESCAPE '!'
    OR  `person`.`last_name` LIKE '%%' ESCAPE '!'
    OR  CONCAT(person.first_name, " ", person.last_name) LIKE '%%' ESCAPE '!'
    OR  `ospos_giftcards`.`giftcard_number` LIKE '%%' ESCAPE '!'
    OR  `ospos_giftcards`.`person_id` LIKE '%%' ESCAPE '!'
     )
    AND `ospos_giftcards`.`deleted` = 0
    ORDER BY (SELECT (CASE WHEN (5937=5937) THEN 1 ELSE (SELECT 4996 UNION SELECT 4231) END)) ASC
    

    So as you can see the ORDER BY clause is vulnerable to injection even in CI 4.5.1 using $builder->orderBy(). This particular injection is only returning '1', but it's proof of concept that the field is vulnerable.

    The solution I think is to filter and/or validate the inputs

    		$search = $this->request->getGet('search', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    		$limit  = $this->request->getGet('limit', FILTER_SANITIZE_NUMBER_INT);
    		$offset = $this->request->getGet('offset', FILTER_SANITIZE_NUMBER_INT);
    		$sort   = $this->request->getGet('sort', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    		$order  = $this->request->getGet('order', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    
    		if(!in_array($sort, $giftcard->get_sortable_columns()))
    		{
    			// Invalid sort column, handle the error
    		}
    
    		if(!in_array($order, ['ASC','DESC']))
    		{
    			// Invalid order direction, handle the error
    		}
    
    		$giftcards = $this->giftcard->search($search, $limit, $offset, $sort, $order);
    

    Maybe do this or just silently filter out anything that is not a valid input. I think it would involve creating a field in each model we do sorting and a getter function to return an array of sortable columns, since we may not want sorting on every column. thoughts?

  10. objecttothis commented on Apr 17, 2024

    @objecttothis
    MemberAuthor

    If we want to use CodeIgniter's validation engine, it wouldn't be too difficult to write a custom rule. You can even pass the acceptable sort columns to the rule. It's pretty clean that way. Then if it doesn't pass validation we can do what we want with it.

  11. jekkos commented on Apr 17, 2024

    @jekkos
    Member

    @objecttothis are you sure that it is vulnerable? I just tried this url
    https://dev.opensourcepos.org/giftcards/search?search=&offset=0&limit=25&sort=(SELECT%20(CASE%20WHEN%20(5937=5937)%20THEN%201%20ELSE%20(SELECT%204996%20UNION%20SELECT%204231)%20END))

    it does not seem to misbehave at first sight

  12. jekkos commented on Apr 17, 2024

    @jekkos
    Member

    No you are right, it's still vulnerable. I tried this one sort=1 AND (SELECT 3335 FROM (SELECT(SLEEP(5)))uafX) and the response is delayed with a couple of seconds, meaning that the sleep is indeed executed.

    The PR that I did was indeed about to validate the parameter passed in to the sort column. In this case it would check whether the param has a column name that is present in the db, if not then it would fall back to a default sorting order and ignore the input.

  13. objecttothis commented on Apr 17, 2024

    @objecttothis
    MemberAuthor

    Take a look at the query I posted. That's the result of $builder->getCompiledSelect(). It runs the injected select which just produces '1' on my database rather than enumerating tables, however it's enough for me to know that SQL isn't being escaped going into queryBuilder->orderBy(). So, if more malicious SQL is injected we need to be doing something. Maybe I'm not reading this right. Am I missing something?

  14. objecttothis commented on Apr 17, 2024

    @objecttothis
    MemberAuthor

    Take a look at the query I posted. That's the result of $builder->getCompiledSelect(). It runs the injected select which just produces '1' on my database rather than enumerating tables, however it's enough for me to know that SQL isn't being escaped going into queryBuilder->orderBy(). So, if more malicious SQL is injected we need to be doing something. Maybe I'm not reading this right. Am I missing something?

    (SELECT (CASE WHEN (5937=5937) THEN 1 ELSE (SELECT 4996 UNION SELECT 4231) END))

  15. 12 remaining items

  16. changed the title [-]Security Strategy[/-] [+][Enhancement]: Security strategy for OSPOS[/+] on Apr 1, 2026
  17. jekkos commented on Aug 26, 2026

    @jekkos
    Member

    Security advisory template compliance - DONE

    All 22 published security advisories now conform to the SECURITY.md vulnerability report template.

    Changes applied to every advisory:

    1. ### Impact rewritten to the 5-bullet template format, derived from the CVSS score stored in the structured GitHub fields:
      • Confidentiality / Integrity / Availability: N=Low, L=Medium, H=High (from the CVSS vector)
      • Privilege Required: N=None, L=Low, H=High
      • CVSS v3.1: score + full vector string
    2. ### Affected Versions section added: affected range + fixed-in version.
    3. Patched versions backfilled to 3.4.2 (GitHub structured patched_versions field) for the 5 advisories that were previously blank; all fixes verified present on master:
      • GHSA-66mv-2hrc-v4ff - unauthenticated /migrate (partial upstream fix; set to 3.4.2 by decision)
      • GHSA-c74h-4v79-7xqj - SQL injection via currency symbol
      • GHSA-hmjv-wm3j-pfhw - SQL injection in item search
      • GHSA-jchf-7hr6-h4f3 - Host header injection
      • GHSA-q58g-gg7v-f9rf - stored XSS in item descriptions
    4. Preserved unchanged: Summary / Details / PoC / Patch / References. Credit is kept in the GitHub structured credits field only (not duplicated in the description).

    Edge cases handled:

    • GHSA-86fx-63rc-rg56 - no CVSS score assigned yet; Impact bullets marked n/a (not yet classified) and CVSS line marked pending (score can be added later)
    • GHSA-94jm-c32g-48r5 & GHSA-xgr7-7pvw-fpmh - had malformed version ranges (<= 3.4., > 3.4.0); normalized to <= 3.4.1
    • Two advisories had an invalid package.ecosystem value that the PATCH API rejects on re-edit; normalized to a valid value (other)

    Result: 22/22 published advisories verified conformant (structured 5-bullet Impact + Affected Versions + set patched versions).

  18. jekkos commented on Aug 28, 2026

    @jekkos
    Member

    CVSS scoring applied to the 7 in-draft advisories

    The seven advisories that were still in draft and had no structured CVSS score now each have a CVSS v3.1 vector assigned. GitHub computes and stores the score server-side, and the severity field is derived from it automatically. All severities/vectors are anchored to the same vectors already used by published advisories in this repo (e.g. the 9.9 RCE mirrors GHSA-8573-73r6-mhwv).

    Advisory Title Severity Score Vector
    GHSA-5j9m-2f98-cjqw SQL Injection in Summary Sales Taxes Report high 8.8 AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H
    GHSA-995p-52qw-5hh2 Race condition: gift-card / reward-points / inventory double-spend medium 6.5 AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:N
    GHSA-v5mv-5cg8-gghr reCAPTCHA bypass via premature session authentication medium 6.5 AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N
    GHSA-hwjh-f7jr-846c RCE via dompdf (sales_quote_format) critical 9.9 AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H
    GHSA-xq63-3v4g-39r5 Path traversal in getPicThumb (arbitrary file read) medium 6.5 AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:N/A:N
    GHSA-h6wm-fhw2-m3q3 RCE via receipt_template (view-include path traversal) critical 9.9 AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H
    GHSA-9qx8-x8m6-2wcp Missing server-side authorization on sales/editItems medium 6.5 AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:N

    How the scores were chosen.

    • Vectors were taken from each advisory's own description where one was already present. Where none was stated (both RCEs, the SQLi, the missing-Authorization), I derived them from the vulnerability class + the access level stated in the report and cross-checked against the nearest published advisory:
      • RCE pair (hwjh, h6wm) → 9.9 / Critical, mirroring the published GHSA-8573-73r6-mhwv (same PR:L / S:C / C:H/I:H/A:H), the only RCE that already had a structured score set.
      • SQLi (5j9m) → AV:N/AC:L/PR:L...C:H/I:H/A:H (full read+write+DoS of the DB) ⇒ 8.8, consistent with other PR:L auth-required issues that compromise integrity and availability.
      • Missing authorization (9qx8) and race conditions (995p) → integrity-only impact (C:N/I:H/A:N) ⇒ 6.5, matching the published mcc2/wv3j race/auth advisories.
      • Path-traversal file read (xq63) → confidentiality-only (C:H/I:N/A:N) ⇒ 6.5, matching 9gr6.
      • reCAPTCHA bypass (v5mv) → unauthenticated session-theft primitive with low per-guess signal ⇒ AV:N/AC:L/PR:N...C:L/I:L/A:N ⇒ 6.5 (I corrected a 5.3 that was stated in the description, which under-stated the impact of an unauthenticated authenticated-session hand-off; 6.5 aligns it with the other auth-bypass class in this repo). GitHub's server-side score for this vector is 6.5.
    • Consistency: severity is now whatever derives directly from the vector (High=5.0–8.9, Critical=9.0–10.0, Medium=4.0–6.9), so there is no mismatch between the severity field, the score, and the vector.

    These are still drafts — nothing has been published. If any of the above vectors disagree with how you actually classify the severity (especially the two 9.9s and the reCAPTCHA one), tell me and I'll adjust the vector before anything goes public.

  19. jekkos commented on Oct 2, 2026

    @jekkos
    Member

    @CodeRabbit can be closed?

  20. coderabbitai commented on Oct 2, 2026

    @coderabbitai
    Contributor
    🧩 Analysis chain

    🏁 Script executed:

    #!/bin/bash
    set -euo pipefail
    gh issue view 3965 --repo opensourcepos/opensourcepos --json title,body,state,url,comments --jq '{title,body,state,url,comments: [.comments[] | {author: .author.login,body}]}'

    Length of output: 18407


    @jekkos Yes—as a completed security-strategy discussion, provided the remaining work is tracked separately.

    The advisory updates complete the documentation work. They do not, by themselves, confirm that all vulnerabilities or security controls are resolved.

    Before closing #3965, I recommend a short summary that:

    • Links the fix for the original sort / ORDER BY injection.
    • Confirms that each draft advisory has separate remediation tracking.
    • Identifies any deferred decisions, such as personal-data encryption and API authentication/CSRF handling.

    Then close this issue without treating closure as confirmation that OSPOS has no remaining security issues.

    I have not closed the issue.

    You are interacting with an AI system.

  21. objecttothis commented on Nov 6, 2026

    @objecttothis
    MemberAuthor

    Claude Issue Checker Agent (cc @objecttothis)

    Investigated against current master.

    Status: Substantially addressed for the concrete vulnerability discussed, but the broader "security strategy" checklist in the issue body is only partially implemented.

    This issue is a broad design/strategy document (escaping, input validation, query security, DB encryption, CSRF, filtering), and the thread's concrete, tested finding was a blind SQL injection via the sort/order GET parameters flowing unsanitized into QueryBuilder::orderBy() (demonstrated live against /giftcards/search with a SLEEP() payload).

    • That specific vulnerability is fixed on master. Secure_Controller::sanitizeSortColumn($headers, $field, $default) validates the requested sort column against an explicit allow-list derived from each view's header definitions, falling back to a safe default otherwise. I verified all 15 controllers that read a sort GET parameter (grep -rl "getGet('sort'" app/Controllers) call sanitizeSortColumn before passing it to a model's search()/orderBy() call — including Giftcards.php ($sort = $this->sanitizeSortColumn(giftcard_headers(), $this->request->getGet('sort', ...), 'giftcard_id')), the exact controller from the reported PoC.
    • Broader items are mixed:
      • DB connection encrypt is false by default (app/Config/Database.php) and there's no field-level PII encryption of names/addresses/emails in the schema — the "Database Security" bullet (encrypting identifying information) has not been implemented.
      • app/Config/Encryption.php exists for general-purpose encryption (used elsewhere, e.g. .env key rotation per issue Isolate PHPUnit encryption bootstrap from persistent configuration and conversion #4775), but it's not applied to personal-data columns.
      • A large volume of security-advisory cleanup/scoring work (documented in this thread) was completed in Aug 2026, but that's documentation of already-known vulnerabilities, not a statement that the full strategy checklist (CSRF/API-key auth design, systematic input-filtering helpers, etc.) is done.
    • CodeRabbit's own bot comment on this thread (Oct 2026) reached a similar conclusion: the advisory work is a reasonable basis to close as a discussion, but shouldn't be read as confirming all underlying security work is complete.

    Given this is an open-ended strategy issue rather than a single bug, I'd call the specific regression that was found and tested (ORDER BY injection) resolved, while the issue's full scope (DB-level PII encryption, a documented CSRF/API-key policy) remains partially open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

CodeIgniter4

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions