Publicus/cvefixes-security-ir-graphrag huggingface dataset:
CVE-2024-22194: Predictable Seed in Pseudo-Random Number Generator (PRNG) (CWE-337)
value: cdo-local-uuid project provides a specialized UUID-generating function that can, on user request, cause a program to generate deterministic UUIDs. An information leakage vulnerability is present in `cdo-local-uuid` at version `0.4.0`, and in `case-utils` in unpatched versions (matching the pattern `0.x.0`) at and since `0.5.0`, before `0.15.0`. The vulnerability stems from a Python function, `cdo_local_uuid.local_uuid()`, and its original implementation `case_utils.local_uuid()`. 
CWE description: A Pseudo-Random Number Generator (PRNG) is initialized from a predictable seed, such as the process ID or system time.
CVSS v3 base score: 2.8
Published: 2024-01-11T03:15Z
Repository: https://github.com/casework/CASE-Utilities-Python
Language: YAML
Files changed: .github/workflows/cicd.yml
Commit date: 2023-12-22 13:12:57 -0500
Commit message: Merge branches 'HotFix-0.8.1-refresh_pre_commit' and 'support-0.7.x' into release-0.8.1

Diff: diff --cc .github/workflows/cicd.yml
index ded9ba3,383e214..074471b
--- a/.github/workflows/cicd.yml
+++ b/.github/workflows/cicd.yml
@@@ -28,13 -30,13 +30,13 @@@ jobs
    build:
  
      runs-on: ubuntu-latest
      strategy:
        matrix:
-         python-version: 
-           - '3.7'
+         python-version:
+           - '3.8'
 -          - '3.10'
 +          - '3.11'
  
      steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-java@v3
        with:
diff --cc case_utils/local_uuid.py
index fd27fd2,3259214..5db3c00
--- a/case_utils/local_uuid.py
+++ b/case_utils/local_uuid.py
@@@ -30,17 -30,33 +30,33 @@@ DEMO_UUID_BASE: typing.Optional[str] = 
  DEMO_UUID_COUNTER: int = 0
  
  _logger = logging.getLogger(pathlib.Path(__file__).name)
  
  
+ def _is_relative_to(p1: pathlib.Path, p2: pathlib.Path) -> bool:
+     """
+     This function provides pathlib.is_relative_to to Pythons before 3.9.  After the End of Life of Python 3.8, this function can be removed.
+     """
+     if sys.version_info < (3, 9):
+         try:
+             _ = p1.relative_to(p2)
+             return True
+         except ValueError:
+             return False
+     else:
+         return p1.is_relative_to(p2)
+ 
+ 
  def configure() -> None:
      global DEMO_UUID_BASE
  
+     # _logger.debug("sys.argv = %r.", sys.argv)
+ 
      if os.getenv("DEMO_UUID_REQUESTING_NONRANDOM") == "NONRANDOM_REQUESTED":
          warnings.warn(
              "Environment variable DEMO_UUID_REQUESTING_NONRANDOM is deprecated.  See case_utils.local_uuid.demo_uuid for usage notes on its replacement, CASE_DEMO_NONRANDOM_UUID_BASE.  Proceeding with random UUIDs.",
 -            DeprecationWarning,
 +            FutureWarning,
          )
          return
  
      env_base_dir_name = os.getenv("CASE_DEMO_NONRANDOM_UUID_BASE")
      if env_base_dir_name is None:

Vulnerable code:          python-version: 
           - '3.7'
Fixed code:          python-version:
           - '3.8'
CVE-2024-22194: Insertion of Sensitive Information Into Debugging Code (CWE-215)
value: cdo-local-uuid project provides a specialized UUID-generating function that can, on user request, cause a program to generate deterministic UUIDs. An information leakage vulnerability is present in `cdo-local-uuid` at version `0.4.0`, and in `case-utils` in unpatched versions (matching the pattern `0.x.0`) at and since `0.5.0`, before `0.15.0`. The vulnerability stems from a Python function, `cdo_local_uuid.local_uuid()`, and its original implementation `case_utils.local_uuid()`. 
CWE description: The product inserts sensitive information into debugging code, which could expose this information if the debugging code is not disabled in production.
CVSS v3 base score: 2.8
Published: 2024-01-11T03:15Z
Repository: https://github.com/casework/CASE-Utilities-Python
Language: Python
Files changed: case_utils/case_sparql_select/__init__.py, setup.cfg
Commit date: 2023-12-22 11:02:52 -0500
Commit message: Merge branches 'HotFix-0.7.1-set_pyshacl_ceiling' and 'support-0.6.x' into release-0.7.1

Diff: diff --cc case_utils/case_sparql_select/__init__.py
index f609a12,87e2b50..64b44c5
--- a/case_utils/case_sparql_select/__init__.py
+++ b/case_utils/case_sparql_select/__init__.py
@@@ -105,17 -105,17 +105,17 @@@ def main() -> None
      ][0]
      variables = select_line.replace(" DISTINCT", "").replace("SELECT ", "").split(" ")
  
      tally = 0
      records = []
 -    select_query_object = rdflib.plugins.sparql.prepareQuery(
 +    select_query_object = rdflib.plugins.sparql.processor.prepareQuery(
          select_query_text, initNs=nsdict
      )
-     for (row_no, row) in enumerate(graph.query(select_query_object)):
+     for row_no, row in enumerate(graph.query(select_query_object)):
          tally = row_no + 1
          record = []
-         for (column_no, column) in enumerate(row):
+         for column_no, column in enumerate(row):
              if column is None:
                  column_value = ""
              elif (
                  isinstance(column, rdflib.term.Literal)
                  and column.datatype == NS_XSD.hexBinary
diff --cc setup.cfg
index 3e8384c,4f7050b..47c2ccb
--- a/setup.cfg
+++ b/setup.cfg
@@@ -18,16 -18,16 +18,16 @@@ license_files 
  
  [options]
  include_package_data = true
  install_requires =
      pandas
 -    pyshacl
 -    rdflib >= 6.0.2, < 6.3.0
 +    pyshacl < 0.22.0
-     rdflib >= 6.2.0
++    rdflib >= 6.2.0, < 6.3.0
      requests
      tabulate
  packages = find:
- python_requires = >=3.7
+ python_requires = >=3.8
  
  [options.entry_points]
  console_scripts =
      case_file = case_utils.case_file:main
      case_sparql_construct = case_utils.case_sparql_construct:main

Vulnerable code:      for (row_no, row) in enumerate(graph.query(select_query_object)):
         for (column_no, column) in enumerate(row):
     rdflib >= 6.2.0
Fixed code:      for row_no, row in enumerate(graph.query(select_query_object)):
         for column_no, column in enumerate(row):
+    rdflib >= 6.2.0, < 6.3.0
CVE-2024-22194: Predictable Seed in Pseudo-Random Number Generator (PRNG) (CWE-337)
value: cdo-local-uuid project provides a specialized UUID-generating function that can, on user request, cause a program to generate deterministic UUIDs. An information leakage vulnerability is present in `cdo-local-uuid` at version `0.4.0`, and in `case-utils` in unpatched versions (matching the pattern `0.x.0`) at and since `0.5.0`, before `0.15.0`. The vulnerability stems from a Python function, `cdo_local_uuid.local_uuid()`, and its original implementation `case_utils.local_uuid()`. 
CWE description: A Pseudo-Random Number Generator (PRNG) is initialized from a predictable seed, such as the process ID or system time.
CVSS v3 base score: 2.8
Published: 2024-01-11T03:15Z
Repository: https://github.com/casework/CASE-Utilities-Python
Language: Python
Files changed: case_utils/case_sparql_select/__init__.py, setup.cfg
Commit date: 2023-12-22 11:02:52 -0500
Commit message: Merge branches 'HotFix-0.7.1-set_pyshacl_ceiling' and 'support-0.6.x' into release-0.7.1

Diff: diff --cc case_utils/case_sparql_select/__init__.py
index f609a12,87e2b50..64b44c5
--- a/case_utils/case_sparql_select/__init__.py
+++ b/case_utils/case_sparql_select/__init__.py
@@@ -105,17 -105,17 +105,17 @@@ def main() -> None
      ][0]
      variables = select_line.replace(" DISTINCT", "").replace("SELECT ", "").split(" ")
  
      tally = 0
      records = []
 -    select_query_object = rdflib.plugins.sparql.prepareQuery(
 +    select_query_object = rdflib.plugins.sparql.processor.prepareQuery(
          select_query_text, initNs=nsdict
      )
-     for (row_no, row) in enumerate(graph.query(select_query_object)):
+     for row_no, row in enumerate(graph.query(select_query_object)):
          tally = row_no + 1
          record = []
-         for (column_no, column) in enumerate(row):
+         for column_no, column in enumerate(row):
              if column is None:
                  column_value = ""
              elif (
                  isinstance(column, rdflib.term.Literal)
                  and column.datatype == NS_XSD.hexBinary
diff --cc setup.cfg
index 3e8384c,4f7050b..47c2ccb
--- a/setup.cfg
+++ b/setup.cfg
@@@ -18,16 -18,16 +18,16 @@@ license_files 
  
  [options]
  include_package_data = true
  install_requires =
      pandas
 -    pyshacl
 -    rdflib >= 6.0.2, < 6.3.0
 +    pyshacl < 0.22.0
-     rdflib >= 6.2.0
++    rdflib >= 6.2.0, < 6.3.0
      requests
      tabulate
  packages = find:
- python_requires = >=3.7
+ python_requires = >=3.8
  
  [options.entry_points]
  console_scripts =
      case_file = case_utils.case_file:main
      case_sparql_construct = case_utils.case_sparql_construct:main

Vulnerable code:      for (row_no, row) in enumerate(graph.query(select_query_object)):
         for (column_no, column) in enumerate(row):
     rdflib >= 6.2.0
Fixed code:      for row_no, row in enumerate(graph.query(select_query_object)):
         for column_no, column in enumerate(row):
+    rdflib >= 6.2.0, < 6.3.0
CVE-2024-22194: Insertion of Sensitive Information Into Debugging Code (CWE-215)
value: cdo-local-uuid project provides a specialized UUID-generating function that can, on user request, cause a program to generate deterministic UUIDs. An information leakage vulnerability is present in `cdo-local-uuid` at version `0.4.0`, and in `case-utils` in unpatched versions (matching the pattern `0.x.0`) at and since `0.5.0`, before `0.15.0`. The vulnerability stems from a Python function, `cdo_local_uuid.local_uuid()`, and its original implementation `case_utils.local_uuid()`. 
CWE description: The product inserts sensitive information into debugging code, which could expose this information if the debugging code is not disabled in production.
CVSS v3 base score: 2.8
Published: 2024-01-11T03:15Z
Repository: https://github.com/casework/CASE-Utilities-Python
Language: Other
Files changed: tests/case_utils/case_validate/uco_test_examples/Makefile
Commit date: 2023-12-22 10:32:55 -0500
Commit message: Merge branches 'HotFix-0.6.1-refresh_pre_commit' and 'support-0.5.x' into release-0.6.1

Diff: diff --cc tests/case_utils/case_validate/uco_test_examples/Makefile
index 271fca7,04a6dc3..948cb4f
--- a/tests/case_utils/case_validate/uco_test_examples/Makefile
+++ b/tests/case_utils/case_validate/uco_test_examples/Makefile
@@@ -13,19 -13,15 +13,17 @@@
  
  SHELL := /bin/bash
  
  top_srcdir := $(shell cd ../../../.. ; pwd)
  
- case_srcdir := $(top_srcdir)/dependencies/CASE
- 
- uco_srcdir := $(case_srcdir)/dependencies/UCO
 -examples_srcdir := $(top_srcdir)/dependencies/CASE/dependencies/UCO/tests/examples
++uco_srcdir := $(top_srcdir)/dependencies/CASE/dependencies/UCO
 +
 +examples_srcdir := $(uco_srcdir)/tests/examples
  
  tests_srcdir := $(top_srcdir)/tests
  
 -RDF_TOOLKIT_JAR := $(tests_srcdir)/lib/rdf-toolkit.jar
 +RDF_TOOLKIT_JAR := $(uco_srcdir)/lib/rdf-toolkit.jar
  
  all: \
    action_inheritance_PASS_validation.ttl \
    action_inheritance_XFAIL_validation.ttl \
    action_result_PASS_validation.ttl \

Vulnerable code:  case_srcdir := $(top_srcdir)/dependencies/CASE
 
 uco_srcdir := $(case_srcdir)/dependencies/UCO
Fixed code: +uco_srcdir := $(top_srcdir)/dependencies/CASE/dependencies/UCO
CVE-2024-22194: Predictable Seed in Pseudo-Random Number Generator (PRNG) (CWE-337)
value: cdo-local-uuid project provides a specialized UUID-generating function that can, on user request, cause a program to generate deterministic UUIDs. An information leakage vulnerability is present in `cdo-local-uuid` at version `0.4.0`, and in `case-utils` in unpatched versions (matching the pattern `0.x.0`) at and since `0.5.0`, before `0.15.0`. The vulnerability stems from a Python function, `cdo_local_uuid.local_uuid()`, and its original implementation `case_utils.local_uuid()`. 
CWE description: A Pseudo-Random Number Generator (PRNG) is initialized from a predictable seed, such as the process ID or system time.
CVSS v3 base score: 2.8
Published: 2024-01-11T03:15Z
Repository: https://github.com/casework/CASE-Utilities-Python
Language: Other
Files changed: tests/case_utils/case_validate/uco_test_examples/Makefile
Commit date: 2023-12-22 10:32:55 -0500
Commit message: Merge branches 'HotFix-0.6.1-refresh_pre_commit' and 'support-0.5.x' into release-0.6.1

Diff: diff --cc tests/case_utils/case_validate/uco_test_examples/Makefile
index 271fca7,04a6dc3..948cb4f
--- a/tests/case_utils/case_validate/uco_test_examples/Makefile
+++ b/tests/case_utils/case_validate/uco_test_examples/Makefile
@@@ -13,19 -13,15 +13,17 @@@
  
  SHELL := /bin/bash
  
  top_srcdir := $(shell cd ../../../.. ; pwd)
  
- case_srcdir := $(top_srcdir)/dependencies/CASE
- 
- uco_srcdir := $(case_srcdir)/dependencies/UCO
 -examples_srcdir := $(top_srcdir)/dependencies/CASE/dependencies/UCO/tests/examples
++uco_srcdir := $(top_srcdir)/dependencies/CASE/dependencies/UCO
 +
 +examples_srcdir := $(uco_srcdir)/tests/examples
  
  tests_srcdir := $(top_srcdir)/tests
  
 -RDF_TOOLKIT_JAR := $(tests_srcdir)/lib/rdf-toolkit.jar
 +RDF_TOOLKIT_JAR := $(uco_srcdir)/lib/rdf-toolkit.jar
  
  all: \
    action_inheritance_PASS_validation.ttl \
    action_inheritance_XFAIL_validation.ttl \
    action_result_PASS_validation.ttl \

Vulnerable code:  case_srcdir := $(top_srcdir)/dependencies/CASE
 
 uco_srcdir := $(case_srcdir)/dependencies/UCO
Fixed code: +uco_srcdir := $(top_srcdir)/dependencies/CASE/dependencies/UCO
CVE-2024-22194: Insertion of Sensitive Information Into Debugging Code (CWE-215)
value: cdo-local-uuid project provides a specialized UUID-generating function that can, on user request, cause a program to generate deterministic UUIDs. An information leakage vulnerability is present in `cdo-local-uuid` at version `0.4.0`, and in `case-utils` in unpatched versions (matching the pattern `0.x.0`) at and since `0.5.0`, before `0.15.0`. The vulnerability stems from a Python function, `cdo_local_uuid.local_uuid()`, and its original implementation `case_utils.local_uuid()`. 
CWE description: The product inserts sensitive information into debugging code, which could expose this information if the debugging code is not disabled in production.
CVSS v3 base score: 2.8
Published: 2024-01-11T03:15Z
Repository: https://github.com/casework/CASE-Utilities-Python
Language: Unknown
Commit date: 2023-12-22 14:55:21 -0500
Commit message: Merge branch 'release-0.11.1' into support-0.11.x
CVE-2024-22194: Predictable Seed in Pseudo-Random Number Generator (PRNG) (CWE-337)
value: cdo-local-uuid project provides a specialized UUID-generating function that can, on user request, cause a program to generate deterministic UUIDs. An information leakage vulnerability is present in `cdo-local-uuid` at version `0.4.0`, and in `case-utils` in unpatched versions (matching the pattern `0.x.0`) at and since `0.5.0`, before `0.15.0`. The vulnerability stems from a Python function, `cdo_local_uuid.local_uuid()`, and its original implementation `case_utils.local_uuid()`. 
CWE description: A Pseudo-Random Number Generator (PRNG) is initialized from a predictable seed, such as the process ID or system time.
CVSS v3 base score: 2.8
Published: 2024-01-11T03:15Z
Repository: https://github.com/casework/CASE-Utilities-Python
Language: Unknown
Commit date: 2023-12-22 14:55:21 -0500
Commit message: Merge branch 'release-0.11.1' into support-0.11.x
CVE-2023-46725: Time-of-check Time-of-use (TOCTOU) Race Condition (CWE-367)
value: FoodCoopShop is open source software for food coops and local shops. Versions starting with 3.2.0 prior to 3.6.1 are vulnerable to server-side request forgery. In the Network module, a manufacturer account can use the `/api/updateProducts.json` endpoint to make the server send a request to an arbitrary host. This means that the server can be used as a proxy into the internal network where the server is. Furthermore, the checks on a valid image are not adequate, leading to a time of check time of use issue. For example, by using a custom server that returns 200 on HEAD requests, then return a valid image on first GET request and then a 302 redirect to final target on second GET request, the server will copy whatever file is at the redirect destination, making this a full SSRF. Version 3.6.1 fixes this vulnerability.
CWE description: The product checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. This can cause the product to perform invalid actions when the resource is in an unexpected state.
CVSS v3 base score: 7.5
Published: 2023-11-02T15:15Z
Repository: https://github.com/foodcoopshop/foodcoopshop
Language: Unknown
Commit date: 2023-11-02 14:04:14 +0100
Commit message: Merge pull request #972 from foodcoopshop/remotefile

Remotefile security fix
CVE-2023-46725: Server-Side Request Forgery (SSRF) (CWE-918)
value: FoodCoopShop is open source software for food coops and local shops. Versions starting with 3.2.0 prior to 3.6.1 are vulnerable to server-side request forgery. In the Network module, a manufacturer account can use the `/api/updateProducts.json` endpoint to make the server send a request to an arbitrary host. This means that the server can be used as a proxy into the internal network where the server is. Furthermore, the checks on a valid image are not adequate, leading to a time of check time of use issue. For example, by using a custom server that returns 200 on HEAD requests, then return a valid image on first GET request and then a 302 redirect to final target on second GET request, the server will copy whatever file is at the redirect destination, making this a full SSRF. Version 3.6.1 fixes this vulnerability.
CWE description: The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
CVSS v3 base score: 7.5
Published: 2023-11-02T15:15Z
Repository: https://github.com/foodcoopshop/foodcoopshop
Language: Unknown
Commit date: 2023-11-02 14:04:14 +0100
Commit message: Merge pull request #972 from foodcoopshop/remotefile

Remotefile security fix
CVE-2014-5386: Cryptographic Issues (CWE-310)
value: The mcrypt_create_iv function in hphp/runtime/ext/mcrypt/ext_mcrypt.cpp in Facebook HipHop Virtual Machine (HHVM) before 3.3.0 does not seed the random number generator, which makes it easier for remote attackers to defeat cryptographic protection mechanisms by leveraging the use of a single initialization vector.
CWE description: Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
Published: 2014-12-28T15:59Z
Repository: https://github.com/facebook/hhvm
Language: C++
Files changed: hphp/runtime/ext/mcrypt/ext_mcrypt.cpp
Commit date: 2014-08-16 20:30:21 -0700
Commit message: Fix mcrypt_create_iv(..., MCRYPT_RAND) to auto-seed RNG

Summary: Without seeding the random number generator,
we'll always get the same IV, and that reduces the security
of this function.

Fortunately, f_rand() has all of that logic for auto-seeding
and selection of a suitable initial seed built-in.

Realistically, using MCRYPT_RAND should be deprecated.
I'm going to wait on PHP Internals to make a decision on
https://wiki.php.net/rfc/deprecate_mcrypt_rand
before adding that warning however, so that our test suite
remains consistent.

Credit: Theodore R. Smith of PHP Experts, Inc. <theodorephpexperts.pro>

Closes #3496

Reviewed By: @ptarjan

Differential Revision: D1502435

Diff: diff --git a/hphp/runtime/ext/mcrypt/ext_mcrypt.cpp b/hphp/runtime/ext/mcrypt/ext_mcrypt.cpp
index 5999750fe3..0dc3ae5d9e 100644
--- a/hphp/runtime/ext/mcrypt/ext_mcrypt.cpp
+++ b/hphp/runtime/ext/mcrypt/ext_mcrypt.cpp
@@ -15,10 +15,11 @@
    +----------------------------------------------------------------------+
 */
 
 #include "hphp/runtime/base/base-includes.h"
 #include "hphp/runtime/base/runtime-error.h"
+#include "hphp/runtime/ext/ext_math.h"
 
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
 
@@ -374,11 +375,12 @@ Variant HHVM_FUNCTION(mcrypt_create_iv, int size, int source /* = 0 */) {
       return false;
     }
   } else {
     n = size;
     while (size) {
-      iv[--size] = (char)(255.0 * rand() / RAND_MAX);
+      // Use userspace rand() function because it handles auto-seeding
+      iv[--size] = (char)f_rand(0, 255);
     }
   }
   return String(iv, n, AttachString);
 }
 

Vulnerable code:       iv[--size] = (char)(255.0 * rand() / RAND_MAX);
Fixed code: #include "hphp/runtime/ext/ext_math.h"
      // Use userspace rand() function because it handles auto-seeding
      iv[--size] = (char)f_rand(0, 255);
CVE-2014-6228: Numeric Errors (CWE-189)
value: Integer overflow in the string_chunk_split function in hphp/runtime/base/zend-string.cpp in Facebook HipHop Virtual Machine (HHVM) before 3.3.0 allows remote attackers to cause a denial of service (application crash) or possibly have unspecified other impact via crafted arguments to the chunk_split function.
CWE description: Weaknesses in this category are related to improper calculation or conversion of numbers.
Published: 2014-12-28T15:59Z
Repository: https://github.com/facebook/hhvm
Language: PHP
Files changed: hphp/runtime/base/zend-string.cpp, hphp/test/slow/ext_string/chunk_split_overflow.php, hphp/test/slow/ext_string/chunk_split_overflow.php.expectf
Commit date: 2014-08-25 22:30:22 -0700
Commit message: Fix integer overflow in chunk_split

Reviewed By: @ptarjan

Differential Revision: D1515947

Diff: diff --git a/hphp/runtime/base/zend-string.cpp b/hphp/runtime/base/zend-string.cpp
index c40a9469f1..7b64a9a924 100644
--- a/hphp/runtime/base/zend-string.cpp
+++ b/hphp/runtime/base/zend-string.cpp
@@ -624,12 +624,18 @@ String string_replace(const char *input, int len,
 String string_chunk_split(const char *src, int srclen, const char *end,
                           int endlen, int chunklen) {
   int chunks = srclen / chunklen; // complete chunks!
   int restlen = srclen - chunks * chunklen; /* srclen % chunklen */
 
-  int out_len = (chunks + 1) * endlen + srclen;
-  String ret(out_len, ReserveString);
+  String ret(
+    safe_address(
+      chunks + 1,
+      endlen,
+      srclen
+    ),
+    ReserveString
+  );
   char *dest = ret.bufferSlice().ptr;
 
   const char *p; char *q;
   const char *pMax = src + srclen - chunklen + 1;
   for (p = src, q = dest; p < pMax; ) {
diff --git a/hphp/test/slow/ext_string/chunk_split_overflow.php b/hphp/test/slow/ext_string/chunk_split_overflow.php
new file mode 100644
index 0000000000..c895bee363
--- /dev/null
+++ b/hphp/test/slow/ext_string/chunk_split_overflow.php
@@ -0,0 +1,3 @@
+<?php
+
+chunk_split(str_repeat('*', 2000000), 1.0, str_repeat('*', 2000000));
diff --git a/hphp/test/slow/ext_string/chunk_split_overflow.php.expectf b/hphp/test/slow/ext_string/chunk_split_overflow.php.expectf
new file mode 100644
index 0000000000..17c953f916
--- /dev/null
+++ b/hphp/test/slow/ext_string/chunk_split_overflow.php.expectf
@@ -0,0 +1,2 @@
+
+Fatal error: String length exceeded 2^31-2: 4000004000000 in %s on line 3

Vulnerable code:   int out_len = (chunks + 1) * endlen + srclen;
  String ret(out_len, ReserveString);
Fixed code:   String ret(
    safe_address(
      chunks + 1,
      endlen,
      srclen
    ),
    ReserveString
  );
<?php

chunk_split(str_repeat('*', 2000000), 1.0, str_repeat('*', 2000000));

Fatal error: String length exceeded 2^31-2: 4000004000000 in %s on line 3
CVE-2014-6229: Exposure of Sensitive Information to an Unauthorized Actor (CWE-200)
value: The HashContext class in hphp/runtime/ext/ext_hash.cpp in Facebook HipHop Virtual Machine (HHVM) before 3.3.0 incorrectly expects that a certain key string uses '\0' for termination, which allows remote attackers to obtain sensitive information by leveraging read access beyond the end of the string, and makes it easier for remote attackers to defeat cryptographic protection mechanisms by leveraging truncation of a string containing an internal '\0' character.
CWE description: The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
Published: 2014-12-28T15:59Z
Repository: https://github.com/facebook/hhvm
Language: C++
Files changed: hphp/runtime/ext/ext_hash.cpp
Commit date: 2014-09-18 13:00:22 -0700
Commit message: Fix potential security leak in HashContext

Summary: CVE-2014-6229

This is not a NUL-terminated string, it's a fixed-size block of data.
The risks were key truncation (if there happens to be a NUL byte in the
key) or over-reading (which would be information leakage).

Reviewed By: @ptarjan

Differential Revision: D1533546

Diff: diff --git a/hphp/runtime/ext/ext_hash.cpp b/hphp/runtime/ext/ext_hash.cpp
index b4edc4b0fd6..cd55297c531 100644
--- a/hphp/runtime/ext/ext_hash.cpp
+++ b/hphp/runtime/ext/ext_hash.cpp
@@ -150,11 +150,16 @@ public:
     assert(ctx->ops->context_size >= 0);
     ops = ctx->ops;
     context = malloc(ops->context_size);
     ops->hash_copy(context, ctx->context);
     options = ctx->options;
-    key = ctx->key ? strdup(ctx->key) : nullptr;
+    if (ctx->key) {
+      key = static_cast<char*>(malloc(ops->block_size));
+      memcpy(key, ctx->key, ops->block_size);
+    } else {
+      key = nullptr;
+    }
   }
 
   ~HashContext() {
     HashContext::sweep();
   }

Vulnerable code:     key = ctx->key ? strdup(ctx->key) : nullptr;
Fixed code:     if (ctx->key) {
      key = static_cast<char*>(malloc(ops->block_size));
      memcpy(key, ctx->key, ops->block_size);
    } else {
      key = nullptr;
    }
CVE-2016-1000109: Improper Initialization (CWE-665)
value: HHVM does not attempt to address RFC 3875 section 4.1.18 namespace conflicts and therefore does not protect CGI applications from the presence of untrusted client data in the HTTP_PROXY environment variable, which might allow remote attackers to redirect a CGI application's outbound HTTP traffic to an arbitrary proxy server via a crafted Proxy header in an HTTP request, aka an "httpoxy" issue. This issue affects HHVM versions prior to 3.9.6, all versions between 3.10.0 and 3.12.4 (inclusive), and all versions between 3.13.0 and 3.14.2 (inclusive).
CWE description: The product does not initialize or incorrectly initializes a resource, which might leave the resource in an unexpected state when it is accessed or used.
CVSS v3 base score: 5.3
Published: 2020-02-19T13:15Z
Repository: https://github.com/facebook/hhvm
Language: C++
Files changed: hphp/runtime/server/fastcgi/fastcgi-transport.cpp
Commit date: 2016-07-18 21:07:11 -0700
Commit message: CVE-2016-1000109: Ignore Proxy HTTP header from fastcgi requests

Summary:
The default PHP behavior is to transform a Proxy header from requests
into the HTTP_PROXY environment variable in the PHP environment running the
request. Some scripts may use this env var to decide which HTTP proxy to
connect to, and we don't want requests to have that kind of control over
scripts' behavior.

Reviewed By: alexmalyshev, Orvid

Differential Revision: D3579221

fbshipit-source-id: 18a405fd73aee65283aea99ff995f8082b3fc3b5

Diff: diff --git a/hphp/runtime/server/fastcgi/fastcgi-transport.cpp b/hphp/runtime/server/fastcgi/fastcgi-transport.cpp
index 5b69d9190cb..756e12e59e1 100644
--- a/hphp/runtime/server/fastcgi/fastcgi-transport.cpp
+++ b/hphp/runtime/server/fastcgi/fastcgi-transport.cpp
@@ -210,10 +210,14 @@ void FastCGITransport::onBodyComplete() {
 void FastCGITransport::onHeader(std::unique_ptr<folly::IOBuf> key_chain,
                                 std::unique_ptr<folly::IOBuf> value_chain) {
   Cursor keyCur(key_chain.get());
   auto key = keyCur.readFixedString(key_chain->computeChainDataLength());
 
+  // Don't allow requests to inject an HTTP_PROXY environment variable by
+  // sending a Proxy header.
+  if (strcasecmp(key.c_str(), "HTTP_PROXY") == 0) return;
+
   Cursor valCur(value_chain.get());
   auto value = valCur.readFixedString(value_chain->computeChainDataLength());
 
   m_requestParams[key] = value;
 }

Fixed code:   // Don't allow requests to inject an HTTP_PROXY environment variable by
  // sending a Proxy header.
  if (strcasecmp(key.c_str(), "HTTP_PROXY") == 0) return;
CVE-2016-6872: Integer Overflow or Wraparound (CWE-190)
value: Integer overflow in StringUtil::implode in Facebook HHVM before 3.15.0 allows attackers to have unspecified impact via unknown vectors.
CWE description: The product performs a calculation that can
         produce an integer overflow or wraparound when the logic
         assumes that the resulting value will always be larger than
         the original value. This occurs when an integer value is
         incremented to a value that is too large to store in the
         associated representation. When this occurs, the value may
         become a very small or negative number.
CVSS v3 base score: 9.8
Published: 2017-02-17T17:59Z
Repository: https://github.com/facebook/hhvm
Language: PHP
Files changed: hphp/runtime/base/string-util.cpp, hphp/test/slow/string_length_overflow/implode.php, hphp/test/slow/string_length_overflow/implode.php.expectf
Commit date: 2016-08-01 15:51:07 -0700
Commit message: Fix integer overflow in StringUtil::implode

Reviewed By: ricklavoie

Differential Revision: D3623922

fbshipit-source-id: 136d124a850c07cc6c63535afc11d36499d576fc

Diff: diff --git a/hphp/runtime/base/string-util.cpp b/hphp/runtime/base/string-util.cpp
index 56d7104c14f..51408ef85a6 100644
--- a/hphp/runtime/base/string-util.cpp
+++ b/hphp/runtime/base/string-util.cpp
@@ -122,12 +122,12 @@ String StringUtil::Implode(const Variant& items, const String& delim,
   int size = getContainerSize(items);
   if (size == 0) return empty_string();
 
   req::vector<String> sitems;
   sitems.reserve(size);
-  int len = 0;
-  int lenDelim = delim.size();
+  size_t len = 0;
+  size_t lenDelim = delim.size();
   for (ArrayIter iter(items); iter; ++iter) {
     sitems.emplace_back(iter.second().toString());
     len += sitems.back().size() + lenDelim;
   }
   len -= lenDelim; // always one delimiter less than count of items
diff --git a/hphp/test/slow/string_length_overflow/implode.php b/hphp/test/slow/string_length_overflow/implode.php
new file mode 100644
index 00000000000..3d348321ac4
--- /dev/null
+++ b/hphp/test/slow/string_length_overflow/implode.php
@@ -0,0 +1,5 @@
+<?php
+
+$stringLarge = str_repeat('*', 300289);
+$arrayLarge = array_fill(0, 49981, '*');
+$string_implode_2 = implode($stringLarge, $arrayLarge);
diff --git a/hphp/test/slow/string_length_overflow/implode.php.expectf b/hphp/test/slow/string_length_overflow/implode.php.expectf
new file mode 100644
index 00000000000..484c51265ce
--- /dev/null
+++ b/hphp/test/slow/string_length_overflow/implode.php.expectf
@@ -0,0 +1,2 @@
+
+Fatal error: String length exceeded 2^31-2: 15008494201 in %s/test/slow/string_length_overflow/implode.php on line 5

Vulnerable code:   int len = 0;
  int lenDelim = delim.size();
Fixed code:   size_t len = 0;
  size_t lenDelim = delim.size();
<?php

$stringLarge = str_repeat('*', 300289);
$arrayLarge = array_fill(0, 49981, '*');
$string_implode_2 = implode($stringLarge, $arrayLarge);

Fatal error: String length exceeded 2^31-2: 15008494201 in %s/test/slow/string_length_overflow/implode.php on line 5
CVE-2018-6340: Out-of-bounds Read (CWE-125)
value: The Memcache::getextendedstats function can be used to trigger an out-of-bounds read. Exploiting this issue requires control over memcached server hostnames and/or ports. This affects all supported versions of HHVM (3.30 and 3.27.4 and below).
CWE description: The product reads data past the end, or before the beginning, of the intended buffer.
CVSS v3 base score: 8.1
Published: 2018-12-31T22:29Z
Repository: https://github.com/facebook/hhvm
Language: C++
Files changed: hphp/runtime/ext/memcache/ext_memcache.cpp
Commit date: 2018-12-18 14:27:43 -0800
Commit message: CVE-2018-6340 Fix buffer overread

Summary:
snprintf() returns the number of would be written bytes if the buffer had
enough size, letting the original code to construct output string from
arbitrary data on the stack.

Fix this by properly assembling the String without trying to arbitrarily
limiting the length to 30 bytes.

Reviewed By: ottoni

Differential Revision: D13509547

fbshipit-source-id: aa401b83d356f5b261433c4b16d777948ba7f9b4

Diff: diff --git a/hphp/runtime/ext/memcache/ext_memcache.cpp b/hphp/runtime/ext/memcache/ext_memcache.cpp
index 221908993f6..776f5f30a44 100644
--- a/hphp/runtime/ext/memcache/ext_memcache.cpp
+++ b/hphp/runtime/ext/memcache/ext_memcache.cpp
@@ -698,13 +698,10 @@ static Array HHVM_METHOD(Memcache, getextendedstats,
 
   Array return_val;
 
   for (int server_id = 0; server_id < server_count; server_id++) {
     memcached_stat_st *stat;
-    char stats_key[30] = {0};
-    size_t key_len;
-
     LMCD_SERVER_POSITION_INSTANCE_TYPE instance =
       memcached_server_instance_by_position(&data->m_memcache, server_id);
     const char *hostname = LMCD_SERVER_HOSTNAME(instance);
     in_port_t port = LMCD_SERVER_PORT(instance);
 
@@ -713,13 +710,17 @@ static Array HHVM_METHOD(Memcache, getextendedstats,
     Array server_stats = memcache_build_stats(&data->m_memcache, stat, &ret);
     if (ret != MEMCACHED_SUCCESS) {
       continue;
     }
 
-    key_len = snprintf(stats_key, sizeof(stats_key), "%s:%d", hostname, port);
-
-    return_val.set(String(stats_key, key_len, CopyString), server_stats);
+    auto const port_str = folly::to<std::string>(port);
+    auto const key_len = strlen(hostname) + 1 + port_str.length();
+    auto key = String(key_len, ReserveString);
+    key += hostname;
+    key += ":";
+    key += port_str;
+    return_val.set(key, server_stats);
   }
 
   free(stats);
   return return_val;
 }

Vulnerable code:     char stats_key[30] = {0};
    size_t key_len;

    key_len = snprintf(stats_key, sizeof(stats_key), "%s:%d", hostname, port);

    return_val.set(String(stats_key, key_len, CopyString), server_stats);
Fixed code:     auto const port_str = folly::to<std::string>(port);
    auto const key_len = strlen(hostname) + 1 + port_str.length();
    auto key = String(key_len, ReserveString);
    key += hostname;
    key += ":";
    key += port_str;
    return_val.set(key, server_stats);
CVE-2019-11926: Out-of-bounds Read (CWE-125)
value: Insufficient boundary checks when processing M_SOFx markers from JPEG headers in the GD extension could allow access to out-of-bounds memory via a maliciously constructed invalid JPEG input. This issue affects HHVM versions prior to 3.30.9, all versions between 4.0.0 and 4.8.3, all versions between 4.9.0 and 4.15.2, and versions 4.16.0 to 4.16.3, 4.17.0 to 4.17.2, 4.18.0 to 4.18.1, 4.19.0, 4.20.0 to 4.20.1.
CWE description: The product reads data past the end, or before the beginning, of the intended buffer.
CVSS v3 base score: 9.8
Published: 2019-09-06T19:15Z
Repository: https://github.com/facebook/hhvm
Language: PHP
Files changed: hphp/runtime/ext/gd/ext_gd.cpp, hphp/test/slow/ext_gd/exifreaddata.php, hphp/test/slow/ext_gd/exifreaddata.php.expectf
Commit date: 2019-09-03 17:20:17 -0700
Commit message: exif_scan_JPEG_header: Added length check to prevent information leak

Summary:
'exif_process_SOFn' assumes that the JPEG header has at least 6 length. On providing a length < 6, this leads to an out of bounds heap read.

Fixes CVE-2019-11926

Reviewed By: fredemmott

Differential Revision: D16927050

fbshipit-source-id: 76c4b7c95acbb7852b0435298613d559d94e7270

Diff: diff --git a/hphp/runtime/ext/gd/ext_gd.cpp b/hphp/runtime/ext/gd/ext_gd.cpp
index 3ff392a41c6..96db385c0a4 100644
--- a/hphp/runtime/ext/gd/ext_gd.cpp
+++ b/hphp/runtime/ext/gd/ext_gd.cpp
@@ -7115,10 +7115,14 @@ static int exif_scan_JPEG_header(image_info_type *ImageInfo) {
       case M_SOF10:
       case M_SOF11:
       case M_SOF13:
       case M_SOF14:
       case M_SOF15:
+        if ((itemlen - 2) < 6) {
+          return 0;
+        }
+
         exif_process_SOFn(Data, marker, &sof_info);
         ImageInfo->Width  = sof_info.width;
         ImageInfo->Height = sof_info.height;
         if (sof_info.num_components == 3) {
           ImageInfo->IsColor = 1;
diff --git a/hphp/test/slow/ext_gd/exifreaddata.php b/hphp/test/slow/ext_gd/exifreaddata.php
new file mode 100644
index 00000000000..e51c9e83da1
--- /dev/null
+++ b/hphp/test/slow/ext_gd/exifreaddata.php
@@ -0,0 +1,8 @@
+<?hh
+
+<<__EntryPoint>>
+function main_exifreaddata() {
+  $jpeg = "\xff\xd8\xc9\x00\x03\x04\x03\xf8";
+  $data_stream = "data://text/plain;base64," . base64_encode($jpeg);
+  var_dump(exif_read_data($data_stream));
+}
diff --git a/hphp/test/slow/ext_gd/exifreaddata.php.expectf b/hphp/test/slow/ext_gd/exifreaddata.php.expectf
new file mode 100644
index 00000000000..34519709efb
--- /dev/null
+++ b/hphp/test/slow/ext_gd/exifreaddata.php.expectf
@@ -0,0 +1,2 @@
+Warning: Invalid JPEG file in %s/ext_gd/exifreaddata.php on line 7
+bool(false)

Fixed code:         if ((itemlen - 2) < 6) {
          return 0;
        }

<?hh

<<__EntryPoint>>
function main_exifreaddata() {
  $jpeg = "\xff\xd8\xc9\x00\x03\x04\x03\xf8";
  $data_stream = "data://text/plain;base64," . base64_encode($jpeg);
  var_dump(exif_read_data($data_stream));
}
Warning: Invalid JPEG file in %s/ext_gd/exifreaddata.php on line 7
bool(false)
CVE-2019-11930: Release of Invalid Pointer or Reference (CWE-763)
value: An invalid free in mb_detect_order can cause the application to crash or potentially result in remote code execution. This issue affects HHVM versions prior to 3.30.12, all versions between 4.0.0 and 4.8.5, all versions between 4.9.0 and 4.23.1, as well as 4.24.0, 4.25.0, 4.26.0, 4.27.0, 4.28.0, and 4.28.1.
CWE description: The product attempts to return a memory resource to the system, but it calls the wrong release function or calls the appropriate release function incorrectly.
CVSS v3 base score: 9.8
Published: 2019-12-04T17:16Z
Repository: https://github.com/facebook/hhvm
Language: PHP
Files changed: hphp/runtime/ext/mbstring/ext_mbstring.cpp, hphp/test/slow/ext_mb/mb_detect_order_t54638796.php, hphp/test/slow/ext_mb/mb_detect_order_t54638796.php.expect
Commit date: 2019-10-28 23:08:20 -0700
Commit message: ext_mbstring: Fix invalid free() in php_mb_parse_encoding

Summary:
A chunk of memory allocated by 'req::calloc_noptrs' was being freed by 'free'. The former internally calls 'calloc' and returns a pointer at an index sizeof(MallocNode) inside the allocated buffer. This led to freeing invalid memory.

CVE-2019-11930

Reviewed By: jjergus

Differential Revision: D18179908

fbshipit-source-id: 0e3fe77628e0b9dee8361e712b8abac59ae5ed22

Diff: diff --git a/hphp/runtime/ext/mbstring/ext_mbstring.cpp b/hphp/runtime/ext/mbstring/ext_mbstring.cpp
index 0766bfd210e7..7a8d15ed2f35 100644
--- a/hphp/runtime/ext/mbstring/ext_mbstring.cpp
+++ b/hphp/runtime/ext/mbstring/ext_mbstring.cpp
@@ -906,11 +906,11 @@ static bool php_mb_parse_encoding(const Variant& encoding,
                                      return_list, return_size,
                                      persistent ? 1 : 0);
   }
   if (!ret) {
     if (return_list && *return_list) {
-      free(*return_list);
+      req::free(*return_list);
       *return_list = nullptr;
     }
     return_size = 0;
   }
   return ret;
diff --git a/hphp/test/slow/ext_mb/mb_detect_order_t54638796.php b/hphp/test/slow/ext_mb/mb_detect_order_t54638796.php
new file mode 100644
index 000000000000..15bea3e341e0
--- /dev/null
+++ b/hphp/test/slow/ext_mb/mb_detect_order_t54638796.php
@@ -0,0 +1,7 @@
+<?hh
+// Copyright 2004-present Facebook. All Rights Reserved.
+
+<<__EntryPoint>>
+function main() {
+  var_dump(mb_detect_order("UTF-8,\x2c"));
+}
diff --git a/hphp/test/slow/ext_mb/mb_detect_order_t54638796.php.expect b/hphp/test/slow/ext_mb/mb_detect_order_t54638796.php.expect
new file mode 100644
index 000000000000..5c0c0681d9c1
--- /dev/null
+++ b/hphp/test/slow/ext_mb/mb_detect_order_t54638796.php.expect
@@ -0,0 +1 @@
+bool(false)

Vulnerable code:       free(*return_list);
Fixed code:       req::free(*return_list);
<?hh
// Copyright 2004-present Facebook. All Rights Reserved.

<<__EntryPoint>>
function main() {
  var_dump(mb_detect_order("UTF-8,\x2c"));
}
bool(false)
CVE-2020-1888: Out-of-bounds Read (CWE-125)
value: Insufficient boundary checks when decoding JSON in handleBackslash reads out of bounds memory, potentially leading to DOS. This issue affects HHVM 4.45.0, 4.44.0, 4.43.0, 4.42.0, 4.41.0, 4.40.0, 4.39.0, versions between 4.33.0 and 4.38.0 (inclusive), versions between 4.9.0 and 4.32.0 (inclusive), and versions prior to 4.8.7.
CWE description: The product reads data past the end, or before the beginning, of the intended buffer.
CVSS v3 base score: 7.5
Published: 2020-03-03T15:15Z
Repository: https://github.com/facebook/hhvm
Language: C++
Files changed: hphp/runtime/ext/json/JSON_parser.cpp
Commit date: 2020-02-20 15:54:42 -0800
Commit message: Fix buffer overrun in SimpleParser::handleBackslash

Summary:
It read 4 chars, then checked for validity, but any of them could have
been the end of the string, so check after each one instead.

Reviewed By: oulgen

Differential Revision: D19611163

fbshipit-source-id: 3da0a39555cb85a93f4fd98048368f17cf37e2e4

Diff: diff --git a/hphp/runtime/ext/json/JSON_parser.cpp b/hphp/runtime/ext/json/JSON_parser.cpp
index b8d52359368d..f6bfbf696fcb 100644
--- a/hphp/runtime/ext/json/JSON_parser.cpp
+++ b/hphp/runtime/ext/json/JSON_parser.cpp
@@ -451,16 +451,17 @@ struct SimpleParser {
       case 'r': out = '\r'; return true;
       case 't': out = '\t'; return true;
       case 'u': {
         if (UNLIKELY(is_tsimplejson)) {
           auto const ch1 = *p++;
+          if (UNLIKELY(ch1 != '0')) return false;
           auto const ch2 = *p++;
+          if (UNLIKELY(ch2 != '0')) return false;
           auto const dch3 = dehexchar(*p++);
+          if (UNLIKELY(dch3 < 0)) return false;
           auto const dch4 = dehexchar(*p++);
-          if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) {
-            return false;
-          }
+          if (UNLIKELY(dch4 < 0)) return false;
           out = (dch3 << 4) | dch4;
           return true;
         } else {
           uint16_t u16cp = 0;
           for (int i = 0; i < 4; i++) {
diff --git a/hphp/test/slow/ext_json/decode_crash.php b/hphp/test/slow/ext_json/decode_crash.php
index 003b886b2f42..4d7f4c20d214 100644
Binary files a/hphp/test/slow/ext_json/decode_crash.php and b/hphp/test/slow/ext_json/decode_crash.php differ
diff --git a/hphp/test/slow/ext_json/decode_crash.php.expect b/hphp/test/slow/ext_json/decode_crash.php.expect
index e2a4ea7d26ca..00a53d981aaa 100644
Binary files a/hphp/test/slow/ext_json/decode_crash.php.expect and b/hphp/test/slow/ext_json/decode_crash.php.expect differ

Vulnerable code:           if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) {
            return false;
          }
Fixed code:           if (UNLIKELY(ch1 != '0')) return false;
          if (UNLIKELY(ch2 != '0')) return false;
          if (UNLIKELY(dch3 < 0)) return false;
          if (UNLIKELY(dch4 < 0)) return false;
CVE-2020-1892: Out-of-bounds Read (CWE-125)
value: Insufficient boundary checks when decoding JSON in JSON_parser allows read access to out of bounds memory, potentially leading to information leak and DOS. This issue affects HHVM 4.45.0, 4.44.0, 4.43.0, 4.42.0, 4.41.0, 4.40.0, 4.39.0, versions between 4.33.0 and 4.38.0 (inclusive), versions between 4.9.0 and 4.32.0 (inclusive), and versions prior to 4.8.7.
CWE description: The product reads data past the end, or before the beginning, of the intended buffer.
CVSS v3 base score: 8.1
Published: 2020-03-03T15:15Z
Repository: https://github.com/facebook/hhvm
Language: C++
Files changed: hphp/runtime/ext/json/JSON_parser.cpp
Commit date: 2020-02-20 15:43:49 -0800
Commit message: Fix a json_decode crash when depth==0

Summary:
Setting depth=0 is an error, and should result in NULL, but we weren't
checking for it, so in the case of a single, top-level string, we
would reading the -1th element of the stack.

Differential Revision: D19609959

fbshipit-source-id: 04ca1e0965e04b44df2d5c806a73c3da99ff66fb

Diff: diff --git a/hphp/runtime/ext/json/JSON_parser.cpp b/hphp/runtime/ext/json/JSON_parser.cpp
index b1b4f51b2e5d..5d3b3cfb25a2 100644
--- a/hphp/runtime/ext/json/JSON_parser.cpp
+++ b/hphp/runtime/ext/json/JSON_parser.cpp
@@ -1146,10 +1146,14 @@ bool JSON_parser(Variant &z, const char *p, int length, bool const assoc,
   json_parser *json = s_json_parser.get(); /* the parser state */
   // Clear and reuse the thread-local string buffers. They are only freed if
   // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread
   // is explicitly flushed (e.g., due to being idle).
   json->initSb(length);
+  if (depth <= 0) {
+    json->error_code = json_error_codes::JSON_ERROR_DEPTH;
+    return false;
+  }
   SCOPE_EXIT {
     constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024;
     if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb();
   };
   // SimpleParser only handles the most common set of options. Also, only use it
diff --git a/hphp/test/slow/ext_json/decode_crash.php b/hphp/test/slow/ext_json/decode_crash.php
new file mode 100644
index 000000000000..9944145e454e
Binary files /dev/null and b/hphp/test/slow/ext_json/decode_crash.php differ
diff --git a/hphp/test/slow/ext_json/decode_crash.php.expect b/hphp/test/slow/ext_json/decode_crash.php.expect
new file mode 100644
index 000000000000..7951defec192
Binary files /dev/null and b/hphp/test/slow/ext_json/decode_crash.php.expect differ

Fixed code:   if (depth <= 0) {
    json->error_code = json_error_codes::JSON_ERROR_DEPTH;
    return false;
  }
CVE-2020-1893: Out-of-bounds Read (CWE-125)
value: Insufficient boundary checks when decoding JSON in TryParse reads out of bounds memory, potentially leading to DOS. This issue affects HHVM 4.45.0, 4.44.0, 4.43.0, 4.42.0, 4.41.0, 4.40.0, 4.39.0, versions between 4.33.0 and 4.38.0 (inclusive), versions between 4.9.0 and 4.32.0 (inclusive), and versions prior to 4.8.7.
CWE description: The product reads data past the end, or before the beginning, of the intended buffer.
CVSS v3 base score: 7.5
Published: 2020-03-03T15:15Z
Repository: https://github.com/facebook/hhvm
Language: C++
Files changed: hphp/runtime/ext/json/JSON_parser.cpp
Commit date: 2020-02-20 15:54:37 -0800
Commit message: Fix a buffer-overrun in SimpleParser

Summary: In the failure case, we might have already consumed the entire string.

Reviewed By: binliu19, ottoni

Differential Revision: D19610775

fbshipit-source-id: d387df15994a310f5a31cfbb5fa11679997f7ae7

Diff: diff --git a/hphp/runtime/ext/json/JSON_parser.cpp b/hphp/runtime/ext/json/JSON_parser.cpp
index 5d3b3cfb25a2..b8d52359368d 100644
--- a/hphp/runtime/ext/json/JSON_parser.cpp
+++ b/hphp/runtime/ext/json/JSON_parser.cpp
@@ -340,12 +340,12 @@ struct SimpleParser {
   static bool TryParse(const char* inp, int length,
                        TypedValue* buf, Variant& out,
                        JSONContainerType container_type, bool is_tsimplejson) {
     SimpleParser parser(inp, length, buf, container_type, is_tsimplejson);
     bool ok = parser.parseValue();
-    parser.skipSpace();
-    if (!ok || parser.p != inp + length) {
+    if (!ok ||
+        (parser.skipSpace(), parser.p != inp + length)) {
       // Unsupported, malformed, or trailing garbage. Release entire stack.
       tvDecRefRange(buf, parser.top);
       return false;
     }
     out = Variant::attach(*--parser.top);
diff --git a/hphp/test/slow/ext_json/decode_crash.php b/hphp/test/slow/ext_json/decode_crash.php
index 9944145e454e..003b886b2f42 100644
Binary files a/hphp/test/slow/ext_json/decode_crash.php and b/hphp/test/slow/ext_json/decode_crash.php differ
diff --git a/hphp/test/slow/ext_json/decode_crash.php.expect b/hphp/test/slow/ext_json/decode_crash.php.expect
index 7951defec192..e2a4ea7d26ca 100644
Binary files a/hphp/test/slow/ext_json/decode_crash.php.expect and b/hphp/test/slow/ext_json/decode_crash.php.expect differ

Vulnerable code:     parser.skipSpace();
    if (!ok || parser.p != inp + length) {
Fixed code:     if (!ok ||
        (parser.skipSpace(), parser.p != inp + length)) {