From 936870c1f04b5203e4f8cfa68da5bd764e600e95 Mon Sep 17 00:00:00 2001 From: albertexye <111392956+albertexye@users.noreply.github.com> Date: Tue, 2 Apr 2024 01:38:45 -0400 Subject: [PATCH] Perform boundary checks before searching to prevent security vulnerabilities (#237) * perform boundary check before searching to prevent security vulnerabilities * when a negative start index is passed to str.find, 0 is used instead * a ValueError is raised when argument 'start' is a negative integer --- src/pocketpy.cpp | 2 ++ tests/04_str.py | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/src/pocketpy.cpp b/src/pocketpy.cpp index 27455846..37603f5b 100644 --- a/src/pocketpy.cpp +++ b/src/pocketpy.cpp @@ -627,6 +627,7 @@ void init_builtins(VM* _vm) { const Str& self = _CAST(Str&, args[0]); const Str& value = CAST(Str&, args[1]); int start = CAST(int, args[2]); + if (start < 0) vm->ValueError("argument 'start' can't be negative"); int index = self.index(value, start); if(index < 0) vm->ValueError("substring not found"); return VAR(index); @@ -636,6 +637,7 @@ void init_builtins(VM* _vm) { const Str& self = _CAST(Str&, args[0]); const Str& value = CAST(Str&, args[1]); int start = CAST(int, args[2]); + if (start < 0) vm->ValueError("argument 'start' can't be negative"); return VAR(self.index(value, start)); }); diff --git a/tests/04_str.py b/tests/04_str.py index 3a588229..c9c78eac 100644 --- a/tests/04_str.py +++ b/tests/04_str.py @@ -250,6 +250,17 @@ try: except ValueError: pass +try: + a.index('1', -1) + exit(1) +except ValueError: + pass + assert a.find('1') == 0 assert a.find('1', 1) == -1 +try: + a.find('1', -1) + exit(1) +except ValueError: + pass