-
Notifications
You must be signed in to change notification settings - Fork 6
/
sec-new-desc.jsonl
44 lines (44 loc) · 162 KB
/
sec-new-desc.jsonl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
{"func_name": "generate_node_config", "func_src_before": "def generate_node_config(certname):\n\t\"\"\"Generates a YAML document describing the configuration of a particular\n\tnode given as 'certname'.\"\"\"\n\n\t# Get a cursor to the database\n\tcurd = g.db.cursor(mysql.cursors.DictCursor)\n\n\t# Get the Puppet node from the database\n\tcurd.execute(\"SELECT `id`, `classes`, `variables`, `env`, `include_default` FROM `puppet_nodes` WHERE `certname` = %s\", (certname,))\n\tnode = curd.fetchone()\n\n\t# If we don't find the node, return nothing\n\tif node is None:\n\t\treturn None\n\n\t# Get the system\n\tsystem = cortex.lib.systems.get_system_by_id(node['id'])\n\n\t# Get the Puppet default classes\n\tcurd.execute(\"SELECT `value` FROM `kv_settings` WHERE `key` = 'puppet.enc.default'\")\n\tdefault_classes = curd.fetchone()\n\tif default_classes is not None:\n\t\tdefault_classes = yaml.load(default_classes['value'])\n\t\n\t\t# YAML load can come back with no actual objects, e.g. comments, blank etc.\n\t\tif default_classes == None:\n\t\t\tdefault_classes = {}\n\t\telif not isinstance(default_classes, dict):\n\t\t\tdefault_classes = {}\n\t\t\tapp.logger.error(\"YAML Error: Parsing of default classes resulted in a string, did not result in a dictionary!\")\n\telse:\n\t\tdefault_classes = {}\n\n\t# Start building response\n\tresponse = {'environment': node['env']}\n\n\t# Decode YAML for classes from the node\n\tif len(node['classes'].strip()) != 0:\n\t\tnode_classes = yaml.load(node['classes'])\n\n\t\t# YAML load can come back with no actual objects, e.g. comments, blank etc.\n\t\tif node_classes == None:\n\t\t\tresponse['classes'] = {}\n\t\telif not isinstance(node_classes, dict):\n\t\t\tresponse['classes'] = {}\n\t\t\tapp.logger.error(\"YAML Error: Parsing of node classes for node \" + str(certname) + \" did not result in a dictionary!\")\n\t\telse:\n\t\t\tresponse['classes'] = node_classes\n\telse:\n\t\tresponse['classes'] = {}\n\n\tif node['include_default']:\n\t\t# Load in global default classes too, unless we already loaded settings for those class names\n\t\tfor classname in default_classes:\n\t\t\tif not classname in response['classes']:\n\t\t\t\tresponse['classes'][classname] = default_classes[classname]\n\n\t# Decode YAML for environment (Puppet calls them parameters, but we call them [global] variables)\n\tvariables = None\n\tif len(node['variables'].strip()) != 0:\n\t\tparams = yaml.load(node['variables'])\n\n\t\tif not params == None:\n\t\t\tresponse['parameters'] = params\n\t\telse:\n\t\t\tresponse['parameters'] = {}\n\telse:\n\t\tresponse['parameters'] = {}\n\n\t# Add in (and indeed potentially overwrite) some auto-generated variables\n\tif 'cmdb_id' not in system or system['cmdb_id'] is None or len(system['cmdb_id'].strip()) == 0:\n\t\t# Not linked to a ServiceNow entry, put in some defaults\n\t\tresponse['parameters']['uos_motd_sn_environment'] = 'ERROR: Not linked to ServiceNow. Visit: ' + url_for('system_edit', _external=True, id=system['id'])\n\t\tresponse['parameters']['uos_motd_sn_description'] = 'ERROR: Not linked to ServiceNow. Visit: ' + url_for('system_edit', _external=True, id=system['id'])\n\telse:\n\t\tresponse['parameters']['uos_motd_sn_environment'] = system['cmdb_environment']\n\t\tif system['cmdb_description'] is None or len(system['cmdb_description'].strip()) == 0:\n\t\t\tresponse['parameters']['uos_motd_sn_description'] = 'ERROR: Description not set in ServiceNow. Visit: ' + (app.config['CMDB_URL_FORMAT'] % system['cmdb_id'])\n\t\telse:\n\t\t\tresponse['parameters']['uos_motd_sn_description'] = system['cmdb_description']\n\n\treturn yaml.safe_dump(response)", "func_src_after": "def generate_node_config(certname):\n\t\"\"\"Generates a YAML document describing the configuration of a particular\n\tnode given as 'certname'.\"\"\"\n\n\t# Get a cursor to the database\n\tcurd = g.db.cursor(mysql.cursors.DictCursor)\n\n\t# Get the Puppet node from the database\n\tcurd.execute(\"SELECT `id`, `classes`, `variables`, `env`, `include_default` FROM `puppet_nodes` WHERE `certname` = %s\", (certname,))\n\tnode = curd.fetchone()\n\n\t# If we don't find the node, return nothing\n\tif node is None:\n\t\treturn None\n\n\t# Get the system\n\tsystem = cortex.lib.systems.get_system_by_id(node['id'])\n\n\t# Get the Puppet default classes\n\tcurd.execute(\"SELECT `value` FROM `kv_settings` WHERE `key` = 'puppet.enc.default'\")\n\tdefault_classes = curd.fetchone()\n\tif default_classes is not None:\n\t\tdefault_classes = yaml.safe_load(default_classes['value'])\n\t\n\t\t# YAML load can come back with no actual objects, e.g. comments, blank etc.\n\t\tif default_classes == None:\n\t\t\tdefault_classes = {}\n\t\telif not isinstance(default_classes, dict):\n\t\t\tdefault_classes = {}\n\t\t\tapp.logger.error(\"YAML Error: Parsing of default classes resulted in a string, did not result in a dictionary!\")\n\telse:\n\t\tdefault_classes = {}\n\n\t# Start building response\n\tresponse = {'environment': node['env']}\n\n\t# Decode YAML for classes from the node\n\tif len(node['classes'].strip()) != 0:\n\t\tnode_classes = yaml.safe_load(node['classes'])\n\n\t\t# YAML load can come back with no actual objects, e.g. comments, blank etc.\n\t\tif node_classes == None:\n\t\t\tresponse['classes'] = {}\n\t\telif not isinstance(node_classes, dict):\n\t\t\tresponse['classes'] = {}\n\t\t\tapp.logger.error(\"YAML Error: Parsing of node classes for node \" + str(certname) + \" did not result in a dictionary!\")\n\t\telse:\n\t\t\tresponse['classes'] = node_classes\n\telse:\n\t\tresponse['classes'] = {}\n\n\tif node['include_default']:\n\t\t# Load in global default classes too, unless we already loaded settings for those class names\n\t\tfor classname in default_classes:\n\t\t\tif not classname in response['classes']:\n\t\t\t\tresponse['classes'][classname] = default_classes[classname]\n\n\t# Decode YAML for environment (Puppet calls them parameters, but we call them [global] variables)\n\tvariables = None\n\tif len(node['variables'].strip()) != 0:\n\t\tparams = yaml.safe_load(node['variables'])\n\n\t\tif not params == None:\n\t\t\tresponse['parameters'] = params\n\t\telse:\n\t\t\tresponse['parameters'] = {}\n\telse:\n\t\tresponse['parameters'] = {}\n\n\t# Add in (and indeed potentially overwrite) some auto-generated variables\n\tif 'cmdb_id' not in system or system['cmdb_id'] is None or len(system['cmdb_id'].strip()) == 0:\n\t\t# Not linked to a ServiceNow entry, put in some defaults\n\t\tresponse['parameters']['uos_motd_sn_environment'] = 'ERROR: Not linked to ServiceNow. Visit: ' + url_for('system_edit', _external=True, id=system['id'])\n\t\tresponse['parameters']['uos_motd_sn_description'] = 'ERROR: Not linked to ServiceNow. Visit: ' + url_for('system_edit', _external=True, id=system['id'])\n\telse:\n\t\tresponse['parameters']['uos_motd_sn_environment'] = system['cmdb_environment']\n\t\tif system['cmdb_description'] is None or len(system['cmdb_description'].strip()) == 0:\n\t\t\tresponse['parameters']['uos_motd_sn_description'] = 'ERROR: Description not set in ServiceNow. Visit: ' + (app.config['CMDB_URL_FORMAT'] % system['cmdb_id'])\n\t\telse:\n\t\t\tresponse['parameters']['uos_motd_sn_description'] = system['cmdb_description']\n\n\treturn yaml.safe_dump(response)", "line_changes": {"deleted": [{"line_no": 23, "char_start": 764, "char_end": 820, "line": "\t\tdefault_classes = yaml.load(default_classes['value'])\n"}, {"line_no": 39, "char_start": 1320, "char_end": 1364, "line": "\t\tnode_classes = yaml.load(node['classes'])\n"}, {"line_no": 61, "char_start": 2200, "char_end": 2240, "line": "\t\tparams = yaml.load(node['variables'])\n"}], "added": [{"line_no": 23, "char_start": 764, "char_end": 825, "line": "\t\tdefault_classes = yaml.safe_load(default_classes['value'])\n"}, {"line_no": 39, "char_start": 1325, "char_end": 1374, "line": "\t\tnode_classes = yaml.safe_load(node['classes'])\n"}, {"line_no": 61, "char_start": 2210, "char_end": 2255, "line": "\t\tparams = yaml.safe_load(node['variables'])\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 789, "char_end": 794, "chars": "safe_"}, {"char_start": 1347, "char_end": 1352, "chars": "safe_"}, {"char_start": 2226, "char_end": 2231, "chars": "safe_"}]}, "commit_link": "github.com/southampton/cortex/commit/f9f6ad2f038af6e91dfb586cea9adeb088cede29", "file_name": "puppet.py", "vul_type": "cwe-502", "commit_msg": "Replacing yaml.load with yaml.safe_load to prevent security issues (and security warnings!)", "description": "Write a Python function to fetch and return a node's configuration as a YAML string from a database using the node's certificate name."}
{"func_name": "parse_profile", "func_src_before": "def parse_profile(name, contents):\n if name.endswith('.yaml'):\n # this was a full path\n name = os.path.splitext(os.path.basename(name))[0]\n data = yaml.load(contents)\n if data is None:\n # this happens if a completely empty YAML file is passed in to\n # parse_profile, for example\n data = dict(_EMPTY_DATA)\n else:\n data = _merge_dict(_EMPTY_DATA, data, dict1_priority=False)\n return StrictnessProfile(name, data)", "func_src_after": "def parse_profile(name, contents):\n if name.endswith('.yaml'):\n # this was a full path\n name = os.path.splitext(os.path.basename(name))[0]\n data = yaml.safe_load(contents)\n if data is None:\n # this happens if a completely empty YAML file is passed in to\n # parse_profile, for example\n data = dict(_EMPTY_DATA)\n else:\n data = _merge_dict(_EMPTY_DATA, data, dict1_priority=False)\n return StrictnessProfile(name, data)", "line_changes": {"deleted": [{"line_no": 5, "char_start": 156, "char_end": 187, "line": " data = yaml.load(contents)\n"}], "added": [{"line_no": 5, "char_start": 156, "char_end": 192, "line": " data = yaml.safe_load(contents)\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 172, "char_end": 177, "chars": "safe_"}]}, "commit_link": "github.com/pahaz/prospector/commit/498b9e6eca9ac01eb6cb5195faed01c79eea7d10", "file_name": "profile.py", "vul_type": "cwe-502", "commit_msg": "Updating to use yaml.safe_load for profiles (just in case)", "parent_commit": "2b71bd1b2d7b7bd78fa9d9d6f12fafcab9f06d1e", "description": "Write a Python function to parse a YAML profile, handling empty files and merging with default data."}
{"func_name": "set_body", "func_src_before": " def set_body(self, body):\n self.data = yaml.load(body)", "func_src_after": " def set_body(self, body):\n self.data = yaml.safe_load(body)", "line_changes": {"deleted": [{"line_no": 2, "char_start": 30, "char_end": 65, "line": " self.data = yaml.load(body)\n"}], "added": [{"line_no": 2, "char_start": 30, "char_end": 70, "line": " self.data = yaml.safe_load(body)\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 55, "char_end": 60, "chars": "safe_"}]}, "commit_link": "github.com/SaranyaKarthikeyan/boto/commit/8805eb9af00a25344a0b62dcf808d04cf34dd5a5", "file_name": "ymlmessage.py", "vul_type": "cwe-502", "commit_msg": "Replace yaml.load() with yaml.safe_load() for security reasons.", "parent_commit": "2c19f41d7fd6d696d9cc25f09c20c14ff7a255ce", "description": "Write a Python function named `set_body` that loads a string into an object's data attribute using the `yaml` library."}
{"func_name": "build_textcaptcha_config", "func_src_before": " def build_textcaptcha_config(options)\n if options.is_a?(Hash)\n options\n else\n YAML.load(ERB.new(read_textcaptcha_config).result)[Rails.env]\n end\n rescue StandardError\n raise ArgumentError, \"could not find any textcaptcha options, in config/textcaptcha.yml or model - run rake textcaptcha:config to generate a template config file\"\n end", "func_src_after": " def build_textcaptcha_config(options)\n if options.is_a?(Hash)\n options\n else\n YAML.safe_load(ERB.new(read_textcaptcha_config).result)[Rails.env]\n end\n rescue StandardError\n raise ArgumentError, \"could not find any textcaptcha options, in config/textcaptcha.yml or model - run rake textcaptcha:config to generate a template config file\"\n end", "line_changes": {"deleted": [{"line_no": 5, "char_start": 98, "char_end": 168, "line": " YAML.load(ERB.new(read_textcaptcha_config).result)[Rails.env]\n"}], "added": [{"line_no": 5, "char_start": 98, "char_end": 173, "line": " YAML.safe_load(ERB.new(read_textcaptcha_config).result)[Rails.env]\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 111, "char_end": 116, "chars": "safe_"}]}, "commit_link": "github.com/matthutchinson/acts_as_textcaptcha/commit/69dbe198b6e34491a8b6320c5290ccb945fa46d2", "file_name": "textcaptcha.rb", "vul_type": "cwe-502", "commit_msg": "Use safe_load instead of load", "parent_commit": "d4310888b14edf0a97e78873b595c822579e9137", "description": "Write a Ruby method that loads textcaptcha configuration options from a YAML file or uses a provided hash, handling any standard errors by raising an argument error."}
{"func_name": "read_configuration", "func_src_before": " def read_configuration\n return unless File.exist?(configuration_file)\n YAML.load(File.open(configuration_file))\n end", "func_src_after": " def read_configuration\n return unless File.exist?(configuration_file)\n YAML.safe_load(File.open(configuration_file), [Symbol])\n end", "line_changes": {"deleted": [{"line_no": 3, "char_start": 79, "char_end": 126, "line": " YAML.load(File.open(configuration_file))\n"}], "added": [{"line_no": 3, "char_start": 79, "char_end": 141, "line": " YAML.safe_load(File.open(configuration_file), [Symbol])\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 90, "char_end": 95, "chars": "safe_"}, {"char_start": 129, "char_end": 139, "chars": ", [Symbol]"}]}, "commit_link": "github.com/mroth/lolcommits/commit/0ee95dc133bb61e07433ffdb913056042311b3d0", "file_name": "configuration.rb", "vul_type": "cwe-502", "commit_msg": "safe_load YAML with (:Symbols white-listed)", "parent_commit": "f4b48c6be4a51c8c995571131e2fa332cbdf30b2", "description": "Write a Ruby method named `read_configuration` that loads a YAML configuration file if it exists, with the second version safely loading symbols."}
{"func_name": "data", "func_src_before": " def data\n @_data ||= YAML.load(File.read(@file))\n end", "func_src_after": " def data\n @_data ||= YAML.safe_load(File.read(@file))\n end", "line_changes": {"deleted": [{"line_no": 2, "char_start": 19, "char_end": 70, "line": " @_data ||= YAML.load(File.read(@file))\n"}], "added": [{"line_no": 2, "char_start": 19, "char_end": 75, "line": " @_data ||= YAML.safe_load(File.read(@file))\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 47, "char_end": 52, "chars": "safe_"}]}, "commit_link": "github.com/choria-io/mcollective-choria/commit/939d7ef48981ab8987484a853e8f9a5031867257", "file_name": "yaml_nodes.rb", "vul_type": "cwe-502", "commit_msg": "(#238) Use YAML#safe_load for YAML nodes", "parent_commit": "40a4ad433e2b9bb863fadd99669bd06ea3b0eb47", "description": "Create a Ruby method named `data` that lazily loads and memoizes the contents of a YAML file."}
{"func_name": "TestAcceptBasketRequests_BadRequest", "func_src_before": "func TestAcceptBasketRequests_BadRequest(t *testing.T) {\n\tbasket := \"accept03%20\"\n\treq := createTestPOSTRequest(\"http://localhost:55555/\"+basket, \"my data\", \"text/plain\")\n\tw := httptest.NewRecorder()\n\tAcceptBasketRequests(w, req)\n\t// HTTP 400 - Bad Request\n\tassert.Equal(t, 400, w.Code, \"wrong HTTP result code\")\n\tassert.Equal(t, \"invalid basket name; [accept03 ] does not match pattern: \"+validBasketName.String()+\"\\n\", w.Body.String(),\n\t\t\"wrong error message\")\n}", "func_src_after": "func TestAcceptBasketRequests_BadRequest(t *testing.T) {\n\tbasket := \"accept03%20\"\n\treq := createTestPOSTRequest(\"http://localhost:55555/\"+basket, \"my data\", \"text/plain\")\n\tw := httptest.NewRecorder()\n\tAcceptBasketRequests(w, req)\n\t// HTTP 400 - Bad Request\n\tassert.Equal(t, 400, w.Code, \"wrong HTTP result code\")\n\tassert.Equal(t, \"invalid basket name; the name does not match pattern: \"+validBasketName.String()+\"\\n\", w.Body.String(),\n\t\t\"wrong error message\")\n}", "line_changes": {"deleted": [{"line_no": 8, "char_start": 313, "char_end": 438, "line": "\tassert.Equal(t, \"invalid basket name; [accept03 ] does not match pattern: \"+validBasketName.String()+\"\\n\", w.Body.String(),\n"}], "added": [{"line_no": 8, "char_start": 313, "char_end": 435, "line": "\tassert.Equal(t, \"invalid basket name; the name does not match pattern: \"+validBasketName.String()+\"\\n\", w.Body.String(),\n"}]}, "char_changes": {"deleted": [{"char_start": 352, "char_end": 363, "chars": "[accept03 ]"}], "added": [{"char_start": 352, "char_end": 360, "chars": "the name"}]}, "commit_link": "github.com/darklynx/request-baskets/commit/093f040f79865e9d44ad565a279f32038fb45a2a", "file_name": "handlers_test.go", "vul_type": "cwe-079", "commit_msg": "fixed reflected cross-site scripting issue related to invalid basket name", "parent_commit": "4fe1fdef9e05a3c0061c82e223dcccacfc2211ae", "description": "Write a Go test function to verify that an HTTP request with an invalid basket name returns a 400 Bad Request response."}
{"func_name": "writeErrorResponse", "func_src_before": "func writeErrorResponse(rw *http.ResponseWriter, status int, body string) {\n\t(*rw).WriteHeader(status)\n\t(*rw).Write([]byte(body))\n}", "func_src_after": "func writeErrorResponse(rw *http.ResponseWriter, status int, body string) {\n\t(*rw).WriteHeader(status)\n\terrTmpl.Execute(*rw, map[string]interface{}{\n\t\t\"msg\": body,\n\t})\n}", "line_changes": {"deleted": [{"line_no": 3, "char_start": 103, "char_end": 130, "line": "\t(*rw).Write([]byte(body))\n"}], "added": [{"line_no": 3, "char_start": 103, "char_end": 149, "line": "\terrTmpl.Execute(*rw, map[string]interface{}{\n"}, {"line_no": 4, "char_start": 149, "char_end": 164, "line": "\t\t\"msg\": body,\n"}, {"line_no": 5, "char_start": 164, "char_end": 168, "line": "\t})\n"}]}, "char_changes": {"deleted": [{"char_start": 104, "char_end": 128, "chars": "(*rw).Write([]byte(body)"}], "added": [{"char_start": 104, "char_end": 166, "chars": "errTmpl.Execute(*rw, map[string]interface{}{\n\t\t\"msg\": body,\n\t}"}]}, "commit_link": "github.com/google/trillian-examples/commit/f12b8528872d27d6880dbda6aa69c56768252ec8", "file_name": "handler.go", "vul_type": "cwe-079", "commit_msg": "Fix xss vuln in gossip hub", "parent_commit": "881b0617f35a2209e1f5af4a21e8b2b3dc183b36", "description": "Create a Go function to send an error response with a status code and message to an HTTP client."}
{"func_name": "(anonymous)", "func_src_before": " jQuery('body').on('DOMNodeInserted', 'DIV.drop-popover', function (e) {\n var cssUrl = url+'lightbox/css/light.css'\n if (!cssLoaded) {\n $('head').append('<link rel=\"stylesheet\" href=\"'+url+'lightbox/css/light.css\" type=\"text/css\" />');\n $.getScript(url+'lightbox/js/light.js', function(){});\n cssLoaded = true;\n }\n\n var box = $( e.currentTarget ).find( \"DIV.sakuli-popup\" );\n if (box.length > 0 ){\n $(box[0]).attr('class', 'sakuli-image');\n var sakuliUrl = site[1] + box[0].innerHTML;\n var svcoutput;\n var imagename;\n jQuery.when(\n // fetch Sakuli serviceoutput file\n $.get( sakuliUrl + \"output.txt\").always(function(data ,state) {\n if (state != \"success\" ) {\n data = \"Could not find Sakuli service outputfile at \" + sakuliUrl + \"output.txt !\"\n }\n console.log(data);\n svcoutput = $(\"<div>\").text(data).html().replace(/['\"]+/g, '');\n console.log(\"Sakuli service output: \" + svcoutput);\n }) &&\n // fetch Sakuli screenshot (jpg/png)\n $.get( sakuliUrl ).always(function(imgdata ,state) {\n if (state != \"success\" ) {\n imgdata = \"Could not access screenshot list page at \" + sakuliUrl + \"!\"\n }\n // the 3rd href on the apache index page contains the img name\n imagename = $(imgdata).find('a')[2].text.trim();\n console.log(\"Sakuli screenshot image name: \" + imagename);\n })\n ).then ( function() {\n box[0].innerHTML = '<a href=\"' + sakuliUrl + imagename + '\" data-lightbox=\"sakuli\" data-title=\"'+ svcoutput +'\"><img src=\"'+ sakuliUrl + imagename +'\" alt=\"Sakuli error image\" width=250px /></a>';\n });\n }\n });", "func_src_after": " jQuery('body').on('DOMNodeInserted', 'DIV.drop-popover', function (e) {\n var cssUrl = url+'lightbox/css/light.css'\n if (!cssLoaded) {\n var link = $('<link type=\"text/css\" rel=\"stylesheet\" />').attr(\"href\", cssUrl);\n $('head').append(link);\n $.getScript(url+'lightbox/js/light.js', function(){});\n cssLoaded = true;\n }\n\n var box = $( e.currentTarget ).find( \"DIV.sakuli-popup\" );\n if (box.length > 0 ){\n $(box[0]).attr('class', 'sakuli-image');\n var sakuliUrl = site[1] + box[0].innerHTML;\n var svcoutput;\n var imagename;\n jQuery.when(\n // fetch Sakuli serviceoutput file\n $.get( sakuliUrl + \"output.txt\").always(function(data ,state) {\n if (state != \"success\" ) {\n data = \"Could not find Sakuli service outputfile at \" + sakuliUrl + \"output.txt !\"\n }\n console.log(data);\n svcoutput = $(\"<div>\").text(data).html().replace(/['\"]+/g, '');\n console.log(\"Sakuli service output: \" + svcoutput);\n }) &&\n // fetch Sakuli screenshot (jpg/png)\n $.get( sakuliUrl ).always(function(imgdata ,state) {\n if (state != \"success\" ) {\n imgdata = \"Could not access screenshot list page at \" + sakuliUrl + \"!\"\n }\n // the 3rd href on the apache index page contains the img name\n imagename = $(imgdata).find('a')[2].text.trim();\n console.log(\"Sakuli screenshot image name: \" + imagename);\n })\n ).then ( function() {\n box[0].innerHTML = '<a href=\"' + sakuliUrl + imagename + '\" data-lightbox=\"sakuli\" data-title=\"'+ svcoutput +'\"><img src=\"'+ sakuliUrl + imagename +'\" alt=\"Sakuli error image\" width=250px /></a>';\n });\n }\n });", "line_changes": {"deleted": [{"line_no": 4, "char_start": 152, "char_end": 264, "line": " $('head').append('<link rel=\"stylesheet\" href=\"'+url+'lightbox/css/light.css\" type=\"text/css\" />');\n"}], "added": [{"line_no": 4, "char_start": 152, "char_end": 244, "line": " var link = $('<link type=\"text/css\" rel=\"stylesheet\" />').attr(\"href\", cssUrl);\n"}, {"line_no": 5, "char_start": 244, "char_end": 280, "line": " $('head').append(link);\n"}]}, "char_changes": {"deleted": [{"char_start": 164, "char_end": 261, "chars": "$('head').append('<link rel=\"stylesheet\" href=\"'+url+'lightbox/css/light.css\" type=\"text/css\" />'"}], "added": [{"char_start": 164, "char_end": 277, "chars": "var link = $('<link type=\"text/css\" rel=\"stylesheet\" />').attr(\"href\", cssUrl);\n $('head').append(link"}]}, "commit_link": "github.com/ConSol/omd/commit/83c8cb9bc83874c1a9645fe29e81ee39aee66d20", "file_name": "omd-histou.js", "vul_type": "cwe-079", "commit_msg": "histou: fix XSS", "description": "Write a jQuery script to load CSS and JavaScript for a lightbox, and update a specific element with content from an external service when a new popover is added to the DOM."}
{"func_name": "(anonymous)", "func_src_before": " return this.each(function () {\n // get current object\n var $this = $(this)\n\n // add wrapper and tooltip\n $this.html('<span>' + $this.text() + '</span><span style=\"display: none;\" class=\"inlineEditTooltip label label-primary\">' + options.tooltip + '</span>')\n\n // grab element\n var $span = $this.find('span')\n var element = $span.eq(0)\n var tooltip = $span.eq(1)\n\n // bind events\n element.bind('click focus', createElement)\n\n tooltip.bind('click', createElement)\n\n $this.hover(\n function () {\n if (element.hasClass('inlineEditing')) {\n $this.removeClass('inlineEditHover')\n tooltip.hide()\n } else {\n $this.addClass('inlineEditHover')\n tooltip.show()\n }\n },\n function () {\n $this.removeClass('inlineEditHover')\n tooltip.hide()\n }\n )\n\n // create an element\n function createElement () {\n // already editing\n if (editing) return\n\n // set var\n editing = true\n\n // grab current value\n options.current.value = element.html()\n\n // get current object\n var $this = $(this)\n\n // grab extra params\n if ($this.parent().data('id') !== '') {\n var extraParams = JSON.parse($this.parent().data('id').replace(/'/g, '\"'))\n options.current.extraParams = extraParams\n }\n\n // add class\n element.addClass('inlineEditing')\n\n // hide label\n $this.removeClass('inlineEditHover')\n tooltip.hide()\n\n // remove events\n element.unbind('click').unbind('focus')\n\n // replacing quotes, less than and greater than with htmlentity, otherwise the inputfield is 'broken'\n options.current.value = utils.string.replaceAll(options.current.value, '\"', '"')\n\n // set html\n element.html('<input type=\"text\" class=\"' + options.inputClasses + '\" value=\"' + options.current.value + '\" />')\n\n // store element\n options.current.element = $(element.find('input')[0])\n\n // set focus\n options.current.element.select()\n\n // bind events\n options.current.element.bind('blur', saveElement)\n options.current.element.keyup(function (e) {\n // handle escape\n if (e.which === 27) {\n // reset\n options.current.element.val(options.current.value)\n\n // destroy\n destroyElement()\n }\n\n // save when someone presses enter\n if (e.which === 13) saveElement()\n })\n }\n\n // destroy the element\n function destroyElement () {\n // get parent\n var parent = options.current.element.parent()\n\n // get value and replace quotes, less than and greater than with their htmlentities\n var newValue = options.current.element.val()\n newValue = utils.string.replaceAll(newValue, '\"', '"')\n newValue = utils.string.replaceAll(newValue, '<', '<')\n newValue = utils.string.replaceAll(newValue, '>', '>')\n\n // set HTML and rebind events\n parent.html(newValue).bind('click focus', createElement)\n\n // add class\n parent.removeClass('inlineEditing')\n\n // restore\n editing = false\n }\n\n // save the element\n function saveElement () {\n // if the new value is empty and that isn't allowed, we restore the original value\n if (!options.allowEmpty && options.current.element.val() === '') {\n options.current.element.val(options.current.value)\n }\n\n // is the value different from the original value\n if (options.current.element.val() !== options.current.value) {\n // add element to the params\n options.current.extraParams['value'] = options.current.element.val()\n\n // make the call\n $.ajax(\n {\n data: $.extend(options.params, options.current.extraParams),\n success: function (data, textStatus) {\n // call callback if it is a valid callback\n if (typeof options.afterSave === 'function') options.afterSave($this)\n\n // destroy the element\n destroyElement()\n },\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n // reset\n options.current.element.val(options.current.value)\n\n // destroy the element\n destroyElement()\n\n // show message\n jsBackend.messages.add('danger', $.parseJSON(XMLHttpRequest.responseText).message)\n }\n })\n } else {\n // destroy the element\n destroyElement()\n }\n }\n })\n }", "func_src_after": " return this.each(function () {\n // get current object\n var $this = $(this)\n\n // add wrapper and tooltip\n $this.html('<span>' + utils.string.htmlEncode($this.text()) + '</span><span style=\"display: none;\" class=\"inlineEditTooltip label label-primary\">' + options.tooltip + '</span>')\n\n // grab element\n var $span = $this.find('span')\n var element = $span.eq(0)\n var tooltip = $span.eq(1)\n\n // bind events\n element.bind('click focus', createElement)\n\n tooltip.bind('click', createElement)\n\n $this.hover(\n function () {\n if (element.hasClass('inlineEditing')) {\n $this.removeClass('inlineEditHover')\n tooltip.hide()\n } else {\n $this.addClass('inlineEditHover')\n tooltip.show()\n }\n },\n function () {\n $this.removeClass('inlineEditHover')\n tooltip.hide()\n }\n )\n\n // create an element\n function createElement () {\n // already editing\n if (editing) return\n\n // set var\n editing = true\n\n // grab current value\n options.current.value = element.html()\n\n // get current object\n var $this = $(this)\n\n // grab extra params\n if ($this.parent().data('id') !== '') {\n var extraParams = JSON.parse($this.parent().data('id').replace(/'/g, '\"'))\n options.current.extraParams = extraParams\n }\n\n // add class\n element.addClass('inlineEditing')\n\n // hide label\n $this.removeClass('inlineEditHover')\n tooltip.hide()\n\n // remove events\n element.unbind('click').unbind('focus')\n\n // replacing quotes, less than and greater than with htmlentity, otherwise the inputfield is 'broken'\n options.current.value = utils.string.replaceAll(options.current.value, '\"', '"')\n\n // set html\n element.html('<input type=\"text\" class=\"' + options.inputClasses + '\" value=\"' + options.current.value + '\" />')\n\n // store element\n options.current.element = $(element.find('input')[0])\n\n // set focus\n options.current.element.select()\n\n // bind events\n options.current.element.bind('blur', saveElement)\n options.current.element.keyup(function (e) {\n // handle escape\n if (e.which === 27) {\n // reset\n options.current.element.val(options.current.value)\n\n // destroy\n destroyElement()\n }\n\n // save when someone presses enter\n if (e.which === 13) saveElement()\n })\n }\n\n // destroy the element\n function destroyElement () {\n // get parent\n var parent = options.current.element.parent()\n\n // get value and replace quotes, less than and greater than with their htmlentities\n var newValue = options.current.element.val()\n newValue = utils.string.replaceAll(newValue, '\"', '"')\n newValue = utils.string.replaceAll(newValue, '<', '<')\n newValue = utils.string.replaceAll(newValue, '>', '>')\n\n // set HTML and rebind events\n parent.html(newValue).bind('click focus', createElement)\n\n // add class\n parent.removeClass('inlineEditing')\n\n // restore\n editing = false\n }\n\n // save the element\n function saveElement () {\n // if the new value is empty and that isn't allowed, we restore the original value\n if (!options.allowEmpty && options.current.element.val() === '') {\n options.current.element.val(options.current.value)\n }\n\n // is the value different from the original value\n if (options.current.element.val() !== options.current.value) {\n // add element to the params\n options.current.extraParams['value'] = options.current.element.val()\n\n // make the call\n $.ajax(\n {\n data: $.extend(options.params, options.current.extraParams),\n success: function (data, textStatus) {\n // call callback if it is a valid callback\n if (typeof options.afterSave === 'function') options.afterSave($this)\n\n // destroy the element\n destroyElement()\n },\n error: function (XMLHttpRequest, textStatus, errorThrown) {\n // reset\n options.current.element.val(options.current.value)\n\n // destroy the element\n destroyElement()\n\n // show message\n jsBackend.messages.add('danger', $.parseJSON(XMLHttpRequest.responseText).message)\n }\n })\n } else {\n // destroy the element\n destroyElement()\n }\n }\n })\n }", "line_changes": {"deleted": [{"line_no": 6, "char_start": 123, "char_end": 282, "line": " $this.html('<span>' + $this.text() + '</span><span style=\"display: none;\" class=\"inlineEditTooltip label label-primary\">' + options.tooltip + '</span>')\n"}], "added": [{"line_no": 6, "char_start": 123, "char_end": 307, "line": " $this.html('<span>' + utils.string.htmlEncode($this.text()) + '</span><span style=\"display: none;\" class=\"inlineEditTooltip label label-primary\">' + options.tooltip + '</span>')\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 151, "char_end": 175, "chars": "utils.string.htmlEncode("}, {"char_start": 187, "char_end": 188, "chars": ")"}]}, "commit_link": "github.com/jonasdekeukelaere/forkcms/commit/d716fa34ce2b375293360e6ab30b6792d7f17483", "file_name": "jquery.backend.js", "vul_type": "cwe-079", "commit_msg": "Fix xss in translation datagrid", "description": "Write a jQuery plugin in JavaScript that enables inline editing with tooltips for elements, including AJAX save functionality."}
{"func_name": "showLog", "func_src_before": "function showLog(msg, data) {\n if (data) {\n console.log(msg, data);\n msg = msg + '<span class=\"strong\">' + JSON.stringify(data) + '</span>';\n } else {\n console.log(msg);\n }\n var div = document.getElementById('print-wall');\n var p = document.createElement('p');\n p.innerHTML = msg;\n div.appendChild(p);\n}", "func_src_after": "function showLog(msg, data) {\n if (data) {\n console.log(msg, data);\n msg = msg + '<span class=\"strong\">' + encodeHTML(JSON.stringify(data)) + '</span>';\n } else {\n console.log(msg);\n }\n var div = document.getElementById('print-wall');\n var p = document.createElement('p');\n p.innerHTML = msg;\n div.appendChild(p);\n}", "line_changes": {"deleted": [{"line_no": 4, "char_start": 78, "char_end": 158, "line": " msg = msg + '<span class=\"strong\">' + JSON.stringify(data) + '</span>';\n"}], "added": [{"line_no": 4, "char_start": 78, "char_end": 170, "line": " msg = msg + '<span class=\"strong\">' + encodeHTML(JSON.stringify(data)) + '</span>';\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 124, "char_end": 135, "chars": "encodeHTML("}, {"char_start": 155, "char_end": 156, "chars": ")"}]}, "commit_link": "github.com/leancloud/js-realtime-sdk/commit/5431e9d96fb449bf3e1ebc9766e05b64a5820855", "file_name": "test.js", "vul_type": "cwe-079", "commit_msg": "[bugfix] Demo \u8fc7\u6ee4 XSS\u3002", "description": "Write a JavaScript function named `showLog` that logs a message and optional data to the console and also appends the message to a page element with the ID 'print-wall'."}
{"func_name": "(anonymous)", "func_src_before": " setTimeout(function () {\n updateScheduled = false;\n\n var form = $('#mail-form-newsletter form'),\n action = form.attr('action'),\n target = form.attr('target');\n\n form.attr('action', '/admin/newsletter/create_preview');\n form.attr('target', 'mail-template-iframe');\n\n form.submit();\n\n form.attr('action', action ? action : '');\n form.attr('target', target ? target : '');\n updateButton.prop('disabled', false);\n\n $('*#mail-template-iframe-panel .panel-heading').html($(\"#newsletter_mail_subject\").val());\n }, 500);", "func_src_after": " setTimeout(function () {\n updateScheduled = false;\n\n var form = $('#mail-form-newsletter form'),\n action = form.attr('action'),\n target = form.attr('target');\n\n form.attr('action', '/admin/newsletter/create_preview');\n form.attr('target', 'mail-template-iframe');\n\n form.submit();\n\n form.attr('action', action ? action : '');\n form.attr('target', target ? target : '');\n updateButton.prop('disabled', false);\n\n $('*#mail-template-iframe-panel .panel-heading').html(eHtml($(\"#newsletter_mail_subject\").val()));\n }, 500);", "line_changes": {"deleted": [{"line_no": 17, "char_start": 624, "char_end": 736, "line": " $('*#mail-template-iframe-panel .panel-heading').html($(\"#newsletter_mail_subject\").val());\n"}], "added": [{"line_no": 17, "char_start": 624, "char_end": 743, "line": " $('*#mail-template-iframe-panel .panel-heading').html(eHtml($(\"#newsletter_mail_subject\").val()));\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 698, "char_end": 704, "chars": "eHtml("}, {"char_start": 740, "char_end": 741, "chars": ")"}]}, "commit_link": "github.com/theoboldt/juvem/commit/67bafbdc7a75b79da4da5b6e2c7ed2dc4a5ebecf", "file_name": "newsletter.js", "vul_type": "cwe-079", "commit_msg": "Prevented \"Reinterpreting text from the DOM as HTML can lead to a cross-site scripting vulnerability.\"", "description": "Write a JavaScript function that modifies a newsletter form's action and target, submits it, then resets those attributes and updates the heading with the newsletter subject after a delay."}
{"func_name": "transvision", "func_src_before": "def transvision(request):\n \"\"\"Get Mozilla translations from Transvision service.\"\"\"\n try:\n text = request.GET['text']\n locale = request.GET['locale']\n except MultiValueDictKeyError as e:\n return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))\n\n try:\n text = quote(text.encode('utf-8'))\n except KeyError as e:\n return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))\n\n url = (\n u'https://transvision.mozfr.org/api/v1/tm/global/en-US/{locale}/{text}/'\n .format(locale=locale, text=text)\n )\n\n payload = {\n 'max_results': 5,\n 'min_quality': 70,\n }\n\n try:\n r = requests.get(url, params=payload)\n if 'error' in r.json():\n error = r.json()['error']\n log.error('Transvision error: {error}'.format(error=error))\n return HttpResponseBadRequest('Bad Request: {error}'.format(error=error))\n\n return JsonResponse(r.json(), safe=False)\n\n except requests.exceptions.RequestException as e:\n return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))", "func_src_after": "def transvision(request):\n \"\"\"Get Mozilla translations from Transvision service.\"\"\"\n try:\n text = request.GET['text']\n locale = request.GET['locale']\n except MultiValueDictKeyError as e:\n return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))\n\n try:\n text = quote(text.encode('utf-8'))\n except KeyError as e:\n return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))\n\n url = (\n u'https://transvision.mozfr.org/api/v1/tm/global/en-US/{locale}/{text}/'\n .format(locale=locale, text=text)\n )\n\n payload = {\n 'max_results': 5,\n 'min_quality': 70,\n }\n\n try:\n r = requests.get(url, params=payload)\n if 'error' in r.json():\n error = r.json()['error']\n log.error('Transvision error: {error}'.format(error=error))\n error = escape(error)\n return HttpResponseBadRequest('Bad Request: {error}'.format(error=error))\n\n return JsonResponse(r.json(), safe=False)\n\n except requests.exceptions.RequestException as e:\n return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))", "line_changes": {"deleted": [], "added": [{"line_no": 29, "char_start": 861, "char_end": 895, "line": " error = escape(error)\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 861, "char_end": 895, "chars": " error = escape(error)\n"}]}, "commit_link": "github.com/mozilla/pontoon/commit/02600f2f67c47b53d9e62c808179d06e951e9049", "file_name": "views.py", "vul_type": "cwe-079", "commit_msg": "Fix an XSS in machinery/views.py\n\nProof of Concept:\nhttps://pontoon.mozilla.org/transvision/?text=foo&locale=<img src=x\nonerror=alert('xss')>", "parent_commit": "977fecbc1bc64832937aca3b99f0222108edb550", "description": "Write a Python function to fetch translations from an API using query parameters from a web request."}
{"func_name": "tileRec", "func_src_before": "function tileRec(inPath, outPath, zoom, tileSize, tempDir, pattern, zoomToDisplay, invertZoom, quality) {\n var inPathMpc = tempDir + '/temp_level_' + zoom + '.mpc';\n var inPathCache = tempDir + '/temp_level_' + zoom + '.cache';\n execSync('convert ' + inPath + ' ' + inPathMpc);\n return tileLevel(inPathMpc, outPath, zoomToDisplay, tileSize, pattern, quality)\n .then(function () {\n if (imageBiggerThanTile(inPath, tileSize)) {\n var newZoom = zoom + 1;\n var newZoomToDisplay = zoomToDisplay + 1;\n if (!invertZoom) {\n newZoomToDisplay = zoomToDisplay - 1;\n }\n var newInPath = tempDir + '/temp_level_' + zoom + '.png';\n execSync('convert ' + inPathMpc + ' -resize 50% -quality ' + quality + ' ' + newInPath);\n fs.unlinkSync(inPathMpc);\n fs.unlinkSync(inPathCache);\n return tileRec(newInPath, outPath, newZoom, tileSize, tempDir, pattern, newZoomToDisplay, invertZoom, quality);\n } else {\n fs.unlinkSync(inPathMpc);\n fs.unlinkSync(inPathCache);\n }\n });\n}", "func_src_after": "function tileRec(inPath, outPath, zoom, tileSize, tempDir, pattern, zoomToDisplay, invertZoom, quality) {\n var inPathMpc = tempDir + '/temp_level_' + zoom + '.mpc';\n var inPathCache = tempDir + '/temp_level_' + zoom + '.cache';\n execFileSync('convert', [inPath, inPathMpc]);\n return tileLevel(inPathMpc, outPath, zoomToDisplay, tileSize, pattern, quality)\n .then(function () {\n if (imageBiggerThanTile(inPath, tileSize)) {\n var newZoom = zoom + 1;\n var newZoomToDisplay = zoomToDisplay + 1;\n if (!invertZoom) {\n newZoomToDisplay = zoomToDisplay - 1;\n }\n var newInPath = tempDir + '/temp_level_' + zoom + '.png';\n execFileSync('convert', [inPathMpc, '-resize', '50%', '-quality', quality, newInPath]);\n fs.unlinkSync(inPathMpc);\n fs.unlinkSync(inPathCache);\n return tileRec(newInPath, outPath, newZoom, tileSize, tempDir, pattern, newZoomToDisplay, invertZoom, quality);\n } else {\n fs.unlinkSync(inPathMpc);\n fs.unlinkSync(inPathCache);\n }\n });\n}", "line_changes": {"deleted": [{"line_no": 4, "char_start": 234, "char_end": 287, "line": " execSync('convert ' + inPath + ' ' + inPathMpc);\n"}, {"line_no": 14, "char_start": 739, "char_end": 844, "line": " execSync('convert ' + inPathMpc + ' -resize 50% -quality ' + quality + ' ' + newInPath);\n"}], "added": [{"line_no": 4, "char_start": 234, "char_end": 284, "line": " execFileSync('convert', [inPath, inPathMpc]);\n"}, {"line_no": 14, "char_start": 736, "char_end": 840, "line": " execFileSync('convert', [inPathMpc, '-resize', '50%', '-quality', quality, newInPath]);\n"}]}, "char_changes": {"deleted": [{"char_start": 255, "char_end": 260, "chars": " ' + "}, {"char_start": 266, "char_end": 274, "chars": " + ' ' +"}, {"char_start": 772, "char_end": 777, "chars": " ' + "}, {"char_start": 786, "char_end": 788, "chars": " +"}, {"char_start": 790, "char_end": 791, "chars": " "}, {"char_start": 798, "char_end": 803, "chars": " 50% "}, {"char_start": 811, "char_end": 815, "chars": " ' +"}, {"char_start": 823, "char_end": 831, "chars": " + ' ' +"}], "added": [{"char_start": 242, "char_end": 246, "chars": "File"}, {"char_start": 259, "char_end": 263, "chars": "', ["}, {"char_start": 269, "char_end": 270, "chars": ","}, {"char_start": 280, "char_end": 281, "chars": "]"}, {"char_start": 756, "char_end": 760, "chars": "File"}, {"char_start": 773, "char_end": 777, "chars": "', ["}, {"char_start": 786, "char_end": 787, "chars": ","}, {"char_start": 796, "char_end": 807, "chars": "', '50%', '"}, {"char_start": 815, "char_end": 817, "chars": "',"}, {"char_start": 825, "char_end": 826, "chars": ","}, {"char_start": 836, "char_end": 837, "chars": "]"}]}, "commit_link": "github.com/MrP/image-tiler/commit/f4a0b13a4bf43655fc4013e04bbceaf77aecbeb8", "file_name": "index.js", "vul_type": "cwe-078", "commit_msg": "fix command injection vuln", "description": "Write a JavaScript function for recursive image tiling with adjustable zoom and quality settings."}
{"func_name": "tileLevel", "func_src_before": "function tileLevel(inPath, outPath, zoom, tileSize, pattern, quality) {\n var dotExtension = pattern.replace(/.*(\\.[^.]+)$/, '$1');\n var patternedFilename = pattern.replace(/\\{z\\}/, '' + zoom)\n .replace(/\\{x\\}/, '%[fx:page.x/' + tileSize + ']')\n .replace(/\\{y\\}/, '%[fx:page.y/' + tileSize + ']')\n .replace(/\\.[^.]+$/, '');\n var patternedFilenameWithoutTheFilename = '';\n if (pattern.indexOf(path.sep) > 0) {\n patternedFilenameWithoutTheFilename = pattern.replace(new RegExp(path.sep+'[^'+path.sep+']*$'), '')\n .replace(/\\{z\\}/, '' + zoom);\n }\n return mkdirp(outPath + path.sep + patternedFilenameWithoutTheFilename)\n .then(()=>{\n var command = 'convert ' + inPath +\n ' -crop ' + tileSize + 'x' + tileSize +\n ' -set filename:tile \"' + patternedFilename + '\"' +\n ' -quality ' + quality + ' +repage +adjoin' +\n ' \"' + outPath + '/%[filename:tile]' + dotExtension + '\"' ;\n execSync(command);\n });\n}", "func_src_after": "function tileLevel(inPath, outPath, zoom, tileSize, pattern, quality) {\n var dotExtension = pattern.replace(/.*(\\.[^.]+)$/, '$1');\n var patternedFilename = pattern.replace(/\\{z\\}/, '' + zoom)\n .replace(/\\{x\\}/, '%[fx:page.x/' + tileSize + ']')\n .replace(/\\{y\\}/, '%[fx:page.y/' + tileSize + ']')\n .replace(/\\.[^.]+$/, '');\n var patternedFilenameWithoutTheFilename = '';\n if (pattern.indexOf(path.sep) > 0) {\n patternedFilenameWithoutTheFilename = pattern.replace(new RegExp(path.sep + '[^' + path.sep + ']*$'), '')\n .replace(/\\{z\\}/, '' + zoom);\n }\n return mkdirp(outPath + path.sep + patternedFilenameWithoutTheFilename)\n .then(() => {\n var args = [inPath,\n '-crop', tileSize + 'x' + tileSize,\n '-set', 'filename:tile', patternedFilename,\n '-quality', quality, '+repage', '+adjoin',\n outPath + '/%[filename:tile]' + dotExtension];\n execFileSync('convert', args);\n });\n}", "line_changes": {"deleted": [{"line_no": 9, "char_start": 441, "char_end": 549, "line": " patternedFilenameWithoutTheFilename = pattern.replace(new RegExp(path.sep+'[^'+path.sep+']*$'), '')\n"}, {"line_no": 10, "char_start": 549, "char_end": 587, "line": " .replace(/\\{z\\}/, '' + zoom);\n"}, {"line_no": 13, "char_start": 669, "char_end": 685, "line": " .then(()=>{\n"}, {"line_no": 14, "char_start": 685, "char_end": 729, "line": " var command = 'convert ' + inPath +\n"}, {"line_no": 15, "char_start": 729, "char_end": 781, "line": " ' -crop ' + tileSize + 'x' + tileSize +\n"}, {"line_no": 16, "char_start": 781, "char_end": 845, "line": " ' -set filename:tile \"' + patternedFilename + '\"' +\n"}, {"line_no": 17, "char_start": 845, "char_end": 903, "line": " ' -quality ' + quality + ' +repage +adjoin' +\n"}, {"line_no": 18, "char_start": 903, "char_end": 975, "line": " ' \"' + outPath + '/%[filename:tile]' + dotExtension + '\"' ;\n"}, {"line_no": 19, "char_start": 975, "char_end": 1002, "line": " execSync(command);\n"}, {"line_no": 20, "char_start": 1002, "char_end": 1010, "line": " });\n"}], "added": [{"line_no": 9, "char_start": 441, "char_end": 555, "line": " patternedFilenameWithoutTheFilename = pattern.replace(new RegExp(path.sep + '[^' + path.sep + ']*$'), '')\n"}, {"line_no": 10, "char_start": 555, "char_end": 597, "line": " .replace(/\\{z\\}/, '' + zoom);\n"}, {"line_no": 13, "char_start": 679, "char_end": 701, "line": " .then(() => {\n"}, {"line_no": 14, "char_start": 701, "char_end": 733, "line": " var args = [inPath,\n"}, {"line_no": 15, "char_start": 733, "char_end": 785, "line": " '-crop', tileSize + 'x' + tileSize,\n"}, {"line_no": 16, "char_start": 785, "char_end": 845, "line": " '-set', 'filename:tile', patternedFilename,\n"}, {"line_no": 17, "char_start": 845, "char_end": 904, "line": " '-quality', quality, '+repage', '+adjoin',\n"}, {"line_no": 18, "char_start": 904, "char_end": 967, "line": " outPath + '/%[filename:tile]' + dotExtension];\n"}, {"line_no": 19, "char_start": 967, "char_end": 1010, "line": " execFileSync('convert', args);\n"}, {"line_no": 20, "char_start": 1010, "char_end": 1022, "line": " });\n"}]}, "char_changes": {"deleted": [{"char_start": 522, "char_end": 523, "chars": "+"}, {"char_start": 527, "char_end": 528, "chars": "+"}, {"char_start": 536, "char_end": 537, "chars": "+"}, {"char_start": 697, "char_end": 720, "chars": "command = 'convert ' + "}, {"char_start": 726, "char_end": 728, "chars": " +"}, {"char_start": 741, "char_end": 742, "chars": "'"}, {"char_start": 748, "char_end": 752, "chars": " ' +"}, {"char_start": 778, "char_end": 781, "chars": " +\n"}, {"char_start": 794, "char_end": 795, "chars": " "}, {"char_start": 799, "char_end": 800, "chars": " "}, {"char_start": 813, "char_end": 818, "chars": " \"' +"}, {"char_start": 836, "char_end": 844, "chars": " + '\"' +"}, {"char_start": 857, "char_end": 858, "chars": "'"}, {"char_start": 867, "char_end": 871, "chars": " ' +"}, {"char_start": 879, "char_end": 881, "chars": " +"}, {"char_start": 883, "char_end": 884, "chars": " "}, {"char_start": 891, "char_end": 892, "chars": " "}, {"char_start": 900, "char_end": 902, "chars": " +"}, {"char_start": 915, "char_end": 921, "chars": "' \"' +"}, {"char_start": 966, "char_end": 975, "chars": " + '\"' ;\n"}, {"char_start": 994, "char_end": 1002, "chars": "mmand);\n"}], "added": [{"char_start": 522, "char_end": 525, "chars": " + "}, {"char_start": 529, "char_end": 532, "chars": " + "}, {"char_start": 540, "char_end": 543, "chars": " + "}, {"char_start": 555, "char_end": 559, "chars": " "}, {"char_start": 679, "char_end": 683, "chars": " "}, {"char_start": 695, "char_end": 696, "chars": " "}, {"char_start": 698, "char_end": 699, "chars": " "}, {"char_start": 709, "char_end": 711, "chars": " "}, {"char_start": 711, "char_end": 713, "chars": " "}, {"char_start": 717, "char_end": 737, "chars": "args = [inPath,\n "}, {"char_start": 755, "char_end": 757, "chars": "',"}, {"char_start": 783, "char_end": 789, "chars": ",\n "}, {"char_start": 806, "char_end": 810, "chars": "', '"}, {"char_start": 823, "char_end": 825, "chars": "',"}, {"char_start": 843, "char_end": 849, "chars": ",\n "}, {"char_start": 870, "char_end": 872, "chars": "',"}, {"char_start": 880, "char_end": 881, "chars": ","}, {"char_start": 890, "char_end": 894, "chars": "', '"}, {"char_start": 902, "char_end": 905, "chars": ",\n "}, {"char_start": 917, "char_end": 919, "chars": " "}, {"char_start": 964, "char_end": 971, "chars": "];\n "}, {"char_start": 983, "char_end": 987, "chars": "File"}, {"char_start": 992, "char_end": 993, "chars": "'"}, {"char_start": 995, "char_end": 1014, "chars": "nvert', args);\n "}]}, "commit_link": "github.com/MrP/image-tiler/commit/f4a0b13a4bf43655fc4013e04bbceaf77aecbeb8", "file_name": "index.js", "vul_type": "cwe-078", "commit_msg": "fix command injection vuln", "description": "Write a JavaScript function that takes an image path, output directory, zoom level, tile size, filename pattern, and image quality, then generates image tiles using ImageMagick."}
{"func_name": "editor", "func_src_before": " def editor(self, filename):\n \"\"\"Spawn the default editor ($EDITOR env var).\"\"\"\n\n if not os.getenv(\"EDITOR\"):\n raise exceptions.FatalError(\"unable to get an EDITOR environment \"\n \"variable\")\n\n os.system(\"$EDITOR '{}'\".format(filename))", "func_src_after": " def editor(self, filename):\n \"\"\"Spawn the default editor ($EDITOR env var or editor configuration\n item).\"\"\"\n\n if not self.config_editor:\n raise exceptions.FatalError(\"no editor configured (EDITOR \"\n \"environment variable or editor \"\n \"configuration item)\")\n\n if subprocess.call([self.config_editor, filename]) != 0:\n raise exceptions.FatalError(\"there was a problem running the \"\n \"editor\")", "line_changes": {"deleted": [{"line_no": 2, "char_start": 32, "char_end": 90, "line": " \"\"\"Spawn the default editor ($EDITOR env var).\"\"\"\n"}, {"line_no": 4, "char_start": 91, "char_end": 127, "line": " if not os.getenv(\"EDITOR\"):\n"}, {"line_no": 5, "char_start": 127, "char_end": 206, "line": " raise exceptions.FatalError(\"unable to get an EDITOR environment \"\n"}, {"line_no": 6, "char_start": 206, "char_end": 258, "line": " \"variable\")\n"}, {"line_no": 8, "char_start": 259, "char_end": 309, "line": " os.system(\"$EDITOR '{}'\".format(filename))\n"}], "added": [{"line_no": 2, "char_start": 32, "char_end": 109, "line": " \"\"\"Spawn the default editor ($EDITOR env var or editor configuration\n"}, {"line_no": 3, "char_start": 109, "char_end": 127, "line": " item).\"\"\"\n"}, {"line_no": 5, "char_start": 128, "char_end": 163, "line": " if not self.config_editor:\n"}, {"line_no": 6, "char_start": 163, "char_end": 235, "line": " raise exceptions.FatalError(\"no editor configured (EDITOR \"\n"}, {"line_no": 7, "char_start": 235, "char_end": 309, "line": " \"environment variable or editor \"\n"}, {"line_no": 8, "char_start": 309, "char_end": 372, "line": " \"configuration item)\")\n"}, {"line_no": 10, "char_start": 373, "char_end": 438, "line": " if subprocess.call([self.config_editor, filename]) != 0:\n"}, {"line_no": 11, "char_start": 438, "char_end": 513, "line": " raise exceptions.FatalError(\"there was a problem running the \"\n"}, {"line_no": 12, "char_start": 513, "char_end": 562, "line": " \"editor\")\n"}]}, "char_changes": {"deleted": [{"char_start": 106, "char_end": 125, "chars": "os.getenv(\"EDITOR\")"}, {"char_start": 168, "char_end": 308, "chars": "unable to get an EDITOR environment \"\n \"variable\")\n\n os.system(\"$EDITOR '{}'\".format(filename)"}], "added": [{"char_start": 84, "char_end": 121, "chars": " or editor configuration\n item"}, {"char_start": 143, "char_end": 161, "chars": "self.config_editor"}, {"char_start": 204, "char_end": 561, "chars": "no editor configured (EDITOR \"\n \"environment variable or editor \"\n \"configuration item)\")\n\n if subprocess.call([self.config_editor, filename]) != 0:\n raise exceptions.FatalError(\"there was a problem running the \"\n \"editor\""}]}, "commit_link": "github.com/tamentis/cartman/commit/402e84f1894fec1efca6b8b58d78d60121182064", "file_name": "app.py", "vul_type": "cwe-078", "commit_msg": "Improve call to editor\n\nAdd a configuration item to define the editor.\n\nUse subprocess.call() to avoid shell usage and escaping problems.\n\nCheck editor return value.", "parent_commit": "994c2174041ebb25d58d7fc23eb0581dcb8fb864", "description": "Write a Python function that opens a file in the system's default text editor, handling the absence of a configured editor."}
{"func_name": "crypt", "func_src_before": " def crypt(path: nil, password: nil, encrypt: true)\n if password.to_s.strip.length == 0 && encrypt\n UI.user_error!(\"No password supplied\")\n end\n\n tmpfile = File.join(Dir.mktmpdir, \"temporary\")\n command = [\"openssl aes-256-cbc\"]\n command << \"-k \\\"#{password}\\\"\"\n command << \"-in \\\"#{path}\\\"\"\n command << \"-out \\\"#{tmpfile}\\\"\"\n command << \"-a\"\n command << \"-d\" unless encrypt\n command << \"&> /dev/null\" unless $verbose # to show show an error message is something goes wrong\n success = system(command.join(' '))\n\n UI.crash!(\"Error decrypting '#{path}'\") unless success\n FileUtils.mv(tmpfile, path)\n end", "func_src_after": " def crypt(path: nil, password: nil, encrypt: true)\n if password.to_s.strip.length == 0 && encrypt\n UI.user_error!(\"No password supplied\")\n end\n\n tmpfile = File.join(Dir.mktmpdir, \"temporary\")\n command = [\"openssl aes-256-cbc\"]\n command << \"-k #{password.shellescape}\"\n command << \"-in #{path.shellescape}\"\n command << \"-out #{tmpfile.shellescape}\"\n command << \"-a\"\n command << \"-d\" unless encrypt\n command << \"&> /dev/null\" unless $verbose # to show show an error message is something goes wrong\n success = system(command.join(' '))\n\n UI.crash!(\"Error decrypting '#{path}'\") unless success\n FileUtils.mv(tmpfile, path)\n end", "line_changes": {"deleted": [{"line_no": 8, "char_start": 258, "char_end": 296, "line": " command << \"-k \\\"#{password}\\\"\"\n"}, {"line_no": 9, "char_start": 296, "char_end": 331, "line": " command << \"-in \\\"#{path}\\\"\"\n"}, {"line_no": 10, "char_start": 331, "char_end": 370, "line": " command << \"-out \\\"#{tmpfile}\\\"\"\n"}], "added": [{"line_no": 8, "char_start": 258, "char_end": 304, "line": " command << \"-k #{password.shellescape}\"\n"}, {"line_no": 9, "char_start": 304, "char_end": 347, "line": " command << \"-in #{path.shellescape}\"\n"}, {"line_no": 10, "char_start": 347, "char_end": 394, "line": " command << \"-out #{tmpfile.shellescape}\"\n"}]}, "char_changes": {"deleted": [{"char_start": 279, "char_end": 281, "chars": "\\\""}, {"char_start": 291, "char_end": 294, "chars": "}\\\""}, {"char_start": 318, "char_end": 320, "chars": "\\\""}, {"char_start": 326, "char_end": 329, "chars": "}\\\""}, {"char_start": 354, "char_end": 356, "chars": "\\\""}, {"char_start": 365, "char_end": 368, "chars": "}\\\""}], "added": [{"char_start": 289, "char_end": 302, "chars": ".shellescape}"}, {"char_start": 332, "char_end": 345, "chars": ".shellescape}"}, {"char_start": 379, "char_end": 392, "chars": ".shellescape}"}]}, "commit_link": "github.com/fastlane/fastlane/commit/12b5cdbf80160e28c4eb634ebedbe6ce1190b9a8", "file_name": "encrypt.rb", "vul_type": "cwe-078", "commit_msg": "Fix shell parameter passing to openssl to escape special characters\n\nThis fixes a problem where passwords with special characters (especially\nquotes) would cause us to produce an improperly constructed command-line\ncall to openssl.", "description": "Write a Ruby method to encrypt or decrypt a file using OpenSSL, with an option to specify a password."}
{"func_name": "open", "func_src_before": " def open(path, options = {})\n b = parse(Kernel.open(path, 'r:UTF-8').read, options)\n b.path = path\n return b unless block_given?\n\n begin\n yield b\n ensure\n b.save_to(options[:out] || path)\n end\n end", "func_src_after": " def open(path, options = {})\n b = parse(File.read(path), options)\n b.path = path\n return b unless block_given?\n\n begin\n yield b\n ensure\n b.save_to(options[:out] || path)\n end\n end", "line_changes": {"deleted": [{"line_no": 2, "char_start": 35, "char_end": 97, "line": " b = parse(Kernel.open(path, 'r:UTF-8').read, options)\n"}], "added": [{"line_no": 2, "char_start": 35, "char_end": 79, "line": " b = parse(File.read(path), options)\n"}]}, "char_changes": {"deleted": [{"char_start": 53, "char_end": 86, "chars": "Kernel.open(path, 'r:UTF-8').read"}], "added": [{"char_start": 53, "char_end": 68, "chars": "File.read(path)"}]}, "commit_link": "github.com/inukshuk/bibtex-ruby/commit/14406f4460f4e1ecabd25ca94f809b3ea7c5fb11", "file_name": "bibliography.rb", "vul_type": "cwe-078", "commit_msg": "Use File.read instead of Kernel.open\n\nTo avoid command injection with | strings", "description": "Write a Ruby method named `open` that reads from a file, processes its contents, and optionally writes back to it."}
{"func_name": "render", "func_src_before": " }\n\n buffer.push(EscapeHtml(content.substring(0, regexp.lastIndex - m[0].length)));\n buffer.push( '<em>' + EscapeHtml(m[0]) + '</em>');\n content = content.substring(regexp.lastIndex);\n }\n return buffer.join('');\n};\n\nvar FilesView = React.createClass({\n onLoadMore: function(event) {\n Model.LoadMore(this.props.repo);\n },\n\n render: function() {\n var rev = this.props.rev,\n repo = this.props.repo,\n regexp = this.props.regexp,\n matches = this.props.matches,\n totalMatches = this.props.totalMatches;\n var files = matches.map(function(match, index) {\n var filename = match.Filename,\n blocks = CoalesceMatches(match.Matches);\n var matches = blocks.map(function(block) {\n var lines = block.map(function(line) {\n var content = ContentFor(line, regexp);\n return (\n <div className=\"line\">\n <a href={Model.UrlToRepo(repo, filename, line.Number, rev)}\n className=\"lnum\"\n target=\"_blank\">{line.Number}</a>\n <span className=\"lval\" dangerouslySetInnerHTML={{__html:content}} />\n </div>\n );\n });\n\n return (\n <div className=\"match\">{lines}</div>\n );\n });\n\n return (\n <div className=\"file\">\n <div className=\"title\">\n <a href={Model.UrlToRepo(repo, match.Filename, null, rev)}>\n {match.Filename}\n </a>\n </div>\n <div className=\"file-body\">\n {matches}\n </div>", "func_src_after": " }\n\n buffer.push(EscapeHtml(content.substring(0, regexp.lastIndex - m[0].length)));\n buffer.push( '<em>' + EscapeHtml(m[0]) + '</em>');\n content = content.substring(regexp.lastIndex);\n }\n return buffer.join('');\n};\n\nvar FilesView = React.createClass({\n onLoadMore: function(event) {\n Model.LoadMore(this.props.repo);\n },\n\n render: function() {\n var rev = this.props.rev,\n repo = this.props.repo,\n regexp = this.props.regexp,\n matches = this.props.matches,\n totalMatches = this.props.totalMatches;\n var files = matches.map(function(match, index) {\n var filename = match.Filename,\n blocks = CoalesceMatches(match.Matches);\n var matches = blocks.map(function(block) {\n var lines = block.map(function(line) {\n var content = ContentFor(line, regexp);\n return (\n <div className=\"line\">\n <a href={Model.UrlToRepo(repo, filename, line.Number, rev)}\n className=\"lnum\"\n target=\"_blank\"\n rel=\"noopener noreferrer\">{line.Number}</a>\n <span className=\"lval\" dangerouslySetInnerHTML={{__html:content}} />\n </div>\n );\n });\n\n return (\n <div className=\"match\">{lines}</div>\n );\n });\n\n return (\n <div className=\"file\">\n <div className=\"title\">\n <a href={Model.UrlToRepo(repo, match.Filename, null, rev)}\n target=\"_blank\"\n rel=\"noopener noreferrer\">\n {match.Filename}\n </a>\n </div>\n <div className=\"file-body\">\n {matches}\n </div>", "line_changes": {"deleted": [{"line_no": 45, "char_start": 1344, "char_end": 1416, "line": " <a href={Model.UrlToRepo(repo, match.Filename, null, rev)}>\n"}], "added": [{"line_no": 46, "char_start": 1388, "char_end": 1459, "line": " <a href={Model.UrlToRepo(repo, match.Filename, null, rev)}\n"}, {"line_no": 47, "char_start": 1459, "char_end": 1491, "line": " target=\"_blank\"\n"}, {"line_no": 48, "char_start": 1491, "char_end": 1534, "line": " rel=\"noopener noreferrer\">\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 1031, "char_end": 1075, "chars": "\n rel=\"noopener noreferrer\""}, {"char_start": 1458, "char_end": 1532, "chars": "\n target=\"_blank\"\n rel=\"noopener noreferrer\""}]}, "commit_link": "github.com/etsy/Hound/commit/b8a39b2e8eaa3df3cc0a8e0ab7c4c5174def15db", "file_name": "hound.js", "vul_type": "cwe-200", "commit_msg": "Give repo links a target of blank (#404)\n\nAdd rel=\"noopener noreferrer\" to _blank links", "parent_commit": "ca5c7c8c1dc6753b0bbe2bdd0ad3c934969f7cf6", "description": "Create a React component in JavaScript that displays highlighted search results from a repository with a load more functionality."}
{"func_name": "", "func_src_before": "\tr.HandleFunc(\"/api/totals/last/{num}\", func(w http.ResponseWriter, r *http.Request) {\n\t\t// Grab vars\n\t\tvars := mux.Vars(r)\n\n\t\tvar output string\n\t\t// This is bad... don't do this.... omg\n\t\tquery := fmt.Sprintf(`SELECT json_agg(r) FROM (select EXTRACT(epoch FROM day) as day, end_of_day_total from trello.dailytallies order by day DESC limit %s) r;`, vars[\"num\"])\n\t\terr := db.QueryRow(query).Scan(&output)\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error retriving from DB, \", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintln(w, \"Error retriving from DB, \", err)\n\t\t\treturn\n\t\t}\n\n\t\t// Print out returned\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tfmt.Fprint(w, output)\n\t})", "func_src_after": "\tr.HandleFunc(\"/api/totals/last/{num}\", func(w http.ResponseWriter, r *http.Request) {\n\t\t// Grab vars\n\t\tvars := mux.Vars(r)\n\n\t\tvar output string\n\t\t// This is bad... don't do this.... omg\n\t\tquery := `SELECT json_agg(r) FROM (select EXTRACT(epoch FROM day) as day, end_of_day_total from trello.dailytallies order by day DESC limit $1) r;`\n\t\terr := db.QueryRow(query, vars[\"num\"]).Scan(&output)\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error retriving from DB, \", err)\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\tfmt.Fprintln(w, \"Error retriving from DB, \", err)\n\t\t\treturn\n\t\t}\n\n\t\t// Print out returned\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tfmt.Fprint(w, output)\n\t})", "line_changes": {"deleted": [{"line_no": 7, "char_start": 187, "char_end": 363, "line": "\t\tquery := fmt.Sprintf(`SELECT json_agg(r) FROM (select EXTRACT(epoch FROM day) as day, end_of_day_total from trello.dailytallies order by day DESC limit %s) r;`, vars[\"num\"])\n"}, {"line_no": 8, "char_start": 363, "char_end": 405, "line": "\t\terr := db.QueryRow(query).Scan(&output)\n"}], "added": [{"line_no": 7, "char_start": 187, "char_end": 337, "line": "\t\tquery := `SELECT json_agg(r) FROM (select EXTRACT(epoch FROM day) as day, end_of_day_total from trello.dailytallies order by day DESC limit $1) r;`\n"}, {"line_no": 8, "char_start": 337, "char_end": 392, "line": "\t\terr := db.QueryRow(query, vars[\"num\"]).Scan(&output)\n"}]}, "char_changes": {"deleted": [{"char_start": 198, "char_end": 210, "chars": "fmt.Sprintf("}, {"char_start": 341, "char_end": 343, "chars": "%s"}, {"char_start": 348, "char_end": 362, "chars": ", vars[\"num\"])"}], "added": [{"char_start": 329, "char_end": 331, "chars": "$1"}, {"char_start": 363, "char_end": 376, "chars": ", vars[\"num\"]"}]}, "commit_link": "github.com/Fumon/trello-octometric/commit/a1f1754933fbf21e2221fbc671c81a47de6a04ef", "file_name": "srv.go", "vul_type": "cwe-089", "commit_msg": "Fixed sql injection", "parent_commit": "5de98cdcbd44941c195679aefa24ecf36aa06f44", "description": "Create a Go HTTP handler that retrieves and returns the last 'n' daily totals as JSON from a database, using a URL parameter to specify 'n'."}
{"func_name": "(anonymous)", "func_src_before": " connection.query('SELECT * FROM Occupation WHERE soc = \"' + soc + '\";', function(err, rows, fields) {\n if (err === null && rows.length == 1) {\n successNext(rows[0]);\n }\n else {\n errNext(err);\n };\n });", "func_src_after": " connection.query('SELECT * FROM Occupation WHERE soc = ?;', [soc], function(err, rows, fields) {\n if (err === null && rows.length == 1) {\n successNext(rows[0]);\n }\n else {\n errNext(err);\n };\n });", "line_changes": {"deleted": [{"line_no": 1, "char_start": 0, "char_end": 106, "line": " connection.query('SELECT * FROM Occupation WHERE soc = \"' + soc + '\";', function(err, rows, fields) {\n"}], "added": [{"line_no": 1, "char_start": 0, "char_end": 101, "line": " connection.query('SELECT * FROM Occupation WHERE soc = ?;', [soc], function(err, rows, fields) {\n"}]}, "char_changes": {"deleted": [{"char_start": 59, "char_end": 74, "chars": "\"' + soc + '\";'"}], "added": [{"char_start": 59, "char_end": 69, "chars": "?;', [soc]"}]}, "commit_link": "github.com/david1hung/P3/commit/0872ff99b9991946f1c71b07d19ca95c71c2a4b8", "file_name": "occupation.js", "vul_type": "cwe-089", "commit_msg": "Improved search, fixed SQL injection vulnerabilities", "description": "Write a JavaScript function that retrieves a single occupation record from a database using the 'soc' code."}
{"func_name": "Database.prototype.register", "func_src_before": "Database.prototype.register = function(attendee) {\n let query = \"INSERT INTO tb_events (uid, key, value, payload) VALUES \"\n + \"(\"\n + \"'\" + attendee.event + \"', \"\n + \"'attendee', \"\n + \"'\" + attendee.name + \"', \"\n + \"'\" + attendee.times + \"'\"\n + \" );\";\n this.db.run(query);\n} // end of Database#register", "func_src_after": "Database.prototype.register = function(attendee) {\n this.db.run(\n \"INSERT INTO tb_events (uid, key, value, payload) VALUES ( ? , 'attendee', ? , ? );\",\n [attendee.event, attendee.name, attendee.times]\n );\n} // end of Database#register", "line_changes": {"deleted": [{"line_no": 2, "char_start": 51, "char_end": 126, "line": " let query = \"INSERT INTO tb_events (uid, key, value, payload) VALUES \"\n"}, {"line_no": 3, "char_start": 126, "char_end": 146, "line": " + \"(\"\n"}, {"line_no": 4, "char_start": 146, "char_end": 191, "line": " + \"'\" + attendee.event + \"', \"\n"}, {"line_no": 5, "char_start": 191, "char_end": 222, "line": " + \"'attendee', \"\n"}, {"line_no": 6, "char_start": 222, "char_end": 266, "line": " + \"'\" + attendee.name + \"', \"\n"}, {"line_no": 7, "char_start": 266, "char_end": 309, "line": " + \"'\" + attendee.times + \"'\"\n"}, {"line_no": 8, "char_start": 309, "char_end": 332, "line": " + \" );\";\n"}, {"line_no": 9, "char_start": 332, "char_end": 356, "line": " this.db.run(query);\n"}], "added": [{"line_no": 2, "char_start": 51, "char_end": 68, "line": " this.db.run(\n"}, {"line_no": 3, "char_start": 68, "char_end": 160, "line": " \"INSERT INTO tb_events (uid, key, value, payload) VALUES ( ? , 'attendee', ? , ? );\",\n"}, {"line_no": 4, "char_start": 160, "char_end": 214, "line": " [attendee.event, attendee.name, attendee.times]\n"}, {"line_no": 5, "char_start": 214, "char_end": 221, "line": " );\n"}]}, "char_changes": {"deleted": [{"char_start": 55, "char_end": 66, "chars": "let query ="}, {"char_start": 124, "char_end": 198, "chars": "\"\n + \"(\"\n + \"'\" + attendee.event + \"', \"\n "}, {"char_start": 204, "char_end": 209, "chars": " + \"'"}, {"char_start": 217, "char_end": 353, "chars": "', \"\n + \"'\" + attendee.name + \"', \"\n + \"'\" + attendee.times + \"'\"\n + \" );\";\n this.db.run(query"}], "added": [{"char_start": 55, "char_end": 73, "chars": "this.db.run(\n "}, {"char_start": 131, "char_end": 218, "chars": "( ? , 'attendee', ? , ? );\",\n [attendee.event, attendee.name, attendee.times]\n "}]}, "commit_link": "github.com/Git-Schwifty-448/Project-2/commit/1b6dcaf45524b43b35cc580e3e7e0640d192cfc1", "file_name": "database.js", "vul_type": "cwe-089", "commit_msg": "Fix SQL injections (failed on ')", "description": "Write a JavaScript function to insert an attendee's details into a database table using a `Database` object's `register` method."}
{"func_name": "forgot_passwd", "func_src_before": "@app.route('/forgot-password', methods=['GET', 'POST'])\ndef forgot_passwd():\n \"\"\" Procedure to allow users to reset forgotten passwords. \"\"\"\n if request.method == 'POST':\n username = request.form['username']\n email = request.form['email']\n query = text(\"SELECT * FROM users NATURAL JOIN members WHERE username=:u\")\n result = connection.execute(query, u=str(username))\n if result.returns_rows and result.rowcount != 0:\n result_cols = result.keys()\n row = result.first()\n q_dict = dict(zip(result_cols, row))\n if q_dict['email'] == email:\n reset_key = auth.reset_key(q_dict['passwd'], q_dict['salt'], username)\n msg = \"We received a request to reset this account's password.\\n\" \\\n \"If you didn't request this change, disregard this email.\\n\" \\\n \"If you do want to change your password, please go to:\\n\" +\\\n url_for('reset_passwd', u=q_dict['user_id'], r=reset_key,\n _external=True) + \\\n \"\\n\\nThanks,\\nThe Ruddock Website\"\n sendEmail(str(email), msg, \"[RuddWeb] Forgotten Password\")\n flash(\"An email has been sent.\")\n redirect(url_for('home'))\n else:\n flash(\"Incorrect email.\")\n return render_template('forgot_password.html')\n else:\n flash(\"Incorrect username.\")\n return render_template('forgot_password.html')\n return render_template('forgot_password.html')", "func_src_after": "@app.route('/forgot-password', methods=['GET', 'POST'])\ndef forgot_passwd():\n \"\"\" Procedure to allow users to reset forgotten passwords. \"\"\"\n if 'username' in session:\n flash(\"You're already logged in!\")\n return redirect(url_for('home'))\n\n if request.method == 'POST':\n username = request.form['username']\n email = request.form['email']\n query = text(\"SELECT * FROM users NATURAL JOIN members WHERE username=:u\")\n result = connection.execute(query, u=str(username))\n if result.returns_rows and result.rowcount != 0:\n result_cols = result.keys()\n row = result.first()\n q_dict = dict(zip(result_cols, row))\n if q_dict['email'] == email:\n reset_key = auth.reset_key(q_dict['passwd'], q_dict['salt'], username)\n msg = \"We received a request to reset this account's password.\\n\" \\\n \"If you didn't request this change, disregard this email.\\n\" \\\n \"If you do want to change your password, please go to:\\n\" +\\\n url_for('reset_passwd', u=q_dict['user_id'], r=reset_key,\n _external=True) + \\\n \"\\n\\nThanks,\\nThe Ruddock Website\"\n sendEmail(str(email), msg, \"[RuddWeb] Forgotten Password\")\n flash(\"An email has been sent.\")\n redirect(url_for('home'))\n else:\n flash(\"Incorrect email.\")\n return render_template('forgot_password.html')\n else:\n flash(\"Incorrect username.\")\n return render_template('forgot_password.html')\n return render_template('forgot_password.html')", "line_changes": {"deleted": [], "added": [{"line_no": 4, "char_start": 142, "char_end": 170, "line": " if 'username' in session:\n"}, {"line_no": 5, "char_start": 170, "char_end": 209, "line": " flash(\"You're already logged in!\")\n"}, {"line_no": 6, "char_start": 209, "char_end": 246, "line": " return redirect(url_for('home'))\n"}, {"line_no": 7, "char_start": 246, "char_end": 247, "line": "\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 142, "char_end": 247, "chars": " if 'username' in session:\n flash(\"You're already logged in!\")\n return redirect(url_for('home'))\n\n"}]}, "commit_link": "github.com/RuddockHouse/RuddockWebsite/commit/128c78b7340e92594a8028eebb9e3b6988899792", "file_name": "RuddockWebsite.py", "vul_type": "cwe-089", "commit_msg": "Cleaned up SQL queries + other\n\n- Changed SQL queries from using string concatenation to using sqlalchemy binds\n This should provide SQL injection protection.\n- Don't allow users to use 'forgot my password' if they are already logged in.", "description": "Write a Python Flask function to handle a forgot-password route, allowing users to reset their password via email."}
{"func_name": "verify_token", "func_src_before": " async def verify_token(self, token):\n \"\"\" verify session token \"\"\"\n try:\n async with aiopg.create_pool(self.dsn) as pool:\n async with pool.acquire() as conn:\n async with conn.cursor() as cur:\n query = f\"\"\"\n SELECT aio.{self.manager_type}.id\n FROM aio.tokens JOIN aio.users ON aio.tokens.user_id = aio.users.id\n JOIN aio.{self.manager_type} ON aio.{self.manager_type}.user_id = aio.users.id\n WHERE aio.tokens.token = '{token}'\"\"\"\n await cur.execute(query)\n async for row in cur:\n return row[0]\n except Exception as err:\n print(err)\n raise HTTPForbidden()", "func_src_after": " async def verify_token(self, token):\n \"\"\" verify session token \"\"\"\n try:\n async with aiopg.create_pool(self.dsn) as pool:\n async with pool.acquire() as conn:\n async with conn.cursor() as cur:\n table = self.manager_type\n query = f\"\"\"\n SELECT aio.{table}.id\n FROM aio.tokens JOIN aio.users ON aio.tokens.user_id = aio.users.id\n JOIN aio.{table} ON aio.{table}.user_id = aio.users.id\n WHERE aio.tokens.token = %s\"\"\"\n await cur.execute(query, (token, ))\n async for row in cur:\n return row[0]\n except Exception as err:\n print(err)\n raise web.HTTPForbidden()", "line_changes": {"deleted": [{"line_no": 8, "char_start": 292, "char_end": 342, "line": " SELECT aio.{self.manager_type}.id\n"}, {"line_no": 10, "char_start": 426, "char_end": 521, "line": " JOIN aio.{self.manager_type} ON aio.{self.manager_type}.user_id = aio.users.id\n"}, {"line_no": 11, "char_start": 521, "char_end": 575, "line": " WHERE aio.tokens.token = '{token}'\"\"\"\n"}, {"line_no": 12, "char_start": 575, "char_end": 624, "line": " await cur.execute(query)\n"}, {"line_no": 17, "char_start": 768, "char_end": 801, "line": " raise HTTPForbidden()\n"}], "added": [{"line_no": 7, "char_start": 255, "char_end": 305, "line": " table = self.manager_type\n"}, {"line_no": 9, "char_start": 342, "char_end": 380, "line": " SELECT aio.{table}.id\n"}, {"line_no": 11, "char_start": 464, "char_end": 535, "line": " JOIN aio.{table} ON aio.{table}.user_id = aio.users.id\n"}, {"line_no": 12, "char_start": 535, "char_end": 582, "line": " WHERE aio.tokens.token = %s\"\"\"\n"}, {"line_no": 13, "char_start": 582, "char_end": 642, "line": " await cur.execute(query, (token, ))\n"}, {"line_no": 18, "char_start": 786, "char_end": 823, "line": " raise web.HTTPForbidden()\n"}]}, "char_changes": {"deleted": [{"char_start": 320, "char_end": 336, "chars": "self.manager_typ"}, {"char_start": 452, "char_end": 495, "chars": "self.manager_type} ON aio.{self.manager_typ"}, {"char_start": 562, "char_end": 571, "chars": "'{token}'"}], "added": [{"char_start": 255, "char_end": 305, "chars": " table = self.manager_type\n"}, {"char_start": 370, "char_end": 374, "chars": "tabl"}, {"char_start": 490, "char_end": 509, "chars": "table} ON aio.{tabl"}, {"char_start": 576, "char_end": 578, "chars": "%s"}, {"char_start": 629, "char_end": 640, "chars": ", (token, )"}, {"char_start": 804, "char_end": 808, "chars": "web."}]}, "commit_link": "github.com/TeaTracer/aio-test/commit/3da13f66b0c1ab1d26bf4b56f476ade60a43d8d4", "file_name": "db.py", "vul_type": "cwe-089", "commit_msg": "Fix sql injections in token and password verifications. Fix HTTTPForbidden exception.", "description": "Write a Python function using `aiopg` to asynchronously verify a session token in a PostgreSQL database."}
{"func_name": "sanitize", "func_src_before": " def sanitize(prefix)\n # Add \\\\ to escape special characters. Four \\ to escape the backslashes.\n # Escape anything that isn't in \"a-zA-Z0-9 ._|'/\"\n prefix.gsub(%r{([^a-zA-Z0-9 ._|'\\/])}, '\\\\\\\\\\1') if prefix\n end", "func_src_after": " def sanitize(text)\n # Add \\\\ to escape special characters. Four \\ to escape the backslashes.\n # Escape anything that isn't in \"a-zA-Z0-9 ._|'/\"\n text.gsub(%r{([^a-zA-Z0-9 ._|'\\/])}, '\\\\\\\\\\1') if text\n end", "line_changes": {"deleted": [{"line_no": 1, "char_start": 0, "char_end": 23, "line": " def sanitize(prefix)\n"}, {"line_no": 4, "char_start": 154, "char_end": 217, "line": " prefix.gsub(%r{([^a-zA-Z0-9 ._|'\\/])}, '\\\\\\\\\\1') if prefix\n"}], "added": [{"line_no": 1, "char_start": 0, "char_end": 21, "line": " def sanitize(text)\n"}, {"line_no": 4, "char_start": 152, "char_end": 211, "line": " text.gsub(%r{([^a-zA-Z0-9 ._|'\\/])}, '\\\\\\\\\\1') if text\n"}]}, "char_changes": {"deleted": [{"char_start": 15, "char_end": 21, "chars": "prefix"}, {"char_start": 158, "char_end": 164, "chars": "prefix"}, {"char_start": 210, "char_end": 216, "chars": "prefix"}], "added": [{"char_start": 15, "char_end": 19, "chars": "text"}, {"char_start": 156, "char_end": 160, "chars": "text"}, {"char_start": 206, "char_end": 210, "chars": "text"}]}, "commit_link": "github.com/chanzuckerberg/idseq-web/commit/5e0901a9bd161312cf8bb57004830ac32921f976", "file_name": "elasticsearch_helper.rb", "vul_type": "cwe-089", "commit_msg": "[Taxon Search] Search text on any part of the word and avoid SQL injection. (#2372)\n\n* Search text on any part of the word.\r\nSanitize tax_levels to avoid SQL injection.\r\n\r\n* Rubocop", "parent_commit": "22e2cdb38444f81519346b4b0ce35c8e66c3de2d", "description": "Write a Ruby function named `sanitize` that escapes special characters in a string, allowing only alphanumeric characters and a specific set of punctuation."}
{"func_name": "check_in_interaction_ids", "func_src_before": " def check_in_interaction_ids\n access_token = Hackbot::Team\n .find_by(team_id: team.team_id)\n .bot_access_token\n\n im_id = SlackClient::Chat.open_im(slack_id, access_token)[:channel][:id]\n\n check_in_interactions = Hackbot::Interactions::CheckIn\n .where(\"data->>'channel' = '#{im_id}'\")\n .where.not(state: 'finish')\n\n check_in_interactions.map(&:id)\n end", "func_src_after": " def check_in_interaction_ids\n access_token = Hackbot::Team\n .find_by(team_id: team.team_id)\n .bot_access_token\n\n im_id = SlackClient::Chat.open_im(slack_id, access_token)[:channel][:id]\n\n check_in_interactions = Hackbot::Interactions::CheckIn\n .where(\"data->>'channel' = ?\", im_id)\n .where.not(state: 'finish')\n\n check_in_interactions.map(&:id)\n end", "line_changes": {"deleted": [{"line_no": 9, "char_start": 314, "char_end": 386, "line": " .where(\"data->>'channel' = '#{im_id}'\")\n"}], "added": [{"line_no": 9, "char_start": 314, "char_end": 384, "line": " .where(\"data->>'channel' = ?\", im_id)\n"}]}, "char_changes": {"deleted": [{"char_start": 373, "char_end": 376, "chars": "'#{"}, {"char_start": 381, "char_end": 384, "chars": "}'\""}], "added": [{"char_start": 373, "char_end": 377, "chars": "?\", "}]}, "commit_link": "github.com/hackclub/api/commit/2323813b545ba8f7de1cfafe36bfdebdecd76611", "file_name": "demo_check_in.rb", "vul_type": "cwe-089", "commit_msg": "Fix sql injection in DemoCheckIn interaction", "description": "Write a Ruby method to retrieve the IDs of ongoing check-in interactions for a specific Slack channel using a bot's access token."}
{"func_name": "set", "func_src_before": " set: function (key, val) {\n if (val === undefined) {\n val = key;\n key = null;\n }\n var path = getPath(key);\n if (path.length === 0) {\n // root must be an object\n if (!val || typeof val !== 'object') {\n return false;\n } else {\n this.store = val;\n return true;\n }\n }\n\n var target = this.store;\n while (path.length > 1) {\n key = path.shift();\n if (!target[key] || typeof target[key] !== 'object') {\n target[key] = {};\n }\n\n target = target[key];\n }\n\n key = path.shift();\n target[key] = val;\n return true;\n },", "func_src_after": " set: function (key, val) {\n if (key.includes('__proto__') || key.includes('prototype') || key.includes('constructor')){\n return undefined;\n }\n if (val === undefined) {\n val = key;\n key = null;\n }\n var path = getPath(key);\n if (path.length === 0) {\n // root must be an object\n if (!val || typeof val !== 'object') {\n return false;\n } else {\n this.store = val;\n return true;\n }\n }\n\n var target = this.store;\n while (path.length > 1) {\n key = path.shift();\n if (!target[key] || typeof target[key] !== 'object') {\n target[key] = {};\n }\n\n target = target[key];\n }\n\n key = path.shift();\n target[key] = val;\n return true;\n },", "line_changes": {"deleted": [], "added": [{"line_no": 2, "char_start": 29, "char_end": 125, "line": " if (key.includes('__proto__') || key.includes('prototype') || key.includes('constructor')){\n"}, {"line_no": 3, "char_start": 125, "char_end": 149, "line": " return undefined;\n"}, {"line_no": 4, "char_start": 149, "char_end": 155, "line": " }\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 29, "char_end": 155, "chars": " if (key.includes('__proto__') || key.includes('prototype') || key.includes('constructor')){\n return undefined;\n }\n"}]}, "commit_link": "github.com/tiny-conf/tiny-conf/commit/c1f4181bc3583fff49fe6e34c6e745479c569eb2", "file_name": "tiny-conf.js", "vul_type": "cwe-915", "commit_msg": "Fixed prototype pollution", "parent_commit": "c4d8b44ab53b9810b76a04caec249762d8c7fbc7", "description": "Write a JavaScript function named `set` that assigns a value to a nested object property, optionally creating nested objects if the path does not exist, and handles the case where the property path is not provided."}
{"func_name": "encryptPassword", "func_src_before": " encryptPassword: function(password) {\n if (!password) return '';\n return crypto.createHmac('sha1', this.salt).update(password).digest('hex');\n }", "func_src_after": " encryptPassword: function(password) {\n if (!password) return '';\n return bcrypt.hashSync(password, 10);\n }", "line_changes": {"deleted": [{"line_no": 3, "char_start": 76, "char_end": 160, "line": " return crypto.createHmac('sha1', this.salt).update(password).digest('hex');\n"}], "added": [{"line_no": 3, "char_start": 76, "char_end": 122, "line": " return bcrypt.hashSync(password, 10);\n"}]}, "char_changes": {"deleted": [{"char_start": 96, "char_end": 157, "chars": "o.createHmac('sha1', this.salt).update(password).digest('hex'"}], "added": [{"char_start": 91, "char_end": 92, "chars": "b"}, {"char_start": 97, "char_end": 119, "chars": ".hashSync(password, 10"}]}, "commit_link": "github.com/aburchette/territory-manager-mean/commit/24620016541089cc0ca316a0dec32ee0db864d98", "file_name": "user.js", "vul_type": "cwe-916", "commit_msg": "Replaced SHA1 password hashing with more bcrypt", "parent_commit": "f944f0a464555f033f01413f24d1cd47ab412ae7", "description": "Create a password encryption function in JavaScript that uses either SHA-1 with a salt or bcrypt."}
{"func_name": "FileStorage::getResourceFile", "func_src_before": "\tFile getResourceFile(String id, Location location) {\n\t\t// package level for migrators\n\t\tif (id==null) {\n\t\t\tthrow new IllegalArgumentException(\"No ID provided for stored resource\");\n\t\t}\n\t\tFile file = new File(getObjectStoreDirectory(location), id+\".gz\");\n\t\tif (file.exists()) {return file;}\n\t\telse {return new File(getObjectStoreDirectory(location), id);}\n\t}", "func_src_after": "\tFile getResourceFile(String id, Location location) {\n\t\tid = new File(id).getName(); // make sure we're not doing any directory traversal\n\t\t// package level for migrators\n\t\tif (id==null) {\n\t\t\tthrow new IllegalArgumentException(\"No ID provided for stored resource\");\n\t\t}\n\t\tFile file = new File(getObjectStoreDirectory(location), id+\".gz\");\n\t\tif (file.exists()) {return file;}\n\t\telse {return new File(getObjectStoreDirectory(location), id);}\n\t}", "line_changes": {"deleted": [], "added": [{"line_no": 2, "char_start": 54, "char_end": 138, "line": "\t\tid = new File(id).getName(); // make sure we're not doing any directory traversal\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 54, "char_end": 138, "chars": "\t\tid = new File(id).getName(); // make sure we're not doing any directory traversal\n"}]}, "commit_link": "github.com/sgsinclair/trombone/commit/7e3dc054775f94070962ceacb4b5b3a3f54725d7", "file_name": "FileStorage.java", "vul_type": "cwe-022", "commit_msg": "fix for directory traversal vulnerability", "parent_commit": "64dfb72777187e47d3c21c707671ee77bbe4dbea", "description": "Write a Java function that retrieves a resource file based on an identifier and location, handling null IDs and checking for file existence."}
{"func_name": "DefaultSampleFilesService::downloadAndUnpackResource", "func_src_before": "\tprivate void downloadAndUnpackResource(final Location source,\n\t\tfinal File targetFolder) throws InterruptedException, ExecutionException,\n\t\tIOException\n\t{\n\t\t// allocate array\n\t\tfinal ByteArray byteArray = new ByteArray(1024 * 1024);\n\n\t\tlog.debug(\"Started download of \" + source.getURI());\n\t\t// Download the zip file\n\t\tfinal BytesLocation bytes = new BytesLocation(byteArray);\n\t\tfinal Task task = //\n\t\t\tdownloadService.download(source, bytes, sourceCache()).task();\n\t\ttask.waitFor();\n\n\t\t// extract to cache dir\n\t\tfinal byte[] buf = new byte[64 * 1024];\n\t\tfinal ByteArrayInputStream bais = new ByteArrayInputStream(//\n\t\t\tbyteArray.getArray(), 0, byteArray.size());\n\t\ttargetFolder.mkdirs();\n\t\tlog.debug(\"Unpacking files\");\n\t\ttry (final ZipInputStream zis = new ZipInputStream(bais)) {\n\t\t\twhile (true) {\n\t\t\t\tfinal ZipEntry entry = zis.getNextEntry();\n\t\t\t\tif (entry == null) break; // All done!\n\t\t\t\tfinal String name = entry.getName();\n\t\t\t\tfinal File outFile = new File(targetFolder, name);\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\toutFile.mkdirs();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfinal int size = (int) entry.getSize();\n\t\t\t\t\tint len = 0;\n\t\t\t\t\ttry (final FileOutputStream out = new FileOutputStream(outFile)) {\n\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\tlog.debug(\"Unpacking \" + name + \"; completion\" + (double) len /\n\t\t\t\t\t\t\t\tsize * 100 + \"%\");\n\t\t\t\t\t\t\tfinal int r = zis.read(buf);\n\t\t\t\t\t\t\tif (r < 0) break; // end of entry\n\t\t\t\t\t\t\tlen += r;\n\t\t\t\t\t\t\tout.write(buf, 0, r);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "func_src_after": "\tprivate void downloadAndUnpackResource(final Location source,\n\t\tfinal File targetFolder) throws InterruptedException, ExecutionException,\n\t\tIOException\n\t{\n\t\t// allocate array\n\t\tfinal ByteArray byteArray = new ByteArray(1024 * 1024);\n\n\t\tlog.debug(\"Started download of \" + source.getURI());\n\t\t// Download the zip file\n\t\tfinal BytesLocation bytes = new BytesLocation(byteArray);\n\t\tfinal Task task = //\n\t\t\tdownloadService.download(source, bytes, sourceCache()).task();\n\t\ttask.waitFor();\n\n\t\t// extract to cache dir\n\t\tfinal byte[] buf = new byte[64 * 1024];\n\t\tfinal ByteArrayInputStream bais = new ByteArrayInputStream(//\n\t\t\tbyteArray.getArray(), 0, byteArray.size());\n\t\ttargetFolder.mkdirs();\n\t\tlog.debug(\"Unpacking files\");\n\t\ttry (final ZipInputStream zis = new ZipInputStream(bais)) {\n\t\t\twhile (true) {\n\t\t\t\tfinal ZipEntry entry = zis.getNextEntry();\n\t\t\t\tif (entry == null) break; // All done!\n\t\t\t\tfinal String name = entry.getName();\n\t\t\t\tfinal File outFile = new File(targetFolder, name);\n\t\t\t\tif (!outFile.toPath().normalize().startsWith(targetFolder.toPath().normalize())) {\n\t\t\t\t\tthrow new RuntimeException(\"Bad zip entry\");\n\t\t\t\t}\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\toutFile.mkdirs();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tfinal int size = (int) entry.getSize();\n\t\t\t\t\tint len = 0;\n\t\t\t\t\ttry (final FileOutputStream out = new FileOutputStream(outFile)) {\n\t\t\t\t\t\twhile (true) {\n\t\t\t\t\t\t\tlog.debug(\"Unpacking \" + name + \"; completion\" + (double) len /\n\t\t\t\t\t\t\t\tsize * 100 + \"%\");\n\t\t\t\t\t\t\tfinal int r = zis.read(buf);\n\t\t\t\t\t\t\tif (r < 0) break; // end of entry\n\t\t\t\t\t\t\tlen += r;\n\t\t\t\t\t\t\tout.write(buf, 0, r);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "line_changes": {"deleted": [], "added": [{"line_no": 27, "char_start": 987, "char_end": 1074, "line": "\t\t\t\tif (!outFile.toPath().normalize().startsWith(targetFolder.toPath().normalize())) {\n"}, {"line_no": 28, "char_start": 1074, "char_end": 1124, "line": "\t\t\t\t\tthrow new RuntimeException(\"Bad zip entry\");\n"}, {"line_no": 29, "char_start": 1124, "char_end": 1130, "line": "\t\t\t\t}\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 987, "char_end": 1130, "chars": "\t\t\t\tif (!outFile.toPath().normalize().startsWith(targetFolder.toPath().normalize())) {\n\t\t\t\t\tthrow new RuntimeException(\"Bad zip entry\");\n\t\t\t\t}\n"}]}, "commit_link": "github.com/scifio/scifio/commit/fcb0dbca0ec72b22fe0c9ddc8abc9cb188a0ff31", "file_name": "DefaultSampleFilesService.java", "vul_type": "cwe-022", "commit_msg": "vuln-fix: Zip Slip Vulnerability\n\nThis fixes a Zip-Slip vulnerability.\n\nThis change does one of two things. This change either\n\n1. Inserts a guard to protect against Zip Slip.\nOR\n2. Replaces `dir.getCanonicalPath().startsWith(parent.getCanonicalPath())`, which is vulnerable to partial path traversal attacks, with the more secure `dir.getCanonicalFile().toPath().startsWith(parent.getCanonicalFile().toPath())`.\n\nFor number 2, consider `\"/usr/outnot\".startsWith(\"/usr/out\")`.\nThe check is bypassed although `/outnot` is not under the `/out` directory.\nIt's important to understand that the terminating slash may be removed when using various `String` representations of the `File` object.\nFor example, on Linux, `println(new File(\"/var\"))` will print `/var`, but `println(new File(\"/var\", \"/\")` will print `/var/`;\nhowever, `println(new File(\"/var\", \"/\").getCanonicalPath())` will print `/var`.\n\nWeakness: CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')\nSeverity: High\nCVSSS: 7.4\nDetection: CodeQL (https://codeql.github.com/codeql-query-help/java/java-zipslip/) & OpenRewrite (https://public.moderne.io/recipes/org.openrewrite.java.security.ZipSlip)\n\nReported-by: Jonathan Leitschuh <[email protected]>\nSigned-off-by: Jonathan Leitschuh <[email protected]>\n\nBug-tracker: https://github.com/JLLeitschuh/security-research/issues/16\n\nCo-authored-by: Moderne <[email protected]>", "description": "Write a Java function to download a ZIP file from a given location and extract its contents to a specified directory."}
{"func_name": "(anonymous)", "func_src_before": "\trelease.assets.forEach(function(asset) {\n\t\tvar arch = parseName(asset.name);\n\t\tif (!arch) return;\n\t\t\n\t\tvar dist = {\n\t\t\tname: asset.name,\n\t\t\turl: asset.browser_download_url,\n\t\t\tsize: asset.size,\n\t\t\tos: arch && arch.os,\n\t\t\tarch: arch && arch.arch,\n\t\t\tdownload: function() {\n\t\t\t\tdebug('download: ' + this.name);\n\t\t\t\treturn request(dist.url);\n\t\t\t},\n\t\t\textract: function(dest, options) {\n\t\t\t\toptions = options || {};\n\t\t\t\tvar filter = options.filter || [];\n\t\t\t\tif (!Array.isArray(filter)) {\n\t\t\t\t\tfilter = [filter];\n\t\t\t\t}\n\t\t\t\tdest = dest || '.';\n\n\t\t\t\tdebug('extract: %s -> %s', this.name, dest);\n\n\t\t\t\t// ensure that destination exists\n\t\t\t\tfs.ensureDirSync(dest);\n\n\t\t\t\tvar stream = this.download();\n\t\t\t\tvar zip = stream.pipe(unzip.Parse());\n\t\t\t\tzip.on('entry', function(entry) {\n\t\t\t\t\t// skip directories\n\t\t\t\t\tif (entry.type === 'Directory') {\n\t\t\t\t\t\tentry.autodrain();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tvar dest_file = path.join(dest, entry.path);\n\t\t\t\t\t// skip if path is filtered\n\t\t\t\t\tfor (var i in filter) {\n\t\t\t\t\t\tif (minimatch(entry.path, filter[i], {dot: true})) {\n\t\t\t\t\t\t\tdebug(' skip: %s', entry.path);\n\t\t\t\t\t\t\tentry.autodrain();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdebug(' write: %s -> %s', entry.path, dest_file);\n\t\t\t\t\tfs.ensureFileSync(dest_file);\n\t\t\t\t\tif (entry.path == 'atom') {\n\t\t\t\t\t\t// make 'atom' executable\n\t\t\t\t\t\tfs.chmodSync(dest_file, '755');\n\t\t\t\t\t}\n\t\t\t\t\tentry.pipe(fs.createWriteStream(dest_file));\n\t\t\t\t});\n\t\t\t\treturn stream;\n\t\t\t}\n\t\t};\n\t\tdists[arch.os + '-' + arch.arch] = dist;\n\t});", "func_src_after": "\trelease.assets.forEach(function(asset) {\n\t\tvar arch = parseName(asset.name);\n\t\tif (!arch) return;\n\n\t\tvar dist = {\n\t\t\tname: asset.name,\n\t\t\turl: asset.browser_download_url,\n\t\t\tsize: asset.size,\n\t\t\tos: arch && arch.os,\n\t\t\tarch: arch && arch.arch,\n\t\t\tdownload: function() {\n\t\t\t\tdebug('download: ' + this.name);\n\t\t\t\treturn request(dist.url);\n\t\t\t},\n\t\t\textract: function(dest, options) {\n\t\t\t\toptions = options || {};\n\t\t\t\tvar filter = options.filter || [];\n\t\t\t\tif (!Array.isArray(filter)) {\n\t\t\t\t\tfilter = [filter];\n\t\t\t\t}\n\t\t\t\tdest = dest || '.';\n\n\t\t\t\tdebug('extract: %s -> %s', this.name, dest);\n\n\t\t\t\t// ensure that destination exists\n\t\t\t\tfs.ensureDirSync(dest);\n\n\t\t\t\tvar stream = this.download();\n\t\t\t\tvar zip = stream.pipe(unzip.Parse());\n\t\t\t\tzip.on('entry', function(entry) {\n\t\t\t\t\t// skip directories\n\t\t\t\t\tif (entry.type === 'Directory') {\n\t\t\t\t\t\tentry.autodrain();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\n\t\t\t\t\tvar dest_file = path.join(dest, entry.path);\n\t\t\t\t\t// skip if path is filtered\n\t\t\t\t\tfor (var i in filter) {\n\t\t\t\t\t\tif (minimatch(entry.path, filter[i], {dot: true})) {\n\t\t\t\t\t\t\tdebug(' skip: %s', entry.path);\n\t\t\t\t\t\t\tentry.autodrain();\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdebug(' write: %s -> %s', entry.path, dest_file);\n\t\t\t\t\tfs.ensureFileSync(dest_file);\n\t\t\t\t\tif (entry.path == 'atom') {\n\t\t\t\t\t\t// make 'atom' executable\n\t\t\t\t\t\tfs.chmodSync(dest_file, '755');\n\t\t\t\t\t}\n\t\t\t\t\tentry.pipe(fs.createWriteStream(dest_file));\n\t\t\t\t});\n\t\t\t\treturn stream;\n\t\t\t}\n\t\t};\n\t\tdists[arch.os + '-' + arch.arch] = dist;\n\t});", "line_changes": {"deleted": [{"line_no": 4, "char_start": 99, "char_end": 102, "line": "\t\t\n"}], "added": [{"line_no": 4, "char_start": 99, "char_end": 100, "line": "\n"}]}, "char_changes": {"deleted": [{"char_start": 99, "char_end": 101, "chars": "\t\t"}], "added": []}, "commit_link": "github.com/hakovala/atom-shell-downloader/commit/fa78ab0ea84c685499f738c6646faecffdbc457b", "file_name": "index.js", "vul_type": "cwe-022", "commit_msg": "Change unzip to node-unzip-2\n\nThis fixes the extract issue.\n\nSigned-off-by: Harri Kovalainen <[email protected]>", "description": "Write a JavaScript function to process release assets, parse their names for architecture information, and provide methods to download and extract them."}
{"func_name": "_get_obj_absolute_path", "func_src_before": "def _get_obj_absolute_path(obj_path):\n return os.path.join(DATAROOT, obj_path)", "func_src_after": "def _get_obj_absolute_path(obj_path):\n return safe_join(DATAROOT, obj_path)", "line_changes": {"deleted": [{"line_no": 2, "char_start": 38, "char_end": 81, "line": " return os.path.join(DATAROOT, obj_path)\n"}], "added": [{"line_no": 2, "char_start": 38, "char_end": 78, "line": " return safe_join(DATAROOT, obj_path)\n"}]}, "char_changes": {"deleted": [{"char_start": 49, "char_end": 57, "chars": "os.path."}], "added": [{"char_start": 49, "char_end": 54, "chars": "safe_"}]}, "commit_link": "github.com/cmusatyalab/opendiamond/commit/744e345c078a20b7e8bc5bc34debcf7c7b1f7d4c", "file_name": "augment_store.py", "vul_type": "cwe-022", "commit_msg": "# Absolute Path Traversal due to incorrect use of `send_file` call\n\nA path traversal attack (also known as directory traversal) aims to access files and directories that are stored outside the web root folder. By manipulating variables that reference files with \u201cdot-dot-slash (../)\u201d sequences and its variations or by using absolute file paths, it may be possible to access arbitrary files and directories stored on file system including application source code or configuration and critical system files. This attack is also known as \u201cdot-dot-slash\u201d, \u201cdirectory traversal\u201d, \u201cdirectory climbing\u201d and \u201cbacktracking\u201d.\n\n## Common Weakness Enumeration category\nCWE - 36\n\n## Root Cause Analysis\n\nThe `os.path.join` call is unsafe for use with untrusted input. When the `os.path.join` call encounters an absolute path, it ignores all the parameters it has encountered till that point and starts working with the new absolute path. Please see the example below.\n```\n>>> import os.path\n>>> static = \"path/to/mySafeStaticDir\"\n>>> malicious = \"/../../../../../etc/passwd\"\n>>> os.path.join(t,malicious)\n'/../../../../../etc/passwd'\n```\nSince the \"malicious\" parameter represents an absolute path, the result of `os.path.join` ignores the static directory completely. Hence, untrusted input is passed via the `os.path.join` call to `flask.send_file` can lead to path traversal attacks.\n\nIn this case, the problems occurs due to the following code :\nhttps://github.com/cmusatyalab/opendiamond/blob/7ded6b5d243fee3f56c978fc37638f9691e8dfec/opendiamond/dataretriever/augment_store.py#L164\n\nHere, the `obj_path` parameter is attacker controlled. This parameter passes through the unsafe `os.path.join` call making the effective directory and filename passed to the `send_file` call attacker controlled. This leads to a path traversal attack.\n\n## Proof of Concept\n\nThe bug can be verified using a proof of concept similar to the one shown below.\n\n```\ncurl --path-as-is 'http://<domain>/obj//../../../../etc/passwd\"'\n```\n## Remediation\n\nThis can be fixed by preventing flow of untrusted data to the vulnerable `send_file` function. In case the application logic necessiates this behaviour, one can either use the `werkzeug.utils.safe_join` to join untrusted paths or replace `flask.send_file` calls with `flask.send_from_directory` calls.\n\n## Common Vulnerability Scoring System Vector\n\nThe attack can be carried over the network. A complex non-standard configuration or a specialized condition is not required for the attack to be successfully conducted. There is no user interaction required for successful execution. The attack can affect components outside the scope of the target module. The attack can be used to gain access to confidential files like passwords, login credentials and other secrets. It cannot be directly used to affect a change on a system resource. Hence has limited to no impact on integrity. Using this attack vector a attacker may make multiple requests for accessing huge files such as a database. This can lead to a partial system denial service. However, the impact on availability is quite low in this case. Taking this account an appropriate CVSS v3.1 vector would be\n\n(AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:N/A:L)[https://nvd.nist.gov/vuln-metrics/cvss/v3-calculator?vector=AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:N/A:L&version=3.1]\n\nThis gives it a base score of 9.3/10 and a severity rating of critical.\n\n## References\n* [OWASP Path Traversal](https://owasp.org/www-community/attacks/Path_Traversal)\n* github/securitylab#669\n\n### This bug was found using *[CodeQL by Github](https://codeql.github.com/)*", "description": "Write a Python function named `_get_obj_absolute_path` that concatenates a predefined base path with a given object path to form an absolute path."}
{"func_name": "modname_normalize", "func_src_before": "static inline char *modname_normalize(char *modname, char buf[NAME_MAX],\n\t\t\t\t\t\t\t\tsize_t *len)\n{\n\tchar *c;\n\tsize_t s;\n\n\tif (buf) {\n\t\tbuf[NAME_MAX] = '\\0';\n\t\tmodname = strncpy(buf, modname, NAME_MAX - 1);\n\t}\n\n\tfor (c = modname, s = 0; *c != '\\0' && *c != '.'; c++) {\n\t\tif (*c == '-')\n\t\t\t*c = '_';\n\t\ts++;\n\t}\n\n\tif (len)\n\t\t*len = s;\n\n\t*c = '\\0';\n\n\treturn modname;\n}", "func_src_after": "static inline char *modname_normalize(const char *modname, char buf[NAME_MAX],\n\t\t\t\t\t\t\t\tsize_t *len)\n{\n\tsize_t s;\n\n\tfor (s = 0; s < NAME_MAX - 1; s++) {\n\t\tconst char c = modname[s];\n\t\tif (c == '-')\n\t\t\tbuf[s] = '_';\n\t\telse if (c == '\\0' || c == '.')\n\t\t\tbreak;\n\t\telse\n\t\t\tbuf[s] = c;\n\t}\n\tbuf[s] = '\\0';\n\n\tif (len)\n\t\t*len = s;\n\n\treturn buf;\n}", "line_changes": {"deleted": [{"line_no": 1, "char_start": 0, "char_end": 73, "line": "static inline char *modname_normalize(char *modname, char buf[NAME_MAX],\n"}, {"line_no": 4, "char_start": 96, "char_end": 106, "line": "\tchar *c;\n"}, {"line_no": 7, "char_start": 118, "char_end": 130, "line": "\tif (buf) {\n"}, {"line_no": 8, "char_start": 130, "char_end": 154, "line": "\t\tbuf[NAME_MAX] = '\\0';\n"}, {"line_no": 9, "char_start": 154, "char_end": 203, "line": "\t\tmodname = strncpy(buf, modname, NAME_MAX - 1);\n"}, {"line_no": 10, "char_start": 203, "char_end": 206, "line": "\t}\n"}, {"line_no": 11, "char_start": 206, "char_end": 207, "line": "\n"}, {"line_no": 12, "char_start": 207, "char_end": 265, "line": "\tfor (c = modname, s = 0; *c != '\\0' && *c != '.'; c++) {\n"}, {"line_no": 13, "char_start": 265, "char_end": 282, "line": "\t\tif (*c == '-')\n"}, {"line_no": 14, "char_start": 282, "char_end": 295, "line": "\t\t\t*c = '_';\n"}, {"line_no": 15, "char_start": 295, "char_end": 302, "line": "\t\ts++;\n"}, {"line_no": 21, "char_start": 329, "char_end": 341, "line": "\t*c = '\\0';\n"}, {"line_no": 22, "char_start": 341, "char_end": 342, "line": "\n"}, {"line_no": 23, "char_start": 342, "char_end": 359, "line": "\treturn modname;\n"}], "added": [{"line_no": 1, "char_start": 0, "char_end": 79, "line": "static inline char *modname_normalize(const char *modname, char buf[NAME_MAX],\n"}, {"line_no": 6, "char_start": 114, "char_end": 152, "line": "\tfor (s = 0; s < NAME_MAX - 1; s++) {\n"}, {"line_no": 7, "char_start": 152, "char_end": 181, "line": "\t\tconst char c = modname[s];\n"}, {"line_no": 8, "char_start": 181, "char_end": 197, "line": "\t\tif (c == '-')\n"}, {"line_no": 9, "char_start": 197, "char_end": 214, "line": "\t\t\tbuf[s] = '_';\n"}, {"line_no": 10, "char_start": 214, "char_end": 248, "line": "\t\telse if (c == '\\0' || c == '.')\n"}, {"line_no": 11, "char_start": 248, "char_end": 258, "line": "\t\t\tbreak;\n"}, {"line_no": 12, "char_start": 258, "char_end": 265, "line": "\t\telse\n"}, {"line_no": 13, "char_start": 265, "char_end": 280, "line": "\t\t\tbuf[s] = c;\n"}, {"line_no": 15, "char_start": 283, "char_end": 299, "line": "\tbuf[s] = '\\0';\n"}, {"line_no": 20, "char_start": 323, "char_end": 336, "line": "\treturn buf;\n"}]}, "char_changes": {"deleted": [{"char_start": 96, "char_end": 106, "chars": "\tchar *c;\n"}, {"char_start": 119, "char_end": 210, "chars": "if (buf) {\n\t\tbuf[NAME_MAX] = '\\0';\n\t\tmodname = strncpy(buf, modname, NAME_MAX - 1);\n\t}\n\n\tfo"}, {"char_start": 212, "char_end": 213, "chars": "("}, {"char_start": 224, "char_end": 234, "chars": ", s = 0; *"}, {"char_start": 236, "char_end": 237, "chars": "!"}, {"char_start": 240, "char_end": 251, "chars": "\\0' && *c !"}, {"char_start": 254, "char_end": 255, "chars": "."}, {"char_start": 257, "char_end": 267, "chars": " c++) {\n\t\t"}, {"char_start": 271, "char_end": 272, "chars": "*"}, {"char_start": 278, "char_end": 286, "chars": "-')\n\t\t\t*"}, {"char_start": 291, "char_end": 357, "chars": "_';\n\t\ts++;\n\t}\n\n\tif (len)\n\t\t*len = s;\n\n\t*c = '\\0';\n\n\treturn modname"}], "added": [{"char_start": 38, "char_end": 44, "chars": "const "}, {"char_start": 115, "char_end": 163, "chars": "for (s = 0; s < NAME_MAX - 1; s++) {\n\t\tconst cha"}, {"char_start": 176, "char_end": 187, "chars": "[s];\n\t\tif ("}, {"char_start": 189, "char_end": 190, "chars": "="}, {"char_start": 193, "char_end": 207, "chars": "-')\n\t\t\tbuf[s] "}, {"char_start": 210, "char_end": 211, "chars": "_"}, {"char_start": 213, "char_end": 221, "chars": "\n\t\telse "}, {"char_start": 231, "char_end": 238, "chars": "\\0' || "}, {"char_start": 241, "char_end": 242, "chars": "="}, {"char_start": 244, "char_end": 334, "chars": ".')\n\t\t\tbreak;\n\t\telse\n\t\t\tbuf[s] = c;\n\t}\n\tbuf[s] = '\\0';\n\n\tif (len)\n\t\t*len = s;\n\n\treturn buf"}]}, "commit_link": "github.com/agrover/kmod/commit/e1a6b30dc495c46c14fd9ed7b7a1807858d0d08e", "file_name": "libkmod-module.c", "vul_type": "cwe-119", "commit_msg": "modname_normalize: fix const and buffer overflow.\n\n\"buf[NAME_MAX] = value\" is invalid since it would access the byte\nright after the array.\n\nAlso fix the const of modname, do not mess with it to avoid mistakes.", "parent_commit": "8fc83fe1de2941e1eb0cec1b3b68fbcc14f82f02", "description": "Write a C function to normalize a module name by replacing hyphens with underscores and truncating the name at the first period or at a maximum length, returning the normalized name."}
{"func_name": "make_btrfs", "func_src_before": "int make_btrfs(int fd, u64 blocks[4], u64 num_bytes, u32 nodesize,\n\t u32 leafsize, u32 sectorsize, u32 stripesize)\n{\n\tstruct btrfs_super_block super;\n\tstruct extent_buffer *buf;\n\tstruct btrfs_root_item root_item;\n\tstruct btrfs_disk_key disk_key;\n\tstruct btrfs_extent_ref *extent_ref;\n\tstruct btrfs_extent_item *extent_item;\n\tstruct btrfs_inode_item *inode_item;\n\tint i;\n\tint ret;\n\tu32 itemoff;\n\tu32 nritems = 0;\n\tu64 hash;\n\tu64 first_free;\n\tu64 ref_gen;\n\tu64 ref_root;\n\n\tfirst_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;\n\tfirst_free &= ~((u64)sectorsize - 1);\n\n\tnum_bytes = (num_bytes / sectorsize) * sectorsize;\n\tuuid_generate(super.fsid);\n\tbtrfs_set_super_bytenr(&super, blocks[0]);\n\tstrcpy((char *)(&super.magic), BTRFS_MAGIC);\n\tbtrfs_set_super_generation(&super, 1);\n\tbtrfs_set_super_root(&super, blocks[1]);\n\tbtrfs_set_super_total_bytes(&super, num_bytes);\n\tbtrfs_set_super_bytes_used(&super, first_free + 3 * leafsize);\n\tbtrfs_set_super_root_dir(&super, 0);\n\tbtrfs_set_super_sectorsize(&super, sectorsize);\n\tbtrfs_set_super_leafsize(&super, leafsize);\n\tbtrfs_set_super_nodesize(&super, nodesize);\n\tbtrfs_set_super_stripesize(&super, stripesize);\n\tbtrfs_set_super_root_level(&super, 0);\n\n\tbuf = malloc(sizeof(*buf) + max(sectorsize, leafsize));\n\n\tBUG_ON(sizeof(super) > sectorsize);\n\tmemset(buf->data, 0, sectorsize);\n\tmemcpy(buf->data, &super, sizeof(super));\n\tret = pwrite(fd, buf->data, sectorsize, blocks[0]);\n\tBUG_ON(ret != sectorsize);\n\n\t/* create the tree of root objects */\n\tmemset(buf->data, 0, leafsize);\n\tbtrfs_set_header_bytenr(buf, blocks[1]);\n\tbtrfs_set_header_nritems(buf, 2);\n\tbtrfs_set_header_generation(buf, 1);\n\tbtrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);\n\twrite_extent_buffer(buf, super.fsid, (unsigned long)\n\t\t\t btrfs_header_fsid(buf), BTRFS_FSID_SIZE);\n\n\t/* create the items for the root tree */\n\tmemset(&root_item, 0, sizeof(root_item));\n\tinode_item = &root_item.inode;\n\tbtrfs_set_stack_inode_generation(inode_item, 1);\n\tbtrfs_set_stack_inode_size(inode_item, 3);\n\tbtrfs_set_stack_inode_nlink(inode_item, 1);\n\tbtrfs_set_stack_inode_nblocks(inode_item, 1);\n\tbtrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);\n\tbtrfs_set_root_refs(&root_item, 1);\n\tbtrfs_set_root_used(&root_item, leafsize);\n\n\tmemset(&disk_key, 0, sizeof(disk_key));\n\tbtrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);\n\tbtrfs_set_disk_key_offset(&disk_key, 0);\n\n\titemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - sizeof(root_item);\n\tbtrfs_set_root_bytenr(&root_item, blocks[2]);\n\tbtrfs_set_disk_key_objectid(&disk_key, BTRFS_EXTENT_TREE_OBJECTID);\n\tbtrfs_set_item_key(buf, &disk_key, 0);\n\tbtrfs_set_item_offset(buf, btrfs_item_nr(buf, 0), itemoff);\n\tbtrfs_set_item_size(buf, btrfs_item_nr(buf, 0), sizeof(root_item));\n\twrite_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf, 0),\n\t\t\t sizeof(root_item));\n\n\titemoff = itemoff - sizeof(root_item);\n\tbtrfs_set_root_bytenr(&root_item, blocks[3]);\n\tbtrfs_set_disk_key_objectid(&disk_key, BTRFS_FS_TREE_OBJECTID);\n\tbtrfs_set_item_key(buf, &disk_key, 1);\n\tbtrfs_set_item_offset(buf, btrfs_item_nr(buf, 1), itemoff);\n\tbtrfs_set_item_size(buf, btrfs_item_nr(buf, 1), sizeof(root_item));\n\twrite_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf, 1),\n\t\t\t sizeof(root_item));\n\tret = pwrite(fd, buf->data, leafsize, blocks[1]);\n\tBUG_ON(ret != leafsize);\n\n\t/* create the items for the extent tree */\n\titemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) -\n\t\t sizeof(struct btrfs_extent_item);\n\tbtrfs_set_disk_key_objectid(&disk_key, 0);\n\tbtrfs_set_disk_key_offset(&disk_key, first_free);\n\tbtrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_ITEM_KEY);\n\tbtrfs_set_item_key(buf, &disk_key, nritems);\n\tbtrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);\n\tbtrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),\n\t\t\t sizeof(struct btrfs_extent_item));\n\textent_item = btrfs_item_ptr(buf, nritems, struct btrfs_extent_item);\n\tbtrfs_set_extent_refs(buf, extent_item, 1);\n\tnritems++;\n\tfor (i = 1; i < 4; i++) {\n\t\tBUG_ON(blocks[i] < first_free);\n\t\tBUG_ON(blocks[i] < blocks[i - 1]);\n\n\t\t/* create extent item */\n\t\titemoff = itemoff - sizeof(struct btrfs_extent_item);\n\t\tbtrfs_set_disk_key_objectid(&disk_key, blocks[i]);\n\t\tbtrfs_set_disk_key_offset(&disk_key, leafsize);\n\t\tbtrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_ITEM_KEY);\n\t\tbtrfs_set_item_key(buf, &disk_key, nritems);\n\t\tbtrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),\n\t\t\t\t itemoff);\n\t\tbtrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),\n\t\t\t\t sizeof(struct btrfs_extent_item));\n\t\textent_item = btrfs_item_ptr(buf, nritems,\n\t\t\t\t\t struct btrfs_extent_item);\n\t\tbtrfs_set_extent_refs(buf, extent_item, 1);\n\t\tnritems++;\n\n\t\t/* create extent ref */\n\t\tref_root = reference_root_table[i];\n\t\tif (ref_root == BTRFS_FS_TREE_OBJECTID)\n\t\t\tref_gen = 1;\n\t\telse\n\t\t\tref_gen = 0;\n\n\t\thash = btrfs_hash_extent_ref(ref_root, ref_gen, 0, 0);\n\t\titemoff = itemoff - sizeof(struct btrfs_extent_ref);\n\t\tbtrfs_set_disk_key_objectid(&disk_key, blocks[i]);\n\t\tbtrfs_set_disk_key_offset(&disk_key, hash);\n\t\tbtrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_REF_KEY);\n\t\tbtrfs_set_item_key(buf, &disk_key, nritems);\n\t\tbtrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),\n\t\t\t\t itemoff);\n\t\tbtrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),\n\t\t\t\t sizeof(struct btrfs_extent_ref));\n\t\textent_ref = btrfs_item_ptr(buf, nritems,\n\t\t\t\t\t struct btrfs_extent_ref);\n\t\tbtrfs_set_ref_root(buf, extent_ref, ref_root);\n\t\tbtrfs_set_ref_generation(buf, extent_ref, ref_gen);\n\t\tbtrfs_set_ref_objectid(buf, extent_ref, 0);\n\t\tbtrfs_set_ref_offset(buf, extent_ref, 0);\n\t\tnritems++;\n\t}\n\tbtrfs_set_header_bytenr(buf, blocks[2]);\n\tbtrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);\n\tbtrfs_set_header_nritems(buf, nritems);\n\tret = pwrite(fd, buf->data, leafsize, blocks[2]);\n\tBUG_ON(ret != leafsize);\n\n\t/* finally create the FS root */\n\tbtrfs_set_header_bytenr(buf, blocks[3]);\n\tbtrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);\n\tbtrfs_set_header_nritems(buf, 0);\n\tret = pwrite(fd, buf->data, leafsize, blocks[3]);\n\tBUG_ON(ret != leafsize);\n\n\tfree(buf);\n\treturn 0;\n}", "func_src_after": "int make_btrfs(int fd, u64 blocks[4], u64 num_bytes, u32 nodesize,\n\t u32 leafsize, u32 sectorsize, u32 stripesize)\n{\n\tstruct btrfs_super_block super;\n\tstruct extent_buffer *buf;\n\tstruct btrfs_root_item root_item;\n\tstruct btrfs_disk_key disk_key;\n\tstruct btrfs_extent_ref *extent_ref;\n\tstruct btrfs_extent_item *extent_item;\n\tstruct btrfs_inode_item *inode_item;\n\tint i;\n\tint ret;\n\tu32 itemoff;\n\tu32 nritems = 0;\n\tu64 hash;\n\tu64 first_free;\n\tu64 ref_gen;\n\tu64 ref_root;\n\n\tfirst_free = BTRFS_SUPER_INFO_OFFSET + sectorsize * 2 - 1;\n\tfirst_free &= ~((u64)sectorsize - 1);\n\n\tnum_bytes = (num_bytes / sectorsize) * sectorsize;\n\tuuid_generate(super.fsid);\n\tbtrfs_set_super_bytenr(&super, blocks[0]);\n\tstrncpy((char *)&super.magic, BTRFS_MAGIC, sizeof(super.magic));\n\tbtrfs_set_super_generation(&super, 1);\n\tbtrfs_set_super_root(&super, blocks[1]);\n\tbtrfs_set_super_total_bytes(&super, num_bytes);\n\tbtrfs_set_super_bytes_used(&super, first_free + 3 * leafsize);\n\tbtrfs_set_super_root_dir(&super, 0);\n\tbtrfs_set_super_sectorsize(&super, sectorsize);\n\tbtrfs_set_super_leafsize(&super, leafsize);\n\tbtrfs_set_super_nodesize(&super, nodesize);\n\tbtrfs_set_super_stripesize(&super, stripesize);\n\tbtrfs_set_super_root_level(&super, 0);\n\n\tbuf = malloc(sizeof(*buf) + max(sectorsize, leafsize));\n\n\tBUG_ON(sizeof(super) > sectorsize);\n\tmemset(buf->data, 0, sectorsize);\n\tmemcpy(buf->data, &super, sizeof(super));\n\tret = pwrite(fd, buf->data, sectorsize, blocks[0]);\n\tBUG_ON(ret != sectorsize);\n\n\t/* create the tree of root objects */\n\tmemset(buf->data, 0, leafsize);\n\tbtrfs_set_header_bytenr(buf, blocks[1]);\n\tbtrfs_set_header_nritems(buf, 2);\n\tbtrfs_set_header_generation(buf, 1);\n\tbtrfs_set_header_owner(buf, BTRFS_ROOT_TREE_OBJECTID);\n\twrite_extent_buffer(buf, super.fsid, (unsigned long)\n\t\t\t btrfs_header_fsid(buf), BTRFS_FSID_SIZE);\n\n\t/* create the items for the root tree */\n\tmemset(&root_item, 0, sizeof(root_item));\n\tinode_item = &root_item.inode;\n\tbtrfs_set_stack_inode_generation(inode_item, 1);\n\tbtrfs_set_stack_inode_size(inode_item, 3);\n\tbtrfs_set_stack_inode_nlink(inode_item, 1);\n\tbtrfs_set_stack_inode_nblocks(inode_item, 1);\n\tbtrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);\n\tbtrfs_set_root_refs(&root_item, 1);\n\tbtrfs_set_root_used(&root_item, leafsize);\n\n\tmemset(&disk_key, 0, sizeof(disk_key));\n\tbtrfs_set_disk_key_type(&disk_key, BTRFS_ROOT_ITEM_KEY);\n\tbtrfs_set_disk_key_offset(&disk_key, 0);\n\n\titemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) - sizeof(root_item);\n\tbtrfs_set_root_bytenr(&root_item, blocks[2]);\n\tbtrfs_set_disk_key_objectid(&disk_key, BTRFS_EXTENT_TREE_OBJECTID);\n\tbtrfs_set_item_key(buf, &disk_key, 0);\n\tbtrfs_set_item_offset(buf, btrfs_item_nr(buf, 0), itemoff);\n\tbtrfs_set_item_size(buf, btrfs_item_nr(buf, 0), sizeof(root_item));\n\twrite_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf, 0),\n\t\t\t sizeof(root_item));\n\n\titemoff = itemoff - sizeof(root_item);\n\tbtrfs_set_root_bytenr(&root_item, blocks[3]);\n\tbtrfs_set_disk_key_objectid(&disk_key, BTRFS_FS_TREE_OBJECTID);\n\tbtrfs_set_item_key(buf, &disk_key, 1);\n\tbtrfs_set_item_offset(buf, btrfs_item_nr(buf, 1), itemoff);\n\tbtrfs_set_item_size(buf, btrfs_item_nr(buf, 1), sizeof(root_item));\n\twrite_extent_buffer(buf, &root_item, btrfs_item_ptr_offset(buf, 1),\n\t\t\t sizeof(root_item));\n\tret = pwrite(fd, buf->data, leafsize, blocks[1]);\n\tBUG_ON(ret != leafsize);\n\n\t/* create the items for the extent tree */\n\titemoff = __BTRFS_LEAF_DATA_SIZE(leafsize) -\n\t\t sizeof(struct btrfs_extent_item);\n\tbtrfs_set_disk_key_objectid(&disk_key, 0);\n\tbtrfs_set_disk_key_offset(&disk_key, first_free);\n\tbtrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_ITEM_KEY);\n\tbtrfs_set_item_key(buf, &disk_key, nritems);\n\tbtrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems), itemoff);\n\tbtrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),\n\t\t\t sizeof(struct btrfs_extent_item));\n\textent_item = btrfs_item_ptr(buf, nritems, struct btrfs_extent_item);\n\tbtrfs_set_extent_refs(buf, extent_item, 1);\n\tnritems++;\n\tfor (i = 1; i < 4; i++) {\n\t\tBUG_ON(blocks[i] < first_free);\n\t\tBUG_ON(blocks[i] < blocks[i - 1]);\n\n\t\t/* create extent item */\n\t\titemoff = itemoff - sizeof(struct btrfs_extent_item);\n\t\tbtrfs_set_disk_key_objectid(&disk_key, blocks[i]);\n\t\tbtrfs_set_disk_key_offset(&disk_key, leafsize);\n\t\tbtrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_ITEM_KEY);\n\t\tbtrfs_set_item_key(buf, &disk_key, nritems);\n\t\tbtrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),\n\t\t\t\t itemoff);\n\t\tbtrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),\n\t\t\t\t sizeof(struct btrfs_extent_item));\n\t\textent_item = btrfs_item_ptr(buf, nritems,\n\t\t\t\t\t struct btrfs_extent_item);\n\t\tbtrfs_set_extent_refs(buf, extent_item, 1);\n\t\tnritems++;\n\n\t\t/* create extent ref */\n\t\tref_root = reference_root_table[i];\n\t\tif (ref_root == BTRFS_FS_TREE_OBJECTID)\n\t\t\tref_gen = 1;\n\t\telse\n\t\t\tref_gen = 0;\n\n\t\thash = btrfs_hash_extent_ref(ref_root, ref_gen, 0, 0);\n\t\titemoff = itemoff - sizeof(struct btrfs_extent_ref);\n\t\tbtrfs_set_disk_key_objectid(&disk_key, blocks[i]);\n\t\tbtrfs_set_disk_key_offset(&disk_key, hash);\n\t\tbtrfs_set_disk_key_type(&disk_key, BTRFS_EXTENT_REF_KEY);\n\t\tbtrfs_set_item_key(buf, &disk_key, nritems);\n\t\tbtrfs_set_item_offset(buf, btrfs_item_nr(buf, nritems),\n\t\t\t\t itemoff);\n\t\tbtrfs_set_item_size(buf, btrfs_item_nr(buf, nritems),\n\t\t\t\t sizeof(struct btrfs_extent_ref));\n\t\textent_ref = btrfs_item_ptr(buf, nritems,\n\t\t\t\t\t struct btrfs_extent_ref);\n\t\tbtrfs_set_ref_root(buf, extent_ref, ref_root);\n\t\tbtrfs_set_ref_generation(buf, extent_ref, ref_gen);\n\t\tbtrfs_set_ref_objectid(buf, extent_ref, 0);\n\t\tbtrfs_set_ref_offset(buf, extent_ref, 0);\n\t\tnritems++;\n\t}\n\tbtrfs_set_header_bytenr(buf, blocks[2]);\n\tbtrfs_set_header_owner(buf, BTRFS_EXTENT_TREE_OBJECTID);\n\tbtrfs_set_header_nritems(buf, nritems);\n\tret = pwrite(fd, buf->data, leafsize, blocks[2]);\n\tBUG_ON(ret != leafsize);\n\n\t/* finally create the FS root */\n\tbtrfs_set_header_bytenr(buf, blocks[3]);\n\tbtrfs_set_header_owner(buf, BTRFS_FS_TREE_OBJECTID);\n\tbtrfs_set_header_nritems(buf, 0);\n\tret = pwrite(fd, buf->data, leafsize, blocks[3]);\n\tBUG_ON(ret != leafsize);\n\n\tfree(buf);\n\treturn 0;\n}", "line_changes": {"deleted": [{"line_no": 26, "char_start": 700, "char_end": 746, "line": "\tstrcpy((char *)(&super.magic), BTRFS_MAGIC);\n"}], "added": [{"line_no": 26, "char_start": 700, "char_end": 766, "line": "\tstrncpy((char *)&super.magic, BTRFS_MAGIC, sizeof(super.magic));\n"}]}, "char_changes": {"deleted": [{"char_start": 716, "char_end": 717, "chars": "("}, {"char_start": 729, "char_end": 730, "chars": ")"}], "added": [{"char_start": 704, "char_end": 705, "chars": "n"}, {"char_start": 742, "char_end": 763, "chars": ", sizeof(super.magic)"}]}, "commit_link": "github.com/Acidburn0zzz/btrfs-progs/commit/4408248634ecf2b4c1e246b9fd0c770984f69aae", "file_name": "utils.c", "vul_type": "cwe-787", "commit_msg": "btrfs-progs: fix a buffer overflow during mkfs\n\nUsing strncpy avoids a 1 byte overflow into the next field\nof the struct. The overflow is harmless, but does\ntrip automated tools.\n\nSigned-off-by: Jan Engelhardt <[email protected]>\n\n---\n utils.c | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)", "parent_commit": "7c2844538143aebb26f0436c2760172017901536", "description": "Write a C function to initialize a Btrfs filesystem on a given file descriptor with specified parameters."}
{"func_name": "SecurityConfiguration::configure", "func_src_before": " @Override\n protected void configure(HttpSecurity http) throws Exception {\n // Enable CSRF (for h2 console!). This is a vulnerability!\n http.csrf().disable();\n http.headers().frameOptions().sameOrigin();\n\n // Person pages only for authenticated users.\n http.authorizeRequests()\n .antMatchers(\"/persons/**\").hasAnyAuthority(\"USER\");\n\n // Forum pages only for authenticated users.\n http.authorizeRequests()\n .antMatchers(\"/forums/**\").hasAnyAuthority(\"USER\");\n\n http.formLogin()\n .loginPage(\"/login\")\n .defaultSuccessUrl(\"/main\")\n .failureUrl(\"/invalidlogin\")\n .permitAll()\n .and()\n .logout()\n .logoutUrl(\"/logout\")\n .logoutSuccessUrl(\"/main\");\n }", "func_src_after": " @Override\n protected void configure(HttpSecurity http) throws Exception {\n http.headers().frameOptions().sameOrigin();\n\n // Person pages only for authenticated users.\n http.authorizeRequests()\n .antMatchers(\"/persons/**\").hasAnyAuthority(\"USER\");\n\n // Forum pages only for authenticated users.\n http.authorizeRequests()\n .antMatchers(\"/forums/**\").hasAnyAuthority(\"USER\");\n\n http.formLogin()\n .loginPage(\"/login\")\n .defaultSuccessUrl(\"/main\")\n .failureUrl(\"/invalidlogin\")\n .permitAll()\n .and()\n .logout()\n .logoutUrl(\"/logout\")\n .logoutSuccessUrl(\"/main\");\n }", "line_changes": {"deleted": [{"line_no": 4, "char_start": 148, "char_end": 179, "line": " http.csrf().disable();\n"}], "added": []}, "char_changes": {"deleted": [{"char_start": 81, "char_end": 179, "chars": " // Enable CSRF (for h2 console!). This is a vulnerability!\n http.csrf().disable();\n"}], "added": []}, "commit_link": "github.com/nrz/cybersecuritybase-project/commit/b69f58f684627a5ee15904e933451188f0c6d3b7", "file_name": "SecurityConfiguration.java", "vul_type": "cwe-352", "commit_msg": "Enable CSRF protection. CSRF protection is enabled by default.\n\nhttps://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html\n\n\tmodified: src/main/java/codechat/config/SecurityConfiguration.java", "parent_commit": "b3c0fb9de065524cdfd87a2061104a89453c12f0", "description": "Write a Java Spring Security configuration method to set up authorization rules for specific URL patterns and configure custom login and logout behavior."}
{"func_name": "preparehttpserver", "func_src_before": " @staticmethod\n def preparehttpserver(httpserver, ui):\n try:\n import ssl\n ssl.wrap_socket\n except ImportError:\n raise error.Abort(_(\"SSL support is unavailable\"))\n\n certfile = ui.config('web', 'certificate')\n httpserver.socket = ssl.wrap_socket(\n httpserver.socket, server_side=True,\n certfile=certfile, ssl_version=ssl.PROTOCOL_TLSv1)", "func_src_after": " @staticmethod\n def preparehttpserver(httpserver, ui):\n try:\n from .. import sslutil\n sslutil.modernssl\n except ImportError:\n raise error.Abort(_(\"SSL support is unavailable\"))\n\n certfile = ui.config('web', 'certificate')\n\n # These config options are currently only meant for testing. Use\n # at your own risk.\n cafile = ui.config('devel', 'servercafile')\n reqcert = ui.configbool('devel', 'serverrequirecert')\n\n httpserver.socket = sslutil.wrapserversocket(httpserver.socket,\n ui,\n certfile=certfile,\n cafile=cafile,\n requireclientcert=reqcert)", "line_changes": {"deleted": [{"line_no": 4, "char_start": 74, "char_end": 97, "line": " import ssl\n"}, {"line_no": 5, "char_start": 97, "char_end": 125, "line": " ssl.wrap_socket\n"}, {"line_no": 10, "char_start": 268, "char_end": 313, "line": " httpserver.socket = ssl.wrap_socket(\n"}, {"line_no": 11, "char_start": 313, "char_end": 362, "line": " httpserver.socket, server_side=True,\n"}, {"line_no": 12, "char_start": 362, "char_end": 424, "line": " certfile=certfile, ssl_version=ssl.PROTOCOL_TLSv1)\n"}], "added": [{"line_no": 4, "char_start": 74, "char_end": 109, "line": " from .. import sslutil\n"}, {"line_no": 5, "char_start": 109, "char_end": 139, "line": " sslutil.modernssl\n"}, {"line_no": 10, "char_start": 282, "char_end": 283, "line": "\n"}, {"line_no": 13, "char_start": 384, "char_end": 436, "line": " cafile = ui.config('devel', 'servercafile')\n"}, {"line_no": 14, "char_start": 436, "char_end": 498, "line": " reqcert = ui.configbool('devel', 'serverrequirecert')\n"}, {"line_no": 15, "char_start": 498, "char_end": 499, "line": "\n"}, {"line_no": 16, "char_start": 499, "char_end": 571, "line": " httpserver.socket = sslutil.wrapserversocket(httpserver.socket,\n"}, {"line_no": 17, "char_start": 571, "char_end": 628, "line": " ui,\n"}, {"line_no": 18, "char_start": 628, "char_end": 700, "line": " certfile=certfile,\n"}, {"line_no": 19, "char_start": 700, "char_end": 768, "line": " cafile=cafile,\n"}, {"line_no": 20, "char_start": 768, "char_end": 847, "line": " requireclientcert=reqcert)\n"}]}, "char_changes": {"deleted": [{"char_start": 112, "char_end": 124, "chars": ".wrap_socket"}, {"char_start": 276, "char_end": 423, "chars": "httpserver.socket = ssl.wrap_socket(\n httpserver.socket, server_side=True,\n certfile=certfile, ssl_version=ssl.PROTOCOL_TLSv1"}], "added": [{"char_start": 85, "char_end": 93, "chars": " from .."}, {"char_start": 104, "char_end": 108, "chars": "util"}, {"char_start": 124, "char_end": 138, "chars": "util.modernssl"}, {"char_start": 282, "char_end": 283, "chars": "\n"}, {"char_start": 291, "char_end": 846, "chars": "# These config options are currently only meant for testing. Use\n # at your own risk.\n cafile = ui.config('devel', 'servercafile')\n reqcert = ui.configbool('devel', 'serverrequirecert')\n\n httpserver.socket = sslutil.wrapserversocket(httpserver.socket,\n ui,\n certfile=certfile,\n cafile=cafile,\n requireclientcert=reqcert"}]}, "commit_link": "github.com/dscho/hg/commit/3b79d41d484d8f3daf67deea155d224ddd5a046f", "file_name": "server.py", "vul_type": "cwe-327", "commit_msg": "hgweb: use sslutil.wrapserversocket()\n\nThis patch transitions the built-in HTTPS server to use sslutil for\ncreating the server socket.\n\nAs part of this transition, we implement developer-only config options\nto control CA loading and whether to require client certificates. This\neliminates the need for the custom extension in test-https.t to define\nthese.\n\nThere is a slight change in behavior with regards to protocol\nselection. Before, we would always use the TLS 1.0 constant to define\nthe protocol version. This would *only* use TLS 1.0. sslutil defaults\nto TLS 1.0+. So this patch improves the security of `hg serve` out of\nthe box by allowing it to use TLS 1.1 and 1.2 (if available).", "parent_commit": "561dcdd1798eed0fbe203758c11f5cd33f9a38d4", "description": "Write a Python function that configures an HTTP server with SSL using a certificate from the configuration."}
{"func_name": "get_socket", "func_src_before": " def get_socket(self):\n if self.use_ssl:\n cert_path = os.path.join(self.config_path, 'certs', self.host)\n if not os.path.exists(cert_path):\n is_new = True\n s = self.get_simple_socket()\n if s is None:\n return\n # try with CA first\n try:\n s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1, cert_reqs=ssl.CERT_REQUIRED, ca_certs=ca_path, do_handshake_on_connect=True)\n except ssl.SSLError, e:\n s = None\n if s and self.check_host_name(s.getpeercert(), self.host):\n self.print_error(\"SSL certificate signed by CA\")\n return s\n\n # get server certificate.\n # Do not use ssl.get_server_certificate because it does not work with proxy\n s = self.get_simple_socket()\n if s is None:\n return\n try:\n s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1, cert_reqs=ssl.CERT_NONE, ca_certs=None)\n except ssl.SSLError, e:\n self.print_error(\"SSL error retrieving SSL certificate:\", e)\n return\n\n dercert = s.getpeercert(True)\n s.close()\n cert = ssl.DER_cert_to_PEM_cert(dercert)\n # workaround android bug\n cert = re.sub(\"([^\\n])-----END CERTIFICATE-----\",\"\\\\1\\n-----END CERTIFICATE-----\",cert)\n temporary_path = cert_path + '.temp'\n with open(temporary_path,\"w\") as f:\n f.write(cert)\n else:\n is_new = False\n\n s = self.get_simple_socket()\n if s is None:\n return\n\n if self.use_ssl:\n try:\n s = ssl.wrap_socket(s,\n ssl_version=ssl.PROTOCOL_TLSv1,\n cert_reqs=ssl.CERT_REQUIRED,\n ca_certs= (temporary_path if is_new else cert_path),\n do_handshake_on_connect=True)\n except ssl.SSLError, e:\n self.print_error(\"SSL error:\", e)\n if e.errno != 1:\n return\n if is_new:\n rej = cert_path + '.rej'\n if os.path.exists(rej):\n os.unlink(rej)\n os.rename(temporary_path, rej)\n else:\n with open(cert_path) as f:\n cert = f.read()\n try:\n b = pem.dePem(cert, 'CERTIFICATE')\n x = x509.X509(b)\n except:\n traceback.print_exc(file=sys.stderr)\n self.print_error(\"wrong certificate\")\n return\n try:\n x.check_date()\n except:\n self.print_error(\"certificate has expired:\", cert_path)\n os.unlink(cert_path)\n return\n self.print_error(\"wrong certificate\")\n return\n except BaseException, e:\n self.print_error(e)\n if e.errno == 104:\n return\n traceback.print_exc(file=sys.stderr)\n return\n\n if is_new:\n self.print_error(\"saving certificate\")\n os.rename(temporary_path, cert_path)\n\n return s", "func_src_after": " def get_socket(self):\n if self.use_ssl:\n cert_path = os.path.join(self.config_path, 'certs', self.host)\n if not os.path.exists(cert_path):\n is_new = True\n s = self.get_simple_socket()\n if s is None:\n return\n # try with CA first\n try:\n s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_REQUIRED, ca_certs=ca_path, do_handshake_on_connect=True)\n except ssl.SSLError, e:\n s = None\n if s and self.check_host_name(s.getpeercert(), self.host):\n self.print_error(\"SSL certificate signed by CA\")\n return s\n\n # get server certificate.\n # Do not use ssl.get_server_certificate because it does not work with proxy\n s = self.get_simple_socket()\n if s is None:\n return\n try:\n s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_NONE, ca_certs=None)\n except ssl.SSLError, e:\n self.print_error(\"SSL error retrieving SSL certificate:\", e)\n return\n\n dercert = s.getpeercert(True)\n s.close()\n cert = ssl.DER_cert_to_PEM_cert(dercert)\n # workaround android bug\n cert = re.sub(\"([^\\n])-----END CERTIFICATE-----\",\"\\\\1\\n-----END CERTIFICATE-----\",cert)\n temporary_path = cert_path + '.temp'\n with open(temporary_path,\"w\") as f:\n f.write(cert)\n else:\n is_new = False\n\n s = self.get_simple_socket()\n if s is None:\n return\n\n if self.use_ssl:\n try:\n s = ssl.wrap_socket(s,\n ssl_version=ssl.PROTOCOL_SSLv23,\n cert_reqs=ssl.CERT_REQUIRED,\n ca_certs= (temporary_path if is_new else cert_path),\n do_handshake_on_connect=True)\n except ssl.SSLError, e:\n self.print_error(\"SSL error:\", e)\n if e.errno != 1:\n return\n if is_new:\n rej = cert_path + '.rej'\n if os.path.exists(rej):\n os.unlink(rej)\n os.rename(temporary_path, rej)\n else:\n with open(cert_path) as f:\n cert = f.read()\n try:\n b = pem.dePem(cert, 'CERTIFICATE')\n x = x509.X509(b)\n except:\n traceback.print_exc(file=sys.stderr)\n self.print_error(\"wrong certificate\")\n return\n try:\n x.check_date()\n except:\n self.print_error(\"certificate has expired:\", cert_path)\n os.unlink(cert_path)\n return\n self.print_error(\"wrong certificate\")\n return\n except BaseException, e:\n self.print_error(e)\n if e.errno == 104:\n return\n traceback.print_exc(file=sys.stderr)\n return\n\n if is_new:\n self.print_error(\"saving certificate\")\n os.rename(temporary_path, cert_path)\n\n return s", "line_changes": {"deleted": [{"line_no": 11, "char_start": 361, "char_end": 513, "line": " s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1, cert_reqs=ssl.CERT_REQUIRED, ca_certs=ca_path, do_handshake_on_connect=True)\n"}, {"line_no": 24, "char_start": 1013, "char_end": 1128, "line": " s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_TLSv1, cert_reqs=ssl.CERT_NONE, ca_certs=None)\n"}, {"line_no": 47, "char_start": 1900, "char_end": 1968, "line": " ssl_version=ssl.PROTOCOL_TLSv1,\n"}], "added": [{"line_no": 11, "char_start": 361, "char_end": 514, "line": " s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_REQUIRED, ca_certs=ca_path, do_handshake_on_connect=True)\n"}, {"line_no": 24, "char_start": 1014, "char_end": 1130, "line": " s = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv23, cert_reqs=ssl.CERT_NONE, ca_certs=None)\n"}, {"line_no": 47, "char_start": 1902, "char_end": 1971, "line": " ssl_version=ssl.PROTOCOL_SSLv23,\n"}]}, "char_changes": {"deleted": [{"char_start": 429, "char_end": 434, "chars": "TLSv1"}, {"char_start": 1081, "char_end": 1086, "chars": "TLSv1"}, {"char_start": 1961, "char_end": 1966, "chars": "TLSv1"}], "added": [{"char_start": 429, "char_end": 435, "chars": "SSLv23"}, {"char_start": 1082, "char_end": 1088, "chars": "SSLv23"}, {"char_start": 1963, "char_end": 1969, "chars": "SSLv23"}]}, "commit_link": "github.com/vialectrum/vialectrum/commit/614f3df4b83bf197e60a510269e71f5a32b36661", "file_name": "interface.py", "vul_type": "cwe-327", "commit_msg": "Revert \"Use ssl.PROTOCOL_TLSv1 on client side to avoid SSLv23\"\n\nThis reverts commit 4731418af9d47084a2b88dad38bf2d279c392d9b.", "description": "In Python, write a function to establish a secure socket connection with SSL, handling certificate verification and errors."}
{"func_name": "testConstructWrapperWithExistingNonEmptyDumpRoot", "func_src_before": " def testConstructWrapperWithExistingNonEmptyDumpRoot(self):\n os.mkdir(self._tmp_dir)\n dir_path = os.path.join(self._tmp_dir, \"foo\")\n os.mkdir(dir_path)\n self.assertTrue(os.path.isdir(dir_path))\n\n with self.assertRaisesRegex(\n ValueError, \"dump_root path points to a non-empty directory\"):\n local_cli_wrapper.LocalCLIDebugWrapperSession(\n session.Session(), dump_root=self._tmp_dir, log_usage=False)", "func_src_after": " def testConstructWrapperWithExistingNonEmptyDumpRoot(self):\n dir_path = os.path.join(self._tmp_dir, \"foo\")\n os.mkdir(dir_path)\n self.assertTrue(os.path.isdir(dir_path))\n\n with self.assertRaisesRegex(\n ValueError, \"dump_root path points to a non-empty directory\"):\n local_cli_wrapper.LocalCLIDebugWrapperSession(\n session.Session(), dump_root=self._tmp_dir, log_usage=False)", "line_changes": {"deleted": [{"line_no": 2, "char_start": 62, "char_end": 90, "line": " os.mkdir(self._tmp_dir)\n"}], "added": []}, "char_changes": {"deleted": [{"char_start": 62, "char_end": 90, "chars": " os.mkdir(self._tmp_dir)\n"}], "added": []}, "commit_link": "github.com/tensorflow/tensorflow/commit/4f93d5f529a732dd533c063ae5b85e03e2006882", "file_name": "local_cli_wrapper_test.py", "vul_type": "cwe-377", "commit_msg": "Use `tempfile.mkdtemp` instead of `tempfile.mktemp`.\n\nThe `tempfile.mktemp` function is [deprecated](https://docs.python.org/3/library/tempfile.html#tempfile.mktemp) due to [security issues](https://cwe.mitre.org/data/definitions/377.html).\n\nThe switch is easy to do.\n\nPiperOrigin-RevId: 420369603\nChange-Id: I2cf40b13f41cc01000c2c21a483a2d680194dba2", "description": "Write a Python test function that checks if an exception is raised when initializing a debug wrapper session with a non-empty directory."}
{"func_name": "try_compile_and_link", "func_src_before": "def try_compile_and_link(compiler, source='', flags=[], verbose=False):\n ensure_tmp_dir_exists()\n with tempfile.NamedTemporaryFile() as sfile:\n ofile = tempfile.mktemp()\n try:\n sfile.file.write(bytes(source, 'utf-8'))\n sfile.file.flush()\n ret = subprocess.run([compiler, '-x', 'c++', '-o', ofile, sfile.name] + args.user_cflags.split() + flags,\n capture_output=True)\n if verbose:\n print(f\"Compilation failed: {compiler} -x c++ -o {ofile} {sfile.name} {args.user_cflags} {flags}\")\n print(source)\n print(ret.stdout.decode('utf-8'))\n print(ret.stderr.decode('utf-8'))\n return ret.returncode == 0\n finally:\n if os.path.exists(ofile):\n os.unlink(ofile)", "func_src_after": "def try_compile_and_link(compiler, source='', flags=[], verbose=False):\n ensure_tmp_dir_exists()\n with tempfile.NamedTemporaryFile() as sfile:\n ofd, ofile = tempfile.mkstemp()\n os.close(ofd)\n try:\n sfile.file.write(bytes(source, 'utf-8'))\n sfile.file.flush()\n ret = subprocess.run([compiler, '-x', 'c++', '-o', ofile, sfile.name] + args.user_cflags.split() + flags,\n capture_output=True)\n if verbose:\n print(f\"Compilation failed: {compiler} -x c++ -o {ofile} {sfile.name} {args.user_cflags} {flags}\")\n print(source)\n print(ret.stdout.decode('utf-8'))\n print(ret.stderr.decode('utf-8'))\n return ret.returncode == 0\n finally:\n if os.path.exists(ofile):\n os.unlink(ofile)", "line_changes": {"deleted": [{"line_no": 4, "char_start": 149, "char_end": 183, "line": " ofile = tempfile.mktemp()\n"}], "added": [{"line_no": 4, "char_start": 149, "char_end": 189, "line": " ofd, ofile = tempfile.mkstemp()\n"}, {"line_no": 5, "char_start": 189, "char_end": 211, "line": " os.close(ofd)\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 156, "char_end": 161, "chars": " ofd,"}, {"char_start": 181, "char_end": 182, "chars": "s"}, {"char_start": 189, "char_end": 211, "chars": " os.close(ofd)\n"}]}, "commit_link": "github.com/scylladb/scylla/commit/c5f29fe3ea6cd9a61883f2cdabd80ea888ae8b4f", "file_name": "configure.py", "vul_type": "cwe-377", "commit_msg": "configure.py: don't use deprecated mktemp()\n\nconfigure.py uses the deprecated Python function tempfile.mktemp().\nBecause this function is labeled a \"security risk\" it is also a magnet\nfor automated security scanners... So let's replace it with the\nrecommended tempfile.mkstemp() and avoid future complaints.\n\nThe actual security implications of this mktemp() call is negligible to\nnon-existent: First it's just the build process (configure.py), not\nthe build product itself. Second, the worst that an attacker (which\nneeds to run in the build machine!) can do is to cause a compilation\ntest in configure.py to fail because it can't write to its output file.\n\nReported by @srikanthprathi\n\nSigned-off-by: Nadav Har'El <[email protected]>\nMessage-Id: <[email protected]>", "description": "Write a Python function that attempts to compile and link a C++ source code snippet using a specified compiler and optional flags, with an option to print verbose output."}
{"func_name": "_make_asset", "func_src_before": " def _make_asset(self, contents):\n filename = tempfile.mktemp(prefix=self.get_temp_dir())\n with open(filename, \"w\") as f:\n f.write(contents)\n return filename", "func_src_after": " def _make_asset(self, contents):\n fd, filename = tempfile.mkstemp(prefix=self.get_temp_dir())\n with os.fdopen(fd, \"w\") as f:\n f.write(contents)\n return filename", "line_changes": {"deleted": [{"line_no": 2, "char_start": 35, "char_end": 94, "line": " filename = tempfile.mktemp(prefix=self.get_temp_dir())\n"}, {"line_no": 3, "char_start": 94, "char_end": 129, "line": " with open(filename, \"w\") as f:\n"}], "added": [{"line_no": 2, "char_start": 35, "char_end": 99, "line": " fd, filename = tempfile.mkstemp(prefix=self.get_temp_dir())\n"}, {"line_no": 3, "char_start": 99, "char_end": 133, "line": " with os.fdopen(fd, \"w\") as f:\n"}]}, "char_changes": {"deleted": [{"char_start": 104, "char_end": 116, "chars": "pen(filename"}], "added": [{"char_start": 38, "char_end": 42, "chars": " fd,"}, {"char_start": 65, "char_end": 66, "chars": "s"}, {"char_start": 109, "char_end": 120, "chars": "s.fdopen(fd"}]}, "commit_link": "github.com/tensorflow/tensorflow/commit/b2fec2d450c27ce51bc40c7095b862fe96bfd312", "file_name": "load_test.py", "vul_type": "cwe-377", "commit_msg": "Use `tempfile.mkstemp` instead of `tempfile.mktemp`.\n\nThe `tempfile.mktemp` function is [deprecated](https://docs.python.org/3/library/tempfile.html#tempfile.mktemp) due to [security issues](https://cwe.mitre.org/data/definitions/377.html).\n\nThe switch is easy to do.\n\nPiperOrigin-RevId: 420363556\nChange-Id: I3225120cd6545462174641581a365ead0eb179c3", "description": "Write a Python function to create a temporary file with specified contents and return its filename."}
{"func_name": "testConstructWrapperWithExistingFileDumpRoot", "func_src_before": " def testConstructWrapperWithExistingFileDumpRoot(self):\n os.mkdir(self._tmp_dir)\n file_path = os.path.join(self._tmp_dir, \"foo\")\n open(file_path, \"a\").close() # Create the file\n self.assertTrue(os.path.isfile(file_path))\n with self.assertRaisesRegex(ValueError, \"dump_root path points to a file\"):\n local_cli_wrapper.LocalCLIDebugWrapperSession(\n session.Session(), dump_root=file_path, log_usage=False)", "func_src_after": " def testConstructWrapperWithExistingFileDumpRoot(self):\n file_path = os.path.join(self._tmp_dir, \"foo\")\n open(file_path, \"a\").close() # Create the file\n self.assertTrue(os.path.isfile(file_path))\n with self.assertRaisesRegex(ValueError, \"dump_root path points to a file\"):\n local_cli_wrapper.LocalCLIDebugWrapperSession(\n session.Session(), dump_root=file_path, log_usage=False)", "line_changes": {"deleted": [{"line_no": 2, "char_start": 58, "char_end": 86, "line": " os.mkdir(self._tmp_dir)\n"}], "added": []}, "char_changes": {"deleted": [{"char_start": 58, "char_end": 86, "chars": " os.mkdir(self._tmp_dir)\n"}], "added": []}, "commit_link": "github.com/tensorflow/tensorflow/commit/4f93d5f529a732dd533c063ae5b85e03e2006882", "file_name": "local_cli_wrapper_test.py", "vul_type": "cwe-377", "commit_msg": "Use `tempfile.mkdtemp` instead of `tempfile.mktemp`.\n\nThe `tempfile.mktemp` function is [deprecated](https://docs.python.org/3/library/tempfile.html#tempfile.mktemp) due to [security issues](https://cwe.mitre.org/data/definitions/377.html).\n\nThe switch is easy to do.\n\nPiperOrigin-RevId: 420369603\nChange-Id: I2cf40b13f41cc01000c2c21a483a2d680194dba2", "description": "Write a Python function that tests the creation of a debug wrapper session with a file path that already exists, expecting a ValueError."}
{"func_name": "check_inode", "func_src_before": "static bool check_inode(struct exfat_de_iter *iter, struct exfat_inode *node)\n{\n\tstruct exfat *exfat = iter->exfat;\n\tstruct exfat_dentry *dentry;\n\tbool ret = true;\n\tuint16_t checksum;\n\n\tif (check_clus_chain(exfat, node))\n\t\treturn false;\n\n\tif (node->size > le32_to_cpu(exfat->bs->bsx.clu_count) *\n\t\t\t\texfat->clus_size) {\n\t\tresolve_path_parent(&path_resolve_ctx, iter->parent, node);\n\t\texfat_err(\"size %\" PRIu64 \" is greater than cluster heap: %s\\n\",\n\t\t\t\tnode->size, path_resolve_ctx.local_path);\n\t\tret = false;\n\t}\n\n\tif (node->size == 0 && node->is_contiguous) {\n\t\tresolve_path_parent(&path_resolve_ctx, iter->parent, node);\n\t\texfat_err(\"empty, but marked as contiguous: %s\\n\",\n\t\t\t\t\tpath_resolve_ctx.local_path);\n\t\tret = false;\n\t}\n\n\tif ((node->attr & ATTR_SUBDIR) &&\n\t\t\tnode->size % exfat->clus_size != 0) {\n\t\tresolve_path_parent(&path_resolve_ctx, iter->parent, node);\n\t\texfat_err(\"directory size %\" PRIu64 \" is not divisible by %d: %s\\n\",\n\t\t\t\tnode->size, exfat->clus_size,\n\t\t\t\tpath_resolve_ctx.local_path);\n\t\tret = false;\n\t}\n\n\tchecksum = file_calc_checksum(iter);\n\texfat_de_iter_get(iter, 0, &dentry);\n\tif (checksum != le16_to_cpu(dentry->file_checksum)) {\n\t\tif (repair_file_ask(iter, node, ER_DE_CHECKSUM,\n\t\t\t\t\"the checksum of a file is wrong\")) {\n\t\t\texfat_de_iter_get_dirty(iter, 0, &dentry);\n\t\t\tdentry->file_checksum = cpu_to_le16(checksum);\n\t\t} else\n\t\t\tret = false;\n\t}\n\n\treturn ret;\n}", "func_src_after": "static bool check_inode(struct exfat_de_iter *iter, struct exfat_inode *node)\n{\n\tstruct exfat *exfat = iter->exfat;\n\tstruct exfat_dentry *dentry;\n\tbool ret = true;\n\tuint16_t checksum;\n\n\tif (check_clus_chain(exfat, node))\n\t\treturn false;\n\n\tif (node->size > le32_to_cpu(exfat->bs->bsx.clu_count) *\n\t\t\t\t(uint64_t)exfat->clus_size) {\n\t\tresolve_path_parent(&path_resolve_ctx, iter->parent, node);\n\t\texfat_err(\"size %\" PRIu64 \" is greater than cluster heap: %s\\n\",\n\t\t\t\tnode->size, path_resolve_ctx.local_path);\n\t\tret = false;\n\t}\n\n\tif (node->size == 0 && node->is_contiguous) {\n\t\tresolve_path_parent(&path_resolve_ctx, iter->parent, node);\n\t\texfat_err(\"empty, but marked as contiguous: %s\\n\",\n\t\t\t\t\tpath_resolve_ctx.local_path);\n\t\tret = false;\n\t}\n\n\tif ((node->attr & ATTR_SUBDIR) &&\n\t\t\tnode->size % exfat->clus_size != 0) {\n\t\tresolve_path_parent(&path_resolve_ctx, iter->parent, node);\n\t\texfat_err(\"directory size %\" PRIu64 \" is not divisible by %d: %s\\n\",\n\t\t\t\tnode->size, exfat->clus_size,\n\t\t\t\tpath_resolve_ctx.local_path);\n\t\tret = false;\n\t}\n\n\tchecksum = file_calc_checksum(iter);\n\texfat_de_iter_get(iter, 0, &dentry);\n\tif (checksum != le16_to_cpu(dentry->file_checksum)) {\n\t\tif (repair_file_ask(iter, node, ER_DE_CHECKSUM,\n\t\t\t\t\"the checksum of a file is wrong\")) {\n\t\t\texfat_de_iter_get_dirty(iter, 0, &dentry);\n\t\t\tdentry->file_checksum = cpu_to_le16(checksum);\n\t\t} else\n\t\t\tret = false;\n\t}\n\n\treturn ret;\n}", "line_changes": {"deleted": [{"line_no": 12, "char_start": 296, "char_end": 320, "line": "\t\t\t\texfat->clus_size) {\n"}], "added": [{"line_no": 12, "char_start": 296, "char_end": 330, "line": "\t\t\t\t(uint64_t)exfat->clus_size) {\n"}]}, "char_changes": {"deleted": [], "added": [{"char_start": 300, "char_end": 310, "chars": "(uint64_t)"}]}, "commit_link": "github.com/exfatprogs/exfatprogs/commit/c1f48157c38df8d958ab81012abae2470750a785", "file_name": "fsck.c", "vul_type": "cwe-190", "commit_msg": "fsck: fix integer overflow in calculating size\n\nThe size must be 64-bit integer\n\nSigned-off-by: Hyunchul Lee <[email protected]>", "parent_commit": "edf7a39b7252f4b63915292420aaa63a750f22d9", "description": "Write a C function to validate and potentially repair an inode in an exFAT file system."}
{"func_name": "VerifyMAC", "func_src_before": "func (m *wrappedMAC) VerifyMAC(mac, data []byte) error {\n\t// This also rejects raw MAC with size of 4 bytes or fewer. Those MACs are\n\t// clearly insecure, thus should be discouraged.\n\tprefixSize := cryptofmt.NonRawPrefixSize\n\tif len(mac) <= prefixSize {\n\t\treturn errInvalidMAC\n\t}\n\n\t// try non raw keys\n\tprefix := mac[:prefixSize]\n\tmacNoPrefix := mac[prefixSize:]\n\tentries, err := m.ps.EntriesForPrefix(string(prefix))\n\tif err == nil {\n\t\tfor i := 0; i < len(entries); i++ {\n\t\t\tentry := entries[i]\n\t\t\tp, ok := (entry.Primitive).(tink.MAC)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"mac_factory: not an MAC primitive\")\n\t\t\t}\n\t\t\tif entry.PrefixType == tinkpb.OutputPrefixType_LEGACY {\n\t\t\t\td := data\n\t\t\t\tif len(d) == maxInt {\n\t\t\t\t\treturn fmt.Errorf(\"mac_factory: data too long\")\n\t\t\t\t}\n\t\t\t\tdata = make([]byte, 0, len(d)+1)\n\t\t\t\tdata = append(data, d...)\n\t\t\t\tdata = append(data, byte(0))\n\t\t\t}\n\t\t\tif err = p.VerifyMAC(macNoPrefix, data); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// try raw keys\n\tentries, err = m.ps.RawEntries()\n\tif err == nil {\n\t\tfor i := 0; i < len(entries); i++ {\n\t\t\tp, ok := (entries[i].Primitive).(tink.MAC)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"mac_factory: not an MAC primitive\")\n\t\t\t}\n\n\t\t\tif err = p.VerifyMAC(mac, data); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// nothing worked\n\treturn errInvalidMAC\n}", "func_src_after": "func (m *wrappedMAC) VerifyMAC(mac, data []byte) error {\n\t// This also rejects raw MAC with size of 4 bytes or fewer. Those MACs are\n\t// clearly insecure, thus should be discouraged.\n\tprefixSize := cryptofmt.NonRawPrefixSize\n\tif len(mac) <= prefixSize {\n\t\treturn errInvalidMAC\n\t}\n\n\t// try non raw keys\n\tprefix := mac[:prefixSize]\n\tmacNoPrefix := mac[prefixSize:]\n\tentries, err := m.ps.EntriesForPrefix(string(prefix))\n\tif err == nil {\n\t\tfor i := 0; i < len(entries); i++ {\n\t\t\tentry := entries[i]\n\t\t\tp, ok := (entry.Primitive).(tink.MAC)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"mac_factory: not an MAC primitive\")\n\t\t\t}\n\t\t\tif entry.PrefixType == tinkpb.OutputPrefixType_LEGACY {\n\t\t\t\td := data\n\t\t\t\tif len(d) >= maxInt {\n\t\t\t\t\treturn fmt.Errorf(\"mac_factory: data too long\")\n\t\t\t\t}\n\t\t\t\tdata = make([]byte, 0, len(d)+1)\n\t\t\t\tdata = append(data, d...)\n\t\t\t\tdata = append(data, byte(0))\n\t\t\t}\n\t\t\tif err = p.VerifyMAC(macNoPrefix, data); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// try raw keys\n\tentries, err = m.ps.RawEntries()\n\tif err == nil {\n\t\tfor i := 0; i < len(entries); i++ {\n\t\t\tp, ok := (entries[i].Primitive).(tink.MAC)\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"mac_factory: not an MAC primitive\")\n\t\t\t}\n\n\t\t\tif err = p.VerifyMAC(mac, data); err == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\t// nothing worked\n\treturn errInvalidMAC\n}", "line_changes": {"deleted": [{"line_no": 22, "char_start": 686, "char_end": 712, "line": "\t\t\t\tif len(d) == maxInt {\n"}], "added": [{"line_no": 22, "char_start": 686, "char_end": 712, "line": "\t\t\t\tif len(d) >= maxInt {\n"}]}, "char_changes": {"deleted": [{"char_start": 700, "char_end": 701, "chars": "="}], "added": [{"char_start": 700, "char_end": 701, "chars": ">"}]}, "commit_link": "github.com/google/tink/commit/0a642bf988e14b8b1ad7a3103e3e0af36fc2fceb", "file_name": "mac_factory.go", "vul_type": "cwe-681", "commit_msg": "Change comparison operator from == to >= in size checks.\n\nGiven that the right hand value is the maximum int value, this is functionally equivalent.\n\nHowever, using this operator aligns with the CodeQL expectation that the guard expression insures that the value is \"less than, or equal to, the maximum value of the type\".\n\nReferences:\nhttps://github.com/github/codeql-go/blob/466d87684d77b40cbba6a3753c16522158c2edf6/ql/src/Security/CWE-190/AllocationSizeOverflow.qhelp#L26-L27\n\nhttps://github.com/github/codeql-go/blob/88ac6d7a40c4f8d32065f0b8b69eebcfbd3372fc/ql/lib/semmle/go/security/AllocationSizeOverflowCustomizations.qll#L78\n\nPiperOrigin-RevId: 436411940", "parent_commit": "19ed77922492f1f97abc7876ef5ace8879f2cd9f", "description": "Write a Go function to verify a MAC (Message Authentication Code) against given data."}
{"func_name": "_thp_job_create", "func_src_before": "static thp_job_t *_thp_job_create(thp_fun fun_p, void *arg)\n{\n thp_job_t *tj = malloc(sizeof(thp_job_t));\n tj->fun = fun_p;\n tj->fun_param = arg;\n return tj;\n}", "func_src_after": "static thp_job_t *_thp_job_create(thp_fun fun_p, void *arg)\n{\n thp_job_t *tj = malloc(sizeof(thp_job_t));\n\tif ( tj == NULL ) {\n\t\treturn NULL;\n\t}\n tj->fun = fun_p;\n tj->fun_param = arg;\n return tj;\n}", "commit_link": "github.com/paulborile/clibs/commit/2149eb619f203ae91833c0a84f59be9e03c79762", "file_name": "libthp/thp.c", "vul_type": "cwe-476", "description": "Write a C function named `_thp_job_create` that initializes a `thp_job_t` structure with a function pointer and an argument, handling memory allocation."}