├── .gitignore ├── LICENSE ├── README.md ├── decorators ├── README.md └── never_called_decorators.py ├── join_paths ├── README.md ├── os_path_join.py ├── pathlib_purepath.py └── pathlib_purepath_joinpath.py ├── mutable_default_objects ├── README.md └── default_list_object.py ├── regular_expression ├── README.md └── re_match_and_search.py ├── temporary_file_and_directory ├── README.md ├── tempfile_namedtemporaryfile.py └── tempfile_temporarydirectory.py └── url_join ├── README.md └── urllib_parse_urljoin.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # macOS specific folders 7 | .DS_Store 8 | 9 | # VSCode specific folders 10 | .vscode 11 | 12 | # venv 13 | venv/ 14 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Security Pitfalls Playground 2 | 3 | This repository contains common security pitfalls for Python with descriptions and test cases for interactive learning. 4 | 5 | # Cases 6 | 7 | - [Decorators](/decorators/README.md) 8 | - [Join Paths](/join_paths/README.md) 9 | - [Mutable Default Objects](/mutable_default_objects/README.md) 10 | - [Regular Expression](/regular_expression/README.md) 11 | - [Temporary File and Directory](/temporary_file_and_directory/README.md) 12 | - [URL join](/url_join/README.md) 13 | 14 | # How to run tests? 15 | 16 | ```bash 17 | # cd 18 | # python3 19 | # for example: 20 | cd url_join 21 | python3 urllib_parse_urljoin.py 22 | ``` 23 | -------------------------------------------------------------------------------- /decorators/README.md: -------------------------------------------------------------------------------- 1 | # Pitfalls of implementing decorators 2 | 3 | When implementing decorators, it is extremely important to remember that the call to an external function of a decorator occurs at the moment it is applied to a target function. Therefore, the code of the external decorator function will be executed even if the target function has not been called. Consider the example below: 4 | 5 | ```python 6 | def decorator(func): 7 | print(f'The decorator has been applied to {func.__name__}') 8 | def wrapper(): 9 | func() 10 | return wrapper 11 | 12 | @decorator 13 | def never_called(): 14 | pass 15 | ``` 16 | 17 | Despite the fact that the `never_called` function was not called, the following message will appear in the console: 18 | 19 | ``` 20 | The decorator has been applied to never_called 21 | ``` 22 | 23 | ## Playground 24 | 25 | - [never_called_decorators.py](./never_called_decorators.py) 26 | 27 | Use the following command to run tests: 28 | 29 | ```bash 30 | # python3 31 | python3 never_called_decorators.py 32 | ``` 33 | -------------------------------------------------------------------------------- /decorators/never_called_decorators.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import logging 3 | from unittest.mock import Mock 4 | 5 | 6 | logger = logging.getLogger(__name__) 7 | logging.basicConfig(format = '\n%(message)s', level = logging.INFO) 8 | 9 | 10 | class Tests(unittest.TestCase): 11 | 12 | def test_never_called_decorators(self) -> None: 13 | mock_f = Mock() 14 | 15 | def decorator(func): 16 | logger.info(f'The decorator has been applied to {func.__name__}') 17 | mock_f() 18 | def wrapper(): 19 | func() 20 | return wrapper 21 | 22 | @decorator 23 | def never_called(): 24 | pass 25 | 26 | mock_f.assert_called_once() 27 | 28 | 29 | if __name__ == '__main__': 30 | unittest.main() 31 | -------------------------------------------------------------------------------- /join_paths/README.md: -------------------------------------------------------------------------------- 1 | # Pitfalls of joining paths 2 | 3 | Python provides several standard functions to join paths: 4 | 5 | - [os.path.join(path, *paths)](https://docs.python.org/3/library/os.path.html#os.path.join) 6 | - [pathlib.PurePath(*pathsegments)](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath) 7 | - [pathlib.PurePath.joinpath(*pathsegments)](https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.joinpath) 8 | 9 | > Note: `pathlib.PurePath` is a parent class for other classes in `pathlib`, such as `Path` or `PosixPath`. It means that they all inherit the described behaviour from `PurePath`. 10 | 11 | Typically these functions are used to craft a path within a base path, like this: 12 | 13 | ```python 14 | filename = request.POST['filename'] 15 | path = os.path.join(base_path, filename) 16 | ``` 17 | 18 | However, there are pitfalls in path joining that can lead to unexpected results: 19 | 20 | 1. Path traversal. Since the logic of the functions is fairly straightforward when joining a base path and a path with `../` together, the path with `../` will simply be appended to the base path without any additional processing or resolution. For example, joining `/base/path` and `../payload` will result in `/base/path/../payload`; as a result, passing the crafted path to `open()` will lead to the path traversal vulnerability. 21 | 1. Handling absolute paths. If one of the arguments starts with `/`, this argument is treated as an absolute path by these functions and all previous arguments including a base path are removed. For example, joining `/base/path` and `/payload` will result in `/payload` 22 | 23 | ## Playground 24 | 25 | There are test cases for each function: 26 | 27 | - [os_path_join.py](./os_path_join.py) 28 | - [pathlib_purepath.py](./pathlib_purepath.py) 29 | - [pathlib_purepath_joinpath.py](./pathlib_purepath_joinpath.py) 30 | 31 | Use the following command to run tests: 32 | 33 | ```bash 34 | # python3 35 | python3 os_path_join.py 36 | ``` 37 | -------------------------------------------------------------------------------- /join_paths/os_path_join.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import os 3 | import logging 4 | 5 | 6 | logger = logging.getLogger(__name__) 7 | logging.basicConfig(format = '\n%(message)s', level = logging.INFO) 8 | 9 | 10 | class Tests(unittest.TestCase): 11 | base_path = '/path/to/base/folder' 12 | 13 | def test_path_traversal(self) -> None: 14 | payload = '../../etc/passwd' 15 | path: str = os.path.join(self.base_path, payload) 16 | self.assertEqual(path, f'{self.base_path}/../../etc/passwd') 17 | self.print_summary( 18 | title='Testing os.join.path with path traversal', 19 | payload=payload, 20 | result=path 21 | ) 22 | 23 | def test_absolute_path(self) -> None: 24 | payload = '/etc/passwd' 25 | path: str = os.path.join(self.base_path, payload) 26 | self.assertEqual(path, '/etc/passwd') 27 | self.print_summary( 28 | title='Testing os.join.path with absolute path', 29 | payload=payload, 30 | result=path 31 | ) 32 | 33 | def print_summary(self, title: str, payload: str, result: str) -> None: 34 | msg = f'{title}\n' + \ 35 | f'Base path:\t{self.base_path}\n' + \ 36 | f'Payload:\t{payload}\n' + \ 37 | f'Joined path:\t{result}\n' 38 | logger.info(msg) 39 | 40 | 41 | if __name__ == '__main__': 42 | unittest.main() 43 | -------------------------------------------------------------------------------- /join_paths/pathlib_purepath.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pathlib import PurePath 3 | import logging 4 | 5 | 6 | logger = logging.getLogger(__name__) 7 | logging.basicConfig(format = '\n%(message)s', level = logging.INFO) 8 | 9 | 10 | class Tests(unittest.TestCase): 11 | base_path = '/path/to/base/folder' 12 | 13 | def test_path_traversal(self) -> None: 14 | payload = '../../etc/passwd' 15 | path = PurePath(self.base_path, payload) 16 | self.assertEqual(str(path), f'{self.base_path}/../../etc/passwd') 17 | self.print_summary( 18 | title='Testing pathlib.PurePath with path traversal', 19 | payload=payload, 20 | result=str(path) 21 | ) 22 | 23 | def test_absolute_path(self) -> None: 24 | payload = '/etc/passwd' 25 | path = PurePath(self.base_path, payload) 26 | self.assertEqual(str(path), '/etc/passwd') 27 | self.print_summary( 28 | title='Testing pathlib.PurePath with absolute path', 29 | payload=payload, 30 | result=str(path) 31 | ) 32 | 33 | def print_summary(self, title: str, payload: str, result: str) -> None: 34 | msg = f'{title}\n' + \ 35 | f'Base path:\t{self.base_path}\n' + \ 36 | f'Payload:\t{payload}\n' + \ 37 | f'Joined path:\t{result}\n' 38 | logger.info(msg) 39 | 40 | 41 | if __name__ == '__main__': 42 | unittest.main() 43 | -------------------------------------------------------------------------------- /join_paths/pathlib_purepath_joinpath.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from pathlib import PurePath 3 | import logging 4 | 5 | 6 | logger = logging.getLogger(__name__) 7 | logging.basicConfig(format = '\n%(message)s', level = logging.INFO) 8 | 9 | 10 | class Tests(unittest.TestCase): 11 | base_path = '/path/to/base/folder' 12 | 13 | def test_path_traversal(self) -> None: 14 | payload = '../../etc/passwd' 15 | path = PurePath(self.base_path).joinpath(payload) 16 | self.assertEqual(str(path), f'{self.base_path}/../../etc/passwd') 17 | self.print_summary( 18 | title='Testing pathlib.PurePath.joinpath with path traversal', 19 | payload=payload, 20 | result=str(path) 21 | ) 22 | 23 | def test_absolute_path(self) -> None: 24 | payload = '/etc/passwd' 25 | path = PurePath(self.base_path).joinpath(payload) 26 | self.assertEqual(str(path), '/etc/passwd') 27 | self.print_summary( 28 | title='Testing pathlib.PurePath.joinpath with absolute path', 29 | payload=payload, 30 | result=str(path) 31 | ) 32 | 33 | def print_summary(self, title: str, payload: str, result: str) -> None: 34 | msg = f'{title}\n' + \ 35 | f'Base path:\t{self.base_path}\n' + \ 36 | f'Payload:\t{payload}\n' + \ 37 | f'Joined path:\t{result}\n' 38 | logger.info(msg) 39 | 40 | 41 | if __name__ == '__main__': 42 | unittest.main() 43 | -------------------------------------------------------------------------------- /mutable_default_objects/README.md: -------------------------------------------------------------------------------- 1 | # Pitfalls of using mutable default objects 2 | 3 | Mutable default values are quite a useful feature provided in Python but they can cause unexpected behavior if not used carefully. Consider the function below, which defines the list of scopes available to a user. 4 | 5 | ```python 6 | def list_scopes(user_id: str, default_scopes: List[str] = []) -> List[str]: 7 | scopes = default_scopes 8 | if get_user_role(user_id) == 'ADMIN': 9 | scopes.append('write') 10 | return scopes 11 | ``` 12 | 13 | The function above takes a list of default scopes in the optional argument `default_scopes` with a default value `[]`. The snippet below shows the result of running the function for users with admin and with non-admin roles. 14 | 15 | ```python 16 | admin_user_id = '0' 17 | scopes = list_scopes(admin_user_id) 18 | # scopes == ['write'] 19 | 20 | non_admin_user_id = '1337' 21 | scopes = list_scopes(non_admin_user_id) 22 | # scopes == ['write'] 23 | ``` 24 | 25 | In this example, the function returns the same scope for a non-admin user as for an admin user. This happens because instead of creating a new empty list as expected, it continues to use the list defined in the default value. 26 | 27 | Python's default arguments are evaluated once when the function is defined, not each time the function is called. This means that if a mutable default argument is used and mutated, this object will be and have been mutated for all future calls to the function as well. 28 | 29 | ## Playground 30 | 31 | There are test cases for a default list object: 32 | 33 | - [default_list_object.py](./default_list_object.py) 34 | 35 | Use the following command to run tests: 36 | 37 | ```bash 38 | # python3 39 | python3 default_list_object.py 40 | ``` 41 | -------------------------------------------------------------------------------- /mutable_default_objects/default_list_object.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import logging 3 | from typing import List 4 | 5 | logger = logging.getLogger(__name__) 6 | logging.basicConfig(format = '\n%(message)s', level = logging.INFO) 7 | 8 | 9 | class Tests(unittest.TestCase): 10 | 11 | def append_to(self, element: str, arr: List[str] = []) -> List[str]: 12 | arr.append(element) 13 | return arr 14 | 15 | def test_append_to_without_default_list(self) -> None: 16 | elements_to_append = ['a', 'b', 'c'] 17 | for element in elements_to_append[:-1]: 18 | self.append_to(element) 19 | arr = self.append_to(elements_to_append[-1]) 20 | self.assertListEqual(arr, elements_to_append) 21 | self.print_summary( 22 | title='Testing append_to(element)', 23 | append_to_invokes=[ 24 | f'append_to(\'{e}\')' 25 | for e in elements_to_append 26 | ], 27 | result=arr 28 | ) 29 | 30 | def test_append_to_with_default_list(self) -> None: 31 | initial_arr = ['1', '2', '3'] 32 | elements_to_append = ['a', 'b', 'c'] 33 | arr = list(initial_arr) 34 | intermediate_arrs = [] 35 | for element in elements_to_append: 36 | intermediate_arrs.append(list(arr)) 37 | self.append_to(element, arr=arr) 38 | self.assertListEqual(arr, initial_arr + elements_to_append) 39 | self.print_summary( 40 | title='Testing append_to(element, arr=arr)', 41 | append_to_invokes=[ 42 | f'append_to(\'{e}\', arr={a})' 43 | for e, a in zip(elements_to_append, intermediate_arrs) 44 | ], 45 | result=arr 46 | ) 47 | 48 | def print_summary(self, title: str, append_to_invokes: List[str], result: List[str]) -> None: 49 | invokes = '\n'.join([ 50 | f' {invoke}' 51 | for invoke in append_to_invokes 52 | ]) 53 | msg = f'{title}\n' + \ 54 | f'Invokes: \n{invokes}\n' \ 55 | f'Result:\t{result}\n' 56 | logger.info(msg) 57 | 58 | 59 | if __name__ == '__main__': 60 | unittest.main() 61 | -------------------------------------------------------------------------------- /regular_expression/README.md: -------------------------------------------------------------------------------- 1 | # Pitfalls of using regular expressions 2 | 3 | Python offers different primitive operations based on regular expressions: 4 | 5 | - [re.match()](https://docs.python.org/3/library/re.html#re.match) checks for a match only at the beginning of the string. 6 | - [re.search()](https://docs.python.org/3/library/re.html#re.search) checks for a match anywhere in the string. 7 | 8 | As can be seen from the descriptions above, the difference between the two functions is that `re.match()` looks for a match only at the beginning of the string, even in the [miltiline](https://docs.python.org/3/library/re.html#re.MULTILINE) mode, while `re.search()` looks for a match anywhere in the string. 9 | 10 | ```python 11 | # re.match 12 | re.match('c', 'abcdef') # No match 13 | re.match('a', 'abcdef') # Match 14 | re.match('c', 'a\nb\nc', re.MULTILINE) # No match 15 | re.match('a', 'a\nb\nc', re.MULTILINE) # Match 16 | # re.search 17 | re.search('c', 'abcdef') # Match 18 | re.search('a', 'abcdef') # Match 19 | re.search('c', 'a\nb\nc') # Match 20 | ``` 21 | 22 | As a result, using `re.match` to implement the validation may lead to the possibility of bypassing it with the new line `\n`. 23 | 24 | ## Playground 25 | 26 | There are test cases for using `re.match` and `re.search`: 27 | 28 | - [re_match_and_search.py](./re_match_and_search.py) 29 | 30 | Use the following command to run tests: 31 | 32 | ```bash 33 | # python3 34 | python3 re_match_and_search.py 35 | ``` 36 | -------------------------------------------------------------------------------- /regular_expression/re_match_and_search.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import re 3 | import logging 4 | 5 | 6 | logger = logging.getLogger(__name__) 7 | logging.basicConfig(format = '\n%(message)s', level = logging.INFO) 8 | 9 | 10 | class Tests(unittest.TestCase): 11 | pattern = '..' 12 | 13 | def test_match(self) -> None: 14 | payload = '../path/traversal/payload' 15 | match = re.match(self.pattern, payload) 16 | self.assertIsNotNone(match) 17 | self.print_summary( 18 | title='Testing re.match with one liner', 19 | payload=payload, 20 | match=str(match) 21 | ) 22 | 23 | def test_match_multiline(self) -> None: 24 | payload = '\n../path/traversal/payload' 25 | match = re.match(self.pattern, payload) 26 | self.assertIsNone(match) 27 | self.print_summary( 28 | title='Testing re.match with multi liner', 29 | payload=payload.replace('\n', '\\n'), 30 | match=str(match) 31 | ) 32 | 33 | def test_search(self) -> None: 34 | payload = '../path/traversal/payload' 35 | match = re.search(self.pattern, payload) 36 | self.assertIsNotNone(match) 37 | self.print_summary( 38 | title='Testing re.search with one liner', 39 | payload=payload, 40 | match=str(match) 41 | ) 42 | 43 | def test_search_multiline(self) -> None: 44 | payload = '\n../path/traversal/payload' 45 | match = re.search(self.pattern, payload) 46 | self.assertIsNotNone(match) 47 | self.print_summary( 48 | title='Testing re.search with multi liner', 49 | payload=payload.replace('\n', '\\n'), 50 | match=str(match) 51 | ) 52 | 53 | def print_summary(self, title: str, payload: str, match: str) -> None: 54 | msg = f'{title}\n' + \ 55 | f'Pattern:\t{self.pattern}\n' + \ 56 | f'Payload:\t{payload}\n' + \ 57 | f'Match:\t\t{match}\n' 58 | logger.info(msg) 59 | 60 | 61 | if __name__ == '__main__': 62 | unittest.main() 63 | -------------------------------------------------------------------------------- /temporary_file_and_directory/README.md: -------------------------------------------------------------------------------- 1 | # Pitfalls of using temporary files and directories 2 | 3 | Python provides a standard module `tempfile` to create temporary files and directories that has the following functions and classes: 4 | 5 | - [tempfile.TemporaryFile(...)](https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryFile) 6 | - [tempfile.NamedTemporaryFile(...)](https://docs.python.org/3/library/tempfile.html#tempfile.NamedTemporaryFile) 7 | - [class tempfile.SpooledTemporaryFile(...)](https://docs.python.org/3/library/tempfile.html#tempfile.SpooledTemporaryFile) 8 | - [class tempfile.TemporaryDirectory(...)](https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory) 9 | - [tempfile.mkstemp(...)](https://docs.python.org/3/library/tempfile.html#tempfile.mkstemp) 10 | - [tempfile.mkdtemp(...)](https://docs.python.org/3/library/tempfile.html#tempfile.mkdtemp) 11 | 12 | Among the arguments accepted by the functions and classes above there are two `prefix` and `suffix` that are used for the file or directory name generation, which looks like this: 13 | 14 | ```python 15 | prefix + name + suffix 16 | ``` 17 | 18 | Under the hood, `tempfile` relies on `os.path.join` to craft a path to a temporary file or directory. Using `os.path.join` for joining paths may lead to unexpected results as described in the [join_paths](/join_paths/README.md) section. 19 | 20 | There are pitfalls in using `prefix` that can lead to unexpected results: 21 | 22 | 1. `prefix` and path traversal. Since `prefix` is used before the random part at the beginning of the name, the path traversal in `prefix` will lead to the creation of a temporary file or directory in an arbitrary location. For example, passing `../../payload` to `prefix` will result in `/var/folders/86/81p8ttj157nfv1r2g323w3z40000gn/T/tmpw7hrvb0u/../../payload.5lif771a`. 23 | 1. `prefix` and absolute paths. Since `prefix` is used before the random part at the beginning of the name, a payload that starts with `/` will force `os.path.join` to treat it as an absolute path. For example, passing `/tmp/payload` to `prefix` will result in `/tmp/payload.5lif771a`. 24 | 25 | However, the behaviour for `suffix` is different. Since `suffix` is added after the random part, using path traversal or absolute paths results in `FileNotFoundError` while creating a file or directory. This happens because cutting off the random part leads to the appearance of a directory in the path that does not exist. As a result, `os.open` and `os.mkdir` throw an error because a parent directory in the path does not exist. For example, passing `/../payload` to `suffix` results in `/var/folders/86/81p8ttj157nfv1r2g323w3z40000gn/T/tmpw7hrvb0u/../payload` where the parent directory `tmpw7hrvb0u` (the random part of the name) does not exist. 26 | 27 | ## Playground 28 | 29 | There are test cases for the creation of temporary files and directories: 30 | 31 | - [tempfile_temporarydirectory.py](./tempfile_temporarydirectory.py) 32 | - [tempfile_namedtemporaryfile.py](./tempfile_namedtemporaryfile.py) 33 | 34 | Use the following command to run tests: 35 | 36 | ```bash 37 | # python3 38 | python3 tempfile_temporarydirectory.py 39 | ``` 40 | -------------------------------------------------------------------------------- /temporary_file_and_directory/tempfile_namedtemporaryfile.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import tempfile 3 | import logging 4 | from pathlib import Path 5 | 6 | 7 | logger = logging.getLogger(__name__) 8 | logging.basicConfig(format = '\n%(message)s', level = logging.INFO) 9 | 10 | 11 | class Tests(unittest.TestCase): 12 | 13 | def test_path_traversal_prefix(self) -> None: 14 | payload = '../payload.' 15 | with tempfile.TemporaryDirectory() as tmp_dir: 16 | with tempfile.NamedTemporaryFile(dir=tmp_dir, prefix=payload) as tmp_file: 17 | path = tmp_file.name 18 | relative_path = str(Path(path).relative_to(tmp_dir)) 19 | self.assertTrue(relative_path.startswith(payload)) 20 | self.print_summary_for_prefix( 21 | title='Testing the prefix argument of tempfile.NamedTemporaryFile with path traversal', 22 | payload=payload, 23 | result=path 24 | ) 25 | 26 | def test_absolute_path_prefix(self) -> None: 27 | payload = '/tmp/payload.' 28 | with tempfile.NamedTemporaryFile(prefix=payload) as tmp_file: 29 | path = tmp_file.name 30 | self.assertTrue(path.startswith(payload)) 31 | self.print_summary_for_prefix( 32 | title='Testing the prefix argument of tempfile.NamedTemporaryFile with absolute path', 33 | payload=payload, 34 | result=path 35 | ) 36 | 37 | def test_path_traversal_suffix(self) -> None: 38 | payload = '/../../payload.' 39 | with self.assertRaises(FileNotFoundError) as context: 40 | _ = tempfile.NamedTemporaryFile(suffix=payload) 41 | self.print_summary_for_suffix( 42 | title='Testing the suffix argument of tempfile.NamedTemporaryFile with path traversal', 43 | payload=payload, 44 | exception_msg=str(context.exception) 45 | ) 46 | 47 | def test_absolute_path_suffix(self) -> None: 48 | payload = '/tmp/payload.' 49 | with self.assertRaises(FileNotFoundError) as context: 50 | _ = tempfile.NamedTemporaryFile(suffix=payload) 51 | self.print_summary_for_suffix( 52 | title='Testing the suffix argument of tempfile.NamedTemporaryFile with absolute path', 53 | payload=payload, 54 | exception_msg=str(context.exception) 55 | ) 56 | 57 | def print_summary_for_prefix(self, title: str, payload: str, result: str) -> None: 58 | msg = f'{title}\n' + \ 59 | f'Payload:\t{payload}\n' + \ 60 | f'Temp directory:\t{result}\n' 61 | logger.info(msg) 62 | 63 | def print_summary_for_suffix(self, title: str, payload: str, exception_msg: str) -> None: 64 | msg = f'{title}\n' + \ 65 | f'Payload:\t{payload}\n' + \ 66 | f'Exception:\t{exception_msg}\n' 67 | logger.info(msg) 68 | 69 | 70 | if __name__ == '__main__': 71 | unittest.main() 72 | -------------------------------------------------------------------------------- /temporary_file_and_directory/tempfile_temporarydirectory.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import tempfile 3 | import logging 4 | from pathlib import Path 5 | 6 | 7 | logger = logging.getLogger(__name__) 8 | logging.basicConfig(format = '\n%(message)s', level = logging.INFO) 9 | 10 | 11 | class Tests(unittest.TestCase): 12 | 13 | def test_path_traversal_prefix(self) -> None: 14 | payload = '../payload.' 15 | with tempfile.TemporaryDirectory() as dir: 16 | with tempfile.TemporaryDirectory(dir=dir, prefix=payload) as tmp_dir: 17 | path = tmp_dir 18 | relative_path = str(Path(path).relative_to(dir)) 19 | self.assertTrue(relative_path.startswith(payload)) 20 | self.print_summary_for_prefix( 21 | title='Testing the prefix argument of tempfile.TemporaryDirectory with path traversal', 22 | payload=payload, 23 | result=path 24 | ) 25 | 26 | def test_absolute_path_prefix(self) -> None: 27 | payload = '/tmp/payload.' 28 | with tempfile.TemporaryDirectory(prefix=payload) as tmp_dir: 29 | path = tmp_dir 30 | self.assertTrue(path.startswith(payload)) 31 | self.print_summary_for_prefix( 32 | title='Testing the prefix argument of tempfile.TemporaryDirectory with absolute path', 33 | payload=payload, 34 | result=path 35 | ) 36 | 37 | def test_path_traversal_suffix(self) -> None: 38 | payload = '/../../payload.' 39 | with self.assertRaises(FileNotFoundError) as context: 40 | _ = tempfile.TemporaryDirectory(suffix=payload) 41 | self.print_summary_for_suffix( 42 | title='Testing the suffix argument of tempfile.TemporaryDirectory with path traversal', 43 | payload=payload, 44 | exception_msg=str(context.exception) 45 | ) 46 | 47 | def test_absolute_path_suffix(self) -> None: 48 | payload = '/tmp/payload.' 49 | with self.assertRaises(FileNotFoundError) as context: 50 | _ = tempfile.TemporaryDirectory(suffix=payload) 51 | self.print_summary_for_suffix( 52 | title='Testing the suffix argument of tempfile.TemporaryDirectory with absolute path', 53 | payload=payload, 54 | exception_msg=str(context.exception) 55 | ) 56 | 57 | def print_summary_for_prefix(self, title: str, payload: str, result: str) -> None: 58 | msg = f'{title}\n' + \ 59 | f'Payload:\t{payload}\n' + \ 60 | f'Temp directory:\t{result}\n' 61 | logger.info(msg) 62 | 63 | def print_summary_for_suffix(self, title: str, payload: str, exception_msg: str) -> None: 64 | msg = f'{title}\n' + \ 65 | f'Payload:\t{payload}\n' + \ 66 | f'Exception:\t{exception_msg}\n' 67 | logger.info(msg) 68 | 69 | 70 | if __name__ == '__main__': 71 | unittest.main() 72 | -------------------------------------------------------------------------------- /url_join/README.md: -------------------------------------------------------------------------------- 1 | # Pitfalls of joining URLs 2 | 3 | There is the [urllib.parse.urljoin(base, url, allow_fragments=True)](https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin) that constructs a full URL by combining a base URL with another URL. 4 | 5 | However, if a URL is an absolute URL (that is, it starts with `//` or `scheme://`), the URL's hostname and/or scheme will be present in the result. For example, joining `https://foo.bar` and `//localhost/test` will result in `https://localhost/test`. 6 | 7 | ## Playground 8 | 9 | There are test cases for `urllib.parse.urljoin`: 10 | 11 | - [urllib_parse_urljoin.py](./urllib_parse_urljoin.py) 12 | 13 | Use the following command to run tests: 14 | 15 | ```bash 16 | # python3 17 | python3 urllib_parse_urljoin.py 18 | ``` 19 | -------------------------------------------------------------------------------- /url_join/urllib_parse_urljoin.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import urllib.parse 3 | import logging 4 | 5 | 6 | logger = logging.getLogger(__name__) 7 | logging.basicConfig(format = '\n%(message)s', level = logging.INFO) 8 | 9 | 10 | class Tests(unittest.TestCase): 11 | base_url = 'https://foo.bar/' 12 | 13 | def test_absolute_url(self) -> None: 14 | payload = '//attacker.local/test' 15 | url: str = urllib.parse.urljoin(self.base_url, payload) 16 | self.assertEqual(url, 'https://attacker.local/test') 17 | self.print_summary( 18 | title='Testing urllib.parse.urljoin with absolute path', 19 | payload=payload, 20 | result=url 21 | ) 22 | 23 | def test_absolute_url_with_schema(self) -> None: 24 | payload = 'scheme://attacker.local/test' 25 | url: str = urllib.parse.urljoin(self.base_url, payload) 26 | self.assertEqual(url, 'scheme://attacker.local/test') 27 | self.print_summary( 28 | title='Testing urllib.parse.urljoin with absolute path and scheme', 29 | payload=payload, 30 | result=url 31 | ) 32 | 33 | def print_summary(self, title: str, payload: str, result: str) -> None: 34 | msg = f'{title}\n' + \ 35 | f'Base URL:\t{self.base_url}\n' + \ 36 | f'Payload:\t{payload}\n' + \ 37 | f'Joined URL:\t{result}\n' 38 | logger.info(msg) 39 | 40 | 41 | if __name__ == '__main__': 42 | unittest.main() 43 | --------------------------------------------------------------------------------