text
stringlengths
79
3.72M
<vulnerable_code> gc_collect() class ImportErrorTests(unittest.TestCase): def test_attributes(self):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> gc_collect() class AttributeErrorTests(unittest.TestCase): def test_a...
<vulnerable_code>/* * AttributeError extends Exception */ SimpleExtendsException(PyExc_Exception, AttributeError, "Attribute not found."); /* * SyntaxError extends Exception<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code...
<vulnerable_code> return result; } PyObject * PyObject_GetAttr(PyObject *v, PyObject *name) { PyTypeObject *tp = Py_TYPE(v); if (!PyUnicode_Check(name)) { PyErr_Format(PyExc_TypeError, "attribute name must be string, not '%.200s'", Py_TYPE(name)->tp_name); ...
<vulnerable_code>#include "pycore_interp.h" // PyInterpreterState.importlib #include "pycore_object.h" // _PyDebug_PrintTotalRefs() #include "pycore_parser.h" // _PyParser_ASTFromString() #include "pycore_pyerrors.h" // _PyErr_Fetch #include "pycore_pylifecycle.h" // _Py_UnhandledKeyboardInt...
<vulnerable_code><commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> #include "Python.h" #include "pycore_pyerrors.h" #define MAX_DISTANCE 3 #define MAX_CANDIDATE_ITEMS 100 #define MAX_STRING_SIZE 20 /* Calculate the Levenshtein distance between string1 ...
<vulnerable_code>Typical use is: import fileinput for line in fileinput.input(): process(line) This iterates over the lines of all files listed in sys.argv[1:], deleted when the output file is closed. In-place filtering is disabled when standard input is read. XXX The current implementation does not...
<vulnerable_code>Tests for fileinput module. Nick Mathewson ''' import os import sys import re # try opening in universal newline mode t1 = self.writeTmp(b"A\nB\r\nC\rD", mode="wb") with warnings_helper.check_warnings(('', DeprecationWarning)): fi = FileInput(files=t1, mode="U") ...
<vulnerable_code> def test_convert_zero_sized_blob(self): self.con.execute("insert into test(cbin) values (?)", (b"",)) cur = self.con.execute("select cbin from test") self.assertEqual(cur.fetchone()[0], b"blobish") class ColNamesTests(unittest.TestCase):<commit_title>[PATCH 003/413] bpo-43...
<vulnerable_code>{ int i, numcols; PyObject* row; PyObject* item = NULL; int coltype; PyObject* converter; PyObject* converted; */ if (converter != Py_None) { const void *blob = sqlite3_column_blob(self->statement->st, i); if (blob == NULL && sqlite3_errc...
<vulnerable_code> self.check_string(b"(1+2+3") def test_decoding_error_at_the_end_of_the_line(self): self.check_string(b"'\u1f'") def test_main(): support.run_unittest(CmdLineTest, IgnoreEnvironmentTest, SyntaxErrorTests)<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (G...
<vulnerable_code> items = [5,43,2,1] s = MySet(items) r = s.pop() self.assertEquals(len(s), len(items) - 1) self.assertNotIn(r, s) self.assertIn(r, items) <commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> ...
<vulnerable_code> with self.assertRaises(sqlite.OperationalError) as cm: with sqlite.connect(':memory:') as bck: self.cx.backup(bck, name='non-existing') self.assertIn( str(cm.exception), ['SQL logic error', 'SQL logic error or missing database'] ...
<vulnerable_code>/*[clinic end generated code: output=306a3e6a38c36334 input=30ae45fc420bfd3b]*/ { int rc; int callback_error = 0; int sleep_ms = (int)(sleep * 1000.0); sqlite3 *bck_conn; sqlite3_backup *bck_handle; bck_handle = sqlite3_backup_init(bck_conn, "main", self->db, name); Py_END_A...
<vulnerable_code> con = sqlite3.connect(":memory:") cur = con.cursor() cur.execute("create table people (name_last, age)") who = "Yeltsin" age = 72 # This is the qmark style: cur.execute("insert into people values (?, ?)", (who, age)) # And this is the named style: cur.execute("select * from people where name_last=:...
<vulnerable_code> gc_collect() class AttributeErrorTests(unittest.TestCase): def test_attributes(self):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> gc_collect() global_for_suggestions = None class NameErrorTests(unitt...
<vulnerable_code>/* * NameError extends Exception */ SimpleExtendsException(PyExc_Exception, NameError, "Name not found globally."); /* * UnboundLocalError extends NameError<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code>...
<vulnerable_code> return; _PyErr_Format(tstate, exc, format_str, obj_str); } static void<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> return; _PyErr_Format(tstate, exc, format_str, obj_str); if (exc == PyExc_NameError) {...
<vulnerable_code>#include "Python.h" #include "pycore_pyerrors.h" #define MAX_DISTANCE 3 #define MAX_CANDIDATE_ITEMS 100 #define MAX_STRING_SIZE 20 /* Calculate the Levenshtein distance between string1 and string2 */ static size_t levenshtein_distance(const char *a, const char *b) { if (a == NULL || b == NULL) {...
<vulnerable_code>EXPORT_FUNC(_Py_BuildValue_SizeT) EXPORT_FUNC(_Py_CheckRecursiveCall) EXPORT_FUNC(_Py_Dealloc) EXPORT_FUNC(_Py_VaBuildValue_SizeT) EXPORT_FUNC(_PyArg_Parse_SizeT) EXPORT_FUNC(_PyArg_ParseTuple_SizeT) EXPORT_FUNC(_PyTrash_destroy_chain) EXPORT_FUNC(_PyTrash_thread_deposit_object) EXPORT_FUNC(_PyTrash_th...
<vulnerable_code>import re import sys import sysconfig from glob import glob, escape import _osx_support SUBPROCESS_BOOTSTRAP = True from distutils import log from distutils.command.build_ext import build_ext from distutils.command.build_scripts import build_scripts from distutils.command.install import install ...
<vulnerable_code>#define ADD_TYPE(module, type) \ do { \ if (PyModule_AddType(module, &type) < 0) { \ Py_DECREF(module); \ return NULL; \ } \ } while (...
<vulnerable_code>Implements the Distutils 'install' command.""" import sys import os from distutils import log from distutils.core import Command HAS_USER_SITE = (USER_SITE is not None) WINDOWS_SCHEME = { 'purelib': '$base/Lib/site-packages', 'platlib': '$base/Lib/site-packages', 'headers': '$base/Inclu...
<vulnerable_code> _PYTHON_BUILD = is_python_build(True) if _PYTHON_BUILD: for scheme in ('posix_prefix', 'posix_home'): _INSTALL_SCHEMES[scheme]['include'] = '{srcdir}/Include' _INSTALL_SCHEMES[scheme]['platinclude'] = '{projectbase}/.' def _subst_vars(s, local_vars): try: return s.fo...
<vulnerable_code> self.assertIn("blech", err.getvalue()) class ImportErrorTests(unittest.TestCase): <commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> self.assertIn("blech", err.getvalue()) def test_attribute_error_with_fail...
<vulnerable_code> err += PyFile_WriteString("?", f); } Py_DECREF(suggestions); } err += PyFile_WriteString("\n", f); Py_XDECREF(tb);<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> err += PyFile_WriteStr...
<vulnerable_code> PyObject *suggestion = NULL; const char *name_str = PyUnicode_AsUTF8(name); if (name_str == NULL) { PyErr_Clear(); return NULL; } for (int i = 0; i < dir_size; ++i) { PyObject *item = PyList_GET_ITEM(dir, i); const char *item_str = PyUnicode_AsUTF8(it...
<vulnerable_code> val = cur.fetchone()[0] self.assertEqual(val, 2) # Regarding deterministic functions: # # Between 3.8.3 and 3.15.0, deterministic functions were only used to<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> ...
<vulnerable_code> sqlite3_value* cur_value; PyObject* cur_py_value; const char* val_str; Py_ssize_t buflen; args = PyTuple_New(argc); if (!args) { cur_py_value = Py_NewRef(Py_None); } break; case SQLITE_BLOB: buflen ...
<vulnerable_code> /* Calculate the Levenshtein distance between string1 and string2 */ static size_t levenshtein_distance(const char *a, const char *b) { const size_t a_size = strlen(a); const size_t b_size = strlen(b); if (a_size > MAX_STRING_SIZE || b_size > MAX_STRING_SIZE) { return 0; Py_...
<vulnerable_code> Traceback (most recent call last): SyntaxError: invalid syntax Make sure that the old "raise X, Y[, Z]" form is gone: >>> raise X, Y Traceback (most recent call last):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> Trace...
<vulnerable_code>#define invalid_if_stmt_type 1200 #define invalid_elif_stmt_type 1201 #define invalid_while_stmt_type 1202 #define _loop0_1_type 1203 #define _loop0_2_type 1204 #define _loop0_4_type 1205 #define _gather_3_type 1206 #define _loop0_6_type 1207 #define _gather_5_type 1208 #define _loop0_8_type 1209 #defi...
<vulnerable_code> def test_binop(self): self.check_stack_size("x + " * self.N + "x") def test_func_and(self): code = "def f(x):\n" code += " x and x\n" * self.N<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> def tes...
<vulnerable_code>#define COMP_SETCOMP 2 #define COMP_DICTCOMP 3 #define IS_TOP_LEVEL_AWAIT(c) ( \ (c->c_flags->cf_flags & PyCF_ALLOW_TOP_LEVEL_AWAIT) \ && (c->u->u_ste->ste_type == ModuleBlock)) */ static int compiler_addop_i(struct compiler *c, int opcode, Py_ssize_t oparg) { struct instr *i; ...
<vulnerable_code> pass elif _is_sunder(key): if key not in ( '_order_', '_create_pseudo_member_', '_generate_next_value_', '_missing_', '_ignore_', '_iter_member_', '_iter_member_by_value_', '_iter_member_by_def_', ...
<vulnerable_code>def _is_private(cls_name, name): # do not use `re` as `re` imports `enum` pattern = '_%s__' % (cls_name, ) if ( len(name) >= 5 and name.startswith(pattern) and name[len(pattern)] != '_' and (name[-1] != '_' or name[-2] != '_') ): ...
<vulnerable_code> triple = 3 value = 4 class TestEnumTypeSubclassing(unittest.TestCase): pass<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> triple = 3 value = 4 class TestHelpers(unittest.TestCase):...
<vulnerable_code> # Missing commas in literals collections should not # produce special error messages regarding missing # parentheses >>> [1, 2 3] Traceback (most recent call last): SyntaxError: invalid syntax >>> {1, 2 3} Traceback (most recent call last): SyntaxError: invalid syntax >>> {1:2, 2:5 3:12} Traceback ...
<vulnerable_code>ASYNC = 56 TYPE_IGNORE = 57 TYPE_COMMENT = 58 # These aren't used by the C tokenizer but are needed for tokenize.py ERRORTOKEN = 59 COMMENT = 60 NL = 61 ENCODING = 62 N_TOKENS = 63 # Special definitions for cooperation with parser NT_OFFSET = 256 <commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWar...
<vulnerable_code> {NULL, -1}, }, }; #define file_type 1000 #define interactive_type 1001 #define eval_type 1002 #define t_atom_type 1174 #define invalid_arguments_type 1175 #define invalid_kwarg_type 1176 #define invalid_named_expression_type 1177 #define invalid_assignment_type 1178 #define invalid_ann_assi...
<vulnerable_code> return _PyPegen_expect_token(p, STRING); } static PyObject * parsenumber_raw(const char *s) { p->tok = tok; p->keywords = NULL; p->n_keyword_lists = -1; p->tokens = PyMem_Malloc(sizeof(Token *)); if (!p->tokens) { PyMem_Free(p);<commit_title>[PATCH 003/413] bpo-43651: F...
<vulnerable_code> "ASYNC", "TYPE_IGNORE", "TYPE_COMMENT", "<ERRORTOKEN>", "<COMMENT>", "<NL>",<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> "ASYNC", "TYPE_IGNORE", "TYPE_COMMENT", "SOFT_KEYWORD", "<ERRORTOKEN...
<vulnerable_code> // Initialize keywords p->keywords = reserved_keywords; p->n_keyword_lists = n_keyword_lists; return start_rule(p); } "NAME": NodeTypes.NAME_TOKEN, "NUMBER": NodeTypes.NUMBER_TOKEN, "STRING": NodeTypes.STRING_TOKEN, } if subheader: self.print(subheader...
<vulnerable_code> ) { D(fprintf(stderr, "%*c+ invalid_kvpair[%d-%d]: %s succeeded!\n", p->level, ' ', _mark, p->mark, "expression !(':')")); _res = RAISE_SYNTAX_ERROR ( "':' expected after dictionary key" ); if (_res == NULL && PyErr_Occurred()) { p->er...
<vulnerable_code>normalize_basic_block(basicblock *bb); static int optimize_cfg(struct assembler *a, PyObject *consts); static int ensure_exits_have_lineno(struct compiler *c); if (consts == NULL) { goto error; } if (optimize_cfg(&a, consts)) { goto error; } Called with codestr poi...
<vulnerable_code>""" import ast import copy import sys import importlib.util <commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> """ import ast import sys import importlib.util
<vulnerable_code>""" from abc import abstractmethod, ABCMeta import ast import collections import collections.abc import contextlib<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> """ from abc import abstractmethod, ABCMeta import collections import co...
<vulnerable_code> __version__ = sys.version[:sys.version.index(' ')] warnings.warn("The distutils package is deprecated and slated for " "removal in Python 3.12. Use setuptools or check " "PEP 632 for potential alternatives", DeprecationWarning, 2)<commit_title>[PATCH 003/413]...
<vulnerable_code>import importlib.util import string import sys from distutils.errors import DistutilsPlatformError from distutils.dep_util import newer from distutils.spawn import spawn direct=1) """ % (optimize, force, prefix, base_dir, verbose)) cmd = [sys.executable] cmd.extend(subproc...
<vulnerable_code>be run. """ import distutils.tests import test.support def test_main(): # used by regrtest test.support.run_unittest(distutils.tests.test_suite()) test.support.reap_children() def load_tests(*_):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_d...
<vulnerable_code> # different hash randomization seed. sub_env = dict(os.environ) sub_env['PYTHONHASHSEED'] = 'random' subprocess.check_call( [sys.executable, '-c', """ from lib2to3.pgen2 import driver as pgen2_driver pgen2_driver.load_grammar(%r, save=...
<vulnerable_code> self.port = self.socket.getsockname()[1] self._handler = handler self._thread = None self.poll_interval = poll_interval def process_message(self, peer, mailfrom, rcpttos, data): :func:`select` or :func:`poll` call by ...
<vulnerable_code>except ImportError: gc = None from test.libregrtest.utils import setup_unraisable_hook def setup_tests(ns): sys.addaudithook(_test_audit_hook) setup_unraisable_hook() if ns.timeout is not None: # For a slow buildbot worker, increase SHORT_TIMEOUT and LONG_TIMEOUT<commit...
<vulnerable_code>orig_unraisablehook = None def regrtest_unraisable_hook(unraisable): global orig_unraisablehook support.environment_altered = True print_warning("Unraisable exception") old_stderr = sys.stderr try: sys.stderr = sys.__stderr__ orig_unraisablehook(unraisable) fin...
<vulnerable_code> def test_unraisable_exc(self): # --fail-env-changed must catch unraisable exception. # The exceptioin must be displayed even if sys.stderr is redirected. code = textwrap.dedent(r""" import unittest import weakref self.assertIn("Warning -- Unr...
<vulnerable_code> self.check_result(handled=True) def test_threading_not_handled(self): ThreadingErrorTestServer(SystemExit) self.check_result(handled=False) @requires_forking def test_forking_handled(self):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-...
<vulnerable_code>platforms_to_skip = ('netbsd5', 'hp-ux11') # A trivial mutable counter. class Counter(object): def __init__(self): if self.should_raise: raise SystemExit cyclic_object = RunSelfFunction(should_raise=False) weak_cyclic_object = weakref.ref(cycli...
<vulnerable_code>/* * UnboundLocalError extends NameError */ SimpleExtendsException(PyExc_NameError, UnboundLocalError, "Local name referenced but not bound to a value."); /*<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> /*...
<vulnerable_code> self.assertNotIn("blech", err.getvalue()) class AttributeErrorTests(unittest.TestCase): def test_attributes(self): # Setting 'attr' should not be a problem.<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> s...
<vulnerable_code>PyObject *_Py_Offer_Suggestions(PyObject *exception) { PyObject *result = NULL; assert(!PyErr_Occurred()); if (PyErr_GivenExceptionMatches(exception, PyExc_AttributeError)) { result = offer_suggestions_for_attribute_error((PyAttributeErrorObject *) exception); } else if (PyErr_G...
<vulnerable_code> t.daemon = True t.start() def handle_request(self, c): ''' Handle a new connection ''' funcname = result = request = None try: connection.deliver_challenge(c, self.authkey) connection.answer_challenge(c, self.a...
<vulnerable_code>import tempfile from subprocess import * req_template = """ [ default ] base_url = http://testca.pythontest.net/testca O = Python Software Foundation CN = {hostname} [req_x509_extensions_simple] subjectAltName = @s...
<vulnerable_code> 'issuer': ((('countryName', 'XY'),), (('organizationName', 'Python Software Foundation CA'),), (('commonName', 'our-ca-server'),)), 'notAfter': 'Jul 7 14:23:16 2028 GMT', 'notBefore': 'Aug 29 14:23:16 2018 GMT', 'serialNumber': 'CB2D80995A69525C', 'subject':...
<vulnerable_code> 'issuer': ((('countryName', 'XY'),), (('organizationName', 'Python Software Foundation CA'),), (('commonName', 'our-ca-server'),)), 'notAfter': 'Jul 7 14:23:16 2028 GMT', 'notBefore': 'Aug 29 14:23:16 2018 GMT', 'serialNumber': 'CB2D80995A69525C', 'subject':...
<vulnerable_code> _setSSLError(NULL, 0, __FILE__, __LINE__); return NULL; } SSL_set_app_data(self->ssl, self); if (sock) { SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_de...
<vulnerable_code> """Return the currently selected NPN protocol as a string, or ``None`` if a next protocol was not negotiated or if NPN is not supported by one of the peers.""" if _ssl.HAS_NPN: return self._sslobj.selected_npn_protocol() def selected_alpn_protocol(self):...
<vulnerable_code>PROTOCOLS = sorted(ssl._PROTOCOL_NAMES) HOST = socket_helper.HOST IS_LIBRESSL = ssl.OPENSSL_VERSION.startswith('LibreSSL') IS_OPENSSL_1_1_0 = not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 0) IS_OPENSSL_1_1_1 = not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 1) IS_OPENSSL_3_0_0 = not IS_...
<vulnerable_code># error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL" #endif #if (OPENSSL_VERSION_NUMBER < 0x10100000L) || defined(LIBRESSL_VERSION_NUMBER) /* OpenSSL < 1.1.0 */ #define EVP_MD_CTX_new EVP_MD_CTX_create #define EVP_MD_CTX_free EVP_MD_CTX_destroy HMAC_CTX * HMAC_CTX_new(void) ...
<vulnerable_code>#define _PySSL_FIX_ERRNO #define PySSL_BEGIN_ALLOW_THREADS_S(save) \ do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0) #define PySSL_END_ALLOW_THREADS_S(save) \ do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0) #define PySSL_BEG...
<vulnerable_code> return 0; } #ifdef HAVE_OPENSSL_KEYLOG static void _PySSL_keylog_callback(const SSL *ssl, const char *line) { SSL_CTX_set_keylog_callback(self->ctx, _PySSL_keylog_callback); return 0; } #endif<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_descri...
<vulnerable_code>log = logging.getLogger("multissl") OPENSSL_OLD_VERSIONS = [ "1.0.2u", "1.1.0l", ] OPENSSL_RECENT_VERSIONS = [ "1.1.1k", # "3.0.0-alpha14" ] LIBRESSL_OLD_VERSIONS = [ "2.9.2", ] LIBRESSL_RECENT_VERSIONS = [ "3.2.4", ] # store files in ../multissl<commit_title>[PATCH 003/413...
<vulnerable_code> for l in (self.missing, self.failed, self.failed_on_import)): print() print("Could not build the ssl module!") print("Python requires an OpenSSL 1.0.2 or 1.1 compatible " "libssl with X509_VERIFY_PARAM_set1_host().") print...
<vulnerable_code> return PyLong_FromLong(RAND_status()); } #ifndef OPENSSL_NO_EGD /* LCOV_EXCL_START */ /*[clinic input] _ssl.RAND_egd path: object(converter="PyUnicode_FSConverter") / Queries the entropy gather daemon (EGD) on the socket named by 'path'. Returns number of bytes read. Raises SSLError if ...
<vulnerable_code> # In addition to checking for actual types here, also check for # string annotations. get_type_hints() won't always work for us # (see https://github.com/python/typing/issues/508 for example), # plus it's expensive and would require an eval for every stirng # annotation. So, make ...
<vulnerable_code> #include "Python.h" /* Redefined below for Windows debug builds after important #includes */ #define _PySSL_FIX_ERRNO #define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save); #define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); } /* Include symbols from _socket module */ #in...
<vulnerable_code> threadstate = PyGILState_Ensure(); ssl_obj = (PySSLSocket *)SSL_get_app_data(ssl); assert(PySSLSocket_Check(ssl_obj)); if (ssl_obj->ctx->msg_cb == NULL) { PyGILState_Release(threadstate); return; threadstate = PyGILState_Ensure(); ssl_obj = (PySSLSocket *)SSL_g...
<vulnerable_code> self.missing.extend(['_ssl', '_hashlib']) return None, None self.add(Extension( '_ssl', ['_ssl.c'], include_dirs=openssl_includes, library_dirs=openssl_libdirs, libraries=openssl_libs, depends=['socketmodule.h'...
<vulnerable_code> sys.__excepthook__(*sys.exc_info()) self.assertIn("global_for_suggestions?", err.getvalue()) def test_name_error_suggestions_do_not_trigger_for_long_names(self): def f(): somethingverywronghehehehehehe = None self.assertNotIn("somethingverywrong...
<vulnerable_code>#include "pycore_pyerrors.h" #define MAX_DISTANCE 3 #define MAX_CANDIDATE_ITEMS 100 #define MAX_STRING_SIZE 25 /* Calculate the Levenshtein distance between string1 and string2 */ } suggestions = calculate_suggestions(dir, name); Py_DECREF(dir); return suggestions; }<commit_title>[PA...
<vulnerable_code> requires_blake2 = unittest.skipUnless(_blake2, 'requires _blake2') try: import _sha3 except ImportError: _sha3 = None requires_sha3 = unittest.skipUnless(_sha3, 'requires _sha3') def hexstr(s): assert isinstance(s, bytes), repr(s) self.check_no_unicode('blake2b') self.c...
<vulnerable_code> self.assertNotIn("blech", err.getvalue()) self.assertNotIn("oh no!", err.getvalue()) class ImportErrorTests(unittest.TestCase): def test_attributes(self):<commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> self...
<vulnerable_code>#define MAX_STRING_SIZE 25 /* Calculate the Levenshtein distance between string1 and string2 */ static size_t levenshtein_distance(const char *a, size_t a_size, const char *b, size_t b_size) { size_t *buffer = PyMem_Calloc(a_size, sizeof(size_t)); if (buffer == NULL) { ...
<vulnerable_code> (r"(@\w+ '''(.|\n)+?''')", bygroups(None)), (r"^(@.*)$", bygroups(None)), ], "actions": [(r"{(.|\n)+?}", bygroups(None)),], "strings": [ (r"'\w+?'", Keyword), (r'"\w+?"', Keyword), (r"'\W+?'", Text), (r'"\W+...
<vulnerable_code>py_sha3_new_impl(PyTypeObject *type, PyObject *data, int usedforsecurity) /*[clinic end generated code: output=90409addc5d5e8b0 input=bcfcdf2e4368347a]*/ { SHA3object *self = newSHA3object(type); if (self == NULL) { goto error; } SHA3State *state = PyType_GetModuleState(type); ...
<vulnerable_code> cert_reqs=cert_reqs, cafile=ca_certs) with create_connection(addr) as sock: with context.wrap_socket(sock) as sslsock: dercert = sslsock.getpeercert(True) return DER_cert_to_PEM_cert(dercert) <commit_...
<vulnerable_code> """Tests that connect to a simple server running in the background""" def setUp(self): server = ThreadedEchoServer(SIGNED_CERTFILE) self.server_addr = (HOST, server.port) server.__enter__() self.addCleanup(server.__exit__, None, None, None) def test_get_serv...
<vulnerable_code> ) self.assertIn(rc, errors) class ContextTests(unittest.TestCase): <commit_title>[PATCH 003/413] bpo-43651: Fix EncodingWarning in test_io (GH-25097)<commit_description><fixed_code> ) self.assertIn(rc, errors) def test_read_write_zero(self): # empty reads ...
<vulnerable_code>_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b) /*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/ { int len; int sockstate; _PySSLError err; int nonblocking; Py_INCREF(sock); } if (b->len > INT_MAX) { PyErr_Format(PyExc_...
<vulnerable_code> # OpenSSL's PKCS5_PBKDF2_HMAC requires OpenSSL 1.0+ with HMAC and SHA from _hashlib import pbkdf2_hmac except ImportError: _trans_5C = bytes((x ^ 0x5C) for x in range(256)) _trans_36 = bytes((x ^ 0x36) for x in range(256)) as OpenSSL's PKCS5_PBKDF2_HMAC for short passwords and ...
<vulnerable_code> CertificateError is raised on failure. On success, the function returns nothing. """ if not cert: raise ValueError("empty or no certificate, match_hostname needs a " "SSL socket or SSL context with either " sslsocket_class = None # SSLSocket is assi...
<vulnerable_code> copy_attributes(info_add, ssl, 'ssl.%s', attributes, formatter=format_attr) for name, ctx in ( ('SSLContext', ssl.SSLContext()), ('default_https_context', ssl._create_default_https_context()), ('stdlib_context', ssl._create_stdlib_context()), ):<commit_title>[PATCH ...
<vulnerable_code> if ssl is None: return None else: return ssl.SSLContext(ssl.PROTOCOL_TLS) def run_briefly(loop): # contains the ssl key and certificate files) differs # between the stdlib and stand-alone asyncio. # Prefer our own if we can find it. context = ss...
<vulnerable_code> _ssl_closing = False def secure_connection(self): context = ssl.SSLContext() context.load_cert_chain(CERTFILE) socket = context.wrap_socket(self.socket, suppress_ragged_eofs=False,<commit_title>[PATCH 003/413]...
<vulnerable_code>from test.support import _4G, bigmemtest from test.support.import_helper import import_fresh_module from test.support import threading_helper from http.client import HTTPException # Were we compiled --with-pydebug or with #define Py_DEBUG? @unittest.skipIf(builtin_hashlib is None, "test requires ...
<vulnerable_code> def get_request(self): newsocket, fromaddr = self.socket.accept() context = ssl.SSLContext() context.load_cert_chain(CERTFILE) connstream = context.wrap_socket(newsocket, server_side=True) return connstream, fromaddr<commit_title>[PAT...
<vulnerable_code> elif cmd == b'STARTTLS\r\n': reader.close() client.sendall(b'382 Begin TLS negotiation now\r\n') context = ssl.SSLContext() context.load_cert_chain(certfile) client = context.wrap_socket(...
<vulnerable_code> def cmd_stls(self, arg): if self.tls_active is False: self.push('+OK Begin TLS negotiation') context = ssl.SSLContext() context.load_cert_chain(CERTFILE) tls_sock = context.wrap_socket(self.socket, ...
<vulnerable_code> # check runtime and dynamic crypto policy settings. A TLS version may # be compiled in but disabled by a policy or config option. ctx = ssl.SSLContext() if ( hasattr(ctx, 'minimum_version') and ctx.minimum_version != ssl.TLSVersion.MINIMUM_SUPPORTED and needs_s...
<vulnerable_code> return NULL; } /* * SSL objects */ { PySSLContext *self; long options; SSL_CTX *ctx = NULL; X509_VERIFY_PARAM *params; int result; return NULL; } PySSL_BEGIN_ALLOW_THREADS switch(proto_version) { #if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3) ...
<vulnerable_code>import socket import select import time import datetime import gc import os import errno PROTOCOLS = sorted(ssl._PROTOCOL_NAMES) HOST = socket_helper.HOST IS_LIBRESSL = ssl.OPENSSL_VERSION.startswith('LibreSSL') IS_OPENSSL_1_1_1 = not IS_LIBRESSL and ssl.OPENSSL_VERSION_INFO >= (1, 1, 1) IS_OPENSSL_3_...
<vulnerable_code> PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST", X509_V_FLAG_TRUSTED_FIRST); /* Alert Descriptions from ssl.h */ /* note RESERVED constants no longer intended for use have been removed */ /* http://www.iana.org/assignments/tls-parameters/tls-parameter...