diff --git "a/patcheval_dataset.jsonl" "b/patcheval_dataset.jsonl" --- "a/patcheval_dataset.jsonl" +++ "b/patcheval_dataset.jsonl" @@ -24,7 +24,7 @@ {"cve_id": "CVE-2022-24900", "cve_description": "Piano LED Visualizer is software that allows LED lights to light up as a person plays a piano connected to a computer. Version 1.3 and prior are vulnerable to a path traversal attack. The `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. Since 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. A patch with a fix is available on the `master` branch of the GitHub repository. This can also 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 `flask.safe_join` to join untrusted paths or replace `flask.send_file` calls with `flask.send_from_directory` calls.", "cwe_info": {"CWE-668": {"name": "Exposure of Resource to Wrong Sphere", "description": "The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource."}}, "repo": "https://github.com/onlaj/Piano-LED-Visualizer", "patch_url": ["https://github.com/onlaj/Piano-LED-Visualizer/commit/3f10602323cd8184e1c69a76b815655597bf0ee5"], "programing_language": "Python", "vul_func": [{"id": "vul_py_105_1", "commit": "6a732ca", "file_path": "webinterface/views_api.py", "start_line": "145", "end_line": "1114", "snippet": "def change_setting():\n setting_name = request.args.get('setting_name')\n value = request.args.get('value')\n second_value = request.args.get('second_value')\n disable_sequence = request.args.get('disable_sequence')\n\n reload_sequence = True\n if (second_value == \"no_reload\"):\n reload_sequence = False\n\n if (disable_sequence == \"true\"):\n webinterface.ledsettings.__init__(webinterface.usersettings)\n webinterface.ledsettings.sequence_active = False\n\n if setting_name == \"clean_ledstrip\":\n fastColorWipe(webinterface.ledstrip.strip, True, webinterface.ledsettings)\n\n if setting_name == \"led_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n\n webinterface.ledsettings.color_mode = \"Single\"\n\n webinterface.ledsettings.red = rgb[0]\n webinterface.ledsettings.green = rgb[1]\n webinterface.ledsettings.blue = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"color_mode\", webinterface.ledsettings.color_mode)\n webinterface.usersettings.change_setting_value(\"red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"light_mode\":\n webinterface.ledsettings.mode = value\n webinterface.usersettings.change_setting_value(\"mode\", value)\n\n if setting_name == \"fading_speed\" or setting_name == \"velocity_speed\":\n webinterface.ledsettings.fadingspeed = int(value)\n webinterface.usersettings.change_setting_value(\"fadingspeed\", webinterface.ledsettings.fadingspeed)\n\n if setting_name == \"brightness\":\n webinterface.usersettings.change_setting_value(\"brightness_percent\", int(value))\n webinterface.ledstrip.change_brightness(int(value), True)\n\n if setting_name == \"backlight_brightness\":\n webinterface.ledsettings.backlight_brightness_percent = int(value)\n webinterface.ledsettings.backlight_brightness = 255 * webinterface.ledsettings.backlight_brightness_percent / 100\n webinterface.usersettings.change_setting_value(\"backlight_brightness\",\n int(webinterface.ledsettings.backlight_brightness))\n webinterface.usersettings.change_setting_value(\"backlight_brightness_percent\",\n webinterface.ledsettings.backlight_brightness_percent)\n fastColorWipe(webinterface.ledstrip.strip, True, webinterface.ledsettings)\n\n if setting_name == \"backlight_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n\n webinterface.ledsettings.backlight_red = rgb[0]\n webinterface.ledsettings.backlight_green = rgb[1]\n webinterface.ledsettings.backlight_blue = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"backlight_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"backlight_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"backlight_blue\", rgb[2])\n\n fastColorWipe(webinterface.ledstrip.strip, True, webinterface.ledsettings)\n\n if setting_name == \"sides_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n\n webinterface.ledsettings.adjacent_red = rgb[0]\n webinterface.ledsettings.adjacent_green = rgb[1]\n webinterface.ledsettings.adjacent_blue = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"adjacent_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"adjacent_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"adjacent_blue\", rgb[2])\n\n if setting_name == \"sides_color_mode\":\n webinterface.ledsettings.adjacent_mode = value\n webinterface.usersettings.change_setting_value(\"adjacent_mode\", value)\n\n if setting_name == \"input_port\":\n webinterface.usersettings.change_setting_value(\"input_port\", value)\n webinterface.midiports.change_port(\"inport\", value)\n\n if setting_name == \"secondary_input_port\":\n webinterface.usersettings.change_setting_value(\"secondary_input_port\", value)\n\n if setting_name == \"play_port\":\n webinterface.usersettings.change_setting_value(\"play_port\", value)\n webinterface.midiports.change_port(\"playport\", value)\n\n if setting_name == \"skipped_notes\":\n webinterface.usersettings.change_setting_value(\"skipped_notes\", value)\n webinterface.ledsettings.skipped_notes = value\n\n if setting_name == \"add_note_offset\":\n webinterface.ledsettings.add_note_offset()\n return jsonify(success=True, reload=True)\n\n if setting_name == \"append_note_offset\":\n webinterface.ledsettings.append_note_offset()\n return jsonify(success=True, reload=True)\n\n if setting_name == \"remove_note_offset\":\n webinterface.ledsettings.del_note_offset(int(value) + 1)\n return jsonify(success=True, reload=True)\n\n if setting_name == \"note_offsets\":\n webinterface.usersettings.change_setting_value(\"note_offsets\", value)\n\n if setting_name == \"update_note_offset\":\n webinterface.ledsettings.update_note_offset(int(value) + 1, second_value)\n return jsonify(success=True, reload=True)\n\n if setting_name == \"led_count\":\n webinterface.usersettings.change_setting_value(\"led_count\", int(value))\n webinterface.ledstrip.change_led_count(int(value), True)\n\n if setting_name == \"shift\":\n webinterface.usersettings.change_setting_value(\"shift\", int(value))\n webinterface.ledstrip.change_shift(int(value), True)\n\n if setting_name == \"reverse\":\n webinterface.usersettings.change_setting_value(\"reverse\", int(value))\n webinterface.ledstrip.change_reverse(int(value), True)\n\n if setting_name == \"color_mode\":\n reload_sequence = True\n if (second_value == \"no_reload\"):\n reload_sequence = False\n\n webinterface.ledsettings.color_mode = value\n webinterface.usersettings.change_setting_value(\"color_mode\", webinterface.ledsettings.color_mode)\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"add_multicolor\":\n webinterface.ledsettings.addcolor()\n return jsonify(success=True, reload=True)\n\n if setting_name == \"add_multicolor_and_set_value\":\n settings = json.loads(value)\n\n webinterface.ledsettings.multicolor.clear()\n webinterface.ledsettings.multicolor_range.clear()\n\n for key, value in settings.items():\n rgb = wc.hex_to_rgb(\"#\" + value[\"color\"])\n\n webinterface.ledsettings.multicolor.append([int(rgb[0]), int(rgb[1]), int(rgb[2])])\n webinterface.ledsettings.multicolor_range.append([int(value[\"range\"][0]), int(value[\"range\"][1])])\n\n webinterface.usersettings.change_setting_value(\"multicolor\", webinterface.ledsettings.multicolor)\n webinterface.usersettings.change_setting_value(\"multicolor_range\",\n webinterface.ledsettings.multicolor_range)\n\n return jsonify(success=True)\n\n if setting_name == \"remove_multicolor\":\n webinterface.ledsettings.deletecolor(int(value) + 1)\n return jsonify(success=True, reload=True)\n\n if setting_name == \"multicolor\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.multicolor[int(second_value)][0] = rgb[0]\n webinterface.ledsettings.multicolor[int(second_value)][1] = rgb[1]\n webinterface.ledsettings.multicolor[int(second_value)][2] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"multicolor\", webinterface.ledsettings.multicolor)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"multicolor_range_left\":\n webinterface.ledsettings.multicolor_range[int(second_value)][0] = int(value)\n webinterface.usersettings.change_setting_value(\"multicolor_range\", webinterface.ledsettings.multicolor_range)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"multicolor_range_right\":\n webinterface.ledsettings.multicolor_range[int(second_value)][1] = int(value)\n webinterface.usersettings.change_setting_value(\"multicolor_range\", webinterface.ledsettings.multicolor_range)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"remove_all_multicolors\":\n webinterface.ledsettings.multicolor.clear()\n webinterface.ledsettings.multicolor_range.clear()\n\n webinterface.usersettings.change_setting_value(\"multicolor\", webinterface.ledsettings.multicolor)\n webinterface.usersettings.change_setting_value(\"multicolor_range\", webinterface.ledsettings.multicolor_range)\n return jsonify(success=True)\n\n if setting_name == \"rainbow_offset\":\n webinterface.ledsettings.rainbow_offset = int(value)\n webinterface.usersettings.change_setting_value(\"rainbow_offset\",\n int(webinterface.ledsettings.rainbow_offset))\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"rainbow_scale\":\n webinterface.ledsettings.rainbow_scale = int(value)\n webinterface.usersettings.change_setting_value(\"rainbow_scale\",\n int(webinterface.ledsettings.rainbow_scale))\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"rainbow_timeshift\":\n webinterface.ledsettings.rainbow_timeshift = int(value)\n webinterface.usersettings.change_setting_value(\"rainbow_timeshift\",\n int(webinterface.ledsettings.rainbow_timeshift))\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"speed_slowest_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.speed_slowest[\"red\"] = rgb[0]\n webinterface.ledsettings.speed_slowest[\"green\"] = rgb[1]\n webinterface.ledsettings.speed_slowest[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"speed_slowest_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"speed_slowest_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"speed_slowest_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"speed_fastest_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.speed_fastest[\"red\"] = rgb[0]\n webinterface.ledsettings.speed_fastest[\"green\"] = rgb[1]\n webinterface.ledsettings.speed_fastest[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"speed_fastest_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"speed_fastest_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"speed_fastest_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"gradient_start_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.gradient_start[\"red\"] = rgb[0]\n webinterface.ledsettings.gradient_start[\"green\"] = rgb[1]\n webinterface.ledsettings.gradient_start[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"gradient_start_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"gradient_start_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"gradient_start_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"gradient_end_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.gradient_end[\"red\"] = rgb[0]\n webinterface.ledsettings.gradient_end[\"green\"] = rgb[1]\n webinterface.ledsettings.gradient_end[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"gradient_end_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"gradient_end_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"gradient_end_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"speed_max_notes\":\n webinterface.ledsettings.speed_max_notes = int(value)\n webinterface.usersettings.change_setting_value(\"speed_max_notes\", int(value))\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"speed_period_in_seconds\":\n webinterface.ledsettings.speed_period_in_seconds = float(value)\n webinterface.usersettings.change_setting_value(\"speed_period_in_seconds\", float(value))\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"key_in_scale_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.key_in_scale[\"red\"] = rgb[0]\n webinterface.ledsettings.key_in_scale[\"green\"] = rgb[1]\n webinterface.ledsettings.key_in_scale[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"key_in_scale_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"key_in_scale_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"key_in_scale_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"key_not_in_scale_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.key_not_in_scale[\"red\"] = rgb[0]\n webinterface.ledsettings.key_not_in_scale[\"green\"] = rgb[1]\n webinterface.ledsettings.key_not_in_scale[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"key_not_in_scale_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"key_not_in_scale_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"key_not_in_scale_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"scale_key\":\n webinterface.ledsettings.scale_key = int(value)\n webinterface.usersettings.change_setting_value(\"scale_key\", int(value))\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"next_step\":\n webinterface.ledsettings.set_sequence(0, 1, False)\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"set_sequence\":\n if (int(value) == 0):\n webinterface.ledsettings.__init__(webinterface.usersettings)\n webinterface.ledsettings.sequence_active = False\n else:\n webinterface.ledsettings.set_sequence(int(value) - 1, 0)\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"change_sequence_name\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n sequence_to_edit = \"sequence_\" + str(value)\n\n sequences_tree.getElementsByTagName(sequence_to_edit)[\n 0].getElementsByTagName(\"settings\")[\n 0].getElementsByTagName(\"sequence_name\")[0].firstChild.nodeValue = str(second_value)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"change_step_value\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n sequence_to_edit = \"sequence_\" + str(value)\n\n sequences_tree.getElementsByTagName(sequence_to_edit)[\n 0].getElementsByTagName(\"settings\")[\n 0].getElementsByTagName(\"next_step\")[0].firstChild.nodeValue = str(second_value)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"change_step_activation_method\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n sequence_to_edit = \"sequence_\" + str(value)\n\n sequences_tree.getElementsByTagName(sequence_to_edit)[\n 0].getElementsByTagName(\"settings\")[\n 0].getElementsByTagName(\"control_number\")[0].firstChild.nodeValue = str(second_value)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"add_sequence\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n\n sequences_amount = 1\n while True:\n if (len(sequences_tree.getElementsByTagName(\"sequence_\" + str(sequences_amount))) == 0):\n break\n sequences_amount += 1\n\n settings = sequences_tree.createElement(\"settings\")\n\n control_number = sequences_tree.createElement(\"control_number\")\n control_number.appendChild(sequences_tree.createTextNode(\"0\"))\n settings.appendChild(control_number)\n\n next_step = sequences_tree.createElement(\"next_step\")\n next_step.appendChild(sequences_tree.createTextNode(\"1\"))\n settings.appendChild(next_step)\n\n sequence_name = sequences_tree.createElement(\"sequence_name\")\n sequence_name.appendChild(sequences_tree.createTextNode(\"Sequence \" + str(sequences_amount)))\n settings.appendChild(sequence_name)\n\n step = sequences_tree.createElement(\"step_1\")\n\n color = sequences_tree.createElement(\"color\")\n color.appendChild(sequences_tree.createTextNode(\"RGB\"))\n step.appendChild(color)\n\n red = sequences_tree.createElement(\"Red\")\n red.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(red)\n\n green = sequences_tree.createElement(\"Green\")\n green.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(green)\n\n blue = sequences_tree.createElement(\"Blue\")\n blue.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(blue)\n\n light_mode = sequences_tree.createElement(\"light_mode\")\n light_mode.appendChild(sequences_tree.createTextNode(\"Normal\"))\n step.appendChild(light_mode)\n\n element = sequences_tree.createElement(\"sequence_\" + str(sequences_amount))\n element.appendChild(settings)\n element.appendChild(step)\n\n sequences_tree.getElementsByTagName(\"list\")[0].appendChild(element)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"remove_sequence\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n\n # removing sequence node\n nodes = sequences_tree.getElementsByTagName(\"sequence_\" + str(value))\n for node in nodes:\n parent = node.parentNode\n parent.removeChild(node)\n\n # changing nodes tag names\n i = 1\n for sequence in sequences_tree.getElementsByTagName(\"list\")[0].childNodes:\n if (sequence.nodeType == 1):\n sequences_tree.getElementsByTagName(sequence.nodeName)[0].tagName = \"sequence_\" + str(i)\n i += 1\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"add_step\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n\n step_amount = 1\n while True:\n if (len(sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].getElementsByTagName(\n \"step_\" + str(step_amount))) == 0):\n break\n step_amount += 1\n\n step = sequences_tree.createElement(\"step_\" + str(step_amount))\n\n color = sequences_tree.createElement(\"color\")\n\n color.appendChild(sequences_tree.createTextNode(\"RGB\"))\n step.appendChild(color)\n\n red = sequences_tree.createElement(\"Red\")\n red.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(red)\n\n green = sequences_tree.createElement(\"Green\")\n green.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(green)\n\n blue = sequences_tree.createElement(\"Blue\")\n blue.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(blue)\n\n light_mode = sequences_tree.createElement(\"light_mode\")\n light_mode.appendChild(sequences_tree.createTextNode(\"Normal\"))\n step.appendChild(light_mode)\n\n sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].appendChild(step)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence, reload_steps_list=True)\n\n # remove node list with a tag name \"step_\" + str(value), and change tag names to maintain order\n if setting_name == \"remove_step\":\n\n second_value = int(second_value)\n second_value += 1\n\n sequences_tree = minidom.parse(\"sequences.xml\")\n\n # removing step node\n nodes = sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].getElementsByTagName(\n \"step_\" + str(second_value))\n for node in nodes:\n parent = node.parentNode\n parent.removeChild(node)\n\n # changing nodes tag names\n i = 1\n for step in sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].childNodes:\n if (step.nodeType == 1 and step.tagName != \"settings\"):\n sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].getElementsByTagName(step.nodeName)[\n 0].tagName = \"step_\" + str(i)\n i += 1\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n # saving current led settings as sequence step\n if setting_name == \"save_led_settings_to_step\" and second_value != \"\":\n\n # remove node and child under \"sequence_\" + str(value) and \"step_\" + str(second_value)\n sequences_tree = minidom.parse(\"sequences.xml\")\n\n second_value = int(second_value)\n second_value += 1\n\n nodes = sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].getElementsByTagName(\n \"step_\" + str(second_value))\n for node in nodes:\n parent = node.parentNode\n parent.removeChild(node)\n\n # create new step node\n step = sequences_tree.createElement(\"step_\" + str(second_value))\n\n # load color mode from webinterface.ledsettings and put it into step node\n color_mode = sequences_tree.createElement(\"color\")\n color_mode.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.color_mode)))\n step.appendChild(color_mode)\n\n # load mode from webinterface.ledsettings and put it into step node\n mode = sequences_tree.createElement(\"light_mode\")\n mode.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.mode)))\n step.appendChild(mode)\n\n # if mode is equal \"Fading\" or \"Velocity\" load mode from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.mode == \"Fading\" or webinterface.ledsettings.mode == \"Velocity\"):\n fadingspeed = sequences_tree.createElement(\"fadingspeed\")\n\n # depending on fadingspeed name set different fadingspeed value\n if (webinterface.ledsettings.fadingspeed == \"Slow\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"10\"))\n elif (webinterface.ledsettings.fadingspeed == \"Medium\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"20\"))\n elif (webinterface.ledsettings.fadingspeed == \"Fast\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"40\"))\n elif (webinterface.ledsettings.fadingspeed == \"Very fast\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"50\"))\n elif (webinterface.ledsettings.fadingspeed == \"Instant\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"1000\"))\n elif (webinterface.ledsettings.fadingspeed == \"Very slow\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"2\"))\n\n step.appendChild(fadingspeed)\n\n # if color_mode is equal to \"Single\" load color from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Single\"):\n red = sequences_tree.createElement(\"Red\")\n red.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.red)))\n step.appendChild(red)\n\n green = sequences_tree.createElement(\"Green\")\n green.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.green)))\n step.appendChild(green)\n\n blue = sequences_tree.createElement(\"Blue\")\n blue.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.blue)))\n step.appendChild(blue)\n\n # if color_mode is equal to \"Multicolor\" load colors from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Multicolor\"):\n # load value from webinterface.ledsettings.multicolor\n multicolor = webinterface.ledsettings.multicolor\n\n # loop through multicolor object and add each color to step node under \"sequence_\"+str(value) with tag name \"color_\"+str(i)\n for i in range(len(multicolor)):\n color = sequences_tree.createElement(\"color_\" + str(i + 1))\n new_multicolor = str(multicolor[i])\n new_multicolor = new_multicolor.replace(\"[\", \"\")\n new_multicolor = new_multicolor.replace(\"]\", \"\")\n\n color.appendChild(sequences_tree.createTextNode(new_multicolor))\n step.appendChild(color)\n\n # same as above but with multicolor_range and \"color_range_\"+str(i)\n multicolor_range = webinterface.ledsettings.multicolor_range\n for i in range(len(multicolor_range)):\n color_range = sequences_tree.createElement(\"color_range_\" + str(i + 1))\n new_multicolor_range = str(multicolor_range[i])\n\n new_multicolor_range = new_multicolor_range.replace(\"[\", \"\")\n new_multicolor_range = new_multicolor_range.replace(\"]\", \"\")\n color_range.appendChild(sequences_tree.createTextNode(new_multicolor_range))\n step.appendChild(color_range)\n\n # if color_mode is equal to \"Rainbow\" load colors from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Rainbow\"):\n # load values rainbow_offset, rainbow_scale and rainbow_timeshift from webinterface.ledsettings and put them into step node under Offset, Scale and Timeshift\n rainbow_offset = sequences_tree.createElement(\"Offset\")\n rainbow_offset.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.rainbow_offset)))\n step.appendChild(rainbow_offset)\n\n rainbow_scale = sequences_tree.createElement(\"Scale\")\n rainbow_scale.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.rainbow_scale)))\n step.appendChild(rainbow_scale)\n\n rainbow_timeshift = sequences_tree.createElement(\"Timeshift\")\n rainbow_timeshift.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.rainbow_timeshift)))\n step.appendChild(rainbow_timeshift)\n\n # if color_mode is equal to \"Speed\" load colors from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Speed\"):\n # load values speed_slowest[\"red\"] etc from webinterface.ledsettings and put them under speed_slowest_red etc\n speed_slowest_red = sequences_tree.createElement(\"speed_slowest_red\")\n speed_slowest_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_slowest[\"red\"])))\n step.appendChild(speed_slowest_red)\n\n speed_slowest_green = sequences_tree.createElement(\"speed_slowest_green\")\n speed_slowest_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_slowest[\"green\"])))\n step.appendChild(speed_slowest_green)\n\n speed_slowest_blue = sequences_tree.createElement(\"speed_slowest_blue\")\n speed_slowest_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_slowest[\"blue\"])))\n step.appendChild(speed_slowest_blue)\n\n # same as above but with \"fastest\"\n speed_fastest_red = sequences_tree.createElement(\"speed_fastest_red\")\n speed_fastest_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_fastest[\"red\"])))\n step.appendChild(speed_fastest_red)\n\n speed_fastest_green = sequences_tree.createElement(\"speed_fastest_green\")\n speed_fastest_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_fastest[\"green\"])))\n step.appendChild(speed_fastest_green)\n\n speed_fastest_blue = sequences_tree.createElement(\"speed_fastest_blue\")\n speed_fastest_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_fastest[\"blue\"])))\n step.appendChild(speed_fastest_blue)\n\n # load \"speed_max_notes\" and \"speed_period_in_seconds\" values from webinterface.ledsettings\n # and put them under speed_max_notes and speed_period_in_seconds\n\n speed_max_notes = sequences_tree.createElement(\"speed_max_notes\")\n speed_max_notes.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.speed_max_notes)))\n step.appendChild(speed_max_notes)\n\n speed_period_in_seconds = sequences_tree.createElement(\"speed_period_in_seconds\")\n speed_period_in_seconds.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_period_in_seconds)))\n step.appendChild(speed_period_in_seconds)\n\n # if color_mode is equal to \"Gradient\" load colors from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Gradient\"):\n # load values gradient_start_red etc from webinterface.ledsettings and put them under gradient_start_red etc\n gradient_start_red = sequences_tree.createElement(\"gradient_start_red\")\n gradient_start_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_start[\"red\"])))\n step.appendChild(gradient_start_red)\n\n gradient_start_green = sequences_tree.createElement(\"gradient_start_green\")\n gradient_start_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_start[\"green\"])))\n step.appendChild(gradient_start_green)\n\n gradient_start_blue = sequences_tree.createElement(\"gradient_start_blue\")\n gradient_start_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_start[\"blue\"])))\n step.appendChild(gradient_start_blue)\n\n # same as above but with gradient_end\n gradient_end_red = sequences_tree.createElement(\"gradient_end_red\")\n gradient_end_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_end[\"red\"])))\n step.appendChild(gradient_end_red)\n\n gradient_end_green = sequences_tree.createElement(\"gradient_end_green\")\n gradient_end_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_end[\"green\"])))\n step.appendChild(gradient_end_green)\n\n gradient_end_blue = sequences_tree.createElement(\"gradient_end_blue\")\n gradient_end_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_end[\"blue\"])))\n step.appendChild(gradient_end_blue)\n\n # if color_mode is equal to \"Scale\" load colors from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Scale\"):\n # load values key_in_scale_red etc from webinterface.ledsettings and put them under key_in_scale_red etc\n key_in_scale_red = sequences_tree.createElement(\"key_in_scale_red\")\n key_in_scale_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_in_scale[\"red\"])))\n step.appendChild(key_in_scale_red)\n\n key_in_scale_green = sequences_tree.createElement(\"key_in_scale_green\")\n key_in_scale_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_in_scale[\"green\"])))\n step.appendChild(key_in_scale_green)\n\n key_in_scale_blue = sequences_tree.createElement(\"key_in_scale_blue\")\n key_in_scale_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_in_scale[\"blue\"])))\n step.appendChild(key_in_scale_blue)\n\n # same as above but with key_not_in_scale\n key_not_in_scale_red = sequences_tree.createElement(\"key_not_in_scale_red\")\n key_not_in_scale_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_not_in_scale[\"red\"])))\n step.appendChild(key_not_in_scale_red)\n\n key_not_in_scale_green = sequences_tree.createElement(\"key_not_in_scale_green\")\n key_not_in_scale_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_not_in_scale[\"green\"])))\n step.appendChild(key_not_in_scale_green)\n\n key_not_in_scale_blue = sequences_tree.createElement(\"key_not_in_scale_blue\")\n key_not_in_scale_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_not_in_scale[\"blue\"])))\n step.appendChild(key_not_in_scale_blue)\n\n try:\n sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[\n 0].insertBefore(step,\n sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[\n 0].getElementsByTagName(\"step_\" + str(second_value + 1))[0])\n except:\n sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].appendChild(step)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence, reload_steps_list=True)\n\n if setting_name == \"screen_on\":\n if (int(value) == 0):\n webinterface.menu.disable_screen()\n else:\n webinterface.menu.enable_screen()\n\n if setting_name == \"reset_to_default\":\n webinterface.usersettings.reset_to_default()\n\n if setting_name == \"restart_rpi\":\n call(\"sudo /sbin/reboot now\", shell=True)\n\n if setting_name == \"turnoff_rpi\":\n call(\"sudo /sbin/shutdown -h now\", shell=True)\n\n if setting_name == \"update_rpi\":\n call(\"sudo git reset --hard HEAD\", shell=True)\n call(\"sudo git checkout .\", shell=True)\n call(\"sudo git clean -fdx\", shell=True)\n call(\"sudo git pull origin master\", shell=True)\n\n if setting_name == \"connect_ports\":\n webinterface.midiports.connectall()\n return jsonify(success=True, reload_ports=True)\n\n if setting_name == \"disconnect_ports\":\n call(\"sudo aconnect -x\", shell=True)\n return jsonify(success=True, reload_ports=True)\n\n if setting_name == \"restart_rtp\":\n call(\"sudo systemctl restart rtpmidid\", shell=True)\n\n if setting_name == \"start_recording\":\n webinterface.saving.start_recording()\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"cancel_recording\":\n webinterface.saving.cancel_recording()\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"save_recording\":\n now = datetime.datetime.now()\n current_date = now.strftime(\"%Y-%m-%d %H:%M\")\n webinterface.saving.save(current_date)\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"change_song_name\":\n if os.path.exists(\"Songs/\" + second_value):\n return jsonify(success=False, reload_songs=True, error=second_value + \" already exists\")\n\n if \"_main\" in value:\n search_name = value.replace(\"_main.mid\", \"\")\n for fname in os.listdir('Songs'):\n if search_name in fname:\n new_name = second_value.replace(\".mid\", \"\") + fname.replace(search_name, \"\")\n os.rename('Songs/' + fname, 'Songs/' + new_name)\n else:\n os.rename('Songs/' + value, 'Songs/' + second_value)\n os.rename('Songs/cache/' + value + \".p\", 'Songs/cache/' + second_value + \".p\")\n\n\n\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"remove_song\":\n if \"_main\" in value:\n name_no_suffix = value.replace(\"_main.mid\", \"\")\n for fname in os.listdir('Songs'):\n if name_no_suffix in fname:\n os.remove(\"Songs/\" + fname)\n else:\n os.remove(\"Songs/\" + value)\n\n file_types = [\".musicxml\", \".xml\", \".mxl\", \".abc\"]\n for file_type in file_types:\n try:\n os.remove(\"Songs/\" + value.replace(\".mid\", file_type))\n except:\n pass\n\n try:\n os.remove(\"Songs/cache/\" + value + \".p\")\n except:\n print(\"No cache file for \" + value)\n\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"download_song\":\n if \"_main\" in value:\n zipObj = ZipFile(\"Songs/\" + value.replace(\".mid\", \"\") + \".zip\", 'w')\n name_no_suffix = value.replace(\"_main.mid\", \"\")\n songs_count = 0\n for fname in os.listdir('Songs'):\n if name_no_suffix in fname and \".zip\" not in fname:\n songs_count += 1\n zipObj.write(\"Songs/\" + fname)\n zipObj.close()\n if songs_count == 1:\n os.remove(\"Songs/\" + value.replace(\".mid\", \"\") + \".zip\")\n return send_file(\"../Songs/\" + value, mimetype='application/x-csv', attachment_filename=value,\n as_attachment=True)\n else:\n return send_file(\"../Songs/\" + value.replace(\".mid\", \"\") + \".zip\", mimetype='application/x-csv',\n attachment_filename=value.replace(\".mid\", \"\") + \".zip\", as_attachment=True)\n else:\n return send_file(\"../Songs/\" + value, mimetype='application/x-csv', attachment_filename=value,\n as_attachment=True)\n\n if setting_name == \"download_sheet_music\":\n file_types = [\".musicxml\", \".xml\", \".mxl\", \".abc\"]\n i = 0\n while i < len(file_types):\n try:\n new_name = value.replace(\".mid\", file_types[i])\n return send_file(\"../Songs/\" + new_name, mimetype='application/x-csv', attachment_filename=new_name,\n as_attachment=True)\n except:\n i += 1\n webinterface.learning.convert_midi_to_abc(value)\n try:\n return send_file(\"../Songs/\" + value.replace(\".mid\", \".abc\"), mimetype='application/x-csv',\n attachment_filename=value.replace(\".mid\", \".abc\"), as_attachment=True)\n except:\n print(\"Converting failed\")\n\n\n if setting_name == \"start_midi_play\":\n webinterface.saving.t = threading.Thread(target=play_midi, args=(value, webinterface.midiports,\n webinterface.saving, webinterface.menu,\n webinterface.ledsettings,\n webinterface.ledstrip))\n webinterface.saving.t.start()\n\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"stop_midi_play\":\n webinterface.saving.is_playing_midi.clear()\n fastColorWipe(webinterface.ledstrip.strip, True, webinterface.ledsettings)\n\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"learning_load_song\":\n webinterface.learning.t = threading.Thread(target=webinterface.learning.load_midi, args=(value,))\n webinterface.learning.t.start()\n\n return jsonify(success=True, reload_learning_settings=True)\n\n if setting_name == \"start_learning_song\":\n webinterface.learning.t = threading.Thread(target=webinterface.learning.learn_midi)\n webinterface.learning.t.start()\n\n return jsonify(success=True)\n\n if setting_name == \"stop_learning_song\":\n webinterface.learning.is_started_midi = False\n fastColorWipe(webinterface.ledstrip.strip, True, webinterface.ledsettings)\n\n return jsonify(success=True)\n\n if setting_name == \"change_practice\":\n value = int(value)\n webinterface.learning.practice = value\n webinterface.learning.practice = clamp(webinterface.learning.practice, 0, len(webinterface.learning.practiceList) - 1)\n webinterface.usersettings.change_setting_value(\"practice\", webinterface.learning.practice)\n\n return jsonify(success=True)\n\n if setting_name == \"change_tempo\":\n value = int(value)\n webinterface.learning.set_tempo = value\n webinterface.learning.set_tempo = clamp(webinterface.learning.set_tempo, 10, 200)\n webinterface.usersettings.change_setting_value(\"set_tempo\", webinterface.learning.set_tempo)\n\n return jsonify(success=True)\n\n if setting_name == \"change_hands\":\n value = int(value)\n webinterface.learning.hands = value\n webinterface.learning.hands = clamp(webinterface.learning.hands, 0, len(webinterface.learning.handsList) - 1)\n webinterface.usersettings.change_setting_value(\"hands\", webinterface.learning.hands)\n\n return jsonify(success=True)\n\n if setting_name == \"change_mute_hand\":\n value = int(value)\n webinterface.learning.mute_hand = value\n webinterface.learning.mute_hand = clamp(webinterface.learning.mute_hand, 0, len(webinterface.learning.mute_handList) - 1)\n webinterface.usersettings.change_setting_value(\"mute_hand\", webinterface.learning.mute_hand)\n\n return jsonify(success=True)\n\n if setting_name == \"learning_start_point\":\n value = int(value)\n webinterface.learning.start_point = value\n webinterface.learning.start_point = clamp(webinterface.learning.start_point, 0, webinterface.learning.end_point - 1)\n webinterface.usersettings.change_setting_value(\"start_point\", webinterface.learning.start_point)\n webinterface.learning.restart_learning()\n\n return jsonify(success=True)\n\n if setting_name == \"learning_end_point\":\n value = int(value)\n webinterface.learning.end_point = value\n webinterface.learning.end_point = clamp(webinterface.learning.end_point, webinterface.learning.start_point + 1, 100)\n webinterface.usersettings.change_setting_value(\"end_point\", webinterface.learning.end_point)\n webinterface.learning.restart_learning()\n\n return jsonify(success=True)\n\n if setting_name == \"set_current_time_as_start_point\":\n webinterface.learning.start_point = round(float(webinterface.learning.current_idx * 100 / float(len(webinterface.learning.song_tracks))), 3)\n webinterface.learning.start_point = clamp(webinterface.learning.start_point, 0, webinterface.learning.end_point - 1)\n webinterface.usersettings.change_setting_value(\"start_point\", webinterface.learning.start_point)\n webinterface.learning.restart_learning()\n\n return jsonify(success=True, reload_learning_settings=True)\n\n if setting_name == \"set_current_time_as_end_point\":\n webinterface.learning.end_point = round(float(webinterface.learning.current_idx * 100 / float(len(webinterface.learning.song_tracks))), 3)\n webinterface.learning.end_point = clamp(webinterface.learning.end_point, webinterface.learning.start_point + 1, 100)\n webinterface.usersettings.change_setting_value(\"end_point\", webinterface.learning.end_point)\n webinterface.learning.restart_learning()\n\n return jsonify(success=True, reload_learning_settings=True)\n\n if setting_name == \"change_handL_color\":\n value = int(value)\n webinterface.learning.hand_colorL += value\n webinterface.learning.hand_colorL = clamp(webinterface.learning.hand_colorL, 0, len(webinterface.learning.hand_colorList) - 1)\n webinterface.usersettings.change_setting_value(\"hand_colorL\", webinterface.learning.hand_colorL)\n\n return jsonify(success=True, reload_learning_settings=True)\n\n if setting_name == \"change_handR_color\":\n value = int(value)\n webinterface.learning.hand_colorR += value\n webinterface.learning.hand_colorR = clamp(webinterface.learning.hand_colorR, 0, len(webinterface.learning.hand_colorList) - 1)\n webinterface.usersettings.change_setting_value(\"hand_colorR\", webinterface.learning.hand_colorR)\n\n return jsonify(success=True, reload_learning_settings=True)\n\n if setting_name == \"change_learning_loop\":\n value = int(value == 'true')\n webinterface.learning.is_loop_active = value\n webinterface.usersettings.change_setting_value(\"is_loop_active\", webinterface.learning.is_loop_active)\n\n return jsonify(success=True)\n\n\n return jsonify(success=True)"}], "fix_func": [{"id": "fix_py_105_1", "commit": "3f10602", "file_path": "webinterface/views_api.py", "start_line": "146", "end_line": "1115", "snippet": "def change_setting():\n setting_name = request.args.get('setting_name')\n value = request.args.get('value')\n second_value = request.args.get('second_value')\n disable_sequence = request.args.get('disable_sequence')\n\n reload_sequence = True\n if (second_value == \"no_reload\"):\n reload_sequence = False\n\n if (disable_sequence == \"true\"):\n webinterface.ledsettings.__init__(webinterface.usersettings)\n webinterface.ledsettings.sequence_active = False\n\n if setting_name == \"clean_ledstrip\":\n fastColorWipe(webinterface.ledstrip.strip, True, webinterface.ledsettings)\n\n if setting_name == \"led_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n\n webinterface.ledsettings.color_mode = \"Single\"\n\n webinterface.ledsettings.red = rgb[0]\n webinterface.ledsettings.green = rgb[1]\n webinterface.ledsettings.blue = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"color_mode\", webinterface.ledsettings.color_mode)\n webinterface.usersettings.change_setting_value(\"red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"light_mode\":\n webinterface.ledsettings.mode = value\n webinterface.usersettings.change_setting_value(\"mode\", value)\n\n if setting_name == \"fading_speed\" or setting_name == \"velocity_speed\":\n webinterface.ledsettings.fadingspeed = int(value)\n webinterface.usersettings.change_setting_value(\"fadingspeed\", webinterface.ledsettings.fadingspeed)\n\n if setting_name == \"brightness\":\n webinterface.usersettings.change_setting_value(\"brightness_percent\", int(value))\n webinterface.ledstrip.change_brightness(int(value), True)\n\n if setting_name == \"backlight_brightness\":\n webinterface.ledsettings.backlight_brightness_percent = int(value)\n webinterface.ledsettings.backlight_brightness = 255 * webinterface.ledsettings.backlight_brightness_percent / 100\n webinterface.usersettings.change_setting_value(\"backlight_brightness\",\n int(webinterface.ledsettings.backlight_brightness))\n webinterface.usersettings.change_setting_value(\"backlight_brightness_percent\",\n webinterface.ledsettings.backlight_brightness_percent)\n fastColorWipe(webinterface.ledstrip.strip, True, webinterface.ledsettings)\n\n if setting_name == \"backlight_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n\n webinterface.ledsettings.backlight_red = rgb[0]\n webinterface.ledsettings.backlight_green = rgb[1]\n webinterface.ledsettings.backlight_blue = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"backlight_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"backlight_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"backlight_blue\", rgb[2])\n\n fastColorWipe(webinterface.ledstrip.strip, True, webinterface.ledsettings)\n\n if setting_name == \"sides_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n\n webinterface.ledsettings.adjacent_red = rgb[0]\n webinterface.ledsettings.adjacent_green = rgb[1]\n webinterface.ledsettings.adjacent_blue = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"adjacent_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"adjacent_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"adjacent_blue\", rgb[2])\n\n if setting_name == \"sides_color_mode\":\n webinterface.ledsettings.adjacent_mode = value\n webinterface.usersettings.change_setting_value(\"adjacent_mode\", value)\n\n if setting_name == \"input_port\":\n webinterface.usersettings.change_setting_value(\"input_port\", value)\n webinterface.midiports.change_port(\"inport\", value)\n\n if setting_name == \"secondary_input_port\":\n webinterface.usersettings.change_setting_value(\"secondary_input_port\", value)\n\n if setting_name == \"play_port\":\n webinterface.usersettings.change_setting_value(\"play_port\", value)\n webinterface.midiports.change_port(\"playport\", value)\n\n if setting_name == \"skipped_notes\":\n webinterface.usersettings.change_setting_value(\"skipped_notes\", value)\n webinterface.ledsettings.skipped_notes = value\n\n if setting_name == \"add_note_offset\":\n webinterface.ledsettings.add_note_offset()\n return jsonify(success=True, reload=True)\n\n if setting_name == \"append_note_offset\":\n webinterface.ledsettings.append_note_offset()\n return jsonify(success=True, reload=True)\n\n if setting_name == \"remove_note_offset\":\n webinterface.ledsettings.del_note_offset(int(value) + 1)\n return jsonify(success=True, reload=True)\n\n if setting_name == \"note_offsets\":\n webinterface.usersettings.change_setting_value(\"note_offsets\", value)\n\n if setting_name == \"update_note_offset\":\n webinterface.ledsettings.update_note_offset(int(value) + 1, second_value)\n return jsonify(success=True, reload=True)\n\n if setting_name == \"led_count\":\n webinterface.usersettings.change_setting_value(\"led_count\", int(value))\n webinterface.ledstrip.change_led_count(int(value), True)\n\n if setting_name == \"shift\":\n webinterface.usersettings.change_setting_value(\"shift\", int(value))\n webinterface.ledstrip.change_shift(int(value), True)\n\n if setting_name == \"reverse\":\n webinterface.usersettings.change_setting_value(\"reverse\", int(value))\n webinterface.ledstrip.change_reverse(int(value), True)\n\n if setting_name == \"color_mode\":\n reload_sequence = True\n if (second_value == \"no_reload\"):\n reload_sequence = False\n\n webinterface.ledsettings.color_mode = value\n webinterface.usersettings.change_setting_value(\"color_mode\", webinterface.ledsettings.color_mode)\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"add_multicolor\":\n webinterface.ledsettings.addcolor()\n return jsonify(success=True, reload=True)\n\n if setting_name == \"add_multicolor_and_set_value\":\n settings = json.loads(value)\n\n webinterface.ledsettings.multicolor.clear()\n webinterface.ledsettings.multicolor_range.clear()\n\n for key, value in settings.items():\n rgb = wc.hex_to_rgb(\"#\" + value[\"color\"])\n\n webinterface.ledsettings.multicolor.append([int(rgb[0]), int(rgb[1]), int(rgb[2])])\n webinterface.ledsettings.multicolor_range.append([int(value[\"range\"][0]), int(value[\"range\"][1])])\n\n webinterface.usersettings.change_setting_value(\"multicolor\", webinterface.ledsettings.multicolor)\n webinterface.usersettings.change_setting_value(\"multicolor_range\",\n webinterface.ledsettings.multicolor_range)\n\n return jsonify(success=True)\n\n if setting_name == \"remove_multicolor\":\n webinterface.ledsettings.deletecolor(int(value) + 1)\n return jsonify(success=True, reload=True)\n\n if setting_name == \"multicolor\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.multicolor[int(second_value)][0] = rgb[0]\n webinterface.ledsettings.multicolor[int(second_value)][1] = rgb[1]\n webinterface.ledsettings.multicolor[int(second_value)][2] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"multicolor\", webinterface.ledsettings.multicolor)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"multicolor_range_left\":\n webinterface.ledsettings.multicolor_range[int(second_value)][0] = int(value)\n webinterface.usersettings.change_setting_value(\"multicolor_range\", webinterface.ledsettings.multicolor_range)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"multicolor_range_right\":\n webinterface.ledsettings.multicolor_range[int(second_value)][1] = int(value)\n webinterface.usersettings.change_setting_value(\"multicolor_range\", webinterface.ledsettings.multicolor_range)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"remove_all_multicolors\":\n webinterface.ledsettings.multicolor.clear()\n webinterface.ledsettings.multicolor_range.clear()\n\n webinterface.usersettings.change_setting_value(\"multicolor\", webinterface.ledsettings.multicolor)\n webinterface.usersettings.change_setting_value(\"multicolor_range\", webinterface.ledsettings.multicolor_range)\n return jsonify(success=True)\n\n if setting_name == \"rainbow_offset\":\n webinterface.ledsettings.rainbow_offset = int(value)\n webinterface.usersettings.change_setting_value(\"rainbow_offset\",\n int(webinterface.ledsettings.rainbow_offset))\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"rainbow_scale\":\n webinterface.ledsettings.rainbow_scale = int(value)\n webinterface.usersettings.change_setting_value(\"rainbow_scale\",\n int(webinterface.ledsettings.rainbow_scale))\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"rainbow_timeshift\":\n webinterface.ledsettings.rainbow_timeshift = int(value)\n webinterface.usersettings.change_setting_value(\"rainbow_timeshift\",\n int(webinterface.ledsettings.rainbow_timeshift))\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"speed_slowest_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.speed_slowest[\"red\"] = rgb[0]\n webinterface.ledsettings.speed_slowest[\"green\"] = rgb[1]\n webinterface.ledsettings.speed_slowest[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"speed_slowest_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"speed_slowest_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"speed_slowest_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"speed_fastest_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.speed_fastest[\"red\"] = rgb[0]\n webinterface.ledsettings.speed_fastest[\"green\"] = rgb[1]\n webinterface.ledsettings.speed_fastest[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"speed_fastest_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"speed_fastest_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"speed_fastest_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"gradient_start_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.gradient_start[\"red\"] = rgb[0]\n webinterface.ledsettings.gradient_start[\"green\"] = rgb[1]\n webinterface.ledsettings.gradient_start[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"gradient_start_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"gradient_start_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"gradient_start_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"gradient_end_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.gradient_end[\"red\"] = rgb[0]\n webinterface.ledsettings.gradient_end[\"green\"] = rgb[1]\n webinterface.ledsettings.gradient_end[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"gradient_end_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"gradient_end_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"gradient_end_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"speed_max_notes\":\n webinterface.ledsettings.speed_max_notes = int(value)\n webinterface.usersettings.change_setting_value(\"speed_max_notes\", int(value))\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"speed_period_in_seconds\":\n webinterface.ledsettings.speed_period_in_seconds = float(value)\n webinterface.usersettings.change_setting_value(\"speed_period_in_seconds\", float(value))\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"key_in_scale_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.key_in_scale[\"red\"] = rgb[0]\n webinterface.ledsettings.key_in_scale[\"green\"] = rgb[1]\n webinterface.ledsettings.key_in_scale[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"key_in_scale_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"key_in_scale_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"key_in_scale_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"key_not_in_scale_color\":\n rgb = wc.hex_to_rgb(\"#\" + value)\n webinterface.ledsettings.key_not_in_scale[\"red\"] = rgb[0]\n webinterface.ledsettings.key_not_in_scale[\"green\"] = rgb[1]\n webinterface.ledsettings.key_not_in_scale[\"blue\"] = rgb[2]\n\n webinterface.usersettings.change_setting_value(\"key_not_in_scale_red\", rgb[0])\n webinterface.usersettings.change_setting_value(\"key_not_in_scale_green\", rgb[1])\n webinterface.usersettings.change_setting_value(\"key_not_in_scale_blue\", rgb[2])\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"scale_key\":\n webinterface.ledsettings.scale_key = int(value)\n webinterface.usersettings.change_setting_value(\"scale_key\", int(value))\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"next_step\":\n webinterface.ledsettings.set_sequence(0, 1, False)\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"set_sequence\":\n if (int(value) == 0):\n webinterface.ledsettings.__init__(webinterface.usersettings)\n webinterface.ledsettings.sequence_active = False\n else:\n webinterface.ledsettings.set_sequence(int(value) - 1, 0)\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"change_sequence_name\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n sequence_to_edit = \"sequence_\" + str(value)\n\n sequences_tree.getElementsByTagName(sequence_to_edit)[\n 0].getElementsByTagName(\"settings\")[\n 0].getElementsByTagName(\"sequence_name\")[0].firstChild.nodeValue = str(second_value)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"change_step_value\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n sequence_to_edit = \"sequence_\" + str(value)\n\n sequences_tree.getElementsByTagName(sequence_to_edit)[\n 0].getElementsByTagName(\"settings\")[\n 0].getElementsByTagName(\"next_step\")[0].firstChild.nodeValue = str(second_value)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"change_step_activation_method\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n sequence_to_edit = \"sequence_\" + str(value)\n\n sequences_tree.getElementsByTagName(sequence_to_edit)[\n 0].getElementsByTagName(\"settings\")[\n 0].getElementsByTagName(\"control_number\")[0].firstChild.nodeValue = str(second_value)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"add_sequence\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n\n sequences_amount = 1\n while True:\n if (len(sequences_tree.getElementsByTagName(\"sequence_\" + str(sequences_amount))) == 0):\n break\n sequences_amount += 1\n\n settings = sequences_tree.createElement(\"settings\")\n\n control_number = sequences_tree.createElement(\"control_number\")\n control_number.appendChild(sequences_tree.createTextNode(\"0\"))\n settings.appendChild(control_number)\n\n next_step = sequences_tree.createElement(\"next_step\")\n next_step.appendChild(sequences_tree.createTextNode(\"1\"))\n settings.appendChild(next_step)\n\n sequence_name = sequences_tree.createElement(\"sequence_name\")\n sequence_name.appendChild(sequences_tree.createTextNode(\"Sequence \" + str(sequences_amount)))\n settings.appendChild(sequence_name)\n\n step = sequences_tree.createElement(\"step_1\")\n\n color = sequences_tree.createElement(\"color\")\n color.appendChild(sequences_tree.createTextNode(\"RGB\"))\n step.appendChild(color)\n\n red = sequences_tree.createElement(\"Red\")\n red.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(red)\n\n green = sequences_tree.createElement(\"Green\")\n green.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(green)\n\n blue = sequences_tree.createElement(\"Blue\")\n blue.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(blue)\n\n light_mode = sequences_tree.createElement(\"light_mode\")\n light_mode.appendChild(sequences_tree.createTextNode(\"Normal\"))\n step.appendChild(light_mode)\n\n element = sequences_tree.createElement(\"sequence_\" + str(sequences_amount))\n element.appendChild(settings)\n element.appendChild(step)\n\n sequences_tree.getElementsByTagName(\"list\")[0].appendChild(element)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"remove_sequence\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n\n # removing sequence node\n nodes = sequences_tree.getElementsByTagName(\"sequence_\" + str(value))\n for node in nodes:\n parent = node.parentNode\n parent.removeChild(node)\n\n # changing nodes tag names\n i = 1\n for sequence in sequences_tree.getElementsByTagName(\"list\")[0].childNodes:\n if (sequence.nodeType == 1):\n sequences_tree.getElementsByTagName(sequence.nodeName)[0].tagName = \"sequence_\" + str(i)\n i += 1\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n if setting_name == \"add_step\":\n sequences_tree = minidom.parse(\"sequences.xml\")\n\n step_amount = 1\n while True:\n if (len(sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].getElementsByTagName(\n \"step_\" + str(step_amount))) == 0):\n break\n step_amount += 1\n\n step = sequences_tree.createElement(\"step_\" + str(step_amount))\n\n color = sequences_tree.createElement(\"color\")\n\n color.appendChild(sequences_tree.createTextNode(\"RGB\"))\n step.appendChild(color)\n\n red = sequences_tree.createElement(\"Red\")\n red.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(red)\n\n green = sequences_tree.createElement(\"Green\")\n green.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(green)\n\n blue = sequences_tree.createElement(\"Blue\")\n blue.appendChild(sequences_tree.createTextNode(\"255\"))\n step.appendChild(blue)\n\n light_mode = sequences_tree.createElement(\"light_mode\")\n light_mode.appendChild(sequences_tree.createTextNode(\"Normal\"))\n step.appendChild(light_mode)\n\n sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].appendChild(step)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence, reload_steps_list=True)\n\n # remove node list with a tag name \"step_\" + str(value), and change tag names to maintain order\n if setting_name == \"remove_step\":\n\n second_value = int(second_value)\n second_value += 1\n\n sequences_tree = minidom.parse(\"sequences.xml\")\n\n # removing step node\n nodes = sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].getElementsByTagName(\n \"step_\" + str(second_value))\n for node in nodes:\n parent = node.parentNode\n parent.removeChild(node)\n\n # changing nodes tag names\n i = 1\n for step in sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].childNodes:\n if (step.nodeType == 1 and step.tagName != \"settings\"):\n sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].getElementsByTagName(step.nodeName)[\n 0].tagName = \"step_\" + str(i)\n i += 1\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence)\n\n # saving current led settings as sequence step\n if setting_name == \"save_led_settings_to_step\" and second_value != \"\":\n\n # remove node and child under \"sequence_\" + str(value) and \"step_\" + str(second_value)\n sequences_tree = minidom.parse(\"sequences.xml\")\n\n second_value = int(second_value)\n second_value += 1\n\n nodes = sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].getElementsByTagName(\n \"step_\" + str(second_value))\n for node in nodes:\n parent = node.parentNode\n parent.removeChild(node)\n\n # create new step node\n step = sequences_tree.createElement(\"step_\" + str(second_value))\n\n # load color mode from webinterface.ledsettings and put it into step node\n color_mode = sequences_tree.createElement(\"color\")\n color_mode.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.color_mode)))\n step.appendChild(color_mode)\n\n # load mode from webinterface.ledsettings and put it into step node\n mode = sequences_tree.createElement(\"light_mode\")\n mode.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.mode)))\n step.appendChild(mode)\n\n # if mode is equal \"Fading\" or \"Velocity\" load mode from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.mode == \"Fading\" or webinterface.ledsettings.mode == \"Velocity\"):\n fadingspeed = sequences_tree.createElement(\"fadingspeed\")\n\n # depending on fadingspeed name set different fadingspeed value\n if (webinterface.ledsettings.fadingspeed == \"Slow\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"10\"))\n elif (webinterface.ledsettings.fadingspeed == \"Medium\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"20\"))\n elif (webinterface.ledsettings.fadingspeed == \"Fast\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"40\"))\n elif (webinterface.ledsettings.fadingspeed == \"Very fast\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"50\"))\n elif (webinterface.ledsettings.fadingspeed == \"Instant\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"1000\"))\n elif (webinterface.ledsettings.fadingspeed == \"Very slow\"):\n fadingspeed.appendChild(sequences_tree.createTextNode(\"2\"))\n\n step.appendChild(fadingspeed)\n\n # if color_mode is equal to \"Single\" load color from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Single\"):\n red = sequences_tree.createElement(\"Red\")\n red.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.red)))\n step.appendChild(red)\n\n green = sequences_tree.createElement(\"Green\")\n green.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.green)))\n step.appendChild(green)\n\n blue = sequences_tree.createElement(\"Blue\")\n blue.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.blue)))\n step.appendChild(blue)\n\n # if color_mode is equal to \"Multicolor\" load colors from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Multicolor\"):\n # load value from webinterface.ledsettings.multicolor\n multicolor = webinterface.ledsettings.multicolor\n\n # loop through multicolor object and add each color to step node under \"sequence_\"+str(value) with tag name \"color_\"+str(i)\n for i in range(len(multicolor)):\n color = sequences_tree.createElement(\"color_\" + str(i + 1))\n new_multicolor = str(multicolor[i])\n new_multicolor = new_multicolor.replace(\"[\", \"\")\n new_multicolor = new_multicolor.replace(\"]\", \"\")\n\n color.appendChild(sequences_tree.createTextNode(new_multicolor))\n step.appendChild(color)\n\n # same as above but with multicolor_range and \"color_range_\"+str(i)\n multicolor_range = webinterface.ledsettings.multicolor_range\n for i in range(len(multicolor_range)):\n color_range = sequences_tree.createElement(\"color_range_\" + str(i + 1))\n new_multicolor_range = str(multicolor_range[i])\n\n new_multicolor_range = new_multicolor_range.replace(\"[\", \"\")\n new_multicolor_range = new_multicolor_range.replace(\"]\", \"\")\n color_range.appendChild(sequences_tree.createTextNode(new_multicolor_range))\n step.appendChild(color_range)\n\n # if color_mode is equal to \"Rainbow\" load colors from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Rainbow\"):\n # load values rainbow_offset, rainbow_scale and rainbow_timeshift from webinterface.ledsettings and put them into step node under Offset, Scale and Timeshift\n rainbow_offset = sequences_tree.createElement(\"Offset\")\n rainbow_offset.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.rainbow_offset)))\n step.appendChild(rainbow_offset)\n\n rainbow_scale = sequences_tree.createElement(\"Scale\")\n rainbow_scale.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.rainbow_scale)))\n step.appendChild(rainbow_scale)\n\n rainbow_timeshift = sequences_tree.createElement(\"Timeshift\")\n rainbow_timeshift.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.rainbow_timeshift)))\n step.appendChild(rainbow_timeshift)\n\n # if color_mode is equal to \"Speed\" load colors from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Speed\"):\n # load values speed_slowest[\"red\"] etc from webinterface.ledsettings and put them under speed_slowest_red etc\n speed_slowest_red = sequences_tree.createElement(\"speed_slowest_red\")\n speed_slowest_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_slowest[\"red\"])))\n step.appendChild(speed_slowest_red)\n\n speed_slowest_green = sequences_tree.createElement(\"speed_slowest_green\")\n speed_slowest_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_slowest[\"green\"])))\n step.appendChild(speed_slowest_green)\n\n speed_slowest_blue = sequences_tree.createElement(\"speed_slowest_blue\")\n speed_slowest_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_slowest[\"blue\"])))\n step.appendChild(speed_slowest_blue)\n\n # same as above but with \"fastest\"\n speed_fastest_red = sequences_tree.createElement(\"speed_fastest_red\")\n speed_fastest_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_fastest[\"red\"])))\n step.appendChild(speed_fastest_red)\n\n speed_fastest_green = sequences_tree.createElement(\"speed_fastest_green\")\n speed_fastest_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_fastest[\"green\"])))\n step.appendChild(speed_fastest_green)\n\n speed_fastest_blue = sequences_tree.createElement(\"speed_fastest_blue\")\n speed_fastest_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_fastest[\"blue\"])))\n step.appendChild(speed_fastest_blue)\n\n # load \"speed_max_notes\" and \"speed_period_in_seconds\" values from webinterface.ledsettings\n # and put them under speed_max_notes and speed_period_in_seconds\n\n speed_max_notes = sequences_tree.createElement(\"speed_max_notes\")\n speed_max_notes.appendChild(sequences_tree.createTextNode(str(webinterface.ledsettings.speed_max_notes)))\n step.appendChild(speed_max_notes)\n\n speed_period_in_seconds = sequences_tree.createElement(\"speed_period_in_seconds\")\n speed_period_in_seconds.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.speed_period_in_seconds)))\n step.appendChild(speed_period_in_seconds)\n\n # if color_mode is equal to \"Gradient\" load colors from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Gradient\"):\n # load values gradient_start_red etc from webinterface.ledsettings and put them under gradient_start_red etc\n gradient_start_red = sequences_tree.createElement(\"gradient_start_red\")\n gradient_start_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_start[\"red\"])))\n step.appendChild(gradient_start_red)\n\n gradient_start_green = sequences_tree.createElement(\"gradient_start_green\")\n gradient_start_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_start[\"green\"])))\n step.appendChild(gradient_start_green)\n\n gradient_start_blue = sequences_tree.createElement(\"gradient_start_blue\")\n gradient_start_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_start[\"blue\"])))\n step.appendChild(gradient_start_blue)\n\n # same as above but with gradient_end\n gradient_end_red = sequences_tree.createElement(\"gradient_end_red\")\n gradient_end_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_end[\"red\"])))\n step.appendChild(gradient_end_red)\n\n gradient_end_green = sequences_tree.createElement(\"gradient_end_green\")\n gradient_end_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_end[\"green\"])))\n step.appendChild(gradient_end_green)\n\n gradient_end_blue = sequences_tree.createElement(\"gradient_end_blue\")\n gradient_end_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.gradient_end[\"blue\"])))\n step.appendChild(gradient_end_blue)\n\n # if color_mode is equal to \"Scale\" load colors from webinterface.ledsettings and put it into step node\n if (webinterface.ledsettings.color_mode == \"Scale\"):\n # load values key_in_scale_red etc from webinterface.ledsettings and put them under key_in_scale_red etc\n key_in_scale_red = sequences_tree.createElement(\"key_in_scale_red\")\n key_in_scale_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_in_scale[\"red\"])))\n step.appendChild(key_in_scale_red)\n\n key_in_scale_green = sequences_tree.createElement(\"key_in_scale_green\")\n key_in_scale_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_in_scale[\"green\"])))\n step.appendChild(key_in_scale_green)\n\n key_in_scale_blue = sequences_tree.createElement(\"key_in_scale_blue\")\n key_in_scale_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_in_scale[\"blue\"])))\n step.appendChild(key_in_scale_blue)\n\n # same as above but with key_not_in_scale\n key_not_in_scale_red = sequences_tree.createElement(\"key_not_in_scale_red\")\n key_not_in_scale_red.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_not_in_scale[\"red\"])))\n step.appendChild(key_not_in_scale_red)\n\n key_not_in_scale_green = sequences_tree.createElement(\"key_not_in_scale_green\")\n key_not_in_scale_green.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_not_in_scale[\"green\"])))\n step.appendChild(key_not_in_scale_green)\n\n key_not_in_scale_blue = sequences_tree.createElement(\"key_not_in_scale_blue\")\n key_not_in_scale_blue.appendChild(\n sequences_tree.createTextNode(str(webinterface.ledsettings.key_not_in_scale[\"blue\"])))\n step.appendChild(key_not_in_scale_blue)\n\n try:\n sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[\n 0].insertBefore(step,\n sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[\n 0].getElementsByTagName(\"step_\" + str(second_value + 1))[0])\n except:\n sequences_tree.getElementsByTagName(\"sequence_\" + str(value))[0].appendChild(step)\n\n pretty_save(\"sequences.xml\", sequences_tree)\n\n return jsonify(success=True, reload_sequence=reload_sequence, reload_steps_list=True)\n\n if setting_name == \"screen_on\":\n if (int(value) == 0):\n webinterface.menu.disable_screen()\n else:\n webinterface.menu.enable_screen()\n\n if setting_name == \"reset_to_default\":\n webinterface.usersettings.reset_to_default()\n\n if setting_name == \"restart_rpi\":\n call(\"sudo /sbin/reboot now\", shell=True)\n\n if setting_name == \"turnoff_rpi\":\n call(\"sudo /sbin/shutdown -h now\", shell=True)\n\n if setting_name == \"update_rpi\":\n call(\"sudo git reset --hard HEAD\", shell=True)\n call(\"sudo git checkout .\", shell=True)\n call(\"sudo git clean -fdx\", shell=True)\n call(\"sudo git pull origin master\", shell=True)\n\n if setting_name == \"connect_ports\":\n webinterface.midiports.connectall()\n return jsonify(success=True, reload_ports=True)\n\n if setting_name == \"disconnect_ports\":\n call(\"sudo aconnect -x\", shell=True)\n return jsonify(success=True, reload_ports=True)\n\n if setting_name == \"restart_rtp\":\n call(\"sudo systemctl restart rtpmidid\", shell=True)\n\n if setting_name == \"start_recording\":\n webinterface.saving.start_recording()\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"cancel_recording\":\n webinterface.saving.cancel_recording()\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"save_recording\":\n now = datetime.datetime.now()\n current_date = now.strftime(\"%Y-%m-%d %H:%M\")\n webinterface.saving.save(current_date)\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"change_song_name\":\n if os.path.exists(\"Songs/\" + second_value):\n return jsonify(success=False, reload_songs=True, error=second_value + \" already exists\")\n\n if \"_main\" in value:\n search_name = value.replace(\"_main.mid\", \"\")\n for fname in os.listdir('Songs'):\n if search_name in fname:\n new_name = second_value.replace(\".mid\", \"\") + fname.replace(search_name, \"\")\n os.rename('Songs/' + fname, 'Songs/' + new_name)\n else:\n os.rename('Songs/' + value, 'Songs/' + second_value)\n os.rename('Songs/cache/' + value + \".p\", 'Songs/cache/' + second_value + \".p\")\n\n\n\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"remove_song\":\n if \"_main\" in value:\n name_no_suffix = value.replace(\"_main.mid\", \"\")\n for fname in os.listdir('Songs'):\n if name_no_suffix in fname:\n os.remove(\"Songs/\" + fname)\n else:\n os.remove(\"Songs/\" + value)\n\n file_types = [\".musicxml\", \".xml\", \".mxl\", \".abc\"]\n for file_type in file_types:\n try:\n os.remove(\"Songs/\" + value.replace(\".mid\", file_type))\n except:\n pass\n\n try:\n os.remove(\"Songs/cache/\" + value + \".p\")\n except:\n print(\"No cache file for \" + value)\n\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"download_song\":\n if \"_main\" in value:\n zipObj = ZipFile(\"Songs/\" + value.replace(\".mid\", \"\") + \".zip\", 'w')\n name_no_suffix = value.replace(\"_main.mid\", \"\")\n songs_count = 0\n for fname in os.listdir('Songs'):\n if name_no_suffix in fname and \".zip\" not in fname:\n songs_count += 1\n zipObj.write(\"Songs/\" + fname)\n zipObj.close()\n if songs_count == 1:\n os.remove(\"Songs/\" + value.replace(\".mid\", \"\") + \".zip\")\n return send_file(\"../Songs/\" + value, mimetype='application/x-csv', attachment_filename=value,\n as_attachment=True)\n else:\n return send_file(\"../Songs/\" + value.replace(\".mid\", \"\") + \".zip\", mimetype='application/x-csv',\n attachment_filename=value.replace(\".mid\", \"\") + \".zip\", as_attachment=True)\n else:\n return send_file(safe_join(\"../Songs/\" + value), mimetype='application/x-csv', attachment_filename=value,\n as_attachment=True)\n\n if setting_name == \"download_sheet_music\":\n file_types = [\".musicxml\", \".xml\", \".mxl\", \".abc\"]\n i = 0\n while i < len(file_types):\n try:\n new_name = value.replace(\".mid\", file_types[i])\n return send_file(\"../Songs/\" + new_name, mimetype='application/x-csv', attachment_filename=new_name,\n as_attachment=True)\n except:\n i += 1\n webinterface.learning.convert_midi_to_abc(value)\n try:\n return send_file(safe_join(\"../Songs/\", value.replace(\".mid\", \".abc\")), mimetype='application/x-csv',\n attachment_filename=value.replace(\".mid\", \".abc\"), as_attachment=True)\n except:\n print(\"Converting failed\")\n\n\n if setting_name == \"start_midi_play\":\n webinterface.saving.t = threading.Thread(target=play_midi, args=(value, webinterface.midiports,\n webinterface.saving, webinterface.menu,\n webinterface.ledsettings,\n webinterface.ledstrip))\n webinterface.saving.t.start()\n\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"stop_midi_play\":\n webinterface.saving.is_playing_midi.clear()\n fastColorWipe(webinterface.ledstrip.strip, True, webinterface.ledsettings)\n\n return jsonify(success=True, reload_songs=True)\n\n if setting_name == \"learning_load_song\":\n webinterface.learning.t = threading.Thread(target=webinterface.learning.load_midi, args=(value,))\n webinterface.learning.t.start()\n\n return jsonify(success=True, reload_learning_settings=True)\n\n if setting_name == \"start_learning_song\":\n webinterface.learning.t = threading.Thread(target=webinterface.learning.learn_midi)\n webinterface.learning.t.start()\n\n return jsonify(success=True)\n\n if setting_name == \"stop_learning_song\":\n webinterface.learning.is_started_midi = False\n fastColorWipe(webinterface.ledstrip.strip, True, webinterface.ledsettings)\n\n return jsonify(success=True)\n\n if setting_name == \"change_practice\":\n value = int(value)\n webinterface.learning.practice = value\n webinterface.learning.practice = clamp(webinterface.learning.practice, 0, len(webinterface.learning.practiceList) - 1)\n webinterface.usersettings.change_setting_value(\"practice\", webinterface.learning.practice)\n\n return jsonify(success=True)\n\n if setting_name == \"change_tempo\":\n value = int(value)\n webinterface.learning.set_tempo = value\n webinterface.learning.set_tempo = clamp(webinterface.learning.set_tempo, 10, 200)\n webinterface.usersettings.change_setting_value(\"set_tempo\", webinterface.learning.set_tempo)\n\n return jsonify(success=True)\n\n if setting_name == \"change_hands\":\n value = int(value)\n webinterface.learning.hands = value\n webinterface.learning.hands = clamp(webinterface.learning.hands, 0, len(webinterface.learning.handsList) - 1)\n webinterface.usersettings.change_setting_value(\"hands\", webinterface.learning.hands)\n\n return jsonify(success=True)\n\n if setting_name == \"change_mute_hand\":\n value = int(value)\n webinterface.learning.mute_hand = value\n webinterface.learning.mute_hand = clamp(webinterface.learning.mute_hand, 0, len(webinterface.learning.mute_handList) - 1)\n webinterface.usersettings.change_setting_value(\"mute_hand\", webinterface.learning.mute_hand)\n\n return jsonify(success=True)\n\n if setting_name == \"learning_start_point\":\n value = int(value)\n webinterface.learning.start_point = value\n webinterface.learning.start_point = clamp(webinterface.learning.start_point, 0, webinterface.learning.end_point - 1)\n webinterface.usersettings.change_setting_value(\"start_point\", webinterface.learning.start_point)\n webinterface.learning.restart_learning()\n\n return jsonify(success=True)\n\n if setting_name == \"learning_end_point\":\n value = int(value)\n webinterface.learning.end_point = value\n webinterface.learning.end_point = clamp(webinterface.learning.end_point, webinterface.learning.start_point + 1, 100)\n webinterface.usersettings.change_setting_value(\"end_point\", webinterface.learning.end_point)\n webinterface.learning.restart_learning()\n\n return jsonify(success=True)\n\n if setting_name == \"set_current_time_as_start_point\":\n webinterface.learning.start_point = round(float(webinterface.learning.current_idx * 100 / float(len(webinterface.learning.song_tracks))), 3)\n webinterface.learning.start_point = clamp(webinterface.learning.start_point, 0, webinterface.learning.end_point - 1)\n webinterface.usersettings.change_setting_value(\"start_point\", webinterface.learning.start_point)\n webinterface.learning.restart_learning()\n\n return jsonify(success=True, reload_learning_settings=True)\n\n if setting_name == \"set_current_time_as_end_point\":\n webinterface.learning.end_point = round(float(webinterface.learning.current_idx * 100 / float(len(webinterface.learning.song_tracks))), 3)\n webinterface.learning.end_point = clamp(webinterface.learning.end_point, webinterface.learning.start_point + 1, 100)\n webinterface.usersettings.change_setting_value(\"end_point\", webinterface.learning.end_point)\n webinterface.learning.restart_learning()\n\n return jsonify(success=True, reload_learning_settings=True)\n\n if setting_name == \"change_handL_color\":\n value = int(value)\n webinterface.learning.hand_colorL += value\n webinterface.learning.hand_colorL = clamp(webinterface.learning.hand_colorL, 0, len(webinterface.learning.hand_colorList) - 1)\n webinterface.usersettings.change_setting_value(\"hand_colorL\", webinterface.learning.hand_colorL)\n\n return jsonify(success=True, reload_learning_settings=True)\n\n if setting_name == \"change_handR_color\":\n value = int(value)\n webinterface.learning.hand_colorR += value\n webinterface.learning.hand_colorR = clamp(webinterface.learning.hand_colorR, 0, len(webinterface.learning.hand_colorList) - 1)\n webinterface.usersettings.change_setting_value(\"hand_colorR\", webinterface.learning.hand_colorR)\n\n return jsonify(success=True, reload_learning_settings=True)\n\n if setting_name == \"change_learning_loop\":\n value = int(value == 'true')\n webinterface.learning.is_loop_active = value\n webinterface.usersettings.change_setting_value(\"is_loop_active\", webinterface.learning.is_loop_active)\n\n return jsonify(success=True)\n\n\n return jsonify(success=True)"}], "vul_patch": "--- a/webinterface/views_api.py\n+++ b/webinterface/views_api.py\n@@ -823,7 +823,7 @@\n return send_file(\"../Songs/\" + value.replace(\".mid\", \"\") + \".zip\", mimetype='application/x-csv',\n attachment_filename=value.replace(\".mid\", \"\") + \".zip\", as_attachment=True)\n else:\n- return send_file(\"../Songs/\" + value, mimetype='application/x-csv', attachment_filename=value,\n+ return send_file(safe_join(\"../Songs/\" + value), mimetype='application/x-csv', attachment_filename=value,\n as_attachment=True)\n \n if setting_name == \"download_sheet_music\":\n@@ -838,7 +838,7 @@\n i += 1\n webinterface.learning.convert_midi_to_abc(value)\n try:\n- return send_file(\"../Songs/\" + value.replace(\".mid\", \".abc\"), mimetype='application/x-csv',\n+ return send_file(safe_join(\"../Songs/\", value.replace(\".mid\", \".abc\")), mimetype='application/x-csv',\n attachment_filename=value.replace(\".mid\", \".abc\"), as_attachment=True)\n except:\n print(\"Converting failed\")\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2022-1058", "cve_description": "Open Redirect on login in GitHub repository go-gitea/gitea prior to 1.16.5.", "cwe_info": {"CWE-601": {"name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "The web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a redirect."}}, "repo": "https://github.com/go-gitea/gitea", "patch_url": ["https://github.com/go-gitea/gitea/commit/e3d8e92bdc67562783de9a76b5b7842b68daeb48"], "programing_language": "Go", "vul_func": [{"id": "vul_go_250_1", "commit": "6fc73a84332643ffbd431f6e7fcb16942c505c04", "file_path": "modules/context/context.go", "start_line": 178, "end_line": 194, "snippet": "func (ctx *Context) RedirectToFirst(location ...string) {\n\tfor _, loc := range location {\n\t\tif len(loc) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tu, err := url.Parse(loc)\n\t\tif err != nil || ((u.Scheme != \"\" || u.Host != \"\") && !strings.HasPrefix(strings.ToLower(loc), strings.ToLower(setting.AppURL))) {\n\t\t\tcontinue\n\t\t}\n\n\t\tctx.Redirect(loc)\n\t\treturn\n\t}\n\n\tctx.Redirect(setting.AppSubURL + \"/\")\n}"}], "fix_func": [{"id": "fix_go_250_1", "commit": "e3d8e92bdc67562783de9a76b5b7842b68daeb48", "file_path": "modules/context/context.go", "start_line": 178, "end_line": 200, "snippet": "func (ctx *Context) RedirectToFirst(location ...string) {\n\tfor _, loc := range location {\n\t\tif len(loc) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Unfortunately browsers consider a redirect Location with preceding \"//\" and \"/\\\" as meaning redirect to \"http(s)://REST_OF_PATH\"\n\t\t// Therefore we should ignore these redirect locations to prevent open redirects\n\t\tif len(loc) > 1 && loc[0] == '/' && (loc[1] == '/' || loc[1] == '\\\\') {\n\t\t\tcontinue\n\t\t}\n\n\t\tu, err := url.Parse(loc)\n\t\tif err != nil || ((u.Scheme != \"\" || u.Host != \"\") && !strings.HasPrefix(strings.ToLower(loc), strings.ToLower(setting.AppURL))) {\n\t\t\tcontinue\n\t\t}\n\n\t\tctx.Redirect(loc)\n\t\treturn\n\t}\n\n\tctx.Redirect(setting.AppSubURL + \"/\")\n}"}], "vul_patch": "--- a/modules/context/context.go\n+++ b/modules/context/context.go\n@@ -1,6 +1,12 @@\n func (ctx *Context) RedirectToFirst(location ...string) {\n \tfor _, loc := range location {\n \t\tif len(loc) == 0 {\n+\t\t\tcontinue\n+\t\t}\n+\n+\t\t// Unfortunately browsers consider a redirect Location with preceding \"//\" and \"/\\\" as meaning redirect to \"http(s)://REST_OF_PATH\"\n+\t\t// Therefore we should ignore these redirect locations to prevent open redirects\n+\t\tif len(loc) > 1 && loc[0] == '/' && (loc[1] == '/' || loc[1] == '\\\\') {\n \t\t\tcontinue\n \t\t}\n \n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2024-56136", "cve_description": "Zulip server provides an open-source team chat that helps teams stay productive and focused. Zulip Server 7.0 and above are vulnerable to an information disclose attack, where, if a Zulip server is hosting multiple organizations, an unauthenticated user can make a request and determine if an email address is in use by a user. Zulip Server 9.4 resolves the issue, as does the `main` branch of Zulip Server. Users are advised to upgrade. There are no known workarounds for this issue.", "cwe_info": {"CWE-200": {"name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information."}}, "repo": "https://github.com/zulip/zulip", "patch_url": ["https://github.com/zulip/zulip/commit/c6334a765b1e6d71760e4a3b32ae5b8367f2ed4d"], "programing_language": "Python", "vul_func": [{"id": "vul_py_344_1", "commit": "ff5512e5a93ac3ecf327288b3f37e032de0aaf81", "file_path": "zerver/views/auth.py", "start_line": 989, "end_line": 1001, "snippet": "def get_api_key_fetch_authenticate_failure(return_data: dict[str, bool]) -> JsonableError:\n if return_data.get(\"inactive_user\"):\n return UserDeactivatedError()\n if return_data.get(\"inactive_realm\"):\n return RealmDeactivatedError()\n if return_data.get(\"password_auth_disabled\"):\n return PasswordAuthDisabledError()\n if return_data.get(\"password_reset_needed\"):\n return PasswordResetRequiredError()\n if return_data.get(\"invalid_subdomain\"):\n raise InvalidSubdomainError\n\n return AuthenticationFailedError()"}], "fix_func": [{"id": "fix_py_344_1", "commit": "c6334a765b1e6d71760e4a3b32ae5b8367f2ed4d", "file_path": "zerver/views/auth.py", "start_line": 989, "end_line": 1004, "snippet": "def get_api_key_fetch_authenticate_failure(return_data: dict[str, bool]) -> JsonableError:\n if return_data.get(\"inactive_user\"):\n return UserDeactivatedError()\n if return_data.get(\"inactive_realm\"):\n return RealmDeactivatedError()\n if return_data.get(\"password_auth_disabled\"):\n return PasswordAuthDisabledError()\n if return_data.get(\"password_reset_needed\"):\n return PasswordResetRequiredError()\n if return_data.get(\"invalid_subdomain\"):\n # We must not report invalid_subdomain here; that value is intended only for informing server logs,\n # and should never be exposed to end users, since it would leak whether there exists\n # an account in a different organization with the same email address.\n return AuthenticationFailedError()\n\n return AuthenticationFailedError()"}], "vul_patch": "--- a/zerver/views/auth.py\n+++ b/zerver/views/auth.py\n@@ -8,6 +8,9 @@\n if return_data.get(\"password_reset_needed\"):\n return PasswordResetRequiredError()\n if return_data.get(\"invalid_subdomain\"):\n- raise InvalidSubdomainError\n+ # We must not report invalid_subdomain here; that value is intended only for informing server logs,\n+ # and should never be exposed to end users, since it would leak whether there exists\n+ # an account in a different organization with the same email address.\n+ return AuthenticationFailedError()\n \n return AuthenticationFailedError()\n\n", "poc_patch": null, "unit_test_cmd": null} -{"cve_id": "CVE-2025-43859", "cve_description": "h11 is a Python implementation of HTTP/1.1. Prior to version 0.16.0, a leniency in h11's parsing of line terminators in chunked-coding message bodies can lead to request smuggling vulnerabilities under certain conditions. This issue has been patched in version 0.16.0. Since exploitation requires the combination of buggy h11 with a buggy (reverse) proxy, fixing either component is sufficient to mitigate this issue.", "cwe_info": {"CWE-444": {"name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination."}}, "repo": "https://github.com/python-hyper/h11", "patch_url": ["https://github.com/python-hyper/h11/commit/114803a29ce50116dc47951c690ad4892b1a36ed"], "programing_language": "Python", "vul_func": [{"id": "vul_py_68_1", "commit": "114803a29ce50116dc47951c690ad4892b1a36ed", "file_path": "h11/_readers.py", "start_line": 149, "end_line": 154, "snippet": " def __init__(self) -> None:\n self._bytes_in_chunk = 0\n # After reading a chunk, we have to throw away the trailing \\r\\n.\n # This tracks the bytes that we need to match and throw away.\n self._bytes_to_discard = b\"\"\n self._reading_trailer = False"}, {"id": "vul_py_68_2", "commit": "114803a29ce50116dc47951c690ad4892b1a36ed", "file_path": "h11/_readers.py", "start_line": 156, "end_line": 204, "snippet": " def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]:\n if self._reading_trailer:\n lines = buf.maybe_extract_lines()\n if lines is None:\n return None\n return EndOfMessage(headers=list(_decode_header_lines(lines)))\n if self._bytes_to_discard:\n data = buf.maybe_extract_at_most(len(self._bytes_to_discard))\n if data is None:\n return None\n if data != self._bytes_to_discard[:len(data)]:\n raise LocalProtocolError(\n f\"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})\"\n )\n self._bytes_to_discard = self._bytes_to_discard[len(data):]\n if self._bytes_to_discard:\n return None\n # else, fall through and read some more\n assert self._bytes_to_discard == b\"\"\n if self._bytes_in_chunk == 0:\n # We need to refill our chunk count\n chunk_header = buf.maybe_extract_next_line()\n if chunk_header is None:\n return None\n matches = validate(\n chunk_header_re,\n chunk_header,\n \"illegal chunk header: {!r}\",\n chunk_header,\n )\n # XX FIXME: we discard chunk extensions. Does anyone care?\n self._bytes_in_chunk = int(matches[\"chunk_size\"], base=16)\n if self._bytes_in_chunk == 0:\n self._reading_trailer = True\n return self(buf)\n chunk_start = True\n else:\n chunk_start = False\n assert self._bytes_in_chunk > 0\n data = buf.maybe_extract_at_most(self._bytes_in_chunk)\n if data is None:\n return None\n self._bytes_in_chunk -= len(data)\n if self._bytes_in_chunk == 0:\n self._bytes_to_discard = b\"\\r\\n\"\n chunk_end = True\n else:\n chunk_end = False\n return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end)"}], "fix_func": [{"id": "fix_py_68_1", "commit": "114803a29ce50116dc47951c690ad4892b1a36ed", "file_path": "h11/_readers.py", "start_line": 149, "end_line": 154, "snippet": " def __init__(self) -> None:\n self._bytes_in_chunk = 0\n # After reading a chunk, we have to throw away the trailing \\r\\n.\n # This tracks the bytes that we need to match and throw away.\n self._bytes_to_discard = b\"\"\n self._reading_trailer = False"}, {"id": "fix_py_68_2", "commit": "114803a29ce50116dc47951c690ad4892b1a36ed", "file_path": "h11/_readers.py", "start_line": 156, "end_line": 204, "snippet": " def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]:\n if self._reading_trailer:\n lines = buf.maybe_extract_lines()\n if lines is None:\n return None\n return EndOfMessage(headers=list(_decode_header_lines(lines)))\n if self._bytes_to_discard:\n data = buf.maybe_extract_at_most(len(self._bytes_to_discard))\n if data is None:\n return None\n if data != self._bytes_to_discard[:len(data)]:\n raise LocalProtocolError(\n f\"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})\"\n )\n self._bytes_to_discard = self._bytes_to_discard[len(data):]\n if self._bytes_to_discard:\n return None\n # else, fall through and read some more\n assert self._bytes_to_discard == b\"\"\n if self._bytes_in_chunk == 0:\n # We need to refill our chunk count\n chunk_header = buf.maybe_extract_next_line()\n if chunk_header is None:\n return None\n matches = validate(\n chunk_header_re,\n chunk_header,\n \"illegal chunk header: {!r}\",\n chunk_header,\n )\n # XX FIXME: we discard chunk extensions. Does anyone care?\n self._bytes_in_chunk = int(matches[\"chunk_size\"], base=16)\n if self._bytes_in_chunk == 0:\n self._reading_trailer = True\n return self(buf)\n chunk_start = True\n else:\n chunk_start = False\n assert self._bytes_in_chunk > 0\n data = buf.maybe_extract_at_most(self._bytes_in_chunk)\n if data is None:\n return None\n self._bytes_in_chunk -= len(data)\n if self._bytes_in_chunk == 0:\n self._bytes_to_discard = b\"\\r\\n\"\n chunk_end = True\n else:\n chunk_end = False\n return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end)"}], "vul_patch": "\n\n\n\n", "poc_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2025-43859:latest\n# bash /workspace/fix-run.sh\nset -e\n\ncd /workspace/h11\ngit apply --whitespace=nowarn /workspace/test.patch /workspace/fix.patch\n/workspace/PoC_env/CVE-2025-43859/bin/python -m pytest h11/tests/test_io.py -k \"t_body_reader or test_ChunkedReader or test_ContentLengthWriter\"\n", "unit_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2025-43859:latest\n# bash /workspace/unit_test.sh\nset -e\n\ncd /workspace/h11\ngit apply --whitespace=nowarn /workspace/test.patch\n/workspace/PoC_env/CVE-2025-43859/bin/python -m pytest h11/tests/test_io.py -k \"not test_ChunkedReader\" -p no:warning --disable-warnings\n"} +{"cve_id": "CVE-2025-43859", "cve_description": "h11 is a Python implementation of HTTP/1.1. Prior to version 0.16.0, a leniency in h11's parsing of line terminators in chunked-coding message bodies can lead to request smuggling vulnerabilities under certain conditions. This issue has been patched in version 0.16.0. Since exploitation requires the combination of buggy h11 with a buggy (reverse) proxy, fixing either component is sufficient to mitigate this issue.", "cwe_info": {"CWE-444": {"name": "Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')", "description": "The product acts as an intermediary HTTP agent\n (such as a proxy or firewall) in the data flow between two\n entities such as a client and server, but it does not\n interpret malformed HTTP requests or responses in ways that\n are consistent with how the messages will be processed by\n those entities that are at the ultimate destination."}}, "repo": "https://github.com/python-hyper/h11", "patch_url": ["https://github.com/python-hyper/h11/commit/114803a29ce50116dc47951c690ad4892b1a36ed"], "programing_language": "Python", "vul_func": [{"id": "vul_py_68_1", "commit": "9462006f6ce4941661888228cbd4ac1ea80689b0", "file_path": "h11/_readers.py", "start_line": 149, "end_line": 155, "snippet": " def __init__(self) -> None:\n self._bytes_in_chunk = 0\n # After reading a chunk, we have to throw away the trailing \\r\\n.\n # This tracks the bytes that we need to match and throw away.\n # de-chunkification.\n self._bytes_to_discard = 0\n self._reading_trailer = False"}, {"id": "vul_py_68_2", "commit": "9462006f6ce4941661888228cbd4ac1ea80689b0", "file_path": "h11/_readers.py", "start_line": 157, "end_line": 201, "snippet": " def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]:\n if self._reading_trailer:\n lines = buf.maybe_extract_lines()\n if lines is None:\n return None\n return EndOfMessage(headers=list(_decode_header_lines(lines)))\n if self._bytes_to_discard >0 :\n data = buf.maybe_extract_at_most(self._bytes_to_discard)\n if data is None:\n return None\n self._bytes_to_discard -= len(data)\n if self._bytes_to_discard > 0:\n return None\n # else, fall through and read some more\n assert self._bytes_to_discard == 0\n if self._bytes_in_chunk == 0:\n # We need to refill our chunk count\n chunk_header = buf.maybe_extract_next_line()\n if chunk_header is None:\n return None\n matches = validate(\n chunk_header_re,\n chunk_header,\n \"illegal chunk header: {!r}\",\n chunk_header,\n )\n # XX FIXME: we discard chunk extensions. Does anyone care?\n self._bytes_in_chunk = int(matches[\"chunk_size\"], base=16)\n if self._bytes_in_chunk == 0:\n self._reading_trailer = True\n return self(buf)\n chunk_start = True\n else:\n chunk_start = False\n assert self._bytes_in_chunk > 0\n data = buf.maybe_extract_at_most(self._bytes_in_chunk)\n if data is None:\n return None\n self._bytes_in_chunk -= len(data)\n if self._bytes_in_chunk == 0:\n self._bytes_to_discard = 2\n chunk_end = True\n else:\n chunk_end = False\n return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end)"}], "fix_func": [{"id": "fix_py_68_1", "commit": "114803a29ce50116dc47951c690ad4892b1a36ed", "file_path": "h11/_readers.py", "start_line": 149, "end_line": 154, "snippet": " def __init__(self) -> None:\n self._bytes_in_chunk = 0\n # After reading a chunk, we have to throw away the trailing \\r\\n.\n # This tracks the bytes that we need to match and throw away.\n self._bytes_to_discard = b\"\"\n self._reading_trailer = False"}, {"id": "fix_py_68_2", "commit": "114803a29ce50116dc47951c690ad4892b1a36ed", "file_path": "h11/_readers.py", "start_line": 156, "end_line": 204, "snippet": " def __call__(self, buf: ReceiveBuffer) -> Union[Data, EndOfMessage, None]:\n if self._reading_trailer:\n lines = buf.maybe_extract_lines()\n if lines is None:\n return None\n return EndOfMessage(headers=list(_decode_header_lines(lines)))\n if self._bytes_to_discard:\n data = buf.maybe_extract_at_most(len(self._bytes_to_discard))\n if data is None:\n return None\n if data != self._bytes_to_discard[:len(data)]:\n raise LocalProtocolError(\n f\"malformed chunk footer: {data!r} (expected {self._bytes_to_discard!r})\"\n )\n self._bytes_to_discard = self._bytes_to_discard[len(data):]\n if self._bytes_to_discard:\n return None\n # else, fall through and read some more\n assert self._bytes_to_discard == b\"\"\n if self._bytes_in_chunk == 0:\n # We need to refill our chunk count\n chunk_header = buf.maybe_extract_next_line()\n if chunk_header is None:\n return None\n matches = validate(\n chunk_header_re,\n chunk_header,\n \"illegal chunk header: {!r}\",\n chunk_header,\n )\n # XX FIXME: we discard chunk extensions. Does anyone care?\n self._bytes_in_chunk = int(matches[\"chunk_size\"], base=16)\n if self._bytes_in_chunk == 0:\n self._reading_trailer = True\n return self(buf)\n chunk_start = True\n else:\n chunk_start = False\n assert self._bytes_in_chunk > 0\n data = buf.maybe_extract_at_most(self._bytes_in_chunk)\n if data is None:\n return None\n self._bytes_in_chunk -= len(data)\n if self._bytes_in_chunk == 0:\n self._bytes_to_discard = b\"\\r\\n\"\n chunk_end = True\n else:\n chunk_end = False\n return Data(data=data, chunk_start=chunk_start, chunk_end=chunk_end)"}], "vul_patch": "\n\n\n\n", "poc_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2025-43859:latest\n# bash /workspace/fix-run.sh\nset -e\n\ncd /workspace/h11\ngit apply --whitespace=nowarn /workspace/test.patch /workspace/fix.patch\n/workspace/PoC_env/CVE-2025-43859/bin/python -m pytest h11/tests/test_io.py -k \"t_body_reader or test_ChunkedReader or test_ContentLengthWriter\"\n", "unit_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2025-43859:latest\n# bash /workspace/unit_test.sh\nset -e\n\ncd /workspace/h11\ngit apply --whitespace=nowarn /workspace/test.patch\n/workspace/PoC_env/CVE-2025-43859/bin/python -m pytest h11/tests/test_io.py -k \"not test_ChunkedReader\" -p no:warning --disable-warnings\n"} {"cve_id": "CVE-2022-4720", "cve_description": "Open Redirect in GitHub repository ikus060/rdiffweb prior to 2.5.5.", "cwe_info": {"CWE-601": {"name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "The web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a redirect."}}, "repo": "https://github.com/ikus060/rdiffweb", "patch_url": ["https://github.com/ikus060/rdiffweb/commit/6afaae56a29536f0118b3380d296c416aa6d078d"], "programing_language": "Python", "vul_func": [{"id": "vul_py_147_1", "commit": "b0c1422", "file_path": "rdiffweb/core/notification.py", "start_line": 66, "end_line": 78, "snippet": " def access_token_added(self, userobj, name):\n if not self.send_changed:\n return\n\n if not userobj.email:\n logger.info(\"can't sent mail to user [%s] without an email\", userobj.username)\n return\n\n # Send a mail notification\n body = self.app.templates.compile_template(\n \"access_token_added.html\", **{\"header_name\": self.app.cfg.header_name, 'user': userobj, 'name': name}\n )\n self.bus.publish('queue_mail', to=userobj.email, subject=_(\"A new access token has been created\"), message=body)"}, {"id": "vul_py_147_2", "commit": "b0c1422", "file_path": "rdiffweb/core/notification.py", "start_line": 111, "end_line": 123, "snippet": " def user_password_changed(self, userobj):\n if not self.send_changed:\n return\n\n if not userobj.email:\n logger.info(\"can't sent mail to user [%s] without an email\", userobj.username)\n return\n\n # If the email attributes was changed, send a mail notification.\n body = self.app.templates.compile_template(\n \"password_changed.html\", **{\"header_name\": self.app.cfg.header_name, 'user': userobj}\n )\n self.bus.publish('queue_mail', to=userobj.email, subject=_(\"Password changed\"), message=body)"}], "fix_func": [{"id": "fix_py_147_1", "commit": "6afaae5", "file_path": "rdiffweb/core/notification.py", "start_line": 66, "end_line": 78, "snippet": " def access_token_added(self, userobj, name):\n if not self.send_changed:\n return\n\n if not userobj.email:\n logger.info(\"can't sent mail to user [%s] without an email\", userobj.username)\n return\n\n # Send a mail notification\n body = self.app.templates.compile_template(\n \"email_access_token_added.html\", **{\"header_name\": self.app.cfg.header_name, 'user': userobj, 'name': name}\n )\n self.bus.publish('queue_mail', to=userobj.email, subject=_(\"A new access token has been created\"), message=body)"}, {"id": "fix_py_147_2", "commit": "6afaae5", "file_path": "rdiffweb/core/notification.py", "start_line": 111, "end_line": 123, "snippet": " def user_password_changed(self, userobj):\n if not self.send_changed:\n return\n\n if not userobj.email:\n logger.info(\"can't sent mail to user [%s] without an email\", userobj.username)\n return\n\n # If the email attributes was changed, send a mail notification.\n body = self.app.templates.compile_template(\n \"email_password_changed.html\", **{\"header_name\": self.app.cfg.header_name, 'user': userobj}\n )\n self.bus.publish('queue_mail', to=userobj.email, subject=_(\"Password changed\"), message=body)"}], "vul_patch": "--- a/rdiffweb/core/notification.py\n+++ b/rdiffweb/core/notification.py\n@@ -8,6 +8,6 @@\n \n # Send a mail notification\n body = self.app.templates.compile_template(\n- \"access_token_added.html\", **{\"header_name\": self.app.cfg.header_name, 'user': userobj, 'name': name}\n+ \"email_access_token_added.html\", **{\"header_name\": self.app.cfg.header_name, 'user': userobj, 'name': name}\n )\n self.bus.publish('queue_mail', to=userobj.email, subject=_(\"A new access token has been created\"), message=body)\n\n--- a/rdiffweb/core/notification.py\n+++ b/rdiffweb/core/notification.py\n@@ -8,6 +8,6 @@\n \n # If the email attributes was changed, send a mail notification.\n body = self.app.templates.compile_template(\n- \"password_changed.html\", **{\"header_name\": self.app.cfg.header_name, 'user': userobj}\n+ \"email_password_changed.html\", **{\"header_name\": self.app.cfg.header_name, 'user': userobj}\n )\n self.bus.publish('queue_mail', to=userobj.email, subject=_(\"Password changed\"), message=body)\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2022-23470", "cve_description": "Galaxy is an open-source platform for data analysis. An arbitrary file read exists in Galaxy 22.01 and Galaxy 22.05 due to the switch to Gunicorn, which can be used to read any file accessible to the operating system user under which Galaxy is running. This vulnerability affects Galaxy 22.01 and higher, after the switch to gunicorn, which serve static contents directly. Additionally, the vulnerability is mitigated when using Nginx or Apache to serve /static/* contents, instead of Galaxy's internal middleware. This issue has been patched in commit `e5e6bda4f` and will be included in future releases. Users are advised to manually patch their installations. There are no known workarounds for this vulnerability.", "cwe_info": {"CWE-22": {"name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory."}}, "repo": "https://github.com/galaxyproject/galaxy", "patch_url": ["https://github.com/galaxyproject/galaxy/commit/e5e6bda4f014f807ca77ee0cf6af777a55918346"], "programing_language": "Python", "vul_func": [{"id": "vul_py_108_1", "commit": "7136d72", "file_path": "lib/galaxy/web/framework/middleware/static.py", "start_line": 17, "end_line": 60, "snippet": " def __call__(self, environ, start_response):\n path_info = environ.get('PATH_INFO', '')\n if not path_info:\n # See if this is a static file hackishly mapped.\n if os.path.exists(self.directory) and os.path.isfile(self.directory):\n app = FileApp(self.directory)\n if self.cache_seconds:\n app.cache_control(max_age=int(self.cache_seconds))\n return app(environ, start_response)\n return self.add_slash(environ, start_response)\n if path_info == '/':\n # @@: This should obviously be configurable\n filename = 'index.html'\n else:\n filename = request.path_info_pop(environ)\n\n directory = self.directory\n host = environ.get('HTTP_HOST')\n if self.directory_per_host and host:\n for host_key, host_val in self.directory_per_host.items():\n if host_key in host:\n directory = host_val\n break\n\n full = os.path.join(directory, filename)\n if not os.path.exists(full):\n return self.not_found(environ, start_response)\n if os.path.isdir(full):\n # @@: Cache?\n return self.__class__(full)(environ, start_response)\n if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':\n return self.error_extra_path(environ, start_response)\n if_none_match = environ.get('HTTP_IF_NONE_MATCH')\n if if_none_match:\n mytime = os.stat(full).st_mtime\n if str(mytime) == if_none_match:\n headers: List[Tuple[str, str]] = []\n ETAG.update(headers, mytime)\n start_response('304 Not Modified', headers)\n return [''] # empty body\n app = FileApp(full)\n if self.cache_seconds:\n app.cache_control(max_age=int(self.cache_seconds))\n return app(environ, start_response)"}], "fix_func": [{"id": "fix_py_108_1", "commit": "e5e6bda", "file_path": "lib/galaxy/web/framework/middleware/static.py", "start_line": 17, "end_line": 64, "snippet": " def __call__(self, environ, start_response):\n path_info = environ.get('PATH_INFO', '')\n if not path_info:\n # See if this is a static file hackishly mapped.\n if os.path.exists(self.directory) and os.path.isfile(self.directory):\n app = FileApp(self.directory)\n if self.cache_seconds:\n app.cache_control(max_age=int(self.cache_seconds))\n return app(environ, start_response)\n return self.add_slash(environ, start_response)\n if path_info == '/':\n # @@: This should obviously be configurable\n filename = 'index.html'\n else:\n filename = request.path_info_pop(environ)\n\n directory = self.directory\n host = environ.get('HTTP_HOST')\n if self.directory_per_host and host:\n for host_key, host_val in self.directory_per_host.items():\n if host_key in host:\n directory = host_val\n break\n\n full = self.normpath(os.path.join(directory, filename))\n if not full.startswith(directory):\n # Out of bounds\n return self.not_found(environ, start_response)\n\n if not os.path.exists(full):\n return self.not_found(environ, start_response)\n if os.path.isdir(full):\n # @@: Cache?\n return self.__class__(full)(environ, start_response)\n if environ.get('PATH_INFO') and environ.get('PATH_INFO') != '/':\n return self.error_extra_path(environ, start_response)\n if_none_match = environ.get('HTTP_IF_NONE_MATCH')\n if if_none_match:\n mytime = os.stat(full).st_mtime\n if str(mytime) == if_none_match:\n headers: List[Tuple[str, str]] = []\n ETAG.update(headers, mytime)\n start_response('304 Not Modified', headers)\n return [''] # empty body\n app = FileApp(full)\n if self.cache_seconds:\n app.cache_control(max_age=int(self.cache_seconds))\n return app(environ, start_response)"}], "vul_patch": "--- a/lib/galaxy/web/framework/middleware/static.py\n+++ b/lib/galaxy/web/framework/middleware/static.py\n@@ -22,7 +22,11 @@\n directory = host_val\n break\n \n- full = os.path.join(directory, filename)\n+ full = self.normpath(os.path.join(directory, filename))\n+ if not full.startswith(directory):\n+ # Out of bounds\n+ return self.not_found(environ, start_response)\n+\n if not os.path.exists(full):\n return self.not_found(environ, start_response)\n if os.path.isdir(full):\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2024-52294", "cve_description": "Khoj is a self-hostable artificial intelligence app. Prior to version 1.29.10, an Insecure Direct Object Reference (IDOR) vulnerability in the update_subscription endpoint allows any authenticated user to manipulate other users' Stripe subscriptions by simply modifying the email parameter in the request. The vulnerability exists in the subscription endpoint at `/api/subscription`. The endpoint uses an email parameter as a direct reference to user subscriptions without verifying object ownership. While authentication is required, there is no authorization check to verify if the authenticated user owns the referenced subscription. The issue was fixed in version 1.29.10. Support for arbitrarily presenting an email for update has been deprecated.", "cwe_info": {"CWE-862": {"name": "Missing Authorization", "description": "The product does not perform an authorization check when an actor attempts to access a resource or perform an action."}, "CWE-639": {"name": "Authorization Bypass Through User-Controlled Key", "description": "The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data."}}, "repo": "https://github.com/khoj-ai/khoj", "patch_url": ["https://github.com/khoj-ai/khoj/commit/47d3c8c23597900af708bdc60aced3ae5d2064c1"], "programing_language": "Python", "vul_func": [{"id": "vul_py_286_1", "commit": "d702710", "file_path": "src/khoj/routers/api_subscription.py", "start_line": 97, "end_line": 120, "snippet": "async def update_subscription(request: Request, email: str, operation: str):\n # Retrieve the customer's details\n customers = stripe.Customer.list(email=email).auto_paging_iter()\n customer = next(customers, None)\n if customer is None:\n return {\"success\": False, \"message\": \"Customer not found\"}\n\n if operation == \"cancel\":\n customer_id = customer.id\n for subscription in stripe.Subscription.list(customer=customer_id):\n stripe.Subscription.modify(subscription.id, cancel_at_period_end=True)\n return {\"success\": True}\n\n elif operation == \"resubscribe\":\n subscriptions = stripe.Subscription.list(customer=customer.id).auto_paging_iter()\n # Find the subscription that is set to cancel at the end of the period\n for subscription in subscriptions:\n if subscription.cancel_at_period_end:\n # Update the subscription to not cancel at the end of the period\n stripe.Subscription.modify(subscription.id, cancel_at_period_end=False)\n return {\"success\": True}\n return {\"success\": False, \"message\": \"No subscription found that is set to cancel\"}\n\n return {\"success\": False, \"message\": \"Invalid operation\"}"}], "fix_func": [{"id": "fix_py_286_1", "commit": "47d3c8c23597900af708bdc60aced3ae5d2064c1", "file_path": "src/khoj/routers/api_subscription.py", "start_line": 97, "end_line": 121, "snippet": "async def update_subscription(request: Request, operation: str):\n # Retrieve the customer's details\n email = request.user.object.email\n customers = stripe.Customer.list(email=email).auto_paging_iter()\n customer = next(customers, None)\n if customer is None:\n return {\"success\": False, \"message\": \"Customer not found\"}\n\n if operation == \"cancel\":\n customer_id = customer.id\n for subscription in stripe.Subscription.list(customer=customer_id):\n stripe.Subscription.modify(subscription.id, cancel_at_period_end=True)\n return {\"success\": True}\n\n elif operation == \"resubscribe\":\n subscriptions = stripe.Subscription.list(customer=customer.id).auto_paging_iter()\n # Find the subscription that is set to cancel at the end of the period\n for subscription in subscriptions:\n if subscription.cancel_at_period_end:\n # Update the subscription to not cancel at the end of the period\n stripe.Subscription.modify(subscription.id, cancel_at_period_end=False)\n return {\"success\": True}\n return {\"success\": False, \"message\": \"No subscription found that is set to cancel\"}\n\n return {\"success\": False, \"message\": \"Invalid operation\"}"}], "vul_patch": "--- a/src/khoj/routers/api_subscription.py\n+++ b/src/khoj/routers/api_subscription.py\n@@ -1,5 +1,6 @@\n-async def update_subscription(request: Request, email: str, operation: str):\n+async def update_subscription(request: Request, operation: str):\n # Retrieve the customer's details\n+ email = request.user.object.email\n customers = stripe.Customer.list(email=email).auto_paging_iter()\n customer = next(customers, None)\n if customer is None:\n\n", "poc_patch": null, "unit_test_cmd": null} @@ -333,7 +333,7 @@ {"cve_id": "CVE-2020-7631", "cve_description": "diskusage-ng through 0.2.4 is vulnerable to Command Injection.It allows execution of arbitrary commands via the path argument.", "cwe_info": {"CWE-78": {"name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component."}}, "repo": "https://github.com/iximiuz/node-diskusage-ng", "patch_url": ["https://github.com/iximiuz/node-diskusage-ng/commit/48e7e093486b528f0c81ec699573e0e4a431b8d3"], "programing_language": "JavaScript", "vul_func": [{"id": "vul_js_15_1", "commit": "53c505506553c83861d1bd67823d6a382d3a5a43", "file_path": "lib/posix.js", "start_line": 6, "end_line": 22, "snippet": "function diskusage(path, cb) {\n if (path.indexOf('\"') !== -1) {\n return cb(new Error('Paths with double quotes are not supported yet'));\n }\n\n exec('df -k \"' + path + '\"', function(err, stdout) {\n if (err) {\n return cb(err);\n }\n\n try {\n cb(null, parse(stdout));\n } catch (e) {\n cb(e);\n }\n });\n}"}], "fix_func": [{"id": "fix_js_15_1", "commit": "48e7e093486b528f0c81ec699573e0e4a431b8d3", "file_path": "lib/posix.js", "start_line": 6, "end_line": 18, "snippet": "function diskusage(path, cb) {\n execFile('df', ['-k', path], function(err, stdout) {\n if (err) {\n return cb(err);\n }\n\n try {\n cb(null, parse(stdout));\n } catch (e) {\n cb(e);\n }\n });\n}"}, {"id": "fix_js_15_2", "commit": "48e7e093486b528f0c81ec699573e0e4a431b8d3", "file_path": "lib/posix.js", "start_line": 3, "end_line": 3, "snippet": "var execFile = require('child_process').execFile;"}], "vul_patch": "--- a/lib/posix.js\n+++ b/lib/posix.js\n@@ -1,9 +1,5 @@\n function diskusage(path, cb) {\n- if (path.indexOf('\"') !== -1) {\n- return cb(new Error('Paths with double quotes are not supported yet'));\n- }\n-\n- exec('df -k \"' + path + '\"', function(err, stdout) {\n+ execFile('df', ['-k', path], function(err, stdout) {\n if (err) {\n return cb(err);\n }\n\n--- /dev/null\n+++ b/lib/posix.js\n@@ -0,0 +1 @@\n+var execFile = require('child_process').execFile;\n\n", "poc_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2020-7631:latest\n# bash /workspace/fix-run.sh\nset -e\n\ncd /workspace/node-diskusage-ng\ngit apply --whitespace=nowarn /workspace/test.patch /workspace/fix.patch\njest ./poc\n", "unit_test_cmd": null} {"cve_id": "CVE-2023-46119", "cve_description": "Parse Server is an open source backend that can be deployed to any infrastructure that can run Node.js. Parse Server crashes when uploading a file without extension. This vulnerability has been patched in versions 5.5.6 and 6.3.1.\n\n", "cwe_info": {"CWE-73": {"name": "External Control of File Name or Path", "description": "The product allows user input to control or influence paths or file names that are used in filesystem operations."}, "CWE-22": {"name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory."}}, "repo": "https://github.com/parse-community/parse-server", "patch_url": ["https://github.com/parse-community/parse-server/commit/686a9f282dc23c31beab3d93e6d21ccd0e1328fe", "https://github.com/parse-community/parse-server/commit/fd86278919556d3682e7e2c856dfccd5beffbfc0"], "programing_language": "JavaScript", "vul_func": [{"id": "vul_js_122_1", "commit": "0bb63d8", "file_path": "src/Routers/FilesRouter.js", "start_line": 102, "end_line": 256, "snippet": " async createHandler(req, res, next) {\n const config = req.config;\n const user = req.auth.user;\n const isMaster = req.auth.isMaster;\n const isLinked = user && Parse.AnonymousUtils.isLinked(user);\n if (!isMaster && !config.fileUpload.enableForAnonymousUser && isLinked) {\n next(\n new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'File upload by anonymous user is disabled.')\n );\n return;\n }\n if (!isMaster && !config.fileUpload.enableForAuthenticatedUser && !isLinked && user) {\n next(\n new Parse.Error(\n Parse.Error.FILE_SAVE_ERROR,\n 'File upload by authenticated user is disabled.'\n )\n );\n return;\n }\n if (!isMaster && !config.fileUpload.enableForPublic && !user) {\n next(new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'File upload by public is disabled.'));\n return;\n }\n const filesController = config.filesController;\n const { filename } = req.params;\n const contentType = req.get('Content-type');\n\n if (!req.body || !req.body.length) {\n next(new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'Invalid file upload.'));\n return;\n }\n\n const error = filesController.validateFilename(filename);\n if (error) {\n next(error);\n return;\n }\n\n const fileExtensions = config.fileUpload?.fileExtensions;\n if (!isMaster && fileExtensions) {\n const isValidExtension = extension => {\n return fileExtensions.some(ext => {\n if (ext === '*') {\n return true;\n }\n const regex = new RegExp(fileExtensions);\n if (regex.test(extension)) {\n return true;\n }\n });\n };\n let extension = contentType;\n if (filename && filename.includes('.')) {\n extension = filename.split('.')[1];\n } else if (contentType && contentType.includes('/')) {\n extension = contentType.split('/')[1];\n }\n extension = extension.split(' ').join('');\n\n if (!isValidExtension(extension)) {\n next(\n new Parse.Error(\n Parse.Error.FILE_SAVE_ERROR,\n `File upload of extension ${extension} is disabled.`\n )\n );\n return;\n }\n }\n\n const base64 = req.body.toString('base64');\n const file = new Parse.File(filename, { base64 }, contentType);\n const { metadata = {}, tags = {} } = req.fileData || {};\n try {\n // Scan request data for denied keywords\n Utils.checkProhibitedKeywords(config, metadata);\n Utils.checkProhibitedKeywords(config, tags);\n } catch (error) {\n next(new Parse.Error(Parse.Error.INVALID_KEY_NAME, error));\n return;\n }\n file.setTags(tags);\n file.setMetadata(metadata);\n const fileSize = Buffer.byteLength(req.body);\n const fileObject = { file, fileSize };\n try {\n // run beforeSaveFile trigger\n const triggerResult = await triggers.maybeRunFileTrigger(\n triggers.Types.beforeSave,\n fileObject,\n config,\n req.auth\n );\n let saveResult;\n // if a new ParseFile is returned check if it's an already saved file\n if (triggerResult instanceof Parse.File) {\n fileObject.file = triggerResult;\n if (triggerResult.url()) {\n // set fileSize to null because we wont know how big it is here\n fileObject.fileSize = null;\n saveResult = {\n url: triggerResult.url(),\n name: triggerResult._name,\n };\n }\n }\n // if the file returned by the trigger has already been saved skip saving anything\n if (!saveResult) {\n // if the ParseFile returned is type uri, download the file before saving it\n await addFileDataIfNeeded(fileObject.file);\n // update fileSize\n const bufferData = Buffer.from(fileObject.file._data, 'base64');\n fileObject.fileSize = Buffer.byteLength(bufferData);\n // prepare file options\n const fileOptions = {\n metadata: fileObject.file._metadata,\n };\n // some s3-compatible providers (DigitalOcean, Linode) do not accept tags\n // so we do not include the tags option if it is empty.\n const fileTags =\n Object.keys(fileObject.file._tags).length > 0 ? { tags: fileObject.file._tags } : {};\n Object.assign(fileOptions, fileTags);\n // save file\n const createFileResult = await filesController.createFile(\n config,\n fileObject.file._name,\n bufferData,\n fileObject.file._source.type,\n fileOptions\n );\n // update file with new data\n fileObject.file._name = createFileResult.name;\n fileObject.file._url = createFileResult.url;\n fileObject.file._requestTask = null;\n fileObject.file._previousSave = Promise.resolve(fileObject.file);\n saveResult = {\n url: createFileResult.url,\n name: createFileResult.name,\n };\n }\n // run afterSaveFile trigger\n await triggers.maybeRunFileTrigger(triggers.Types.afterSave, fileObject, config, req.auth);\n res.status(201);\n res.set('Location', saveResult.url);\n res.json(saveResult);\n } catch (e) {\n logger.error('Error creating a file: ', e);\n const error = triggers.resolveError(e, {\n code: Parse.Error.FILE_SAVE_ERROR,\n message: `Could not store file: ${fileObject.file._name}.`,\n });\n next(error);\n }\n }"}], "fix_func": [{"id": "fix_js_122_1", "commit": "686a9f2", "file_path": "src/Routers/FilesRouter.js", "start_line": 102, "end_line": 256, "snippet": " async createHandler(req, res, next) {\n const config = req.config;\n const user = req.auth.user;\n const isMaster = req.auth.isMaster;\n const isLinked = user && Parse.AnonymousUtils.isLinked(user);\n if (!isMaster && !config.fileUpload.enableForAnonymousUser && isLinked) {\n next(\n new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'File upload by anonymous user is disabled.')\n );\n return;\n }\n if (!isMaster && !config.fileUpload.enableForAuthenticatedUser && !isLinked && user) {\n next(\n new Parse.Error(\n Parse.Error.FILE_SAVE_ERROR,\n 'File upload by authenticated user is disabled.'\n )\n );\n return;\n }\n if (!isMaster && !config.fileUpload.enableForPublic && !user) {\n next(new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'File upload by public is disabled.'));\n return;\n }\n const filesController = config.filesController;\n const { filename } = req.params;\n const contentType = req.get('Content-type');\n\n if (!req.body || !req.body.length) {\n next(new Parse.Error(Parse.Error.FILE_SAVE_ERROR, 'Invalid file upload.'));\n return;\n }\n\n const error = filesController.validateFilename(filename);\n if (error) {\n next(error);\n return;\n }\n\n const fileExtensions = config.fileUpload?.fileExtensions;\n if (!isMaster && fileExtensions) {\n const isValidExtension = extension => {\n return fileExtensions.some(ext => {\n if (ext === '*') {\n return true;\n }\n const regex = new RegExp(fileExtensions);\n if (regex.test(extension)) {\n return true;\n }\n });\n };\n let extension = contentType;\n if (filename && filename.includes('.')) {\n extension = filename.split('.')[1];\n } else if (contentType && contentType.includes('/')) {\n extension = contentType.split('/')[1];\n }\n extension = extension?.split(' ')?.join('');\n\n if (extension && !isValidExtension(extension)) {\n next(\n new Parse.Error(\n Parse.Error.FILE_SAVE_ERROR,\n `File upload of extension ${extension} is disabled.`\n )\n );\n return;\n }\n }\n\n const base64 = req.body.toString('base64');\n const file = new Parse.File(filename, { base64 }, contentType);\n const { metadata = {}, tags = {} } = req.fileData || {};\n try {\n // Scan request data for denied keywords\n Utils.checkProhibitedKeywords(config, metadata);\n Utils.checkProhibitedKeywords(config, tags);\n } catch (error) {\n next(new Parse.Error(Parse.Error.INVALID_KEY_NAME, error));\n return;\n }\n file.setTags(tags);\n file.setMetadata(metadata);\n const fileSize = Buffer.byteLength(req.body);\n const fileObject = { file, fileSize };\n try {\n // run beforeSaveFile trigger\n const triggerResult = await triggers.maybeRunFileTrigger(\n triggers.Types.beforeSave,\n fileObject,\n config,\n req.auth\n );\n let saveResult;\n // if a new ParseFile is returned check if it's an already saved file\n if (triggerResult instanceof Parse.File) {\n fileObject.file = triggerResult;\n if (triggerResult.url()) {\n // set fileSize to null because we wont know how big it is here\n fileObject.fileSize = null;\n saveResult = {\n url: triggerResult.url(),\n name: triggerResult._name,\n };\n }\n }\n // if the file returned by the trigger has already been saved skip saving anything\n if (!saveResult) {\n // if the ParseFile returned is type uri, download the file before saving it\n await addFileDataIfNeeded(fileObject.file);\n // update fileSize\n const bufferData = Buffer.from(fileObject.file._data, 'base64');\n fileObject.fileSize = Buffer.byteLength(bufferData);\n // prepare file options\n const fileOptions = {\n metadata: fileObject.file._metadata,\n };\n // some s3-compatible providers (DigitalOcean, Linode) do not accept tags\n // so we do not include the tags option if it is empty.\n const fileTags =\n Object.keys(fileObject.file._tags).length > 0 ? { tags: fileObject.file._tags } : {};\n Object.assign(fileOptions, fileTags);\n // save file\n const createFileResult = await filesController.createFile(\n config,\n fileObject.file._name,\n bufferData,\n fileObject.file._source.type,\n fileOptions\n );\n // update file with new data\n fileObject.file._name = createFileResult.name;\n fileObject.file._url = createFileResult.url;\n fileObject.file._requestTask = null;\n fileObject.file._previousSave = Promise.resolve(fileObject.file);\n saveResult = {\n url: createFileResult.url,\n name: createFileResult.name,\n };\n }\n // run afterSaveFile trigger\n await triggers.maybeRunFileTrigger(triggers.Types.afterSave, fileObject, config, req.auth);\n res.status(201);\n res.set('Location', saveResult.url);\n res.json(saveResult);\n } catch (e) {\n logger.error('Error creating a file: ', e);\n const error = triggers.resolveError(e, {\n code: Parse.Error.FILE_SAVE_ERROR,\n message: `Could not store file: ${fileObject.file._name}.`,\n });\n next(error);\n }\n }"}], "vul_patch": "--- a/src/Routers/FilesRouter.js\n+++ b/src/Routers/FilesRouter.js\n@@ -56,9 +56,9 @@\n } else if (contentType && contentType.includes('/')) {\n extension = contentType.split('/')[1];\n }\n- extension = extension.split(' ').join('');\n+ extension = extension?.split(' ')?.join('');\n \n- if (!isValidExtension(extension)) {\n+ if (extension && !isValidExtension(extension)) {\n next(\n new Parse.Error(\n Parse.Error.FILE_SAVE_ERROR,\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2017-1001003", "cve_description": "math.js before 3.17.0 had an issue where private properties such as a constructor could be replaced by using unicode characters when creating an object.", "cwe_info": {"CWE-20": {"name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly."}}, "repo": "https://github.com/josdejong/mathjs", "patch_url": ["https://github.com/josdejong/mathjs/commit/a60f3c8d9dd714244aed7a5569c3dccaa3a4e761"], "programing_language": "JavaScript", "vul_func": [{"id": "vul_js_68_1", "commit": "8d2d48d81", "file_path": "lib/expression/node/ObjectNode.js", "start_line": 55, "end_line": 71, "snippet": " function compileObjectNode(node, defs, args) {\n if (!(node instanceof ObjectNode)) {\n throw new TypeError('No valid ObjectNode')\n }\n\n var entries = [];\n for (var key in node.properties) {\n if (hasOwnProperty(node.properties, key)) {\n if (!isSafeProperty(node.properties, key)) {\n throw new Error('No access to property \"' + key + '\"');\n }\n\n entries.push(stringify(key) + ': ' + compile(node.properties[key], defs, args));\n }\n }\n return '{' + entries.join(', ') + '}';\n }"}], "fix_func": [{"id": "fix_js_68_1", "commit": "a60f3c8d9dd714244aed7a5569c3dccaa3a4e761", "file_path": "lib/expression/node/ObjectNode.js", "start_line": 55, "end_line": 75, "snippet": " function compileObjectNode(node, defs, args) {\n if (!(node instanceof ObjectNode)) {\n throw new TypeError('No valid ObjectNode')\n }\n\n var entries = [];\n for (var key in node.properties) {\n if (hasOwnProperty(node.properties, key)) {\n // we stringify/parse the key here to resolve unicode characters,\n // so you cannot create a key like {\"co\\\\u006Estructor\": null} \n var stringifiedKey = stringify(key)\n var parsedKey = JSON.parse(stringifiedKey)\n if (!isSafeProperty(node.properties, parsedKey)) {\n throw new Error('No access to property \"' + parsedKey + '\"');\n }\n\n entries.push(stringifiedKey + ': ' + compile(node.properties[key], defs, args));\n }\n }\n return '{' + entries.join(', ') + '}';\n }"}], "vul_patch": "--- a/lib/expression/node/ObjectNode.js\n+++ b/lib/expression/node/ObjectNode.js\n@@ -6,11 +6,15 @@\n var entries = [];\n for (var key in node.properties) {\n if (hasOwnProperty(node.properties, key)) {\n- if (!isSafeProperty(node.properties, key)) {\n- throw new Error('No access to property \"' + key + '\"');\n+ // we stringify/parse the key here to resolve unicode characters,\n+ // so you cannot create a key like {\"co\\\\u006Estructor\": null} \n+ var stringifiedKey = stringify(key)\n+ var parsedKey = JSON.parse(stringifiedKey)\n+ if (!isSafeProperty(node.properties, parsedKey)) {\n+ throw new Error('No access to property \"' + parsedKey + '\"');\n }\n \n- entries.push(stringify(key) + ': ' + compile(node.properties[key], defs, args));\n+ entries.push(stringifiedKey + ': ' + compile(node.properties[key], defs, args));\n }\n }\n return '{' + entries.join(', ') + '}';\n\n", "poc_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2017-1001003:latest\n# bash /workspace/fix-run.sh\nset -e\n\ncd /workspace/mathjs\ngit apply --whitespace=nowarn /workspace/test.patch /workspace/fix.patch\nnpx mocha --grep \"should not allow disguising forbidden properties with unicode characters\" test/expression/security.test.js\n", "unit_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2017-1001003:latest\n# bash /workspace/unit_test.sh\nset -e\n\ncd /workspace/mathjs\ngit apply --whitespace=nowarn /workspace/fix.patch\nnpx mocha --timeout 3000 test/expression/security.test.js\n"} -{"cve_id": "CVE-2018-16733", "cve_description": "In Go Ethereum (aka geth) before 1.8.14, TraceChain in eth/api_tracer.go does not verify that the end block is after the start block.", "cwe_info": {"CWE-20": {"name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly."}}, "repo": "https://github.com/ethereum/go-ethereum", "patch_url": ["https://github.com/ethereum/go-ethereum/commit/106d196ec4a6451efedc60ab15957f231fa85639"], "programing_language": "Go", "vul_func": [{"id": "vul_go_185_1", "commit": "6d1e292", "file_path": "eth/api_tracer.go", "start_line": 95, "end_line": 123, "snippet": "func (api *PrivateDebugAPI) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) {\n\t// Fetch the block interval that we want to trace\n\tvar from, to *types.Block\n\n\tswitch start {\n\tcase rpc.PendingBlockNumber:\n\t\tfrom = api.eth.miner.PendingBlock()\n\tcase rpc.LatestBlockNumber:\n\t\tfrom = api.eth.blockchain.CurrentBlock()\n\tdefault:\n\t\tfrom = api.eth.blockchain.GetBlockByNumber(uint64(start))\n\t}\n\tswitch end {\n\tcase rpc.PendingBlockNumber:\n\t\tto = api.eth.miner.PendingBlock()\n\tcase rpc.LatestBlockNumber:\n\t\tto = api.eth.blockchain.CurrentBlock()\n\tdefault:\n\t\tto = api.eth.blockchain.GetBlockByNumber(uint64(end))\n\t}\n\t// Trace the chain if we've found all our blocks\n\tif from == nil {\n\t\treturn nil, fmt.Errorf(\"starting block #%d not found\", start)\n\t}\n\tif to == nil {\n\t\treturn nil, fmt.Errorf(\"end block #%d not found\", end)\n\t}\n\treturn api.traceChain(ctx, from, to, config)\n}"}], "fix_func": [{"id": "fix_go_185_1", "commit": "6d1e292", "file_path": "eth/api_tracer.go", "start_line": 95, "end_line": 126, "snippet": "func (api *PrivateDebugAPI) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) {\n\t// Fetch the block interval that we want to trace\n\tvar from, to *types.Block\n\n\tswitch start {\n\tcase rpc.PendingBlockNumber:\n\t\tfrom = api.eth.miner.PendingBlock()\n\tcase rpc.LatestBlockNumber:\n\t\tfrom = api.eth.blockchain.CurrentBlock()\n\tdefault:\n\t\tfrom = api.eth.blockchain.GetBlockByNumber(uint64(start))\n\t}\n\tswitch end {\n\tcase rpc.PendingBlockNumber:\n\t\tto = api.eth.miner.PendingBlock()\n\tcase rpc.LatestBlockNumber:\n\t\tto = api.eth.blockchain.CurrentBlock()\n\tdefault:\n\t\tto = api.eth.blockchain.GetBlockByNumber(uint64(end))\n\t}\n\t// Trace the chain if we've found all our blocks\n\tif from == nil {\n\t\treturn nil, fmt.Errorf(\"starting block #%d not found\", start)\n\t}\n\tif to == nil {\n\t\treturn nil, fmt.Errorf(\"end block #%d not found\", end)\n\t}\n\treturn api.traceChain(ctx, from, to, config)\n}\n\n// traceChain configures a new tracer according to the provided configuration, and\n// executes all the transactions contained within. The return value will be one item"}], "vul_patch": "--- a/eth/api_tracer.go\n+++ b/eth/api_tracer.go\n@@ -27,3 +27,6 @@\n \t}\n \treturn api.traceChain(ctx, from, to, config)\n }\n+\n+// traceChain configures a new tracer according to the provided configuration, and\n+// executes all the transactions contained within. The return value will be one item\n\n", "poc_patch": null, "unit_test_cmd": null} +{"cve_id": "CVE-2018-16733", "cve_description": "In Go Ethereum (aka geth) before 1.8.14, TraceChain in eth/api_tracer.go does not verify that the end block is after the start block.", "cwe_info": {"CWE-20": {"name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly."}}, "repo": "https://github.com/ethereum/go-ethereum", "patch_url": ["https://github.com/ethereum/go-ethereum/commit/106d196ec4a6451efedc60ab15957f231fa85639"], "programing_language": "Go", "vul_func": [{"id": "vul_go_185_1", "commit": "6d1e292", "file_path": "eth/api_tracer.go", "start_line": 95, "end_line": 123, "snippet": "func (api *PrivateDebugAPI) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) {\n\t// Fetch the block interval that we want to trace\n\tvar from, to *types.Block\n\n\tswitch start {\n\tcase rpc.PendingBlockNumber:\n\t\tfrom = api.eth.miner.PendingBlock()\n\tcase rpc.LatestBlockNumber:\n\t\tfrom = api.eth.blockchain.CurrentBlock()\n\tdefault:\n\t\tfrom = api.eth.blockchain.GetBlockByNumber(uint64(start))\n\t}\n\tswitch end {\n\tcase rpc.PendingBlockNumber:\n\t\tto = api.eth.miner.PendingBlock()\n\tcase rpc.LatestBlockNumber:\n\t\tto = api.eth.blockchain.CurrentBlock()\n\tdefault:\n\t\tto = api.eth.blockchain.GetBlockByNumber(uint64(end))\n\t}\n\t// Trace the chain if we've found all our blocks\n\tif from == nil {\n\t\treturn nil, fmt.Errorf(\"starting block #%d not found\", start)\n\t}\n\tif to == nil {\n\t\treturn nil, fmt.Errorf(\"end block #%d not found\", end)\n\t}\n\treturn api.traceChain(ctx, from, to, config)\n}"}], "fix_func": [{"id": "fix_go_185_1", "commit": "106d196ec4a6451efedc60ab15957f231fa85639", "file_path": "eth/api_tracer.go", "start_line": 95, "end_line": 126, "snippet": "func (api *PrivateDebugAPI) TraceChain(ctx context.Context, start, end rpc.BlockNumber, config *TraceConfig) (*rpc.Subscription, error) {\n\t// Fetch the block interval that we want to trace\n\tvar from, to *types.Block\n\n\tswitch start {\n\tcase rpc.PendingBlockNumber:\n\t\tfrom = api.eth.miner.PendingBlock()\n\tcase rpc.LatestBlockNumber:\n\t\tfrom = api.eth.blockchain.CurrentBlock()\n\tdefault:\n\t\tfrom = api.eth.blockchain.GetBlockByNumber(uint64(start))\n\t}\n\tswitch end {\n\tcase rpc.PendingBlockNumber:\n\t\tto = api.eth.miner.PendingBlock()\n\tcase rpc.LatestBlockNumber:\n\t\tto = api.eth.blockchain.CurrentBlock()\n\tdefault:\n\t\tto = api.eth.blockchain.GetBlockByNumber(uint64(end))\n\t}\n\t// Trace the chain if we've found all our blocks\n\tif from == nil {\n\t\treturn nil, fmt.Errorf(\"starting block #%d not found\", start)\n\t}\n\tif to == nil {\n\t\treturn nil, fmt.Errorf(\"end block #%d not found\", end)\n\t}\n\tif from.Number().Cmp(to.Number()) >= 0 {\n\t\treturn nil, fmt.Errorf(\"end block (#%d) needs to come after start block (#%d)\", end, start)\n\t}\n\treturn api.traceChain(ctx, from, to, config)\n}"}], "vul_patch": "--- a/eth/api_tracer.go\n+++ b/eth/api_tracer.go\n@@ -27,3 +27,6 @@\n \t}\n \treturn api.traceChain(ctx, from, to, config)\n }\n+\n+// traceChain configures a new tracer according to the provided configuration, and\n+// executes all the transactions contained within. The return value will be one item\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2017-5591", "cve_description": "An incorrect implementation of \"XEP-0280: Message Carbons\" in multiple XMPP clients allows a remote attacker to impersonate any user, including contacts, in the vulnerable application's display. This allows for various kinds of social engineering attacks. This CVE is for SleekXMPP up to 1.3.1 and Slixmpp all versions up to 1.2.3, as bundled in poezio (0.8 - 0.10) and other products.", "cwe_info": {"CWE-20": {"name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly."}}, "repo": "https://github.com/poezio/slixmpp", "patch_url": ["https://github.com/poezio/slixmpp/commit/22664ee7b86c8e010f312b66d12590fb47160ad8"], "programing_language": "Python", "vul_func": [{"id": "vul_py_253_1", "commit": "6476cfc", "file_path": "slixmpp/plugins/xep_0280/carbons.py", "start_line": 63, "end_line": 64, "snippet": " def _handle_carbon_received(self, msg):\n self.xmpp.event('carbon_received', msg)"}, {"id": "vul_py_253_2", "commit": "6476cfc", "file_path": "slixmpp/plugins/xep_0280/carbons.py", "start_line": 66, "end_line": 67, "snippet": " def _handle_carbon_sent(self, msg):\n self.xmpp.event('carbon_sent', msg)"}], "fix_func": [{"id": "fix_py_253_1", "commit": "22664ee", "file_path": "slixmpp/plugins/xep_0280/carbons.py", "start_line": 63, "end_line": 65, "snippet": " def _handle_carbon_received(self, msg):\n if msg['from'].bare == self.xmpp.boundjid.bare:\n self.xmpp.event('carbon_received', msg)"}, {"id": "fix_py_253_2", "commit": "22664ee", "file_path": "slixmpp/plugins/xep_0280/carbons.py", "start_line": 67, "end_line": 69, "snippet": " def _handle_carbon_sent(self, msg):\n if msg['from'].bare == self.xmpp.boundjid.bare:\n self.xmpp.event('carbon_sent', msg)"}], "vul_patch": "--- a/slixmpp/plugins/xep_0280/carbons.py\n+++ b/slixmpp/plugins/xep_0280/carbons.py\n@@ -1,2 +1,3 @@\n def _handle_carbon_received(self, msg):\n- self.xmpp.event('carbon_received', msg)\n+ if msg['from'].bare == self.xmpp.boundjid.bare:\n+ self.xmpp.event('carbon_received', msg)\n\n--- a/slixmpp/plugins/xep_0280/carbons.py\n+++ b/slixmpp/plugins/xep_0280/carbons.py\n@@ -1,2 +1,3 @@\n def _handle_carbon_sent(self, msg):\n- self.xmpp.event('carbon_sent', msg)\n+ if msg['from'].bare == self.xmpp.boundjid.bare:\n+ self.xmpp.event('carbon_sent', msg)\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2023-39349", "cve_description": "Sentry is an error tracking and performance monitoring platform. Starting in version 22.1.0 and prior to version 23.7.2, an attacker with access to a token with few or no scopes can query `/api/0/api-tokens/` for a list of all tokens created by a user, including tokens with greater scopes, and use those tokens in other requests. There is no evidence that the issue was exploited on `sentry.io`. For self-hosted users, it is advised to rotate user auth tokens. A fix is available in version 23.7.2 of `sentry` and `self-hosted`. There are no known workarounds.", "cwe_info": {"CWE-287": {"name": "Improper Authentication", "description": "When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct."}}, "repo": "https://github.com/getsentry/sentry", "patch_url": ["https://github.com/getsentry/sentry/commit/fad12c1150d1135edf9666ea72ca11bc110c1083"], "programing_language": "Python", "vul_func": [{"id": "vul_py_162_1", "commit": "774af7d", "file_path": "src/sentry/api/endpoints/api_tokens.py", "start_line": 24, "end_line": 83, "snippet": "class ApiTokensEndpoint(Endpoint):\n authentication_classes = (SessionAuthentication,)\n permission_classes = (IsAuthenticated,)\n\n @method_decorator(never_cache)\n def get(self, request: Request) -> Response:\n user_id = request.user.id\n if is_active_superuser(request):\n user_id = request.GET.get(\"userId\", user_id)\n\n token_list = list(\n ApiToken.objects.filter(application__isnull=True, user_id=user_id).select_related(\n \"application\"\n )\n )\n\n return Response(serialize(token_list, request.user))\n\n @method_decorator(never_cache)\n def post(self, request: Request) -> Response:\n serializer = ApiTokenSerializer(data=request.data)\n\n if serializer.is_valid():\n result = serializer.validated_data\n\n token = ApiToken.objects.create(\n user_id=request.user.id,\n scope_list=result[\"scopes\"],\n refresh_token=None,\n expires_at=None,\n )\n\n capture_security_activity(\n account=request.user,\n type=\"api-token-generated\",\n actor=request.user,\n ip_address=request.META[\"REMOTE_ADDR\"],\n context={},\n send_email=True,\n )\n\n analytics.record(\"api_token.created\", user_id=request.user.id)\n\n return Response(serialize(token, request.user), status=201)\n return Response(serializer.errors, status=400)\n\n @method_decorator(never_cache)\n def delete(self, request: Request):\n user_id = request.user.id\n if is_active_superuser(request):\n user_id = request.data.get(\"userId\", user_id)\n token = request.data.get(\"token\")\n if not token:\n return Response({\"token\": \"\"}, status=400)\n\n ApiToken.objects.filter(user_id=user_id, token=token, application__isnull=True).delete()\n\n analytics.record(\"api_token.deleted\", user_id=request.user.id)\n\n return Response(status=204)"}], "fix_func": [{"id": "fix_py_162_1", "commit": "fad12c1", "file_path": "src/sentry/api/authentication.py", "start_line": 164, "end_line": 169, "snippet": "class SessionNoAuthTokenAuthentication(SessionAuthentication):\n def authenticate(self, request: Request):\n auth = get_authorization_header(request)\n if auth:\n return None\n return super().authenticate(request)"}, {"id": "fix_py_162_2", "commit": "fad12c1", "file_path": "src/sentry/api/endpoints/api_tokens.py", "start_line": 24, "end_line": 83, "snippet": "class ApiTokensEndpoint(Endpoint):\n authentication_classes = (SessionNoAuthTokenAuthentication,)\n permission_classes = (IsAuthenticated,)\n\n @method_decorator(never_cache)\n def get(self, request: Request) -> Response:\n user_id = request.user.id\n if is_active_superuser(request):\n user_id = request.GET.get(\"userId\", user_id)\n\n token_list = list(\n ApiToken.objects.filter(application__isnull=True, user_id=user_id).select_related(\n \"application\"\n )\n )\n\n return Response(serialize(token_list, request.user))\n\n @method_decorator(never_cache)\n def post(self, request: Request) -> Response:\n serializer = ApiTokenSerializer(data=request.data)\n\n if serializer.is_valid():\n result = serializer.validated_data\n\n token = ApiToken.objects.create(\n user_id=request.user.id,\n scope_list=result[\"scopes\"],\n refresh_token=None,\n expires_at=None,\n )\n\n capture_security_activity(\n account=request.user,\n type=\"api-token-generated\",\n actor=request.user,\n ip_address=request.META[\"REMOTE_ADDR\"],\n context={},\n send_email=True,\n )\n\n analytics.record(\"api_token.created\", user_id=request.user.id)\n\n return Response(serialize(token, request.user), status=201)\n return Response(serializer.errors, status=400)\n\n @method_decorator(never_cache)\n def delete(self, request: Request):\n user_id = request.user.id\n if is_active_superuser(request):\n user_id = request.data.get(\"userId\", user_id)\n token = request.data.get(\"token\")\n if not token:\n return Response({\"token\": \"\"}, status=400)\n\n ApiToken.objects.filter(user_id=user_id, token=token, application__isnull=True).delete()\n\n analytics.record(\"api_token.deleted\", user_id=request.user.id)\n\n return Response(status=204)"}], "vul_patch": "--- a/src/sentry/api/endpoints/api_tokens.py\n+++ b/src/sentry/api/authentication.py\n@@ -1,60 +1,6 @@\n-class ApiTokensEndpoint(Endpoint):\n- authentication_classes = (SessionAuthentication,)\n- permission_classes = (IsAuthenticated,)\n-\n- @method_decorator(never_cache)\n- def get(self, request: Request) -> Response:\n- user_id = request.user.id\n- if is_active_superuser(request):\n- user_id = request.GET.get(\"userId\", user_id)\n-\n- token_list = list(\n- ApiToken.objects.filter(application__isnull=True, user_id=user_id).select_related(\n- \"application\"\n- )\n- )\n-\n- return Response(serialize(token_list, request.user))\n-\n- @method_decorator(never_cache)\n- def post(self, request: Request) -> Response:\n- serializer = ApiTokenSerializer(data=request.data)\n-\n- if serializer.is_valid():\n- result = serializer.validated_data\n-\n- token = ApiToken.objects.create(\n- user_id=request.user.id,\n- scope_list=result[\"scopes\"],\n- refresh_token=None,\n- expires_at=None,\n- )\n-\n- capture_security_activity(\n- account=request.user,\n- type=\"api-token-generated\",\n- actor=request.user,\n- ip_address=request.META[\"REMOTE_ADDR\"],\n- context={},\n- send_email=True,\n- )\n-\n- analytics.record(\"api_token.created\", user_id=request.user.id)\n-\n- return Response(serialize(token, request.user), status=201)\n- return Response(serializer.errors, status=400)\n-\n- @method_decorator(never_cache)\n- def delete(self, request: Request):\n- user_id = request.user.id\n- if is_active_superuser(request):\n- user_id = request.data.get(\"userId\", user_id)\n- token = request.data.get(\"token\")\n- if not token:\n- return Response({\"token\": \"\"}, status=400)\n-\n- ApiToken.objects.filter(user_id=user_id, token=token, application__isnull=True).delete()\n-\n- analytics.record(\"api_token.deleted\", user_id=request.user.id)\n-\n- return Response(status=204)\n+class SessionNoAuthTokenAuthentication(SessionAuthentication):\n+ def authenticate(self, request: Request):\n+ auth = get_authorization_header(request)\n+ if auth:\n+ return None\n+ return super().authenticate(request)\n\n--- /dev/null\n+++ b/src/sentry/api/authentication.py\n@@ -0,0 +1,60 @@\n+class ApiTokensEndpoint(Endpoint):\n+ authentication_classes = (SessionNoAuthTokenAuthentication,)\n+ permission_classes = (IsAuthenticated,)\n+\n+ @method_decorator(never_cache)\n+ def get(self, request: Request) -> Response:\n+ user_id = request.user.id\n+ if is_active_superuser(request):\n+ user_id = request.GET.get(\"userId\", user_id)\n+\n+ token_list = list(\n+ ApiToken.objects.filter(application__isnull=True, user_id=user_id).select_related(\n+ \"application\"\n+ )\n+ )\n+\n+ return Response(serialize(token_list, request.user))\n+\n+ @method_decorator(never_cache)\n+ def post(self, request: Request) -> Response:\n+ serializer = ApiTokenSerializer(data=request.data)\n+\n+ if serializer.is_valid():\n+ result = serializer.validated_data\n+\n+ token = ApiToken.objects.create(\n+ user_id=request.user.id,\n+ scope_list=result[\"scopes\"],\n+ refresh_token=None,\n+ expires_at=None,\n+ )\n+\n+ capture_security_activity(\n+ account=request.user,\n+ type=\"api-token-generated\",\n+ actor=request.user,\n+ ip_address=request.META[\"REMOTE_ADDR\"],\n+ context={},\n+ send_email=True,\n+ )\n+\n+ analytics.record(\"api_token.created\", user_id=request.user.id)\n+\n+ return Response(serialize(token, request.user), status=201)\n+ return Response(serializer.errors, status=400)\n+\n+ @method_decorator(never_cache)\n+ def delete(self, request: Request):\n+ user_id = request.user.id\n+ if is_active_superuser(request):\n+ user_id = request.data.get(\"userId\", user_id)\n+ token = request.data.get(\"token\")\n+ if not token:\n+ return Response({\"token\": \"\"}, status=400)\n+\n+ ApiToken.objects.filter(user_id=user_id, token=token, application__isnull=True).delete()\n+\n+ analytics.record(\"api_token.deleted\", user_id=request.user.id)\n+\n+ return Response(status=204)\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2021-21411", "cve_description": "OAuth2-Proxy is an open source reverse proxy that provides authentication with Google, Github or other providers. The `--gitlab-group` flag for group-based authorization in the GitLab provider stopped working in the v7.0.0 release. Regardless of the flag settings, authorization wasn't restricted. Additionally, any authenticated users had whichever groups were set in `--gitlab-group` added to the new `X-Forwarded-Groups` header to the upstream application. While adding GitLab project based authorization support in #630, a bug was introduced where the user session's groups field was populated with the `--gitlab-group` config entries instead of pulling the individual user's group membership from the GitLab Userinfo endpoint. When the session groups where compared against the allowed groups for authorization, they matched improperly (since both lists were populated with the same data) so authorization was allowed. This impacts GitLab Provider users who relies on group membership for authorization restrictions. Any authenticated users in your GitLab environment can access your applications regardless of `--gitlab-group` membership restrictions. This is patched in v7.1.0. There is no workaround for the Group membership bug. But `--gitlab-project` can be set to use Project membership as the authorization checks instead of groups; it is not broken.", "cwe_info": {"CWE-863": {"name": "Incorrect Authorization", "description": "The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check."}}, "repo": "https://github.com/oauth2-proxy/oauth2-proxy", "patch_url": ["https://github.com/oauth2-proxy/oauth2-proxy/commit/0279fa7dff1752f1710707dbd1ffac839de8bbfc"], "programing_language": "Go", "vul_func": [{"id": "vul_go_57_1", "commit": "73d9f38", "file_path": "./providers/gitlab.go", "start_line": 284, "end_line": 313, "snippet": "func (p *GitLabProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error {\n\t// Retrieve user info\n\tuserInfo, err := p.getUserInfo(ctx, s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to retrieve user info: %v\", err)\n\t}\n\n\t// Check if email is verified\n\tif !p.AllowUnverifiedEmail && !userInfo.EmailVerified {\n\t\treturn fmt.Errorf(\"user email is not verified\")\n\t}\n\n\ts.User = userInfo.Username\n\ts.Email = userInfo.Email\n\n\tp.addGroupsToSession(ctx, s)\n\n\tp.addProjectsToSession(ctx, s)\n\n\treturn nil\n\n}\n\n// addGroupsToSession projects into session.Groups\nfunc (p *GitLabProvider) addGroupsToSession(ctx context.Context, s *sessions.SessionState) {\n\t// Iterate over projects, check if oauth2-proxy can get project information on behalf of the user\n\tfor _, group := range p.Groups {\n\t\ts.Groups = append(s.Groups, fmt.Sprintf(\"group:%s\", group))\n\t}\n}"}], "fix_func": [{"id": "fix_go_57_1", "commit": "0279fa7dff1752f1710707dbd1ffac839de8bbfc", "file_path": "./providers/gitlab.go", "start_line": 284, "end_line": 305, "snippet": "func (p *GitLabProvider) EnrichSession(ctx context.Context, s *sessions.SessionState) error {\n\t// Retrieve user info\n\tuserInfo, err := p.getUserInfo(ctx, s)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to retrieve user info: %v\", err)\n\t}\n\n\t// Check if email is verified\n\tif !p.AllowUnverifiedEmail && !userInfo.EmailVerified {\n\t\treturn fmt.Errorf(\"user email is not verified\")\n\t}\n\n\ts.User = userInfo.Username\n\ts.Email = userInfo.Email\n\tfor _, group := range userInfo.Groups {\n\t\ts.Groups = append(s.Groups, fmt.Sprintf(\"group:%s\", group))\n\t}\n\n\tp.addProjectsToSession(ctx, s)\n\n\treturn nil\n}"}], "vul_patch": "--- a/./providers/gitlab.go\n+++ b/./providers/gitlab.go\n@@ -12,19 +12,11 @@\n \n \ts.User = userInfo.Username\n \ts.Email = userInfo.Email\n-\n-\tp.addGroupsToSession(ctx, s)\n+\tfor _, group := range userInfo.Groups {\n+\t\ts.Groups = append(s.Groups, fmt.Sprintf(\"group:%s\", group))\n+\t}\n \n \tp.addProjectsToSession(ctx, s)\n \n \treturn nil\n-\n }\n-\n-// addGroupsToSession projects into session.Groups\n-func (p *GitLabProvider) addGroupsToSession(ctx context.Context, s *sessions.SessionState) {\n-\t// Iterate over projects, check if oauth2-proxy can get project information on behalf of the user\n-\tfor _, group := range p.Groups {\n-\t\ts.Groups = append(s.Groups, fmt.Sprintf(\"group:%s\", group))\n-\t}\n-}\n\n", "poc_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2021-21411:latest\n# bash /workspace/fix-run.sh\nset -e\n\ncd /workspace/oauth2-proxy\nrm -rf ./providers/gitlab_test.go\ngit apply --whitespace=nowarn /workspace/test.patch /workspace/fix.patch\ngo test -timeout 30s -v -run 'TestProviderSuite/when_filtering_on_gitlab_entities' github.com/oauth2-proxy/oauth2-proxy/v7/providers\n", "unit_test_cmd": null} @@ -409,7 +409,7 @@ {"cve_id": "CVE-2022-30428", "cve_description": "In ginadmin through 05-10-2022, the incoming path value is not filtered, resulting in arbitrary file reading.", "cwe_info": {"CWE-73": {"name": "External Control of File Name or Path", "description": "The product allows user input to control or influence paths or file names that are used in filesystem operations."}, "CWE-22": {"name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory."}}, "repo": "https://github.com/gphper/ginadmin", "patch_url": ["https://github.com/gphper/ginadmin/commit/726109f01ad23523715f36f7d272958064666a30"], "programing_language": "Go", "vul_func": [{"id": "vul_go_224_1", "commit": "f519fa8", "file_path": "internal/controllers/admin/setting/adminSystemController.go", "start_line": 67, "end_line": 108, "snippet": "func (con adminSystemController) GetDir(c *gin.Context) {\n\n\ttype FileNode struct {\n\t\tName string `json:\"name\"`\n\t\tPath string `json:\"path\"`\n\t\tType string `json:\"type\"`\n\t}\n\n\tvar (\n\t\tpath string\n\t\terr error\n\t\tfileSlice []FileNode\n\t\tfiles []fs.FileInfo\n\t)\n\n\tfileSlice = make([]FileNode, 0)\n\tpath = gstrings.JoinStr(configs.RootPath, c.Query(\"path\"))\n\n\tfiles, err = ioutil.ReadDir(path)\n\tif err != nil {\n\t\tcon.Error(c, \"\\u83b7\\u53d6\\u76ee\\u5f55\\u5931\\u8d25\")\n\t\treturn\n\t}\n\n\tfor _, v := range files {\n\t\tvar fileType string\n\t\tif v.IsDir() {\n\t\t\tfileType = \"dir\"\n\t\t} else {\n\t\t\tfileType = \"file\"\n\t\t}\n\t\tfileSlice = append(fileSlice, FileNode{\n\t\t\tName: v.Name(),\n\t\t\tPath: gstrings.JoinStr(c.Query(\"path\"), string(filepath.Separator), v.Name()),\n\t\t\tType: fileType,\n\t\t})\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"data\": fileSlice,\n\t})\n}"}, {"id": "vul_go_224_2", "commit": "f519fa8", "file_path": "internal/controllers/admin/setting/adminSystemController.go", "start_line": 113, "end_line": 162, "snippet": "func (con adminSystemController) View(c *gin.Context) {\n\n\tvar (\n\t\terr error\n\t\tstartLine int\n\t\tendLine int\n\t\tscanner *bufio.Scanner\n\t\tline int\n\t)\n\n\tstartLine, err = strconv.Atoi(c.DefaultQuery(\"start_line\", \"1\"))\n\tif err != nil {\n\t\tcon.ErrorHtml(c, err)\n\t\treturn\n\t}\n\tendLine, err = strconv.Atoi(c.DefaultQuery(\"end_line\", \"20\"))\n\tif err != nil {\n\t\tcon.ErrorHtml(c, err)\n\t\treturn\n\t}\n\n\tvar filecontents []string\n\tfilePath := gstrings.JoinStr(configs.RootPath, c.Query(\"path\"))\n\tfi, err := os.Open(filePath)\n\tif err != nil {\n\t\tcon.ErrorHtml(c, err)\n\t\treturn\n\t}\n\tdefer fi.Close()\n\n\tscanner = bufio.NewScanner(fi)\n\tfor scanner.Scan() {\n\t\tline++\n\t\tif line >= startLine && line <= endLine {\n\t\t\t// \\u5728\\u8981\\u6c42\\u884c\\u6570\\u5185\\u53d6\\u5f97\\u6570\\u636e\n\t\t\tfilecontents = append(filecontents, scanner.Text())\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tc.HTML(http.StatusOK, \"setting/systemlog_view.html\", gin.H{\n\t\t\"file_path\": c.Query(\"path\"),\n\t\t\"filecontents\": filecontents,\n\t\t\"start_line\": startLine,\n\t\t\"end_line\": endLine,\n\t\t\"line\": line,\n\t})\n\n}"}, {"id": "vul_go_224_3", "commit": "f519fa8", "file_path": "pkg/utils/filesystem/filesystem.go", "start_line": 94, "end_line": 103, "snippet": "func JoinStr(items ...interface{}) string {\n\tif len(items) == 0 {\n\t\treturn \"\"\n\t}\n\tvar builder strings.Builder\n\tfor _, v := range items {\n\t\tbuilder.WriteString(v.(string))\n\t}\n\treturn builder.String()\n}"}], "fix_func": [{"id": "fix_go_224_1", "commit": "726109f01ad23523715f36f7d272958064666a30", "file_path": "internal/controllers/admin/setting/adminSystemController.go", "start_line": 68, "end_line": 113, "snippet": "func (con adminSystemController) GetDir(c *gin.Context) {\n\n\ttype FileNode struct {\n\t\tName string `json:\"name\"`\n\t\tPath string `json:\"path\"`\n\t\tType string `json:\"type\"`\n\t}\n\n\tvar (\n\t\tpath string\n\t\terr error\n\t\tfileSlice []FileNode\n\t\tfiles []fs.FileInfo\n\t)\n\n\tfileSlice = make([]FileNode, 0)\n\tpath, err = filesystem.FilterPath(configs.RootPath+\"logs\", c.Query(\"path\"))\n\tif err != nil {\n\t\tcon.Error(c, err.Error())\n\t\treturn\n\t}\n\n\tfiles, err = ioutil.ReadDir(path)\n\tif err != nil {\n\t\tcon.Error(c, \"\\u83b7\\u53d6\\u76ee\\u5f55\\u5931\\u8d25\")\n\t\treturn\n\t}\n\n\tfor _, v := range files {\n\t\tvar fileType string\n\t\tif v.IsDir() {\n\t\t\tfileType = \"dir\"\n\t\t} else {\n\t\t\tfileType = \"file\"\n\t\t}\n\t\tfileSlice = append(fileSlice, FileNode{\n\t\t\tName: v.Name(),\n\t\t\tPath: gstrings.JoinStr(c.Query(\"path\"), string(filepath.Separator), v.Name()),\n\t\t\tType: fileType,\n\t\t})\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"data\": fileSlice,\n\t})\n}"}, {"id": "fix_go_224_2", "commit": "726109f01ad23523715f36f7d272958064666a30", "file_path": "internal/controllers/admin/setting/adminSystemController.go", "start_line": 118, "end_line": 172, "snippet": "func (con adminSystemController) View(c *gin.Context) {\n\n\tvar (\n\t\terr error\n\t\tstartLine int\n\t\tendLine int\n\t\tscanner *bufio.Scanner\n\t\tline int\n\t)\n\n\tstartLine, err = strconv.Atoi(c.DefaultQuery(\"start_line\", \"1\"))\n\tif err != nil {\n\t\tcon.ErrorHtml(c, err)\n\t\treturn\n\t}\n\tendLine, err = strconv.Atoi(c.DefaultQuery(\"end_line\", \"20\"))\n\tif err != nil {\n\t\tcon.ErrorHtml(c, err)\n\t\treturn\n\t}\n\n\tvar filecontents []string\n\tfilePath, err := filesystem.FilterPath(configs.RootPath+\"logs\", c.Query(\"path\"))\n\tif err != nil {\n\t\tcon.ErrorHtml(c, err)\n\t\treturn\n\t}\n\n\tfi, err := os.Open(filePath)\n\tif err != nil {\n\t\tcon.ErrorHtml(c, err)\n\t\treturn\n\t}\n\tdefer fi.Close()\n\n\tscanner = bufio.NewScanner(fi)\n\tfor scanner.Scan() {\n\t\tline++\n\t\tif line >= startLine && line <= endLine {\n\t\t\t// \\u5728\\u8981\\u6c42\\u884c\\u6570\\u5185\\u53d6\\u5f97\\u6570\\u636e\n\t\t\tfilecontents = append(filecontents, scanner.Text())\n\t\t} else {\n\t\t\tcontinue\n\t\t}\n\t}\n\n\tc.HTML(http.StatusOK, \"setting/systemlog_view.html\", gin.H{\n\t\t\"file_path\": c.Query(\"path\"),\n\t\t\"filecontents\": filecontents,\n\t\t\"start_line\": startLine,\n\t\t\"end_line\": endLine,\n\t\t\"line\": line,\n\t})\n\n}"}, {"id": "fix_go_224_3", "commit": "726109f01ad23523715f36f7d272958064666a30", "file_path": "pkg/utils/filesystem/filesystem.go", "start_line": 96, "end_line": 113, "snippet": "func FilterPath(root, path string) (string, error) {\n\n\tnewPath := fmt.Sprintf(\"%s%s\", root, path)\n\tabsPath, err := filepath.Abs(newPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tabsPath = filepath.FromSlash(absPath)\n\tifOver := filepath.HasPrefix(absPath, filepath.FromSlash(root))\n\tfmt.Println(absPath)\n\tfmt.Println(filepath.FromSlash(root))\n\tif !ifOver {\n\t\treturn \"\", errors.New(\"access to the path is prohibited\")\n\t}\n\n\treturn absPath, nil\n}"}], "vul_patch": "--- a/internal/controllers/admin/setting/adminSystemController.go\n+++ b/internal/controllers/admin/setting/adminSystemController.go\n@@ -14,7 +14,11 @@\n \t)\n \n \tfileSlice = make([]FileNode, 0)\n-\tpath = gstrings.JoinStr(configs.RootPath, c.Query(\"path\"))\n+\tpath, err = filesystem.FilterPath(configs.RootPath+\"logs\", c.Query(\"path\"))\n+\tif err != nil {\n+\t\tcon.Error(c, err.Error())\n+\t\treturn\n+\t}\n \n \tfiles, err = ioutil.ReadDir(path)\n \tif err != nil {\n\n--- a/internal/controllers/admin/setting/adminSystemController.go\n+++ b/internal/controllers/admin/setting/adminSystemController.go\n@@ -20,7 +20,12 @@\n \t}\n \n \tvar filecontents []string\n-\tfilePath := gstrings.JoinStr(configs.RootPath, c.Query(\"path\"))\n+\tfilePath, err := filesystem.FilterPath(configs.RootPath+\"logs\", c.Query(\"path\"))\n+\tif err != nil {\n+\t\tcon.ErrorHtml(c, err)\n+\t\treturn\n+\t}\n+\n \tfi, err := os.Open(filePath)\n \tif err != nil {\n \t\tcon.ErrorHtml(c, err)\n\n--- a/pkg/utils/filesystem/filesystem.go\n+++ b/pkg/utils/filesystem/filesystem.go\n@@ -1,10 +1,18 @@\n-func JoinStr(items ...interface{}) string {\n-\tif len(items) == 0 {\n-\t\treturn \"\"\n+func FilterPath(root, path string) (string, error) {\n+\n+\tnewPath := fmt.Sprintf(\"%s%s\", root, path)\n+\tabsPath, err := filepath.Abs(newPath)\n+\tif err != nil {\n+\t\treturn \"\", err\n \t}\n-\tvar builder strings.Builder\n-\tfor _, v := range items {\n-\t\tbuilder.WriteString(v.(string))\n+\n+\tabsPath = filepath.FromSlash(absPath)\n+\tifOver := filepath.HasPrefix(absPath, filepath.FromSlash(root))\n+\tfmt.Println(absPath)\n+\tfmt.Println(filepath.FromSlash(root))\n+\tif !ifOver {\n+\t\treturn \"\", errors.New(\"access to the path is prohibited\")\n \t}\n-\treturn builder.String()\n+\n+\treturn absPath, nil\n }\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2021-41246", "cve_description": "Express OpenID Connect is express JS middleware implementing sign on for Express web apps using OpenID Connect. Versions before and including `2.5.1` do not regenerate the session id and session cookie when user logs in. This behavior opens up the application to various session fixation vulnerabilities. Versions `2.5.2` contains a patch for this issue.", "cwe_info": {"CWE-384": {"name": "Session Fixation", "description": "Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions."}}, "repo": "https://github.com/auth0/express-openid-connect", "patch_url": ["https://github.com/auth0/express-openid-connect/commit/5ab67ff2bd84f76674066b5e129b43ab5f2f430f"], "programing_language": "JavaScript", "vul_func": [{"id": "vul_js_60_1", "commit": "1a0c328921f875720b6268e94747025b3fcd1478", "file_path": "middleware/auth.js", "start_line": 70, "end_line": 144, "snippet": " async (req, res, next) => {\n next = cb(next).once();\n\n client =\n client ||\n (await getClient(config).catch((err) => {\n next(err);\n }));\n\n if (!client) {\n return;\n }\n\n try {\n const redirectUri = res.oidc.getRedirectUri();\n\n let session;\n\n try {\n const callbackParams = client.callbackParams(req);\n const authVerification = transient.getOnce(\n 'auth_verification',\n req,\n res\n );\n\n const { max_age, code_verifier, nonce, state } = authVerification\n ? JSON.parse(authVerification)\n : {};\n\n req.openidState = decodeState(state);\n const checks = {\n max_age,\n code_verifier,\n nonce,\n state,\n };\n\n let extras;\n if (config.tokenEndpointParams) {\n extras = { exchangeBody: config.tokenEndpointParams };\n }\n\n session = await client.callback(\n redirectUri,\n callbackParams,\n checks,\n extras\n );\n } catch (err) {\n throw createError.BadRequest(err.message);\n }\n\n if (config.afterCallback) {\n session = await config.afterCallback(\n req,\n res,\n Object.assign({}, session), // Remove non-enumerable methods from the TokenSet\n req.openidState\n );\n }\n\n Object.assign(req[config.session.name], session);\n attemptSilentLogin.resumeSilentLogin(req, res);\n\n next();\n } catch (err) {\n // Swallow errors if this is a silentLogin\n if (req.openidState && req.openidState.attemptingSilentLogin) {\n next();\n } else {\n next(err);\n }\n }\n },"}], "fix_func": [{"id": "fix_js_60_1", "commit": "5ab67ff2bd84f76674066b5e129b43ab5f2f430f", "file_path": "middleware/auth.js", "start_line": 71, "end_line": 164, "snippet": " async (req, res, next) => {\n next = cb(next).once();\n\n client =\n client ||\n (await getClient(config).catch((err) => {\n next(err);\n }));\n\n if (!client) {\n return;\n }\n\n try {\n const redirectUri = res.oidc.getRedirectUri();\n\n let tokenSet;\n\n try {\n const callbackParams = client.callbackParams(req);\n const authVerification = transient.getOnce(\n 'auth_verification',\n req,\n res\n );\n\n const { max_age, code_verifier, nonce, state } = authVerification\n ? JSON.parse(authVerification)\n : {};\n\n req.openidState = decodeState(state);\n const checks = {\n max_age,\n code_verifier,\n nonce,\n state,\n };\n\n let extras;\n if (config.tokenEndpointParams) {\n extras = { exchangeBody: config.tokenEndpointParams };\n }\n\n tokenSet = await client.callback(\n redirectUri,\n callbackParams,\n checks,\n extras\n );\n } catch (err) {\n throw createError.BadRequest(err.message);\n }\n\n let session = Object.assign({}, tokenSet); // Remove non-enumerable methods from the TokenSet\n\n if (config.afterCallback) {\n session = await config.afterCallback(\n req,\n res,\n session,\n req.openidState\n );\n }\n\n if (req.oidc.isAuthenticated()) {\n if (req.oidc.user.sub === tokenSet.claims().sub) {\n // If it's the same user logging in again, just update the existing session.\n Object.assign(req[config.session.name], session);\n } else {\n // If it's a different user, replace the session to remove any custom user\n // properties on the session\n replaceSession(req, session, config);\n // And regenerate the session id so the previous user wont know the new user's session id\n regenerateSessionStoreId(req, config);\n }\n } else {\n // If a new user is replacing an anonymous session, update the existing session to keep\n // any anonymous session state (eg. checkout basket)\n Object.assign(req[config.session.name], session);\n // But update the session store id so a previous anonymous user wont know the new user's session id\n regenerateSessionStoreId(req, config);\n }\n attemptSilentLogin.resumeSilentLogin(req, res);\n\n next();\n } catch (err) {\n // Swallow errors if this is a silentLogin\n if (req.openidState && req.openidState.attemptingSilentLogin) {\n next();\n } else {\n next(err);\n }\n }\n },"}], "vul_patch": "--- a/middleware/auth.js\n+++ b/middleware/auth.js\n@@ -14,7 +14,7 @@\n try {\n const redirectUri = res.oidc.getRedirectUri();\n \n- let session;\n+ let tokenSet;\n \n try {\n const callbackParams = client.callbackParams(req);\n@@ -41,7 +41,7 @@\n extras = { exchangeBody: config.tokenEndpointParams };\n }\n \n- session = await client.callback(\n+ tokenSet = await client.callback(\n redirectUri,\n callbackParams,\n checks,\n@@ -51,16 +51,35 @@\n throw createError.BadRequest(err.message);\n }\n \n+ let session = Object.assign({}, tokenSet); // Remove non-enumerable methods from the TokenSet\n+\n if (config.afterCallback) {\n session = await config.afterCallback(\n req,\n res,\n- Object.assign({}, session), // Remove non-enumerable methods from the TokenSet\n+ session,\n req.openidState\n );\n }\n \n- Object.assign(req[config.session.name], session);\n+ if (req.oidc.isAuthenticated()) {\n+ if (req.oidc.user.sub === tokenSet.claims().sub) {\n+ // If it's the same user logging in again, just update the existing session.\n+ Object.assign(req[config.session.name], session);\n+ } else {\n+ // If it's a different user, replace the session to remove any custom user\n+ // properties on the session\n+ replaceSession(req, session, config);\n+ // And regenerate the session id so the previous user wont know the new user's session id\n+ regenerateSessionStoreId(req, config);\n+ }\n+ } else {\n+ // If a new user is replacing an anonymous session, update the existing session to keep\n+ // any anonymous session state (eg. checkout basket)\n+ Object.assign(req[config.session.name], session);\n+ // But update the session store id so a previous anonymous user wont know the new user's session id\n+ regenerateSessionStoreId(req, config);\n+ }\n attemptSilentLogin.resumeSilentLogin(req, res);\n \n next();\n\n", "poc_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2021-41246:latest\n# bash /workspace/fix-run.sh\nset -e\n\ncd /workspace/express-openid-connect\ngit apply --whitespace=nowarn /workspace/test.patch /workspace/fix.patch\nnpx mocha --grep \"should replace the cookie session when a new user is logging in over an existing different user|should preserve session but regenerate session id when a new user is logging in over an anonymous session|should regenerate the session when a new user is logging in over an existing different user\"", "unit_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2021-41246:latest\n# bash /workspace/unit_test.sh\nset -e\n\ncd /workspace/express-openid-connect\ngit apply --whitespace=nowarn /workspace/fix.patch\nnpx mocha test/callback.tests.js "} {"cve_id": "CVE-2018-18206", "cve_description": "In the client in Bytom before 1.0.6, checkTopicRegister in p2p/discover/net.go does not prevent negative idx values, leading to a crash.", "cwe_info": {"CWE-190": {"name": "Integer Overflow or Wraparound", "description": "The product performs a calculation that can\n produce an integer overflow or wraparound when the logic\n assumes that the resulting value will always be larger than\n the original value. This occurs when an integer value is\n incremented to a value that is too large to store in the\n associated representation. When this occurs, the value may\n become a very small or negative number."}}, "repo": "https://github.com/Bytom/bytom", "patch_url": ["https://github.com/Bytom/bytom/commit/1ac3c8ac4f2b1e1df9675228290bda6b9586ba42"], "programing_language": "Go", "vul_func": [{"id": "vul_go_291_1", "commit": "69b3d4c7cf41c6628efb34ed79ad35e9e22bbf82", "file_path": "p2p/discover/net.go", "start_line": 1207, "end_line": 1228, "snippet": "func (net *Network) checkTopicRegister(data *topicRegister) (*pong, error) {\n\tvar pongpkt ingressPacket\n\tif err := decodePacket(data.Pong, &pongpkt); err != nil {\n\t\treturn nil, err\n\t}\n\tif pongpkt.ev != pongPacket {\n\t\treturn nil, errors.New(\"is not pong packet\")\n\t}\n\tif pongpkt.remoteID != net.tab.self.ID {\n\t\treturn nil, errors.New(\"not signed by us\")\n\t}\n\t// check that we previously authorised all topics\n\t// that the other side is trying to register.\n\thash, _, _ := wireHash(data.Topics)\n\tif hash != pongpkt.data.(*pong).TopicHash {\n\t\treturn nil, errors.New(\"topic hash mismatch\")\n\t}\n\tif data.Idx < 0 || int(data.Idx) >= len(data.Topics) {\n\t\treturn nil, errors.New(\"topic index out of range\")\n\t}\n\treturn pongpkt.data.(*pong), nil\n}"}], "fix_func": [{"id": "fix_go_291_1", "commit": "1ac3c8ac4f2b1e1df9675228290bda6b9586ba42", "file_path": "p2p/discover/net.go", "start_line": 1207, "end_line": 1228, "snippet": "func (net *Network) checkTopicRegister(data *topicRegister) (*pong, error) {\n\tvar pongpkt ingressPacket\n\tif err := decodePacket(data.Pong, &pongpkt); err != nil {\n\t\treturn nil, err\n\t}\n\tif pongpkt.ev != pongPacket {\n\t\treturn nil, errors.New(\"is not pong packet\")\n\t}\n\tif pongpkt.remoteID != net.tab.self.ID {\n\t\treturn nil, errors.New(\"not signed by us\")\n\t}\n\t// check that we previously authorised all topics\n\t// that the other side is trying to register.\n\thash, _, _ := wireHash(data.Topics)\n\tif hash != pongpkt.data.(*pong).TopicHash {\n\t\treturn nil, errors.New(\"topic hash mismatch\")\n\t}\n\tif int(data.Idx) < 0 || int(data.Idx) >= len(data.Topics) {\n\t\treturn nil, errors.New(\"topic index out of range\")\n\t}\n\treturn pongpkt.data.(*pong), nil\n}"}], "vul_patch": "--- a/p2p/discover/net.go\n+++ b/p2p/discover/net.go\n@@ -15,7 +15,7 @@\n \tif hash != pongpkt.data.(*pong).TopicHash {\n \t\treturn nil, errors.New(\"topic hash mismatch\")\n \t}\n-\tif data.Idx < 0 || int(data.Idx) >= len(data.Topics) {\n+\tif int(data.Idx) < 0 || int(data.Idx) >= len(data.Topics) {\n \t\treturn nil, errors.New(\"topic index out of range\")\n \t}\n \treturn pongpkt.data.(*pong), nil\n\n", "poc_patch": null, "unit_test_cmd": null} -{"cve_id": "CVE-2020-7684", "cve_description": "This affects all versions of package rollup-plugin-serve. There is no path sanitization in readFile operation.", "cwe_info": {"CWE-73": {"name": "External Control of File Name or Path", "description": "The product allows user input to control or influence paths or file names that are used in filesystem operations."}, "CWE-22": {"name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory."}}, "repo": "https://github.com/thgh/rollup-plugin-serve", "patch_url": ["https://github.com/thgh/rollup-plugin-serve/commit/3d144f2f47e86fcba34f5a144968da94220e3969"], "programing_language": "JavaScript", "vul_func": [{"id": "vul_js_166_1", "commit": "71cc20d", "file_path": "src/index.js", "start_line": 27, "end_line": 60, "snippet": " const requestListener = (request, response) => {\n // Remove querystring\n const urlPath = decodeURI(request.url.split('?')[0])\n\n Object.keys(options.headers).forEach((key) => {\n response.setHeader(key, options.headers[key])\n })\n\n readFileFromContentBase(options.contentBase, urlPath, function (error, content, filePath) {\n if (!error) {\n return found(response, filePath, content)\n }\n if (error.code !== 'ENOENT') {\n response.writeHead(500)\n response.end('500 Internal Server Error' +\n '\\n\\n' + filePath +\n '\\n\\n' + Object.values(error).join('\\n') +\n '\\n\\n(rollup-plugin-serve)', 'utf-8')\n return\n }\n if (options.historyApiFallback) {\n var fallbackPath = typeof options.historyApiFallback === 'string' ? options.historyApiFallback : '/index.html'\n readFileFromContentBase(options.contentBase, fallbackPath, function (error, content, filePath) {\n if (error) {\n notFound(response, filePath)\n } else {\n found(response, filePath, content)\n }\n })\n } else {\n notFound(response, filePath)\n }\n })\n }"}], "fix_func": [{"id": "fix_js_166_1", "commit": "71cc20d", "file_path": "src/index.js", "start_line": 27, "end_line": 63, "snippet": " const requestListener = (request, response) => {\n // Remove querystring\n const urlPath = decodeURI(request.url.split('?')[0])\n\n Object.keys(options.headers).forEach((key) => {\n response.setHeader(key, options.headers[key])\n })\n\n readFileFromContentBase(options.contentBase, urlPath, function (error, content, filePath) {\n if (!error) {\n return found(response, filePath, content)\n }\n if (error.code !== 'ENOENT') {\n response.writeHead(500)\n response.end('500 Internal Server Error' +\n '\\n\\n' + filePath +\n '\\n\\n' + Object.values(error).join('\\n') +\n '\\n\\n(rollup-plugin-serve)', 'utf-8')\n return\n }\n if (options.historyApiFallback) {\n var fallbackPath = typeof options.historyApiFallback === 'string' ? options.historyApiFallback : '/index.html'\n readFileFromContentBase(options.contentBase, fallbackPath, function (error, content, filePath) {\n if (error) {\n notFound(response, filePath)\n } else {\n found(response, filePath, content)\n }\n })\n } else {\n notFound(response, filePath)\n }\n })\n }\n\n // release previous server instance if rollup is reloading configuration in watch mode\n if (server) {"}], "vul_patch": "--- a/src/index.js\n+++ b/src/index.js\n@@ -32,3 +32,6 @@\n }\n })\n }\n+\n+ // release previous server instance if rollup is reloading configuration in watch mode\n+ if (server) {\n\n", "poc_patch": null, "unit_test_cmd": null} +{"cve_id": "CVE-2020-7684", "cve_description": "This affects all versions of package rollup-plugin-serve. There is no path sanitization in readFile operation.", "cwe_info": {"CWE-73": {"name": "External Control of File Name or Path", "description": "The product allows user input to control or influence paths or file names that are used in filesystem operations."}, "CWE-22": {"name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory."}}, "repo": "https://github.com/thgh/rollup-plugin-serve", "patch_url": ["https://github.com/thgh/rollup-plugin-serve/commit/3d144f2f47e86fcba34f5a144968da94220e3969"], "programing_language": "JavaScript", "vul_func": [{"id": "vul_js_166_1", "commit": "71cc20d", "file_path": "src/index.js", "start_line": 27, "end_line": 60, "snippet": " const requestListener = (request, response) => {\n // Remove querystring\n const urlPath = decodeURI(request.url.split('?')[0])\n\n Object.keys(options.headers).forEach((key) => {\n response.setHeader(key, options.headers[key])\n })\n\n readFileFromContentBase(options.contentBase, urlPath, function (error, content, filePath) {\n if (!error) {\n return found(response, filePath, content)\n }\n if (error.code !== 'ENOENT') {\n response.writeHead(500)\n response.end('500 Internal Server Error' +\n '\\n\\n' + filePath +\n '\\n\\n' + Object.values(error).join('\\n') +\n '\\n\\n(rollup-plugin-serve)', 'utf-8')\n return\n }\n if (options.historyApiFallback) {\n var fallbackPath = typeof options.historyApiFallback === 'string' ? options.historyApiFallback : '/index.html'\n readFileFromContentBase(options.contentBase, fallbackPath, function (error, content, filePath) {\n if (error) {\n notFound(response, filePath)\n } else {\n found(response, filePath, content)\n }\n })\n } else {\n notFound(response, filePath)\n }\n })\n }"}], "fix_func": [{"id": "fix_js_166_1", "commit": "3d144f2f47e86fcba34f5a144968da94220e3969", "file_path": "src/index.js", "start_line": 27, "end_line": 63, "snippet": " const requestListener = (request, response) => {\n // Remove querystring\n const unsafePath = decodeURI(request.url.split('?')[0])\n\n // Don't allow path traversal\n const urlPath = normalize(unsafePath)\n\n Object.keys(options.headers).forEach((key) => {\n response.setHeader(key, options.headers[key])\n })\n\n readFileFromContentBase(options.contentBase, urlPath, function (error, content, filePath) {\n if (!error) {\n return found(response, filePath, content)\n }\n if (error.code !== 'ENOENT') {\n response.writeHead(500)\n response.end('500 Internal Server Error' +\n '\\n\\n' + filePath +\n '\\n\\n' + Object.values(error).join('\\n') +\n '\\n\\n(rollup-plugin-serve)', 'utf-8')\n return\n }\n if (options.historyApiFallback) {\n var fallbackPath = typeof options.historyApiFallback === 'string' ? options.historyApiFallback : '/index.html'\n readFileFromContentBase(options.contentBase, fallbackPath, function (error, content, filePath) {\n if (error) {\n notFound(response, filePath)\n } else {\n found(response, filePath, content)\n }\n })\n } else {\n notFound(response, filePath)\n }\n })\n }"}], "vul_patch": "--- a/src/index.js\n+++ b/src/index.js\n@@ -32,3 +32,6 @@\n }\n })\n }\n+\n+ // release previous server instance if rollup is reloading configuration in watch mode\n+ if (server) {\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2023-5122", "cve_description": "Grafana is an open-source platform for monitoring and observability. The CSV datasource plugin is a Grafana Labs maintained plugin for Grafana that allows for retrieving and processing CSV data from a remote endpoint configured by an administrator. If this plugin was configured to send requests to a bare host with no path (e.g. https://www.example.com/ https://www.example.com/` ), requests to an endpoint other than the one configured by the administrator could be triggered by a specially crafted request from any user, resulting in an SSRF vector. AV:N/AC:L/PR:L/UI:N/S:C/C:L/I:N/A:N https://nvd.nist.gov/vuln-metrics/cvss/v3-calculator", "cwe_info": {"CWE-918": {"name": "Server-Side Request Forgery (SSRF)", "description": "The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination."}}, "repo": "https://github.com/grafana/grafana-csv-datasource", "patch_url": ["https://github.com/grafana/grafana-csv-datasource/commit/aedd016bdb93b0c43613ce69d8ca257163ec01eb"], "programing_language": "Go", "vul_func": [{"id": "vul_go_63_1", "commit": "572367c", "file_path": "pkg/http_storage.go", "start_line": 83, "end_line": 122, "snippet": "func newRequestFromQuery(settings *backend.DataSourceInstanceSettings, customSettings dataSourceSettings, query dataSourceQuery) (*http.Request, error) {\n\tu, err := url.Parse(settings.URL + query.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparams := make(url.Values)\n\tfor _, p := range query.Params {\n\t\tparams.Set(p[0], p[1])\n\t}\n\n\t// Query params set by admin overrides params set by query editor.\n\tvalues, err := url.ParseQuery(customSettings.QueryParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range values {\n\t\tparams[k] = v\n\t}\n\n\tu.RawQuery = params.Encode()\n\n\tvar method string\n\tif query.Method != \"\" {\n\t\tmethod = query.Method\n\t} else {\n\t\tmethod = \"GET\"\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), strings.NewReader(query.Body))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, p := range query.Headers {\n\t\treq.Header.Set(p[0], p[1])\n\t}\n\n\treturn req, nil\n}"}], "fix_func": [{"id": "fix_go_63_1", "commit": "aedd016", "file_path": "pkg/http_storage.go", "start_line": 83, "end_line": 133, "snippet": "func newRequestFromQuery(settings *backend.DataSourceInstanceSettings, customSettings dataSourceSettings, query dataSourceQuery) (*http.Request, error) {\n\tu, err := url.Parse(settings.URL + query.Path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// we need to verify that `query.Path` did not modify the hostname by doing tricks\n\tsettingsURL, err := url.Parse(settings.URL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid URL\")\n\t}\n\n\tif settingsURL.Host != u.Host {\n\t\t// the host got changed by adding the path to it. this must not happen.\n\t\treturn nil, fmt.Errorf(\"invalid URL + path combination\")\n\t}\n\n\tparams := make(url.Values)\n\tfor _, p := range query.Params {\n\t\tparams.Set(p[0], p[1])\n\t}\n\n\t// Query params set by admin overrides params set by query editor.\n\tvalues, err := url.ParseQuery(customSettings.QueryParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor k, v := range values {\n\t\tparams[k] = v\n\t}\n\n\tu.RawQuery = params.Encode()\n\n\tvar method string\n\tif query.Method != \"\" {\n\t\tmethod = query.Method\n\t} else {\n\t\tmethod = \"GET\"\n\t}\n\n\treq, err := http.NewRequest(method, u.String(), strings.NewReader(query.Body))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, p := range query.Headers {\n\t\treq.Header.Set(p[0], p[1])\n\t}\n\n\treturn req, nil\n}"}], "vul_patch": "--- a/pkg/http_storage.go\n+++ b/pkg/http_storage.go\n@@ -2,6 +2,17 @@\n \tu, err := url.Parse(settings.URL + query.Path)\n \tif err != nil {\n \t\treturn nil, err\n+\t}\n+\n+\t// we need to verify that `query.Path` did not modify the hostname by doing tricks\n+\tsettingsURL, err := url.Parse(settings.URL)\n+\tif err != nil {\n+\t\treturn nil, fmt.Errorf(\"invalid URL\")\n+\t}\n+\n+\tif settingsURL.Host != u.Host {\n+\t\t// the host got changed by adding the path to it. this must not happen.\n+\t\treturn nil, fmt.Errorf(\"invalid URL + path combination\")\n \t}\n \n \tparams := make(url.Values)\n\n", "poc_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2023-5122:latest\n# bash /workspace/fix-run.sh\nset -e\n\ncd /workspace/grafana-csv-datasource\ngit apply --whitespace=nowarn /workspace/test.patch /workspace/fix.patch\ngo test -timeout 30s -run ^TestHTTPStorage_UrlHandling$ github.com/grafana/grafana-csv-datasource/pkg\n", "unit_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2023-5122:latest\n# bash /workspace/unit_test.sh\nset -e\n\ncd /workspace/grafana-csv-datasource\ngit apply --whitespace=nowarn /workspace/fix.patch\ngo test -timeout 30s -run '^(TestHTTPStorage_Settings|TestHTTPStorage_Open|TestHTTPStorage_Stat|TestHTTPStorage_Options)$' github.com/grafana/grafana-csv-datasource/pkg\n"} {"cve_id": "CVE-2023-25653", "cve_description": "node-jose is a JavaScript implementation of the JSON Object Signing and Encryption (JOSE) for web browsers and node.js-based servers. Prior to version 2.2.0, when using the non-default \"fallback\" crypto back-end, ECC operations in `node-jose` can trigger a Denial-of-Service (DoS) condition, due to a possible infinite loop in an internal calculation. For some ECC operations, this condition is triggered randomly; for others, it can be triggered by malicious input. The issue has been patched in version 2.2.0. Since this issue is only present in the \"fallback\" crypto implementation, it can be avoided by ensuring that either WebCrypto or the Node `crypto` module is available in the JS environment where `node-jose` is being run.", "cwe_info": {"CWE-835": {"name": "Loop with Unreachable Exit Condition ('Infinite Loop')", "description": "The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop."}}, "repo": "https://github.com/cisco/node-jose", "patch_url": ["https://github.com/cisco/node-jose/commit/901d91508a70e3b9bdfc45688ea07bb4e1b8210d"], "programing_language": "JavaScript", "vul_func": [{"id": "vul_js_308_1", "commit": "e95481a67b69d0c0a0d5ea33c1a42fa3b81a202a", "file_path": "lib/deps/ecc/math.js", "start_line": 48, "end_line": 56, "snippet": "function barrettReduce(x) {\n x.drShiftTo(this.m.t-1,this.r2);\n if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\n this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\n this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);\n while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);\n x.subTo(this.r2,x);\n while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}"}], "fix_func": [{"id": "fix_js_308_1", "commit": "901d91508a70e3b9bdfc45688ea07bb4e1b8210d", "file_path": "lib/deps/ecc/math.js", "start_line": 48, "end_line": 57, "snippet": "function barrettReduce(x) {\n if (x.s < 0) { throw Error(\"Barrett reduction on negative input\"); }\n x.drShiftTo(this.m.t-1,this.r2);\n if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\n this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\n this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);\n while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);\n x.subTo(this.r2,x);\n while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);\n}"}, {"id": "fix_js_308_2", "commit": "901d91508a70e3b9bdfc45688ea07bb4e1b8210d", "file_path": "lib/deps/forge.js", "start_line": 92, "end_line": 98, "snippet": "const originalModInverse = forge.jsbn.BigInteger.prototype.modInverse;\nconst positiveModInverse = function(m) {\n const inv = originalModInverse.apply(this, [m]);\n return inv.mod(m);\n}\n\nforge.jsbn.BigInteger.prototype.modInverse = positiveModInverse;"}], "vul_patch": "--- a/lib/deps/ecc/math.js\n+++ b/lib/deps/ecc/math.js\n@@ -1,4 +1,5 @@\n function barrettReduce(x) {\n+ if (x.s < 0) { throw Error(\"Barrett reduction on negative input\"); }\n x.drShiftTo(this.m.t-1,this.r2);\n if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }\n this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);\n\n--- /dev/null\n+++ b/lib/deps/ecc/math.js\n@@ -0,0 +1,7 @@\n+const originalModInverse = forge.jsbn.BigInteger.prototype.modInverse;\n+const positiveModInverse = function(m) {\n+ const inv = originalModInverse.apply(this, [m]);\n+ return inv.mod(m);\n+}\n+\n+forge.jsbn.BigInteger.prototype.modInverse = positiveModInverse;\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2018-21036", "cve_description": "Sails.js before v1.0.0-46 allows attackers to cause a denial of service with a single request because there is no error handler in sails-hook-sockets to handle an empty pathname in a WebSocket request.", "cwe_info": {"CWE-20": {"name": "Improper Input Validation", "description": "The product receives input or data, but it does\n not validate or incorrectly validates that the input has the\n properties that are required to process the data safely and\n correctly."}}, "repo": "https://github.com/balderdashy/sails-hook-sockets", "patch_url": ["https://github.com/balderdashy/sails-hook-sockets/commit/0533a4864b1920fd8fbb5287bc0889193c5faf44"], "programing_language": "JavaScript", "vul_func": [{"id": "vul_js_200_1", "commit": "4f78b79", "file_path": "lib/receive-incoming-sails-io-msg.js", "start_line": 90, "end_line": 137, "snippet": " var requestContext = {\n\n transport: 'socket.io', // TODO: consider if this is really helpful or just a waste of LoC\n\n protocol: 'ws', // TODO: consider if this is really helpful or just a waste of LoC\n\n isSocket: true,\n\n ip : ip,\n\n ips : ips,\n\n port : null,\n\n // Access to underlying SIO socket\n socket : options.socket,\n\n url : options.incomingSailsIOMsg.url,\n\n path : url.parse(options.incomingSailsIOMsg.url).pathname,\n\n method : options.eventName,\n\n // Attached data becomes simulated HTTP body (`req.body`)\n // (allow `params` or `data` to be specified for backwards/sideways-compatibility)\n body : _.isArray(options.incomingSailsIOMsg.data) ? options.incomingSailsIOMsg.data : _.extend({}, options.incomingSailsIOMsg.params || {}, options.incomingSailsIOMsg.data || {}),\n\n // Allow optional headers\n headers: _.defaults({\n\n host: app.config.host,\n\n // Default the \"cookie\" request header to what was provided in the handshake.\n cookie: (function (){\n var _cookie;\n try {\n _cookie = options.socket.handshake.headers.cookie;\n }\n catch (e) {}\n // console.log('REQUEST to \"%s %s\" IS USING COOKIE:', options.eventName, options.incomingSailsIOMsg.url, _cookie);\n return _cookie;\n })(),\n\n nosession: options.socket.handshake.headers.nosession ? true : undefined,\n\n }, options.incomingSailsIOMsg.headers || {})\n\n };"}], "fix_func": [{"id": "fix_js_200_1", "commit": "0533a48", "file_path": "lib/receive-incoming-sails-io-msg.js", "start_line": 90, "end_line": 140, "snippet": " var requestContext = {\n\n transport: 'socket.io', // TODO: consider if this is really helpful or just a waste of LoC\n\n protocol: 'ws', // TODO: consider if this is really helpful or just a waste of LoC\n\n isSocket: true,\n\n ip : ip,\n\n ips : ips,\n\n port : null,\n\n // Access to underlying SIO socket\n socket : options.socket,\n\n url : options.incomingSailsIOMsg.url,\n\n path : url.parse(options.incomingSailsIOMsg.url).pathname || '/',\n // ^^ Uses || '/' because otherwise url.parse returns `null`,\n // which is not a string and thus bad when you try to check\n // .match() of it.\n\n method : options.eventName,\n\n // Attached data becomes simulated HTTP body (`req.body`)\n // (allow `params` or `data` to be specified for backwards/sideways-compatibility)\n body : _.isArray(options.incomingSailsIOMsg.data) ? options.incomingSailsIOMsg.data : _.extend({}, options.incomingSailsIOMsg.params || {}, options.incomingSailsIOMsg.data || {}),\n\n // Allow optional headers\n headers: _.defaults({\n\n host: app.config.host,\n\n // Default the \"cookie\" request header to what was provided in the handshake.\n cookie: (function (){\n var _cookie;\n try {\n _cookie = options.socket.handshake.headers.cookie;\n }\n catch (e) {}\n // console.log('REQUEST to \"%s %s\" IS USING COOKIE:', options.eventName, options.incomingSailsIOMsg.url, _cookie);\n return _cookie;\n })(),\n\n nosession: options.socket.handshake.headers.nosession ? true : undefined,\n\n }, options.incomingSailsIOMsg.headers || {})\n\n };"}], "vul_patch": "--- a/lib/receive-incoming-sails-io-msg.js\n+++ b/lib/receive-incoming-sails-io-msg.js\n@@ -17,7 +17,10 @@\n \n url : options.incomingSailsIOMsg.url,\n \n- path : url.parse(options.incomingSailsIOMsg.url).pathname,\n+ path : url.parse(options.incomingSailsIOMsg.url).pathname || '/',\n+ // ^^ Uses || '/' because otherwise url.parse returns `null`,\n+ // which is not a string and thus bad when you try to check\n+ // .match() of it.\n \n method : options.eventName,\n \n\n", "poc_patch": null, "unit_test_cmd": null} @@ -587,7 +587,7 @@ {"cve_id": "CVE-2020-9402", "cve_description": "Django 1.11 before 1.11.29, 2.2 before 2.2.11, and 3.0 before 3.0.4 allows SQL Injection if untrusted data is used as a tolerance parameter in GIS functions and aggregates on Oracle. By passing a suitably crafted tolerance to GIS functions and aggregates on Oracle, it was possible to break escaping and inject malicious SQL.", "cwe_info": {"CWE-89": {"name": "Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')", "description": "The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data."}}, "repo": "https://github.com/django/django", "patch_url": ["https://github.com/django/django/commit/6695d29b1c1ce979725816295a26ecc64ae0e927"], "programing_language": "Python", "vul_func": [{"id": "vul_py_296_1", "commit": "65ab4f9", "file_path": "django/contrib/gis/db/models/aggregates.py", "start_line": 29, "end_line": 32, "snippet": " def as_oracle(self, compiler, connection, **extra_context):\n tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05)\n template = None if self.is_extent else '%(function)s(SDOAGGRTYPE(%(expressions)s,%(tolerance)s))'\n return self.as_sql(compiler, connection, template=template, tolerance=tolerance, **extra_context)"}, {"id": "vul_py_296_2", "commit": "65ab4f9", "file_path": "django/contrib/gis/db/models/functions.py", "start_line": 113, "end_line": 119, "snippet": " def as_oracle(self, compiler, connection, **extra_context):\n tol = self.extra.get('tolerance', self.tolerance)\n return self.as_sql(\n compiler, connection,\n template=\"%%(function)s(%%(expressions)s, %s)\" % tol,\n **extra_context\n )"}], "fix_func": [{"id": "fix_py_296_1", "commit": "6695d29b1c1ce979725816295a26ecc64ae0e927", "file_path": "django/contrib/gis/db/models/aggregates.py", "start_line": 29, "end_line": 39, "snippet": " def as_oracle(self, compiler, connection, **extra_context):\n if not self.is_extent:\n tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05)\n clone = self.copy()\n clone.set_source_expressions([\n *self.get_source_expressions(),\n Value(tolerance),\n ])\n template = '%(function)s(SDOAGGRTYPE(%(expressions)s))'\n return clone.as_sql(compiler, connection, template=template, **extra_context)\n return self.as_sql(compiler, connection, **extra_context)"}, {"id": "fix_py_296_2", "commit": "6695d29b1c1ce979725816295a26ecc64ae0e927", "file_path": "django/contrib/gis/db/models/functions.py", "start_line": 113, "end_line": 121, "snippet": " def as_oracle(self, compiler, connection, **extra_context):\n tolerance = Value(self._handle_param(\n self.extra.get('tolerance', self.tolerance),\n 'tolerance',\n NUMERIC_TYPES,\n ))\n clone = self.copy()\n clone.set_source_expressions([*self.get_source_expressions(), tolerance])\n return clone.as_sql(compiler, connection, **extra_context)"}], "vul_patch": "--- a/django/contrib/gis/db/models/aggregates.py\n+++ b/django/contrib/gis/db/models/aggregates.py\n@@ -1,4 +1,11 @@\n def as_oracle(self, compiler, connection, **extra_context):\n- tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05)\n- template = None if self.is_extent else '%(function)s(SDOAGGRTYPE(%(expressions)s,%(tolerance)s))'\n- return self.as_sql(compiler, connection, template=template, tolerance=tolerance, **extra_context)\n+ if not self.is_extent:\n+ tolerance = self.extra.get('tolerance') or getattr(self, 'tolerance', 0.05)\n+ clone = self.copy()\n+ clone.set_source_expressions([\n+ *self.get_source_expressions(),\n+ Value(tolerance),\n+ ])\n+ template = '%(function)s(SDOAGGRTYPE(%(expressions)s))'\n+ return clone.as_sql(compiler, connection, template=template, **extra_context)\n+ return self.as_sql(compiler, connection, **extra_context)\n\n--- a/django/contrib/gis/db/models/functions.py\n+++ b/django/contrib/gis/db/models/functions.py\n@@ -1,7 +1,9 @@\n def as_oracle(self, compiler, connection, **extra_context):\n- tol = self.extra.get('tolerance', self.tolerance)\n- return self.as_sql(\n- compiler, connection,\n- template=\"%%(function)s(%%(expressions)s, %s)\" % tol,\n- **extra_context\n- )\n+ tolerance = Value(self._handle_param(\n+ self.extra.get('tolerance', self.tolerance),\n+ 'tolerance',\n+ NUMERIC_TYPES,\n+ ))\n+ clone = self.copy()\n+ clone.set_source_expressions([*self.get_source_expressions(), tolerance])\n+ return clone.as_sql(compiler, connection, **extra_context)\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2021-21354", "cve_description": "Pollbot is open source software which \"frees its human masters from the toilsome task of polling for the state of things during the Firefox release process.\" In Pollbot before version 1.4.4 there is an open redirection vulnerability in the path of \"https://pollbot.services.mozilla.com/\". An attacker can redirect anyone to malicious sites. To Reproduce type in this URL: \"https://pollbot.services.mozilla.com//evil.com/\". Affected versions will redirect to that website when you inject a payload like \"//evil.com/\". This is fixed in version 1.4.4.", "cwe_info": {"CWE-601": {"name": "URL Redirection to Untrusted Site ('Open Redirect')", "description": "The web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a redirect."}}, "repo": "https://github.com/mozilla/PollBot", "patch_url": ["https://github.com/mozilla/PollBot/commit/6db74a4fcbff258c7cdf51a6ff0724fc10c485e5"], "programing_language": "Python", "vul_func": [{"id": "vul_py_33_1", "commit": "78539af", "file_path": "pollbot/middlewares.py", "start_line": 61, "end_line": 69, "snippet": "async def handle_404(request, response):\n if 'json' not in response.headers['Content-Type']:\n if request.path.endswith('/'):\n return web.HTTPFound(request.path.rstrip('/'))\n return web.json_response({\n \"status\": 404,\n \"message\": \"Page '{}' not found\".format(request.path)\n }, status=404)\n return response"}], "fix_func": [{"id": "fix_py_33_1", "commit": "6db74a4fcbff258c7cdf51a6ff0724fc10c485e5", "file_path": "pollbot/middlewares.py", "start_line": 61, "end_line": 69, "snippet": "async def handle_404(request, response):\n if 'json' not in response.headers['Content-Type']:\n if request.path.endswith('/'):\n return web.HTTPFound('/' + request.path.strip('/'))\n return web.json_response({\n \"status\": 404,\n \"message\": \"Page '{}' not found\".format(request.path)\n }, status=404)\n return response"}], "vul_patch": "--- a/pollbot/middlewares.py\n+++ b/pollbot/middlewares.py\n@@ -1,7 +1,7 @@\n async def handle_404(request, response):\n if 'json' not in response.headers['Content-Type']:\n if request.path.endswith('/'):\n- return web.HTTPFound(request.path.rstrip('/'))\n+ return web.HTTPFound('/' + request.path.strip('/'))\n return web.json_response({\n \"status\": 404,\n \"message\": \"Page '{}' not found\".format(request.path)\n\n", "poc_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2021-21354:latest\n# bash /workspace/fix-run.sh\nset -e\n\ncd /workspace/PollBot\ngit apply --whitespace=nowarn /workspace/test.patch /workspace/fix.patch\n/workspace/PoC_env/CVE-2021-21354/bin/python -m pytest tests/test_views.py::test_redirects_strip_leading_slashes -p no:warning --disable-warnings\n", "unit_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2021-21354:latest\n# bash /workspace/unit_test.sh\nset -e\n\ncd /workspace/PollBot\ngit apply --whitespace=nowarn /workspace/fix.patch\n/workspace/PoC_env/CVE-2021-21354/bin/python -m pytest tests/test_views.py -k \"not test_beta_partner_repacks and \\\nnot test_release_bedrock_release_notes and \\\nnot test_devedition_bedrock_release_notes and \\\nnot test_release_bedrock_esr_release_notes and \\\nnot test_heartbeat and \\\nnot test_version_view_return_200 and \\\nnot test_endpoint_have_got_cache_control_headers\" \\\n-p no:warning --disable-warnings\n"} {"cve_id": "CVE-2024-39690", "cve_description": "Capsule is a multi-tenancy and policy-based framework for Kubernetes. In Capsule v0.7.0 and earlier, the tenant-owner can patch any arbitrary namespace that has not been taken over by a tenant (i.e., namespaces without the ownerReference field), thereby gaining control of that namespace.", "cwe_info": {"CWE-863": {"name": "Incorrect Authorization", "description": "The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check."}}, "repo": "https://github.com/projectcapsule/capsule", "patch_url": ["https://github.com/projectcapsule/capsule/commit/d620b0457ddec01616b8eab8512a10611611f584"], "programing_language": "Go", "vul_func": [{"id": "vul_go_281_1", "commit": "1d9fcc7a0d3dbd1ac44cfa10fb2ecd923f7e0d2e", "file_path": "pkg/webhook/ownerreference/patching.go", "start_line": 52, "end_line": 102, "snippet": "func (h *handler) OnUpdate(_ client.Client, decoder admission.Decoder, _ record.EventRecorder) capsulewebhook.Func {\n\treturn func(_ context.Context, req admission.Request) *admission.Response {\n\t\toldNs := &corev1.Namespace{}\n\t\tif err := decoder.DecodeRaw(req.OldObject, oldNs); err != nil {\n\t\t\treturn utils.ErroredResponse(err)\n\t\t}\n\n\t\tif len(oldNs.OwnerReferences) == 0 {\n\t\t\treturn nil\n\t\t}\n\n\t\tnewNs := &corev1.Namespace{}\n\t\tif err := decoder.Decode(req, newNs); err != nil {\n\t\t\treturn utils.ErroredResponse(err)\n\t\t}\n\n\t\to, err := json.Marshal(newNs.DeepCopy())\n\t\tif err != nil {\n\t\t\tresponse := admission.Errored(http.StatusInternalServerError, err)\n\n\t\t\treturn &response\n\t\t}\n\n\t\tvar refs []metav1.OwnerReference\n\n\t\tfor _, ref := range oldNs.OwnerReferences {\n\t\t\tif capsuleutils.IsTenantOwnerReference(ref) {\n\t\t\t\trefs = append(refs, ref)\n\t\t\t}\n\t\t}\n\n\t\tfor _, ref := range newNs.OwnerReferences {\n\t\t\tif !capsuleutils.IsTenantOwnerReference(ref) {\n\t\t\t\trefs = append(refs, ref)\n\t\t\t}\n\t\t}\n\n\t\tnewNs.OwnerReferences = refs\n\n\t\tc, err := json.Marshal(newNs)\n\t\tif err != nil {\n\t\t\tresponse := admission.Errored(http.StatusInternalServerError, err)\n\n\t\t\treturn &response\n\t\t}\n\n\t\tresponse := admission.PatchResponseFromRaw(o, c)\n\n\t\treturn &response\n\t}\n}"}], "fix_func": [{"id": "fix_go_281_1", "commit": "d620b0457ddec01616b8eab8512a10611611f584", "file_path": "pkg/webhook/ownerreference/patching.go", "start_line": 53, "end_line": 114, "snippet": "func (h *handler) OnUpdate(c client.Client, decoder admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func {\n\treturn func(ctx context.Context, req admission.Request) *admission.Response {\n\t\toldNs := &corev1.Namespace{}\n\t\tif err := decoder.DecodeRaw(req.OldObject, oldNs); err != nil {\n\t\t\treturn utils.ErroredResponse(err)\n\t\t}\n\n\t\ttntList := &capsulev1beta2.TenantList{}\n\t\tif err := c.List(ctx, tntList, client.MatchingFieldsSelector{\n\t\t\tSelector: fields.OneTermEqualSelector(\".status.namespaces\", oldNs.Name),\n\t\t}); err != nil {\n\t\t\treturn utils.ErroredResponse(err)\n\t\t}\n\n\t\tif !h.namespaceIsOwned(oldNs, tntList, req) {\n\t\t\trecorder.Eventf(oldNs, corev1.EventTypeWarning, \"OfflimitNamespace\", \"Namespace %s can not be patched\", oldNs.GetName())\n\n\t\t\tresponse := admission.Denied(\"Denied patch request for this namespace\")\n\n\t\t\treturn &response\n\t\t}\n\n\t\tnewNs := &corev1.Namespace{}\n\t\tif err := decoder.Decode(req, newNs); err != nil {\n\t\t\treturn utils.ErroredResponse(err)\n\t\t}\n\n\t\to, err := json.Marshal(newNs.DeepCopy())\n\t\tif err != nil {\n\t\t\tresponse := admission.Errored(http.StatusInternalServerError, err)\n\n\t\t\treturn &response\n\t\t}\n\n\t\tvar refs []metav1.OwnerReference\n\n\t\tfor _, ref := range oldNs.OwnerReferences {\n\t\t\tif capsuleutils.IsTenantOwnerReference(ref) {\n\t\t\t\trefs = append(refs, ref)\n\t\t\t}\n\t\t}\n\n\t\tfor _, ref := range newNs.OwnerReferences {\n\t\t\tif !capsuleutils.IsTenantOwnerReference(ref) {\n\t\t\t\trefs = append(refs, ref)\n\t\t\t}\n\t\t}\n\n\t\tnewNs.OwnerReferences = refs\n\n\t\tc, err := json.Marshal(newNs)\n\t\tif err != nil {\n\t\t\tresponse := admission.Errored(http.StatusInternalServerError, err)\n\n\t\t\treturn &response\n\t\t}\n\n\t\tresponse := admission.PatchResponseFromRaw(o, c)\n\n\t\treturn &response\n\t}\n}"}, {"id": "fix_go_281_2", "commit": "d620b0457ddec01616b8eab8512a10611611f584", "file_path": "pkg/webhook/ownerreference/patching.go", "start_line": 116, "end_line": 129, "snippet": "func (h *handler) namespaceIsOwned(ns *corev1.Namespace, tenantList *capsulev1beta2.TenantList, req admission.Request) bool {\n\tfor _, tenant := range tenantList.Items {\n\t\tfor _, ownerRef := range ns.OwnerReferences {\n\t\t\tif !capsuleutils.IsTenantOwnerReference(ownerRef) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif ownerRef.UID == tenant.UID && utils.IsTenantOwner(tenant.Spec.Owners, req.UserInfo) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}"}], "vul_patch": "--- a/pkg/webhook/ownerreference/patching.go\n+++ b/pkg/webhook/ownerreference/patching.go\n@@ -1,12 +1,23 @@\n-func (h *handler) OnUpdate(_ client.Client, decoder admission.Decoder, _ record.EventRecorder) capsulewebhook.Func {\n-\treturn func(_ context.Context, req admission.Request) *admission.Response {\n+func (h *handler) OnUpdate(c client.Client, decoder admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func {\n+\treturn func(ctx context.Context, req admission.Request) *admission.Response {\n \t\toldNs := &corev1.Namespace{}\n \t\tif err := decoder.DecodeRaw(req.OldObject, oldNs); err != nil {\n \t\t\treturn utils.ErroredResponse(err)\n \t\t}\n \n-\t\tif len(oldNs.OwnerReferences) == 0 {\n-\t\t\treturn nil\n+\t\ttntList := &capsulev1beta2.TenantList{}\n+\t\tif err := c.List(ctx, tntList, client.MatchingFieldsSelector{\n+\t\t\tSelector: fields.OneTermEqualSelector(\".status.namespaces\", oldNs.Name),\n+\t\t}); err != nil {\n+\t\t\treturn utils.ErroredResponse(err)\n+\t\t}\n+\n+\t\tif !h.namespaceIsOwned(oldNs, tntList, req) {\n+\t\t\trecorder.Eventf(oldNs, corev1.EventTypeWarning, \"OfflimitNamespace\", \"Namespace %s can not be patched\", oldNs.GetName())\n+\n+\t\t\tresponse := admission.Denied(\"Denied patch request for this namespace\")\n+\n+\t\t\treturn &response\n \t\t}\n \n \t\tnewNs := &corev1.Namespace{}\n\n--- /dev/null\n+++ b/pkg/webhook/ownerreference/patching.go\n@@ -0,0 +1,14 @@\n+func (h *handler) namespaceIsOwned(ns *corev1.Namespace, tenantList *capsulev1beta2.TenantList, req admission.Request) bool {\n+\tfor _, tenant := range tenantList.Items {\n+\t\tfor _, ownerRef := range ns.OwnerReferences {\n+\t\t\tif !capsuleutils.IsTenantOwnerReference(ownerRef) {\n+\t\t\t\tcontinue\n+\t\t\t}\n+\t\t\tif ownerRef.UID == tenant.UID && utils.IsTenantOwner(tenant.Spec.Owners, req.UserInfo) {\n+\t\t\t\treturn true\n+\t\t\t}\n+\t\t}\n+\t}\n+\n+\treturn false\n+}\n\n", "poc_patch": null, "unit_test_cmd": null} -{"cve_id": "CVE-2024-0815", "cve_description": "Command injection in paddle.utils.download._wget_download (bypass filter) in paddlepaddle/paddle 2.6.0", "cwe_info": {"CWE-94": {"name": "Improper Control of Generation of Code ('Code Injection')", "description": "The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment."}, "CWE-77": {"name": "Improper Neutralization of Special Elements used in a Command ('Command Injection')", "description": "The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component."}, "CWE-78": {"name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component."}}, "repo": "https://github.com/PaddlePaddle/Paddle", "patch_url": ["https://github.com/PaddlePaddle/Paddle/commit/4c0888d7b8f10405e2e79adc41c224264f93e816"], "programing_language": "Python", "vul_func": [{"id": "vul_py_168_1", "commit": "22cf91f", "file_path": "python/paddle/utils/download.py", "start_line": 201, "end_line": 228, "snippet": "def _wget_download(url: str, fullname: str):\n try:\n assert urlparse(url).scheme in (\n 'http',\n 'https',\n ), 'Only support https and http url'\n # using wget to download url\n tmp_fullname = shlex.quote(fullname + \"_tmp\")\n url = shlex.quote(url)\n # \\u2013user-agent\n command = f'wget -O {tmp_fullname} -t {DOWNLOAD_RETRY_LIMIT} {url}'\n subprc = subprocess.Popen(\n command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n _ = subprc.communicate()\n\n if subprc.returncode != 0:\n raise RuntimeError(\n f'{command} failed. Please make sure `wget` is installed or {url} exists'\n )\n\n shutil.move(tmp_fullname, fullname)\n\n except Exception as e: # requests.exceptions.ConnectionError\n logger.info(f\"Downloading {url} failed with exception {str(e)}\")\n return False\n\n return fullname"}, {"id": "vul_py_168_2", "commit": "22cf91f", "file_path": "python/paddle/utils/download.py", "start_line": 231, "end_line": 234, "snippet": "_download_methods = {\n 'get': _get_download,\n 'wget': _wget_download,\n}"}, {"id": "vul_py_168_3", "commit": "22cf91f", "file_path": "python/paddle/hapi/hub.py", "start_line": 83, "end_line": 136, "snippet": "def _get_cache_or_reload(repo, force_reload, verbose=True, source='github'):\n # Setup hub_dir to save downloaded files\n hub_dir = HUB_DIR\n\n _make_dirs(hub_dir)\n\n # Parse github/gitee repo information\n repo_owner, repo_name, branch = _parse_repo_info(repo, source)\n # Github allows branch name with slash '/',\n # this causes confusion with path on both Linux and Windows.\n # Backslash is not allowed in Github branch name so no need to\n # to worry about it.\n normalized_br = branch.replace('/', '_')\n # Github renames folder repo/v1.x.x to repo-1.x.x\n # We don't know the repo name before downloading the zip file\n # and inspect name from it.\n # To check if cached repo exists, we need to normalize folder names.\n repo_dir = os.path.join(\n hub_dir, '_'.join([repo_owner, repo_name, normalized_br])\n )\n\n use_cache = (not force_reload) and os.path.exists(repo_dir)\n\n if use_cache:\n if verbose:\n sys.stderr.write(f'Using cache found in {repo_dir}\\n')\n else:\n cached_file = os.path.join(hub_dir, normalized_br + '.zip')\n _remove_if_exists(cached_file)\n\n url = _git_archive_link(repo_owner, repo_name, branch, source=source)\n\n fpath = get_path_from_url(\n url,\n hub_dir,\n check_exist=not force_reload,\n decompress=False,\n method=('wget' if source == 'gitee' else 'get'),\n )\n shutil.move(fpath, cached_file)\n\n with zipfile.ZipFile(cached_file) as cached_zipfile:\n extracted_repo_name = cached_zipfile.infolist()[0].filename\n extracted_repo = os.path.join(hub_dir, extracted_repo_name)\n _remove_if_exists(extracted_repo)\n # Unzip the code and rename the base folder\n cached_zipfile.extractall(hub_dir)\n\n _remove_if_exists(cached_file)\n _remove_if_exists(repo_dir)\n # Rename the repo\n shutil.move(extracted_repo, repo_dir)\n\n return repo_dir"}], "fix_func": [{"id": "fix_py_168_1", "commit": "22cf91f", "file_path": "python/paddle/hapi/hub.py", "start_line": 83, "end_line": 135, "snippet": "def _get_cache_or_reload(repo, force_reload, verbose=True, source='github'):\n # Setup hub_dir to save downloaded files\n hub_dir = HUB_DIR\n\n _make_dirs(hub_dir)\n\n # Parse github/gitee repo information\n repo_owner, repo_name, branch = _parse_repo_info(repo, source)\n # Github allows branch name with slash '/',\n # this causes confusion with path on both Linux and Windows.\n # Backslash is not allowed in Github branch name so no need to\n # to worry about it.\n normalized_br = branch.replace('/', '_')\n # Github renames folder repo/v1.x.x to repo-1.x.x\n # We don't know the repo name before downloading the zip file\n # and inspect name from it.\n # To check if cached repo exists, we need to normalize folder names.\n repo_dir = os.path.join(\n hub_dir, '_'.join([repo_owner, repo_name, normalized_br])\n )\n\n use_cache = (not force_reload) and os.path.exists(repo_dir)\n\n if use_cache:\n if verbose:\n sys.stderr.write(f'Using cache found in {repo_dir}\\n')\n else:\n cached_file = os.path.join(hub_dir, normalized_br + '.zip')\n _remove_if_exists(cached_file)\n\n url = _git_archive_link(repo_owner, repo_name, branch, source=source)\n\n fpath = get_path_from_url(\n url,\n hub_dir,\n check_exist=not force_reload,\n decompress=False,\n method=('wget' if source == 'gitee' else 'get'),\n )\n shutil.move(fpath, cached_file)\n\n with zipfile.ZipFile(cached_file) as cached_zipfile:\n extracted_repo_name = cached_zipfile.infolist()[0].filename\n extracted_repo = os.path.join(hub_dir, extracted_repo_name)\n _remove_if_exists(extracted_repo)\n # Unzip the code and rename the base folder\n cached_zipfile.extractall(hub_dir)\n\n _remove_if_exists(cached_file)\n _remove_if_exists(repo_dir)\n # Rename the repo\n shutil.move(extracted_repo, repo_dir)\n"}], "vul_patch": "--- a/python/paddle/utils/download.py\n+++ b/python/paddle/hapi/hub.py\n@@ -1,28 +1,52 @@\n-def _wget_download(url: str, fullname: str):\n- try:\n- assert urlparse(url).scheme in (\n- 'http',\n- 'https',\n- ), 'Only support https and http url'\n- # using wget to download url\n- tmp_fullname = shlex.quote(fullname + \"_tmp\")\n- url = shlex.quote(url)\n- # \\u2013user-agent\n- command = f'wget -O {tmp_fullname} -t {DOWNLOAD_RETRY_LIMIT} {url}'\n- subprc = subprocess.Popen(\n- command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n+def _get_cache_or_reload(repo, force_reload, verbose=True, source='github'):\n+ # Setup hub_dir to save downloaded files\n+ hub_dir = HUB_DIR\n+\n+ _make_dirs(hub_dir)\n+\n+ # Parse github/gitee repo information\n+ repo_owner, repo_name, branch = _parse_repo_info(repo, source)\n+ # Github allows branch name with slash '/',\n+ # this causes confusion with path on both Linux and Windows.\n+ # Backslash is not allowed in Github branch name so no need to\n+ # to worry about it.\n+ normalized_br = branch.replace('/', '_')\n+ # Github renames folder repo/v1.x.x to repo-1.x.x\n+ # We don't know the repo name before downloading the zip file\n+ # and inspect name from it.\n+ # To check if cached repo exists, we need to normalize folder names.\n+ repo_dir = os.path.join(\n+ hub_dir, '_'.join([repo_owner, repo_name, normalized_br])\n+ )\n+\n+ use_cache = (not force_reload) and os.path.exists(repo_dir)\n+\n+ if use_cache:\n+ if verbose:\n+ sys.stderr.write(f'Using cache found in {repo_dir}\\n')\n+ else:\n+ cached_file = os.path.join(hub_dir, normalized_br + '.zip')\n+ _remove_if_exists(cached_file)\n+\n+ url = _git_archive_link(repo_owner, repo_name, branch, source=source)\n+\n+ fpath = get_path_from_url(\n+ url,\n+ hub_dir,\n+ check_exist=not force_reload,\n+ decompress=False,\n+ method=('wget' if source == 'gitee' else 'get'),\n )\n- _ = subprc.communicate()\n+ shutil.move(fpath, cached_file)\n \n- if subprc.returncode != 0:\n- raise RuntimeError(\n- f'{command} failed. Please make sure `wget` is installed or {url} exists'\n- )\n+ with zipfile.ZipFile(cached_file) as cached_zipfile:\n+ extracted_repo_name = cached_zipfile.infolist()[0].filename\n+ extracted_repo = os.path.join(hub_dir, extracted_repo_name)\n+ _remove_if_exists(extracted_repo)\n+ # Unzip the code and rename the base folder\n+ cached_zipfile.extractall(hub_dir)\n \n- shutil.move(tmp_fullname, fullname)\n-\n- except Exception as e: # requests.exceptions.ConnectionError\n- logger.info(f\"Downloading {url} failed with exception {str(e)}\")\n- return False\n-\n- return fullname\n+ _remove_if_exists(cached_file)\n+ _remove_if_exists(repo_dir)\n+ # Rename the repo\n+ shutil.move(extracted_repo, repo_dir)\n\n--- a/python/paddle/utils/download.py\n+++ /dev/null\n@@ -1,4 +0,0 @@\n-_download_methods = {\n- 'get': _get_download,\n- 'wget': _wget_download,\n-}\n\n--- a/python/paddle/hapi/hub.py\n+++ /dev/null\n@@ -1,54 +0,0 @@\n-def _get_cache_or_reload(repo, force_reload, verbose=True, source='github'):\n- # Setup hub_dir to save downloaded files\n- hub_dir = HUB_DIR\n-\n- _make_dirs(hub_dir)\n-\n- # Parse github/gitee repo information\n- repo_owner, repo_name, branch = _parse_repo_info(repo, source)\n- # Github allows branch name with slash '/',\n- # this causes confusion with path on both Linux and Windows.\n- # Backslash is not allowed in Github branch name so no need to\n- # to worry about it.\n- normalized_br = branch.replace('/', '_')\n- # Github renames folder repo/v1.x.x to repo-1.x.x\n- # We don't know the repo name before downloading the zip file\n- # and inspect name from it.\n- # To check if cached repo exists, we need to normalize folder names.\n- repo_dir = os.path.join(\n- hub_dir, '_'.join([repo_owner, repo_name, normalized_br])\n- )\n-\n- use_cache = (not force_reload) and os.path.exists(repo_dir)\n-\n- if use_cache:\n- if verbose:\n- sys.stderr.write(f'Using cache found in {repo_dir}\\n')\n- else:\n- cached_file = os.path.join(hub_dir, normalized_br + '.zip')\n- _remove_if_exists(cached_file)\n-\n- url = _git_archive_link(repo_owner, repo_name, branch, source=source)\n-\n- fpath = get_path_from_url(\n- url,\n- hub_dir,\n- check_exist=not force_reload,\n- decompress=False,\n- method=('wget' if source == 'gitee' else 'get'),\n- )\n- shutil.move(fpath, cached_file)\n-\n- with zipfile.ZipFile(cached_file) as cached_zipfile:\n- extracted_repo_name = cached_zipfile.infolist()[0].filename\n- extracted_repo = os.path.join(hub_dir, extracted_repo_name)\n- _remove_if_exists(extracted_repo)\n- # Unzip the code and rename the base folder\n- cached_zipfile.extractall(hub_dir)\n-\n- _remove_if_exists(cached_file)\n- _remove_if_exists(repo_dir)\n- # Rename the repo\n- shutil.move(extracted_repo, repo_dir)\n-\n- return repo_dir\n\n", "poc_patch": null, "unit_test_cmd": null} +{"cve_id": "CVE-2024-0815", "cve_description": "Command injection in paddle.utils.download._wget_download (bypass filter) in paddlepaddle/paddle 2.6.0", "cwe_info": {"CWE-94": {"name": "Improper Control of Generation of Code ('Code Injection')", "description": "The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment."}, "CWE-77": {"name": "Improper Neutralization of Special Elements used in a Command ('Command Injection')", "description": "The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component."}, "CWE-78": {"name": "Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')", "description": "The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component."}}, "repo": "https://github.com/PaddlePaddle/Paddle", "patch_url": ["https://github.com/PaddlePaddle/Paddle/commit/4c0888d7b8f10405e2e79adc41c224264f93e816"], "programing_language": "Python", "vul_func": [{"id": "vul_py_168_1", "commit": "22cf91f", "file_path": "python/paddle/utils/download.py", "start_line": 201, "end_line": 228, "snippet": "def _wget_download(url: str, fullname: str):\n try:\n assert urlparse(url).scheme in (\n 'http',\n 'https',\n ), 'Only support https and http url'\n # using wget to download url\n tmp_fullname = shlex.quote(fullname + \"_tmp\")\n url = shlex.quote(url)\n # \\u2013user-agent\n command = f'wget -O {tmp_fullname} -t {DOWNLOAD_RETRY_LIMIT} {url}'\n subprc = subprocess.Popen(\n command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n _ = subprc.communicate()\n\n if subprc.returncode != 0:\n raise RuntimeError(\n f'{command} failed. Please make sure `wget` is installed or {url} exists'\n )\n\n shutil.move(tmp_fullname, fullname)\n\n except Exception as e: # requests.exceptions.ConnectionError\n logger.info(f\"Downloading {url} failed with exception {str(e)}\")\n return False\n\n return fullname"}, {"id": "vul_py_168_2", "commit": "22cf91f", "file_path": "python/paddle/utils/download.py", "start_line": 231, "end_line": 234, "snippet": "_download_methods = {\n 'get': _get_download,\n 'wget': _wget_download,\n}"}, {"id": "vul_py_168_3", "commit": "22cf91f", "file_path": "python/paddle/hapi/hub.py", "start_line": 83, "end_line": 136, "snippet": "def _get_cache_or_reload(repo, force_reload, verbose=True, source='github'):\n # Setup hub_dir to save downloaded files\n hub_dir = HUB_DIR\n\n _make_dirs(hub_dir)\n\n # Parse github/gitee repo information\n repo_owner, repo_name, branch = _parse_repo_info(repo, source)\n # Github allows branch name with slash '/',\n # this causes confusion with path on both Linux and Windows.\n # Backslash is not allowed in Github branch name so no need to\n # to worry about it.\n normalized_br = branch.replace('/', '_')\n # Github renames folder repo/v1.x.x to repo-1.x.x\n # We don't know the repo name before downloading the zip file\n # and inspect name from it.\n # To check if cached repo exists, we need to normalize folder names.\n repo_dir = os.path.join(\n hub_dir, '_'.join([repo_owner, repo_name, normalized_br])\n )\n\n use_cache = (not force_reload) and os.path.exists(repo_dir)\n\n if use_cache:\n if verbose:\n sys.stderr.write(f'Using cache found in {repo_dir}\\n')\n else:\n cached_file = os.path.join(hub_dir, normalized_br + '.zip')\n _remove_if_exists(cached_file)\n\n url = _git_archive_link(repo_owner, repo_name, branch, source=source)\n\n fpath = get_path_from_url(\n url,\n hub_dir,\n check_exist=not force_reload,\n decompress=False,\n method=('wget' if source == 'gitee' else 'get'),\n )\n shutil.move(fpath, cached_file)\n\n with zipfile.ZipFile(cached_file) as cached_zipfile:\n extracted_repo_name = cached_zipfile.infolist()[0].filename\n extracted_repo = os.path.join(hub_dir, extracted_repo_name)\n _remove_if_exists(extracted_repo)\n # Unzip the code and rename the base folder\n cached_zipfile.extractall(hub_dir)\n\n _remove_if_exists(cached_file)\n _remove_if_exists(repo_dir)\n # Rename the repo\n shutil.move(extracted_repo, repo_dir)\n\n return repo_dir"}], "fix_func": [{"id": "fix_py_168_1", "commit": "4c0888d7b8f10405e2e79adc41c224264f93e816", "file_path": "python/paddle/hapi/hub.py", "start_line": 83, "end_line": 135, "snippet": "def _get_cache_or_reload(repo, force_reload, verbose=True, source='github'):\n # Setup hub_dir to save downloaded files\n hub_dir = HUB_DIR\n\n _make_dirs(hub_dir)\n\n # Parse github/gitee repo information\n repo_owner, repo_name, branch = _parse_repo_info(repo, source)\n # Github allows branch name with slash '/',\n # this causes confusion with path on both Linux and Windows.\n # Backslash is not allowed in Github branch name so no need to\n # to worry about it.\n normalized_br = branch.replace('/', '_')\n # Github renames folder repo/v1.x.x to repo-1.x.x\n # We don't know the repo name before downloading the zip file\n # and inspect name from it.\n # To check if cached repo exists, we need to normalize folder names.\n repo_dir = os.path.join(\n hub_dir, '_'.join([repo_owner, repo_name, normalized_br])\n )\n\n use_cache = (not force_reload) and os.path.exists(repo_dir)\n\n if use_cache:\n if verbose:\n sys.stderr.write(f'Using cache found in {repo_dir}\\n')\n else:\n cached_file = os.path.join(hub_dir, normalized_br + '.zip')\n _remove_if_exists(cached_file)\n\n url = _git_archive_link(repo_owner, repo_name, branch, source=source)\n\n fpath = get_path_from_url(\n url,\n hub_dir,\n check_exist=not force_reload,\n decompress=False,\n )\n shutil.move(fpath, cached_file)\n\n with zipfile.ZipFile(cached_file) as cached_zipfile:\n extracted_repo_name = cached_zipfile.infolist()[0].filename\n extracted_repo = os.path.join(hub_dir, extracted_repo_name)\n _remove_if_exists(extracted_repo)\n # Unzip the code and rename the base folder\n cached_zipfile.extractall(hub_dir)\n\n _remove_if_exists(cached_file)\n _remove_if_exists(repo_dir)\n # Rename the repo\n shutil.move(extracted_repo, repo_dir)\n\n return repo_dir"}], "vul_patch": "--- a/python/paddle/utils/download.py\n+++ b/python/paddle/hapi/hub.py\n@@ -1,28 +1,52 @@\n-def _wget_download(url: str, fullname: str):\n- try:\n- assert urlparse(url).scheme in (\n- 'http',\n- 'https',\n- ), 'Only support https and http url'\n- # using wget to download url\n- tmp_fullname = shlex.quote(fullname + \"_tmp\")\n- url = shlex.quote(url)\n- # \\u2013user-agent\n- command = f'wget -O {tmp_fullname} -t {DOWNLOAD_RETRY_LIMIT} {url}'\n- subprc = subprocess.Popen(\n- command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n+def _get_cache_or_reload(repo, force_reload, verbose=True, source='github'):\n+ # Setup hub_dir to save downloaded files\n+ hub_dir = HUB_DIR\n+\n+ _make_dirs(hub_dir)\n+\n+ # Parse github/gitee repo information\n+ repo_owner, repo_name, branch = _parse_repo_info(repo, source)\n+ # Github allows branch name with slash '/',\n+ # this causes confusion with path on both Linux and Windows.\n+ # Backslash is not allowed in Github branch name so no need to\n+ # to worry about it.\n+ normalized_br = branch.replace('/', '_')\n+ # Github renames folder repo/v1.x.x to repo-1.x.x\n+ # We don't know the repo name before downloading the zip file\n+ # and inspect name from it.\n+ # To check if cached repo exists, we need to normalize folder names.\n+ repo_dir = os.path.join(\n+ hub_dir, '_'.join([repo_owner, repo_name, normalized_br])\n+ )\n+\n+ use_cache = (not force_reload) and os.path.exists(repo_dir)\n+\n+ if use_cache:\n+ if verbose:\n+ sys.stderr.write(f'Using cache found in {repo_dir}\\n')\n+ else:\n+ cached_file = os.path.join(hub_dir, normalized_br + '.zip')\n+ _remove_if_exists(cached_file)\n+\n+ url = _git_archive_link(repo_owner, repo_name, branch, source=source)\n+\n+ fpath = get_path_from_url(\n+ url,\n+ hub_dir,\n+ check_exist=not force_reload,\n+ decompress=False,\n+ method=('wget' if source == 'gitee' else 'get'),\n )\n- _ = subprc.communicate()\n+ shutil.move(fpath, cached_file)\n \n- if subprc.returncode != 0:\n- raise RuntimeError(\n- f'{command} failed. Please make sure `wget` is installed or {url} exists'\n- )\n+ with zipfile.ZipFile(cached_file) as cached_zipfile:\n+ extracted_repo_name = cached_zipfile.infolist()[0].filename\n+ extracted_repo = os.path.join(hub_dir, extracted_repo_name)\n+ _remove_if_exists(extracted_repo)\n+ # Unzip the code and rename the base folder\n+ cached_zipfile.extractall(hub_dir)\n \n- shutil.move(tmp_fullname, fullname)\n-\n- except Exception as e: # requests.exceptions.ConnectionError\n- logger.info(f\"Downloading {url} failed with exception {str(e)}\")\n- return False\n-\n- return fullname\n+ _remove_if_exists(cached_file)\n+ _remove_if_exists(repo_dir)\n+ # Rename the repo\n+ shutil.move(extracted_repo, repo_dir)\n\n--- a/python/paddle/utils/download.py\n+++ /dev/null\n@@ -1,4 +0,0 @@\n-_download_methods = {\n- 'get': _get_download,\n- 'wget': _wget_download,\n-}\n\n--- a/python/paddle/hapi/hub.py\n+++ /dev/null\n@@ -1,54 +0,0 @@\n-def _get_cache_or_reload(repo, force_reload, verbose=True, source='github'):\n- # Setup hub_dir to save downloaded files\n- hub_dir = HUB_DIR\n-\n- _make_dirs(hub_dir)\n-\n- # Parse github/gitee repo information\n- repo_owner, repo_name, branch = _parse_repo_info(repo, source)\n- # Github allows branch name with slash '/',\n- # this causes confusion with path on both Linux and Windows.\n- # Backslash is not allowed in Github branch name so no need to\n- # to worry about it.\n- normalized_br = branch.replace('/', '_')\n- # Github renames folder repo/v1.x.x to repo-1.x.x\n- # We don't know the repo name before downloading the zip file\n- # and inspect name from it.\n- # To check if cached repo exists, we need to normalize folder names.\n- repo_dir = os.path.join(\n- hub_dir, '_'.join([repo_owner, repo_name, normalized_br])\n- )\n-\n- use_cache = (not force_reload) and os.path.exists(repo_dir)\n-\n- if use_cache:\n- if verbose:\n- sys.stderr.write(f'Using cache found in {repo_dir}\\n')\n- else:\n- cached_file = os.path.join(hub_dir, normalized_br + '.zip')\n- _remove_if_exists(cached_file)\n-\n- url = _git_archive_link(repo_owner, repo_name, branch, source=source)\n-\n- fpath = get_path_from_url(\n- url,\n- hub_dir,\n- check_exist=not force_reload,\n- decompress=False,\n- method=('wget' if source == 'gitee' else 'get'),\n- )\n- shutil.move(fpath, cached_file)\n-\n- with zipfile.ZipFile(cached_file) as cached_zipfile:\n- extracted_repo_name = cached_zipfile.infolist()[0].filename\n- extracted_repo = os.path.join(hub_dir, extracted_repo_name)\n- _remove_if_exists(extracted_repo)\n- # Unzip the code and rename the base folder\n- cached_zipfile.extractall(hub_dir)\n-\n- _remove_if_exists(cached_file)\n- _remove_if_exists(repo_dir)\n- # Rename the repo\n- shutil.move(extracted_repo, repo_dir)\n-\n- return repo_dir\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2024-0439", "cve_description": "As a manager, you should not be able to modify a series of settings. In the UI this is indeed hidden as a convenience for the role since most managers would not be savvy enough to modify these settings. They can use their token to still modify those settings though through a standard HTTP request\n\nWhile this is not a critical vulnerability, it does indeed need to be patched to enforce the expected permission level.", "cwe_info": {"CWE-269": {"name": "Improper Privilege Management", "description": "The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor."}}, "repo": "https://github.com/mintplex-labs/anything-llm", "patch_url": ["https://github.com/mintplex-labs/anything-llm/commit/7200a06ef07d92eef5f3c4c8be29824aa001d688"], "programing_language": "JavaScript", "vul_func": [{"id": "vul_js_223_1", "commit": "3c859ba", "file_path": "server/endpoints/system.js", "start_line": 284, "end_line": 295, "snippet": " async (request, response) => {\n try {\n const body = reqBody(request);\n const { newValues, error } = updateENV(body);\n if (process.env.NODE_ENV === \"production\") await dumpENV();\n response.status(200).json({ newValues, error });\n } catch (e) {\n console.log(e.message, e);\n response.sendStatus(500).end();\n }\n }\n );"}], "fix_func": [{"id": "fix_js_223_1", "commit": "7200a06ef07d92eef5f3c4c8be29824aa001d688", "file_path": "server/endpoints/system.js", "start_line": 284, "end_line": 301, "snippet": " async (request, response) => {\n try {\n const user = await userFromSession(request, response);\n if (!!user && user.role !== \"admin\") {\n response.sendStatus(401).end();\n return;\n }\n\n const body = reqBody(request);\n const { newValues, error } = updateENV(body);\n if (process.env.NODE_ENV === \"production\") await dumpENV();\n response.status(200).json({ newValues, error });\n } catch (e) {\n console.log(e.message, e);\n response.sendStatus(500).end();\n }\n }\n );"}], "vul_patch": "--- a/server/endpoints/system.js\n+++ b/server/endpoints/system.js\n@@ -1,5 +1,11 @@\n async (request, response) => {\n try {\n+ const user = await userFromSession(request, response);\n+ if (!!user && user.role !== \"admin\") {\n+ response.sendStatus(401).end();\n+ return;\n+ }\n+\n const body = reqBody(request);\n const { newValues, error } = updateENV(body);\n if (process.env.NODE_ENV === \"production\") await dumpENV();\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2018-6596", "cve_description": "webhooks/base.py in Anymail (aka django-anymail) before 1.2.1 is prone to a timing attack vulnerability on the WEBHOOK_AUTHORIZATION secret, which allows remote attackers to post arbitrary e-mail tracking events.", "cwe_info": {"CWE-200": {"name": "Exposure of Sensitive Information to an Unauthorized Actor", "description": "The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information."}}, "repo": "https://github.com/anymail/django-anymail", "patch_url": ["https://github.com/anymail/django-anymail/commit/c07998304b4a31df4c61deddcb03d3607a04691b"], "programing_language": "Python", "vul_func": [{"id": "vul_py_370_1", "commit": "7029298b930620b1655dab2548f72d6640a5905e", "file_path": "anymail/webhooks/base.py", "start_line": 41, "end_line": 48, "snippet": " def validate_request(self, request):\n \"\"\"If configured for webhook basic auth, validate request has correct auth.\"\"\"\n if self.basic_auth:\n basic_auth = get_request_basic_auth(request)\n if basic_auth is None or basic_auth not in self.basic_auth:\n # noinspection PyUnresolvedReferences\n raise AnymailWebhookValidationFailure(\n \"Missing or invalid basic auth in Anymail %s webhook\" % self.esp_name)"}], "fix_func": [{"id": "fix_py_370_1", "commit": "c07998304b4a31df4c61deddcb03d3607a04691b", "file_path": "anymail/webhooks/base.py", "start_line": 42, "end_line": 54, "snippet": " def validate_request(self, request):\n \"\"\"If configured for webhook basic auth, validate request has correct auth.\"\"\"\n if self.basic_auth:\n request_auth = get_request_basic_auth(request)\n # Use constant_time_compare to avoid timing attack on basic auth. (It's OK that any()\n # can terminate early: we're not trying to protect how many auth strings are allowed,\n # just the contents of each individual auth string.)\n auth_ok = any(constant_time_compare(request_auth, allowed_auth)\n for allowed_auth in self.basic_auth)\n if not auth_ok:\n # noinspection PyUnresolvedReferences\n raise AnymailWebhookValidationFailure(\n \"Missing or invalid basic auth in Anymail %s webhook\" % self.esp_name)"}], "vul_patch": "--- a/anymail/webhooks/base.py\n+++ b/anymail/webhooks/base.py\n@@ -1,8 +1,13 @@\n def validate_request(self, request):\n \"\"\"If configured for webhook basic auth, validate request has correct auth.\"\"\"\n if self.basic_auth:\n- basic_auth = get_request_basic_auth(request)\n- if basic_auth is None or basic_auth not in self.basic_auth:\n+ request_auth = get_request_basic_auth(request)\n+ # Use constant_time_compare to avoid timing attack on basic auth. (It's OK that any()\n+ # can terminate early: we're not trying to protect how many auth strings are allowed,\n+ # just the contents of each individual auth string.)\n+ auth_ok = any(constant_time_compare(request_auth, allowed_auth)\n+ for allowed_auth in self.basic_auth)\n+ if not auth_ok:\n # noinspection PyUnresolvedReferences\n raise AnymailWebhookValidationFailure(\n \"Missing or invalid basic auth in Anymail %s webhook\" % self.esp_name)\n\n", "poc_patch": null, "unit_test_cmd": null} {"cve_id": "CVE-2022-31506", "cve_description": "The cmusatyalab/opendiamond repository through 10.1.1 on GitHub allows absolute path traversal because the Flask send_file function is used unsafely.", "cwe_info": {"CWE-73": {"name": "External Control of File Name or Path", "description": "The product allows user input to control or influence paths or file names that are used in filesystem operations."}, "CWE-22": {"name": "Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')", "description": "The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory."}}, "repo": "https://github.com/cmusatyalab/opendiamond", "patch_url": ["https://github.com/cmusatyalab/opendiamond/commit/398049c187ee644beabab44d6fece82251c1ea56"], "programing_language": "Python", "vul_func": [{"id": "vul_py_22_1", "commit": "d2f20ffff793f88335f2c0244679d7193295abe2", "file_path": "opendiamond/dataretriever/diamond_store.py", "start_line": 122, "end_line": 123, "snippet": "def _get_obj_absolute_path(obj_path):\n return os.path.join(DATAROOT, obj_path)"}], "fix_func": [{"id": "fix_py_22_1", "commit": "398049c187ee644beabab44d6fece82251c1ea56", "file_path": "opendiamond/dataretriever/diamond_store.py", "start_line": 123, "end_line": 124, "snippet": "def _get_obj_absolute_path(obj_path):\n return safe_join(DATAROOT, obj_path)"}], "vul_patch": "--- a/opendiamond/dataretriever/diamond_store.py\n+++ b/opendiamond/dataretriever/diamond_store.py\n@@ -1,2 +1,2 @@\n def _get_obj_absolute_path(obj_path):\n- return os.path.join(DATAROOT, obj_path)\n+ return safe_join(DATAROOT, obj_path)\n\n", "poc_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2022-31506:latest\n# bash /workspace/fix-run.sh\nset -e\n\ncd /workspace/opendiamond\ngit apply --whitespace=nowarn /workspace/test.patch /workspace/fix.patch\n/workspace/PoC_env/CVE-2022-31506/bin/python hand_test.py\n", "unit_test_cmd": "#!/bin/bash\n# From ghcr.io/anonymous2578-data/cve-2022-31506:latest\n# bash /workspace/unit_test.sh\nset -e\n\ncd /workspace/opendiamond\ngit apply --whitespace=nowarn /workspace/fix.patch\n/workspace/PoC_env/CVE-2022-31506/bin/python -m pytest -v tests/ --deselect=tests/test_client.py --deselect=tests/test_bundle.py --deselect=tests/test_attributes.py::test_rgbimage_attr --deselect=tests/test_attributes.py::test_string_attr --deselect=tests/test_attributes.py::test_integer_attr --deselect=tests/test_attributes.py::test_float_attr --deselect=tests/test_attributes.py::test_patches_attr --deselect=tests/test_blobcache.py::test_blobcache_add --deselect=tests/test_blobcache.py::test_blobcache_contains --deselect=tests/test_blobcache.py::test_blobcache_prune --deselect=tests/test_blobcache.py::test_blobcache_gc_rescue --deselect=tests/test_blobcache.py::test_executable_blobcache\n"}