authoring-lora-data-sr / authoring.train.jsonl
odoom's picture
search/replace relabel: 60 train (adecbbf)
656261b verified
Raw
History Blame Contribute Delete
460 kB
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2011-10007: 2-argument open() injection (CWE-78/CWE-73) in the Perl module File::Find::Rule (<= 0.34). Perl's 2-arg open interprets a leading '>', '>>', or '|' in the string as a mode/pipe, so a file whose basename is e.g. Merely running File::Find::Rule->grep over a directory that contains an attacker-named file therefore yields arbitrary file write or command execution. nixpkgs ships File::Find::Rule 0.34 (perlPackages.FileFindRule).\n\n# Vulnerable source (lib/File/Find/Rule.pm)\n```perl\nthem in anonymous arrays. Should a negative specifier match the\niteration is aborted and the clause is failed. For example:\n\n $rule->grep( qr/^#!.*\\bperl/, [ sub { 1 } ] );\n\nIs a passing clause if the first line of a file looks like a perl\nshebang line.\n\n=cut\n\nsub grep {\n my $self = _force_object shift;\n my @pattern = map {\n ref $_\n ? ref $_ eq 'ARRAY'\n ? map { [ ( ref $_ ? $_ : qr/$_/ ) => 0 ] } @$_\n : [ $_ => 1 ]\n : [ qr/$_/ => 1 ]\n } @_;\n\n $self->exec( sub {\n local *FILE;\n open FILE, $_ or return;\n local ($_, $.);\n while (<FILE>) {\n for my $p (@pattern) {\n my ($rule, $ret) = @$p;\n return $ret\n if ref $rule eq 'Regexp'\n ? /$rule/\n : $rule->(@_);\n }\n }\n return;\n } );\n}\n\n=item C<maxdepth( $level )>\n\nDescend at most C<$level> (a non-negative integer) levels of directories\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\n $self->exec( sub {\n local *FILE;\n open FILE, $_ or return;\n local ($_, $.);\n while (<FILE>) {\n for my $p (@pattern) {\n=======\n\n $self->exec( sub {\n local *FILE;\n open FILE, '<', $_ or return;\n local ($_, $.);\n while (<FILE>) {\n for my $p (@pattern) {\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2014-9913: unzip list_files() uses a 4-byte output slot for the algorithm label in its file listing; the unpatched code writes a 3-digit decimal string without checking if the algorithm index has grown beyond the 3-digit range, so an oversized index overruns the 4-byte slot and corrupts an adjacent byte on the heap.\n\n# Vulnerable source (list.c)\n```c\n } else\n#endif /* USE_EF_UT_TIME */\n {\n yr = ((((unsigned)(G.crec.last_mod_dos_datetime >> 25) & 0x7f)\n + 1980));\n mo = ((unsigned)(G.crec.last_mod_dos_datetime >> 21) & 0x0f);\n dy = ((unsigned)(G.crec.last_mod_dos_datetime >> 16) & 0x1f);\n hh = (((unsigned)G.crec.last_mod_dos_datetime >> 11) & 0x1f);\n mm = (((unsigned)G.crec.last_mod_dos_datetime >> 5) & 0x3f);\n }\n /* permute date so it displays according to nat'l convention\n * ('methnum' is not yet set, it is used as temporary buffer) */\n switch (date_format) {\n case DF_YMD:\n methnum = mo;\n mo = yr; yr = dy; dy = methnum;\n break;\n case DF_DMY:\n methnum = mo;\n mo = dy; dy = methnum;\n }\n\n csiz = G.crec.csize;\n if (G.crec.general_purpose_bit_flag & 1)\n csiz -= 12; /* if encrypted, don't count encryption header */\n if ((cfactor = ratio(G.crec.ucsize, csiz)) < 0) {\n#ifndef WINDLL\n sgn = '-';\n#endif\n cfactor = (-cfactor + 5) / 10;\n } else {\n#ifndef WINDLL\n sgn = ' ';\n#endif\n cfactor = (cfactor + 5) / 10;\n }\n\n methnum = find_compr_idx(G.crec.compression_method);\n zfstrcpy(methbuf, method[methnum]);\n if (G.crec.compression_method == DEFLATED ||\n G.crec.compression_method == ENHDEFLATED) {\n methbuf[5] = dtype[(G.crec.general_purpose_bit_flag>>1) & 3];\n } else if (methnum >= NUM_METHODS) {\n sprintf(&methbuf[4], \"%03u\", G.crec.compression_method);\n }\n\n#if 0 /* GRR/Euro: add this? */\n#if defined(DOS_FLX_NLM_OS2_W32) || defined(THEOS) || defined(UNIX)\n for (p = G.filename; *p; ++p)\n if (!isprint(*p))\n *p = '?'; /* change non-printable chars to '?' */\n#endif /* DOS_FLX_NLM_OS2_W32 || THEOS || UNIX */\n#endif /* 0 */\n\n#ifdef WINDLL\n /* send data to application for formatting and printing */\n if (G.lpUserFunctions->SendApplicationMessage != NULL)\n (*G.lpUserFunctions->SendApplicationMessage)(G.crec.ucsize,\n csiz, (unsigned)cfactor, mo, dy, yr, hh, mm,\n (char)(G.pInfo->lcflag ? '^' : ' '),\n (LPCSTR)fnfilter(G.filename, slide, (WSIZE>>1)),\n (LPCSTR)methbuf, G.crec.crc32,\n (char)((G.crec.general_purpose_bit_flag & 1) ? 'E' : ' '));\n else if (G.lpUserFunctions->SendApplicationMessage_i32 != NULL) {\n unsigned long ucsize_lo, csiz_lo;\n unsigned long ucsize_hi=0L, csiz_hi=0L;\n ucsize_lo = (unsigned long)(G.crec.ucsize);\n csiz_lo = (unsigned long)(csiz);\n#ifdef ZIP64_SUPPORT\n ucsize_hi = (unsigned long)(G.crec.ucsize >> 32);\n csiz_hi = (unsigned long)(csiz >> 32);\n#endif /* ZIP64_SUPPORT */\n (*G.lpUserFunctions->SendApplicationMessage_i32)(ucsize_lo,\n ucsize_hi, csiz_lo, csiz_hi, (unsigned)cfactor,\n mo, dy, yr, hh, mm,\n (char)(G.pInfo->lcflag ? '^' : ' '),\n (LPCSTR)fnfilter(G.filename, slide, (WSIZE>>1)),\n (LPCSTR)methbuf, G.crec.crc32,\n (char)((G.crec.general_purpose_bit_flag & 1) ? 'E' : ' '));\n }\n#else /* !WINDLL */\n if (cfactor == 100)\n sprintf(cfactorstr, LoadFarString(CompFactor100));\n else\n sprintf(cfactorstr, LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr)\n Info(slide, 0, ((char *)slide, LoadFarString(LongHdrStats),\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n G.crec.compression_method == ENHDEFLATED) {\n methbuf[5] = dtype[(G.crec.general_purpose_bit_flag>>1) & 3];\n } else if (methnum >= NUM_METHODS) {\n sprintf(&methbuf[4], \"%03u\", G.crec.compression_method);\n }\n\n#if 0 /* GRR/Euro: add this? */\n=======\n G.crec.compression_method == ENHDEFLATED) {\n methbuf[5] = dtype[(G.crec.general_purpose_bit_flag>>1) & 3];\n } else if (methnum >= NUM_METHODS) {\n /* 2013-02-26 SMS.\n * http://sourceforge.net/p/infozip/bugs/27/ CVE-2014-9913.\n * Unexpectedly large compression methods overflow\n * &methbuf[]. Use the old, three-digit decimal format\n * for values which fit. Otherwise, sacrifice the\n * colon, and use four-digit hexadecimal.\n */\n if (G.crec.compression_method <= 999) {\n sprintf( &methbuf[ 4], \"%03u\", G.crec.compression_method);\n } else {\n sprintf( &methbuf[ 3], \"%04X\", G.crec.compression_method);\n }\n }\n\n#if 0 /* GRR/Euro: add this? */\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2015-1419: vsftpd vsf_filename_passes_filter() compares the deny-file pattern against the raw FTP-supplied filename without first resolving symlinks; a user can point a symlink at a forbidden destination and bypass the block entirely since the matcher sees only the link name, not the resolved absolute location.\n\n# Vulnerable source (ls.c)\n```c\n/*\n * Part of Very Secure FTPd\n * Licence: GPL v2\n * Author: Chris Evans\n * ls.c\n *\n * Would you believe, code to handle directory listing.\n */\n\n#include \"ls.h\"\n#include \"access.h\"\n#include \"defs.h\"\n#include \"str.h\"\n#include \"strlist.h\"\n#include \"sysstr.h\"\n#include \"sysutil.h\"\n#include \"tunables.h\"\n\nstatic void build_dir_line(struct mystr* p_str,\n const struct mystr* p_filename_str,\n const struct vsf_sysutil_statbuf* p_stat,\n long curr_time);\n\nvoid\nvsf_ls_populate_dir_list(struct mystr_list* p_list,\n struct mystr_list* p_subdir_list,\n struct vsf_sysutil_dir* p_dir,\n const struct mystr* p_base_dir_str,\n const struct mystr* p_option_str,\n const struct mystr* p_filter_str,\n int is_verbose)\n{\n struct mystr dirline_str = INIT_MYSTR;\n struct mystr normalised_base_dir_str = INIT_MYSTR;\n struct str_locate_result loc_result;\n int a_option;\n int r_option;\n int t_option;\n int F_option;\n int do_stat = 0;\n long curr_time = 0;\n loc_result = str_locate_char(p_option_str, 'a');\n a_option = loc_result.found;\n loc_result = str_locate_char(p_option_str, 'r');\n r_option = loc_result.found;\n loc_result = str_locate_char(p_option_str, 't');\n t_option = loc_result.found;\n loc_result = str_locate_char(p_option_str, 'F');\n F_option = loc_result.found;\n loc_result = str_locate_char(p_option_str, 'l');\n if (loc_result.found)\n {\n is_verbose = 1;\n }\n /* Invert \"reverse\" arg for \"-t\", the time sorting */\n if (t_option)\n {\n r_option = !r_option;\n }\n if (is_verbose || t_option || F_option || p_subdir_list != 0)\n {\n do_stat = 1;\n }\n /* If the filter starts with a . then implicitly enable -a */\n if (!str_isempty(p_filter_str) && str_get_char_at(p_filter_str, 0) == '.')\n {\n a_option = 1;\n }\n /* \"Normalise\" the incoming base directory string by making sure it\n * ends in a '/' if it is nonempty\n */\n if (!str_equal_text(p_base_dir_str, \".\"))\n {\n str_copy(&normalised_base_dir_str, p_base_dir_str);\n }\n if (!str_isempty(&normalised_base_dir_str))\n {\n unsigned int len = str_getlen(&normalised_base_dir_str);\n if (str_get_char_at(&normalised_base_dir_str, len - 1) != '/')\n {\n str_append_char(&normalised_base_dir_str, '/');\n }\n }\n /* If we're going to need to do time comparisions, cache the local time */\n if (is_verbose)\n {\n curr_time = vsf_sysutil_get_time_sec();\n }\n while (1)\n {\n static struct mystr s_next_filename_str;\n static struct mystr s_next_path_and_filename_str;\n static struct vsf_sysutil_statbuf* s_p_statbuf;\n str_next_dirent(&s_next_filename_str, p_dir);\n if (str_isempty(&s_next_filename_str))\n {\n break;\n }\n {\n unsigned int len = str_getlen(&s_next_filename_str);\n if (len > 0 && str_get_char_at(&s_next_filename_str, 0) == '.')\n {\n if (!a_option && !tunable_force_dot_files)\n {\n continue;\n }\n if (!a_option &&\n ((len == 2 && str_get_char_at(&s_next_filename_str, 1) == '.') ||\n len == 1))\n {\n continue;\n }\n }\n }\n /* Don't show hidden directory entries */\n if (!vsf_access_check_file_visible(&s_next_filename_str))\n {\n continue;\n }\n /* If we have an ls option which is a filter, apply it */\n if (!str_isempty(p_filter_str))\n {\n unsigned int iters = 0;\n if (!vsf_filename_passes_filter(&s_next_filename_str, p_filter_str,\n &iters))\n {\n continue;\n }\n }\n /* Calculate the full path (relative to CWD) for lstat() and\n * output purposes\n */\n str_copy(&s_next_path_and_filename_str, &normalised_base_dir_str);\n str_append_str(&s_next_path_and_filename_str, &s_next_filename_str);\n if (do_stat)\n {\n /* lstat() the file. Of course there's a race condition - the\n * directory entry may have gone away whilst we read it, so\n * ignore failure to stat\n */\n int retval = str_lstat(&s_next_path_and_filename_str, &s_p_statbuf);\n if (vsf_sysutil_retval_is_error(retval))\n {\n continue;\n }\n }\n if (is_verbose)\n {\n static struct mystr s_final_file_str;\n /* If it's a damn symlink, we need to append the target */\n str_copy(&s_final_file_str, &s_next_filename_str);\n if (vsf_sysutil_statbuf_is_symlink(s_p_statbuf))\n {\n static struct mystr s_temp_str;\n int retval = str_readlink(&s_temp_str, &s_next_path_and_filename_str);\n if (retval == 0 && !str_isempty(&s_temp_str))\n {\n str_append_text(&s_final_file_str, \" -> \");\n str_append_str(&s_final_file_str, &s_temp_str);\n }\n }\n if (F_option && vsf_sysutil_statbuf_is_dir(s_p_statbuf))\n {\n str_append_char(&s_final_file_str, '/');\n }\n build_dir_line(&dirline_str, &s_final_file_str, s_p_statbuf, curr_time);\n }\n else\n {\n /* Just emit the filenames - note, we prepend the directory for NLST\n * but not for LIST\n */\n str_copy(&dirline_str, &s_next_path_and_filename_str);\n if (F_option)\n {\n if (vsf_sysutil_statbuf_is_dir(s_p_statbuf))\n {\n str_append_char(&dirline_str, '/');\n }\n else if (vsf_sysutil_statbuf_is_symlink(s_p_statbuf))\n {\n str_append_char(&dirline_str, '@');\n }\n }\n str_append_text(&dirline_str, \"\\r\\n\");\n }\n /* Add filename into our sorted list - sorting by filename or time. Also,\n * if we are required to, maintain a distinct list of direct\n * subdirectories.\n */\n {\n static struct mystr s_temp_str;\n const struct mystr* p_sort_str = 0;\n const struct mystr* p_sort_subdir_str = 0;\n if (!t_option)\n {\n p_sort_str = &s_next_filename_str;\n }\n else\n {\n str_alloc_text(&s_temp_str,\n vsf_sysutil_statbuf_get_sortkey_mtime(s_p_statbuf));\n p_sort_str = &s_temp_str;\n p_sort_subdir_str = &s_temp_str;\n }\n str_list_add(p_list, &dirline_str, p_sort_str);\n if (p_subdir_list != 0 && vsf_sysutil_statbuf_is_dir(s_p_statbuf))\n {\n str_list_add(p_subdir_list, &s_next_filename_str, p_sort_subdir_str);\n }\n }\n } /* END: while(1) */\n str_list_sort(p_list, r_option);\n if (p_subdir_list != 0)\n {\n str_list_sort(p_subdir_list, r_option);\n }\n str_free(&dirline_str);\n str_free(&normalised_base_dir_str);\n}\n\nint\nvsf_filename_passes_filter(const struct mystr* p_filename_str,\n const struct mystr* p_filter_str,\n unsigned int* iters)\n{\n /* A simple routine to match a filename against a pattern.\n * This routine is used instead of e.g. fnmatch(3), because we should be\n * reluctant to trust the latter. fnmatch(3) involves _lots_ of string\n * parsing and handling. There is broad potential for any given fnmatch(3)\n * implementation to be buggy.\n *\n * Currently supported pattern(s):\n * - any number of wildcards, \"*\" or \"?\"\n * - {,} syntax (not nested)\n *\n * Note that pattern matching is only supported within the last path\n * component. For example, searching for /a/b/? will work, but searching\n * for /a/?/c will not.\n */\n struct mystr filter_remain_str = INIT_MYSTR;\n struct mystr name_remain_str = INIT_MYSTR;\n struct mystr temp_str = INIT_MYSTR;\n struct mystr brace_list_str = INIT_MYSTR;\n struct mystr new_filter_str = INIT_MYSTR;\n int ret = 0;\n char last_token = 0;\n int must_match_at_current_pos = 1;\n str_copy(&filter_remain_str, p_filter_str);\n str_copy(&name_remain_str, p_filename_str);\n\n while (!str_isempty(&filter_remain_str) && *iters < VSFTP_MATCHITERS_MAX)\n {\n static struct mystr s_match_needed_str;\n /* Locate next special token */\n struct str_locate_result locate_result =\n str_locate_chars(&filter_remain_str, \"*?{\");\n (*iters)++;\n /* Isolate text leading up to token (if any) - needs to be matched */\n if (locate_result.found)\n {\n unsigned int indexx = locate_result.index;\n str_left(&filter_remain_str, &s_match_needed_str, indexx);\n str_mid_to_end(&filter_remain_str, &temp_str, indexx + 1);\n str_copy(&filter_remain_str, &temp_str);\n last_token = locate_result.char_found;\n }\n else\n {\n /* No more tokens. Must match remaining filter string exactly. */\n str_copy(&s_match_needed_str, &filter_remain_str);\n str_empty(&filter_remain_str);\n last_token = 0;\n }\n if (!str_isempty(&s_match_needed_str))\n {\n /* Need to match something.. could be a match which has to start at\n * current position, or we could allow it to start anywhere\n */\n unsigned int indexx;\n locate_result = str_locate_str(&name_remain_str, &s_match_needed_str);\n if (!locate_result.found)\n {\n /* Fail */\n goto out;\n }\n indexx = locate_result.index;\n if (must_match_at_current_pos && indexx > 0)\n {\n goto out;\n }\n /* Chop matched string out of remainder */\n str_mid_to_end(&name_remain_str, &temp_str,\n indexx + str_getlen(&s_match_needed_str));\n str_copy(&name_remain_str, &temp_str);\n }\n if (last_token == '?')\n {\n if (str_isempty(&name_remain_str))\n {\n goto out;\n }\n str_right(&name_remain_str, &temp_str, str_getlen(&name_remain_str) - 1);\n str_copy(&name_remain_str, &temp_str);\n must_match_at_current_pos = 1;\n }\n else if (last_token == '{')\n {\n struct str_locate_result end_brace =\n str_locate_char(&filter_remain_str, '}');\n must_match_at_current_pos = 1;\n if (end_brace.found)\n {\n str_split_char(&filter_remain_str, &temp_str, '}');\n str_copy(&brace_list_str, &filter_remain_str);\n str_copy(&filter_remain_str, &temp_str);\n str_split_char(&brace_list_str, &temp_str, ',');\n while (!str_isempty(&brace_list_str))\n {\n str_copy(&new_filter_str, &brace_list_str);\n str_append_str(&new_filter_str, &filter_remain_str);\n if (vsf_filename_passes_filter(&name_remain_str, &new_filter_str,\n iters))\n {\n ret = 1;\n goto out;\n }\n str_copy(&brace_list_str, &temp_str);\n str_split_char(&brace_list_str, &temp_str, ',');\n }\n goto out;\n }\n else if (str_isempty(&name_remain_str) ||\n str_get_char_at(&name_remain_str, 0) != '{')\n {\n goto out;\n }\n else\n {\n str_right(&name_remain_str, &temp_str,\n str_getlen(&name_remain_str) - 1);\n str_copy(&name_remain_str, &temp_str);\n }\n }\n else\n {\n must_match_at_current_pos = 0;\n }\n }\n /* Any incoming string left means no match unless we ended on the correct\n * type of wildcard.\n */\n if (str_getlen(&name_remain_str) > 0 && last_token != '*')\n {\n goto out;\n }\n /* OK, a match */\n ret = 1;\n if (*iters == VSFTP_MATCHITERS_MAX) {\n ret = 0;\n }\nout:\n str_free(&filter_remain_str);\n str_free(&name_remain_str);\n str_free(&temp_str);\n str_free(&brace_list_str);\n str_free(&new_filter_str);\n return ret;\n}\n\nstatic void\nbuild_dir_line(struct mystr* p_str, const struct mystr* p_filename_str,\n const struct vsf_sysutil_statbuf* p_stat, long curr_time)\n{\n static struct mystr s_tmp_str;\n filesize_t size = vsf_sysutil_statbuf_get_size(p_stat);\n /* Permissions */\n str_alloc_text(p_str, vsf_sysutil_statbuf_get_perms(p_stat));\n str_append_char(p_str, ' ');\n /* Hard link count */\n str_alloc_ulong(&s_tmp_str, vsf_sysutil_statbuf_get_links(p_stat));\n str_lpad(&s_tmp_str, 4);\n str_append_str(p_str, &s_tmp_str);\n str_append_char(p_str, ' ');\n /* User */\n if (tunable_hide_ids)\n {\n str_alloc_text(&s_tmp_str, \"ftp\");\n }\n else\n {\n int uid = vsf_sysutil_statbuf_get_uid(p_stat);\n struct vsf_sysutil_user* p_user = 0;\n if (tunable_text_userdb_names)\n {\n p_user = vsf_sysutil_getpwuid(uid);\n }\n if (p_user == 0)\n {\n str_alloc_ulong(&s_tmp_str, (unsigned long) uid);\n }\n else\n {\n str_alloc_text(&s_tmp_str, vsf_sysutil_user_getname(p_user));\n }\n }\n str_rpad(&s_tmp_str, 8);\n str_append_str(p_str, &s_tmp_str);\n str_append_char(p_str, ' ');\n /* Group */\n if (tunable_hide_ids)\n {\n str_alloc_text(&s_tmp_str, \"ftp\");\n }\n else\n {\n int gid = vsf_sysutil_statbuf_get_gid(p_stat);\n struct vsf_sysutil_group* p_group = 0;\n if (tunable_text_userdb_names)\n {\n p_group = vsf_sysutil_getgrgid(gid);\n }\n if (p_group == 0)\n {\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n * Would you believe, code to handle directory listing.\n */\n\n#include \"ls.h\"\n#include \"access.h\"\n#include \"defs.h\"\n=======\n * Would you believe, code to handle directory listing.\n */\n\n#include <stdlib.h>\n#include \"ls.h\"\n#include \"access.h\"\n#include \"defs.h\"\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n struct mystr temp_str = INIT_MYSTR;\n struct mystr brace_list_str = INIT_MYSTR;\n struct mystr new_filter_str = INIT_MYSTR;\n int ret = 0;\n char last_token = 0;\n int must_match_at_current_pos = 1;\n str_copy(&filter_remain_str, p_filter_str);\n str_copy(&name_remain_str, p_filename_str);\n\n while (!str_isempty(&filter_remain_str) && *iters < VSFTP_MATCHITERS_MAX)\n {\n=======\n struct mystr temp_str = INIT_MYSTR;\n struct mystr brace_list_str = INIT_MYSTR;\n struct mystr new_filter_str = INIT_MYSTR;\n struct mystr normalize_filename_str = INIT_MYSTR;\n const char *normname;\n const char *path;\n int ret = 0;\n char last_token = 0;\n int must_match_at_current_pos = 1;\n\n str_copy(&filter_remain_str, p_filter_str);\n\n /* normalize filepath */\n path = str_strdup(p_filename_str);\n normname = realpath(path, NULL);\n if (normname == NULL)\n goto out;\n str_alloc_text(&normalize_filename_str, normname);\n\n if (!str_isempty (&filter_remain_str) && !str_isempty(&normalize_filename_str)) {\n if (str_get_char_at(p_filter_str, 0) == '/') {\n if (str_get_char_at(&normalize_filename_str, 0) != '/') {\n str_getcwd (&name_remain_str);\n\n if (str_getlen(&name_remain_str) > 1) /* cwd != root dir */\n str_append_char (&name_remain_str, '/');\n\n str_append_str (&name_remain_str, &normalize_filename_str);\n }\n else\n str_copy (&name_remain_str, &normalize_filename_str);\n } else {\n if (str_get_char_at(p_filter_str, 0) != '{')\n str_basename (&name_remain_str, &normalize_filename_str);\n else\n str_copy (&name_remain_str, &normalize_filename_str);\n }\n } else\n str_copy(&name_remain_str, &normalize_filename_str);\n\n while (!str_isempty(&filter_remain_str) && *iters < VSFTP_MATCHITERS_MAX)\n {\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n ret = 0;\n }\nout:\n str_free(&filter_remain_str);\n str_free(&name_remain_str);\n str_free(&temp_str);\n=======\n ret = 0;\n }\nout:\n free((char*) normname);\n free((char*) path);\n str_free(&normalize_filename_str);\n str_free(&filter_remain_str);\n str_free(&name_remain_str);\n str_free(&temp_str);\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2016-9844: unzip zipinfo mode uses a 4-byte output slot for the algorithm label; the unpatched code writes a 3-digit decimal string without checking if the algorithm index has grown beyond the 3-digit range, so an oversized index overruns the slot and corrupts an adjacent byte.\n\n# Vulnerable source (zipinfo.c)\n```c\n#endif\n int k, error, error_in_archive=PK_COOL;\n unsigned hostnum, hostver, methid, methnum, xattr;\n char *p, workspace[12], attribs[16];\n char methbuf[5];\n static ZCONST char dtype[5]=\"NXFS\"; /* normal, maximum, fast, superfast */\n static ZCONST char Far os[NUM_HOSTS+1][4] = {\n \"fat\", \"ami\", \"vms\", \"unx\", \"cms\", \"atr\", \"hpf\", \"mac\", \"zzz\",\n \"cpm\", \"t20\", \"ntf\", \"qds\", \"aco\", \"vft\", \"mvs\", \"be \", \"nsk\",\n \"ths\", \"osx\", \"???\", \"???\", \"???\", \"???\", \"???\", \"???\", \"???\",\n \"???\", \"???\", \"???\", \"ath\", \"???\"\n };\n#ifdef OLD_THEOS_EXTRA\n static ZCONST char Far os_TheosOld[] = \"tho\";\n#endif\n static ZCONST char Far method[NUM_METHODS+1][5] = {\n \"stor\", \"shrk\", \"re:1\", \"re:2\", \"re:3\", \"re:4\", \"i#:#\", \"tokn\",\n \"def#\", \"d64#\", \"dcli\", \"bzp2\", \"lzma\", \"ters\", \"lz77\", \"wavp\",\n \"ppmd\", \"u###\"\n };\n\n\n/*---------------------------------------------------------------------------\n Print out various interesting things about the compressed file.\n ---------------------------------------------------------------------------*/\n\n methid = (unsigned)(G.crec.compression_method);\n methnum = find_compr_idx(G.crec.compression_method);\n hostnum = (unsigned)(G.pInfo->hostnum);\n hostver = (unsigned)(G.pInfo->hostver);\n/*\n extnum = (unsigned)MIN(G.crec.version_needed_to_extract[1], NUM_HOSTS);\n extver = (unsigned)G.crec.version_needed_to_extract[0];\n */\n\n zfstrcpy(methbuf, method[methnum]);\n if (methid == IMPLODED) {\n methbuf[1] = (char)((G.crec.general_purpose_bit_flag & 2)? '8' : '4');\n methbuf[3] = (char)((G.crec.general_purpose_bit_flag & 4)? '3' : '2');\n } else if (methid == DEFLATED || methid == ENHDEFLATED) {\n ush dnum=(ush)((G.crec.general_purpose_bit_flag>>1) & 3);\n methbuf[3] = dtype[dnum];\n } else if (methnum >= NUM_METHODS) { /* unknown */\n sprintf(&methbuf[1], \"%03u\", G.crec.compression_method);\n }\n\n for (k = 0; k < 15; ++k)\n attribs[k] = ' ';\n attribs[15] = 0;\n\n xattr = (unsigned)((G.crec.external_file_attributes >> 16) & 0xFFFF);\n switch (hostnum) {\n case VMS_:\n { int i, j;\n\n for (k = 0; k < 12; ++k)\n workspace[k] = 0;\n if (xattr & VMS_IRUSR)\n workspace[0] = 'R';\n if (xattr & VMS_IWUSR) {\n workspace[1] = 'W';\n workspace[3] = 'D';\n }\n if (xattr & VMS_IXUSR)\n workspace[2] = 'E';\n if (xattr & VMS_IRGRP)\n workspace[4] = 'R';\n if (xattr & VMS_IWGRP) {\n workspace[5] = 'W';\n workspace[7] = 'D';\n }\n if (xattr & VMS_IXGRP)\n workspace[6] = 'E';\n if (xattr & VMS_IROTH)\n workspace[8] = 'R';\n if (xattr & VMS_IWOTH) {\n workspace[9] = 'W';\n workspace[11] = 'D';\n }\n if (xattr & VMS_IXOTH)\n workspace[10] = 'E';\n\n p = attribs;\n for (k = j = 0; j < 3; ++j) { /* groups of permissions */\n for (i = 0; i < 4; ++i, ++k) /* perms within a group */\n if (workspace[k])\n *p++ = workspace[k];\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n ush dnum=(ush)((G.crec.general_purpose_bit_flag>>1) & 3);\n methbuf[3] = dtype[dnum];\n } else if (methnum >= NUM_METHODS) { /* unknown */\n sprintf(&methbuf[1], \"%03u\", G.crec.compression_method);\n }\n\n for (k = 0; k < 15; ++k)\n=======\n ush dnum=(ush)((G.crec.general_purpose_bit_flag>>1) & 3);\n methbuf[3] = dtype[dnum];\n } else if (methnum >= NUM_METHODS) { /* unknown */\n /* 2016-12-05 SMS.\n * https://launchpad.net/bugs/1643750\n * Unexpectedly large compression methods overflow\n * &methbuf[]. Use the old, three-digit decimal format\n * for values which fit. Otherwise, sacrifice the \"u\",\n * and use four-digit hexadecimal.\n */\n if (G.crec.compression_method <= 999) {\n sprintf( &methbuf[ 1], \"%03u\", G.crec.compression_method);\n } else {\n sprintf( &methbuf[ 0], \"%04X\", G.crec.compression_method);\n }\n }\n\n for (k = 0; k < 15; ++k)\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2018-18384: unzip list_files() stores a compression-ratio string in a 10-byte on-stack buffer and writes it via an unchecked format call; an archive producing a ratio string longer than 9 bytes overruns the buffer and overwrites adjacent stack data.\n\n# Vulnerable source (list.c)\n```c\n \"-------- ------ ------- ---- ---------- ----- -------- ----\";\n static ZCONST char Far *Headers[][2] =\n { {HeadersS, HeadersS1}, {HeadersL, HeadersL1} };\n\n static ZCONST char Far CaseConversion[] =\n \"%s (\\\"^\\\" ==> case\\n%s conversion)\\n\";\n static ZCONST char Far LongHdrStats[] =\n \"%s %-7s%s %4s %02u%c%02u%c%02u %02u:%02u %08lx %c\";\n static ZCONST char Far LongFileTrailer[] =\n \"-------- ------- --- \\\n -------\\n%s %s %4s %lu file%s\\n\";\n#ifdef OS2_EAS\n static ZCONST char Far ShortHdrStats[] =\n \"%s %6lu %6lu %02u%c%02u%c%02u %02u:%02u %c\";\n static ZCONST char Far ShortFileTrailer[] =\n \"--------- ----- ----- \\\n -------\\n%s %6lu %6lu %lu file%s\\n\";\n static ZCONST char Far OS2ExtAttrTrailer[] =\n \"%lu file%s %lu bytes of OS/2 extended attributes attached.\\n\";\n static ZCONST char Far OS2ACLTrailer[] =\n \"%lu file%s %lu bytes of access control lists attached.\\n\";\n#else\n static ZCONST char Far ShortHdrStats[] =\n \"%s %02u%c%02u%c%02u %02u:%02u %c\";\n static ZCONST char Far ShortFileTrailer[] =\n \"--------- -------\\n%s\\\n %lu file%s\\n\";\n#endif /* ?OS2_EAS */\n#endif /* !WINDLL */\n\n\n\n\n\n/*************************/\n/* Function list_files() */\n/*************************/\n\nint list_files(__G) /* return PK-type error code */\n __GDEF\n{\n int do_this_file=FALSE, cfactor, error, error_in_archive=PK_COOL;\n#ifndef WINDLL\n char sgn, cfactorstr[10];\n int longhdr=(uO.vflag>1);\n#endif\n int date_format;\n char dt_sepchar;\n ulg members=0L;\n zusz_t j;\n unsigned methnum;\n#ifdef USE_EF_UT_TIME\n iztimes z_utime;\n struct tm *t;\n#endif\n unsigned yr, mo, dy, hh, mm;\n zusz_t csiz, tot_csize=0L, tot_ucsize=0L;\n#ifdef OS2_EAS\n ulg ea_size, tot_easize=0L, tot_eafiles=0L;\n ulg acl_size, tot_aclsize=0L, tot_aclfiles=0L;\n#endif\n min_info info;\n char methbuf[8];\n static ZCONST char dtype[]=\"NXFS\"; /* see zi_short() */\n static ZCONST char Far method[NUM_METHODS+1][8] =\n {\"Stored\", \"Shrunk\", \"Reduce1\", \"Reduce2\", \"Reduce3\", \"Reduce4\",\n \"Implode\", \"Token\", \"Defl:#\", \"Def64#\", \"ImplDCL\", \"BZip2\",\n \"LZMA\", \"Terse\", \"IBMLZ77\", \"WavPack\", \"PPMd\", \"Unk:###\"};\n\n\n\n/*---------------------------------------------------------------------------\n Unlike extract_or_test_files(), this routine confines itself to the cen-\n tral directory. Thus its structure is somewhat simpler, since we can do\n just a single loop through the entire directory, listing files as we go.\n\n So to start off, print the heading line and then begin main loop through\n the central directory. The results will look vaguely like the following:\n\n Length Method Size Ratio Date Time CRC-32 Name (\"^\" ==> case\n-------- ------ ------- ----- ---- ---- ------ ---- conversion)\n 44004 Implode 13041 71% 11-02-89 19:34 8b4207f7 Makefile.UNIX\n 3438 Shrunk 2209 36% 09-15-90 14:07 a2394fd8 ^dos-file.ext\n 16717 Defl:X 5252 69% 11-03-97 06:40 1ce0f189 WHERE\n-------- ------- --- -------\n 64159 20502 68% 3 files\n ---------------------------------------------------------------------------*/\n\n G.pInfo = &info;\n date_format = DATE_FORMAT;\n dt_sepchar = DATE_SEPCHAR;\n\n#ifndef WINDLL\n if (uO.qflag < 2) {\n if (uO.L_flag)\n Info(slide, 0, ((char *)slide, LoadFarString(CaseConversion),\n LoadFarStringSmall(Headers[longhdr][0]),\n LoadFarStringSmall2(Headers[longhdr][1])));\n else\n Info(slide, 0, ((char *)slide, \"%s\\n%s\\n\",\n LoadFarString(Headers[longhdr][0]),\n LoadFarStringSmall(Headers[longhdr][1])));\n }\n#endif /* !WINDLL */\n\n for (j = 1L;;j++) {\n\n if (readbuf(__G__ G.sig, 4) == 0)\n return PK_EOF;\n if (memcmp(G.sig, central_hdr_sig, 4)) { /* is it a CentDir entry? */\n /* no new central directory entry\n * -> is the number of processed entries compatible with the\n * number of entries as stored in the end_central record?\n */\n if (((j - 1) &\n (ulg)(G.ecrec.have_ecr64 ? MASK_ZUCN64 : MASK_ZUCN16))\n == (ulg)G.ecrec.total_entries_central_dir)\n {\n /* \"j modulus 4T/64k\" matches the reported 64/16-bit-unsigned\n * number of directory entries -> probably, the regular\n * end of the central directory has been reached\n */\n break;\n } else {\n Info(slide, 0x401,\n ((char *)slide, LoadFarString(CentSigMsg), j));\n Info(slide, 0x401,\n ((char *)slide, LoadFarString(ReportMsg)));\n return PK_BADERR; /* sig not found */\n }\n }\n /* process_cdir_file_hdr() sets pInfo->hostnum, pInfo->lcflag, ...: */\n if ((error = process_cdir_file_hdr(__G)) != PK_COOL)\n return error; /* only PK_EOF defined */\n\n /*\n * We could DISPLAY the filename instead of storing (and possibly trun-\n * cating, in the case of a very long name) and printing it, but that\n * has the disadvantage of not allowing case conversion--and it's nice\n * to be able to see in the listing precisely how you have to type each\n * filename in order for unzip to consider it a match. Speaking of\n * which, if member names were specified on the command line, check in\n * with match() to see if the current file is one of them, and make a\n * note of it if it is.\n */\n\n if ((error = do_string(__G__ G.crec.filename_length, DS_FN)) !=\n PK_COOL) /* ^--(uses pInfo->lcflag) */\n {\n error_in_archive = error;\n if (error > PK_WARN) /* fatal: can't continue */\n return error;\n }\n if (G.extra_field != (uch *)NULL) {\n free(G.extra_field);\n G.extra_field = (uch *)NULL;\n }\n if ((error = do_string(__G__ G.crec.extra_field_length, EXTRA_FIELD))\n != 0)\n {\n error_in_archive = error;\n if (error > PK_WARN) /* fatal */\n return error;\n }\n if (!G.process_all_files) { /* check if specified on command line */\n unsigned i;\n\n if (G.filespecs == 0)\n do_this_file = TRUE;\n else { /* check if this entry matches an `include' argument */\n do_this_file = FALSE;\n for (i = 0; i < G.filespecs; i++)\n if (match(G.filename, G.pfnames[i], uO.C_flag WISEP)) {\n do_this_file = TRUE;\n break; /* found match, so stop looping */\n }\n }\n if (do_this_file) { /* check if this is an excluded file */\n for (i = 0; i < G.xfilespecs; i++)\n if (match(G.filename, G.pxnames[i], uO.C_flag WISEP)) {\n do_this_file = FALSE; /* ^-- ignore case in match */\n break;\n }\n }\n }\n /*\n * If current file was specified on command line, or if no names were\n * specified, do the listing for this file. Otherwise, get rid of the\n * file comment and go back for the next file.\n */\n\n if (G.process_all_files || do_this_file) {\n\n#ifdef OS2DLL\n /* this is used by UzpFileTree() to allow easy processing of lists\n * of zip directory contents */\n if (G.processExternally) {\n if ((G.processExternally)(G.filename, &G.crec))\n break;\n ++members;\n } else {\n#endif\n#ifdef OS2_EAS\n {\n uch *ef_ptr = G.extra_field;\n int ef_size, ef_len = G.crec.extra_field_length;\n ea_size = acl_size = 0;\n\n while (ef_len >= EB_HEADSIZE) {\n ef_size = makeword(&ef_ptr[EB_LEN]);\n switch (makeword(&ef_ptr[EB_ID])) {\n case EF_OS2:\n ea_size = makelong(&ef_ptr[EB_HEADSIZE]);\n break;\n case EF_ACL:\n acl_size = makelong(&ef_ptr[EB_HEADSIZE]);\n break;\n }\n ef_ptr += (ef_size + EB_HEADSIZE);\n ef_len -= (ef_size + EB_HEADSIZE);\n }\n }\n#endif\n#ifdef USE_EF_UT_TIME\n if (G.extra_field &&\n#ifdef IZ_CHECK_TZ\n G.tz_is_valid &&\n#endif\n (ef_scan_for_izux(G.extra_field, G.crec.extra_field_length, 1,\n G.crec.last_mod_dos_datetime, &z_utime, NULL)\n & EB_UT_FL_MTIME))\n {\n TIMET_TO_NATIVE(z_utime.mtime) /* NOP unless MSC 7.0, Mac */\n t = localtime(&(z_utime.mtime));\n } else\n t = (struct tm *)NULL;\n if (t != (struct tm *)NULL) {\n mo = (unsigned)(t->tm_mon + 1);\n dy = (unsigned)(t->tm_mday);\n yr = (unsigned)(t->tm_year + 1900);\n hh = (unsigned)(t->tm_hour);\n mm = (unsigned)(t->tm_min);\n } else\n#endif /* USE_EF_UT_TIME */\n {\n yr = ((((unsigned)(G.crec.last_mod_dos_datetime >> 25) & 0x7f)\n + 1980));\n mo = ((unsigned)(G.crec.last_mod_dos_datetime >> 21) & 0x0f);\n dy = ((unsigned)(G.crec.last_mod_dos_datetime >> 16) & 0x1f);\n hh = (((unsigned)G.crec.last_mod_dos_datetime >> 11) & 0x1f);\n mm = (((unsigned)G.crec.last_mod_dos_datetime >> 5) & 0x3f);\n }\n /* permute date so it displays according to nat'l convention\n * ('methnum' is not yet set, it is used as temporary buffer) */\n switch (date_format) {\n case DF_YMD:\n methnum = mo;\n mo = yr; yr = dy; dy = methnum;\n break;\n case DF_DMY:\n methnum = mo;\n mo = dy; dy = methnum;\n }\n\n csiz = G.crec.csize;\n if (G.crec.general_purpose_bit_flag & 1)\n csiz -= 12; /* if encrypted, don't count encryption header */\n if ((cfactor = ratio(G.crec.ucsize, csiz)) < 0) {\n#ifndef WINDLL\n sgn = '-';\n#endif\n cfactor = (-cfactor + 5) / 10;\n } else {\n#ifndef WINDLL\n sgn = ' ';\n#endif\n cfactor = (cfactor + 5) / 10;\n }\n\n methnum = find_compr_idx(G.crec.compression_method);\n zfstrcpy(methbuf, method[methnum]);\n if (G.crec.compression_method == DEFLATED ||\n G.crec.compression_method == ENHDEFLATED) {\n methbuf[5] = dtype[(G.crec.general_purpose_bit_flag>>1) & 3];\n } else if (methnum >= NUM_METHODS) {\n sprintf(&methbuf[4], \"%03u\", G.crec.compression_method);\n }\n\n#if 0 /* GRR/Euro: add this? */\n#if defined(DOS_FLX_NLM_OS2_W32) || defined(THEOS) || defined(UNIX)\n for (p = G.filename; *p; ++p)\n if (!isprint(*p))\n *p = '?'; /* change non-printable chars to '?' */\n#endif /* DOS_FLX_NLM_OS2_W32 || THEOS || UNIX */\n#endif /* 0 */\n\n#ifdef WINDLL\n /* send data to application for formatting and printing */\n if (G.lpUserFunctions->SendApplicationMessage != NULL)\n (*G.lpUserFunctions->SendApplicationMessage)(G.crec.ucsize,\n csiz, (unsigned)cfactor, mo, dy, yr, hh, mm,\n (char)(G.pInfo->lcflag ? '^' : ' '),\n (LPCSTR)fnfilter(G.filename, slide, (WSIZE>>1)),\n (LPCSTR)methbuf, G.crec.crc32,\n (char)((G.crec.general_purpose_bit_flag & 1) ? 'E' : ' '));\n else if (G.lpUserFunctions->SendApplicationMessage_i32 != NULL) {\n unsigned long ucsize_lo, csiz_lo;\n unsigned long ucsize_hi=0L, csiz_hi=0L;\n ucsize_lo = (unsigned long)(G.crec.ucsize);\n csiz_lo = (unsigned long)(csiz);\n#ifdef ZIP64_SUPPORT\n ucsize_hi = (unsigned long)(G.crec.ucsize >> 32);\n csiz_hi = (unsigned long)(csiz >> 32);\n#endif /* ZIP64_SUPPORT */\n (*G.lpUserFunctions->SendApplicationMessage_i32)(ucsize_lo,\n ucsize_hi, csiz_lo, csiz_hi, (unsigned)cfactor,\n mo, dy, yr, hh, mm,\n (char)(G.pInfo->lcflag ? '^' : ' '),\n (LPCSTR)fnfilter(G.filename, slide, (WSIZE>>1)),\n (LPCSTR)methbuf, G.crec.crc32,\n (char)((G.crec.general_purpose_bit_flag & 1) ? 'E' : ' '));\n }\n#else /* !WINDLL */\n if (cfactor == 100)\n sprintf(cfactorstr, LoadFarString(CompFactor100));\n else\n sprintf(cfactorstr, LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr)\n Info(slide, 0, ((char *)slide, LoadFarString(LongHdrStats),\n FmZofft(G.crec.ucsize, \"8\", \"u\"), methbuf,\n FmZofft(csiz, \"8\", \"u\"), cfactorstr,\n mo, dt_sepchar, dy, dt_sepchar, yr, hh, mm,\n G.crec.crc32, (G.pInfo->lcflag? '^':' ')));\n else\n#ifdef OS2_EAS\n Info(slide, 0, ((char *)slide, LoadFarString(ShortHdrStats),\n FmZofft(G.crec.ucsize, \"9\", \"u\"), ea_size, acl_size,\n mo, dt_sepchar, dy, dt_sepchar, yr, hh, mm,\n (G.pInfo->lcflag? '^':' ')));\n#else\n Info(slide, 0, ((char *)slide, LoadFarString(ShortHdrStats),\n FmZofft(G.crec.ucsize, \"9\", \"u\"),\n mo, dt_sepchar, dy, dt_sepchar, yr, hh, mm,\n (G.pInfo->lcflag? '^':' ')));\n#endif\n fnprint(__G);\n#endif /* ?WINDLL */\n\n if ((error = do_string(__G__ G.crec.file_comment_length,\n QCOND? DISPL_8 : SKIP)) != 0)\n {\n error_in_archive = error; /* might be just warning */\n if (error > PK_WARN) /* fatal */\n return error;\n }\n tot_ucsize += G.crec.ucsize;\n tot_csize += csiz;\n ++members;\n#ifdef OS2_EAS\n if (ea_size) {\n tot_easize += ea_size;\n ++tot_eafiles;\n }\n if (acl_size) {\n tot_aclsize += acl_size;\n ++tot_aclfiles;\n }\n#endif\n#ifdef OS2DLL\n } /* end of \"if (G.processExternally) {...} else {...\" */\n#endif\n } else { /* not listing this file */\n SKIP_(G.crec.file_comment_length)\n }\n } /* end for-loop (j: files in central directory) */\n\n/*---------------------------------------------------------------------------\n Print footer line and totals (compressed size, uncompressed size, number\n of members in zipfile).\n ---------------------------------------------------------------------------*/\n\n if (uO.qflag < 2\n#ifdef OS2DLL\n && !G.processExternally\n#endif\n ) {\n if ((cfactor = ratio(tot_ucsize, tot_csize)) < 0) {\n#ifndef WINDLL\n sgn = '-';\n#endif\n cfactor = (-cfactor + 5) / 10;\n } else {\n#ifndef WINDLL\n sgn = ' ';\n#endif\n cfactor = (cfactor + 5) / 10;\n }\n#ifdef WINDLL\n /* pass the totals back to the calling application */\n G.lpUserFunctions->TotalSizeComp = tot_csize;\n G.lpUserFunctions->TotalSize = tot_ucsize;\n G.lpUserFunctions->CompFactor = (ulg)cfactor;\n G.lpUserFunctions->NumMembers = members;\n\n#else /* !WINDLL */\n if (cfactor == 100)\n sprintf(cfactorstr, LoadFarString(CompFactor100));\n else\n sprintf(cfactorstr, LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr) {\n Info(slide, 0, ((char *)slide, LoadFarString(LongFileTrailer),\n FmZofft(tot_ucsize, \"8\", \"u\"), FmZofft(tot_csize, \"8\", \"u\"),\n cfactorstr, members, members==1? \"\":\"s\"));\n#ifdef OS2_EAS\n if (tot_easize || tot_aclsize)\n Info(slide, 0, ((char *)slide, \"\\n\"));\n if (tot_eafiles && tot_easize)\n Info(slide, 0, ((char *)slide, LoadFarString(OS2ExtAttrTrailer),\n tot_eafiles, tot_eafiles == 1? \" has\" : \"s have a total of\",\n tot_easize));\n if (tot_aclfiles && tot_aclsize)\n Info(slide, 0, ((char *)slide, LoadFarString(OS2ACLTrailer),\n tot_aclfiles,\n tot_aclfiles == 1 ? \" has\" : \"s have a total of\",\n tot_aclsize));\n#endif /* OS2_EAS */\n } else\n#ifdef OS2_EAS\n Info(slide, 0, ((char *)slide, LoadFarString(ShortFileTrailer),\n FmZofft(tot_ucsize, \"9\", \"u\"), tot_easize, tot_aclsize,\n members, members == 1 ? \"\" : \"s\"));\n#else\n Info(slide, 0, ((char *)slide, LoadFarString(ShortFileTrailer),\n FmZofft(tot_ucsize, \"9\", \"u\"),\n members, members == 1 ? \"\" : \"s\"));\n#endif /* OS2_EAS */\n#endif /* ?WINDLL */\n }\n\n /* Skip the following checks in case of a premature listing break. */\n if (error_in_archive <= PK_WARN) {\n\n/*---------------------------------------------------------------------------\n Double check that we're back at the end-of-central-directory record.\n ---------------------------------------------------------------------------*/\n\n if ( (memcmp(G.sig,\n (G.ecrec.have_ecr64 ?\n end_central64_sig : end_central_sig),\n 4) != 0)\n && (!G.ecrec.is_zip64_archive)\n && (memcmp(G.sig, end_central_sig, 4) != 0)\n ) { /* just to make sure again */\n Info(slide, 0x401, ((char *)slide, LoadFarString(EndSigMsg)));\n error_in_archive = PK_WARN; /* didn't find sig */\n }\n\n /* Set specific return code when no files have been found. */\n if (members == 0L && error_in_archive <= PK_WARN)\n error_in_archive = PK_FIND;\n\n }\n\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n{\n int do_this_file=FALSE, cfactor, error, error_in_archive=PK_COOL;\n#ifndef WINDLL\n char sgn, cfactorstr[10];\n int longhdr=(uO.vflag>1);\n#endif\n int date_format;\n=======\n{\n int do_this_file=FALSE, cfactor, error, error_in_archive=PK_COOL;\n#ifndef WINDLL\n char sgn, cfactorstr[1+10+1+1];\t/* <sgn><int>%NUL */\n int longhdr=(uO.vflag>1);\n#endif\n int date_format;\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n }\n#else /* !WINDLL */\n if (cfactor == 100)\n sprintf(cfactorstr, LoadFarString(CompFactor100));\n else\n sprintf(cfactorstr, LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr)\n Info(slide, 0, ((char *)slide, LoadFarString(LongHdrStats),\n FmZofft(G.crec.ucsize, \"8\", \"u\"), methbuf,\n=======\n }\n#else /* !WINDLL */\n if (cfactor == 100)\n snprintf(cfactorstr, sizeof(cfactorstr), LoadFarString(CompFactor100));\n else\n snprintf(cfactorstr, sizeof(cfactorstr), LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr)\n Info(slide, 0, ((char *)slide, LoadFarString(LongHdrStats),\n FmZofft(G.crec.ucsize, \"8\", \"u\"), methbuf,\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\n#else /* !WINDLL */\n if (cfactor == 100)\n sprintf(cfactorstr, LoadFarString(CompFactor100));\n else\n sprintf(cfactorstr, LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr) {\n Info(slide, 0, ((char *)slide, LoadFarString(LongFileTrailer),\n FmZofft(tot_ucsize, \"8\", \"u\"), FmZofft(tot_csize, \"8\", \"u\"),\n=======\n\n#else /* !WINDLL */\n if (cfactor == 100)\n snprintf(cfactorstr, sizeof(cfactorstr), LoadFarString(CompFactor100));\n else\n snprintf(cfactorstr, sizeof(cfactorstr), LoadFarString(CompFactorStr), sgn, cfactor);\n if (longhdr) {\n Info(slide, 0, ((char *)slide, LoadFarString(LongFileTrailer),\n FmZofft(tot_ucsize, \"8\", \"u\"), FmZofft(tot_csize, \"8\", \"u\"),\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2021-28918: Improper input validation (CWE-20) in the Perl module Net::CIDR::Lite before 0.22. When parsing a dotted-quad IPv4 address, each octet was accepted as long as it was one to three digits and numerically at most 255, with no check on a leading zero. An octet written with a leading zero, such as the first octet of 010.0.0.0/8, therefore passed and was interpreted as the decimal value 10, whereas many other network stacks read a zero-padded octet as octal. A CIDR allow-list or deny-list built from attacker-influenced input consequently covers a different address range than the author intended, enabling an access-control or SSRF-filter bypass. Affects perlPackages.NetCIDRLite.\n\n# Vulnerable source (Lite.pm)\n```perl\n } elsif (_pack_ipv6($ip)) {\n $nbits = 136;\n $pack = \\&_pack_ipv6;\n $unpack = \\&_unpack_ipv6;\n } else {\n return;\n }\n $$self{PACK} = $pack;\n $$self{UNPACK} = $unpack;\n $$self{NBITS} = $nbits;\n $$self{MASKS} = $masks{$nbits} ||= [\n map { pack(\"B*\", substr(\"1\" x $_ . \"0\" x $nbits, 0, $nbits))\n } 0..$nbits\n ];\n $$self{RANGES} = {};\n $self;\n}\n\nsub _pack_ipv4 {\n my @nums = split /\\./, shift(), -1;\n return unless @nums == 4;\n for (@nums) {\n return unless /^\\d{1,3}$/ and $_ <= 255;\n }\n pack(\"CC*\", 0, @nums);\n}\n\nsub _unpack_ipv4 {\n join(\".\", unpack(\"xC*\", shift));\n}\n\nsub _pack_ipv6 {\n my $ip = shift;\n $ip =~ s/^::$/::0/;\n return if $ip =~ /^:/ and $ip !~ s/^::/:/;\n return if $ip =~ /:$/ and $ip !~ s/::$/:/;\n my @nums = split /:/, $ip, -1;\n return unless @nums <= 8;\n my ($empty, $ipv4, $str) = (0,'','');\n for (@nums) {\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n my @nums = split /\\./, shift(), -1;\n return unless @nums == 4;\n for (@nums) {\n return unless /^\\d{1,3}$/ and $_ <= 255;\n }\n pack(\"CC*\", 0, @nums);\n}\n=======\n my @nums = split /\\./, shift(), -1;\n return unless @nums == 4;\n for (@nums) {\n return unless /^\\d{1,3}$/ and !/^0\\d{1,2}$/ and $_ <= 255;\n }\n pack(\"CC*\", 0, @nums);\n}\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2021-40633: giflib 5.2.2 gif2rgb tool leaked heap memory when processing GIF images: after rendering a GIF to RGB bitmap data, the row-level allocations for the image height were released only at the outer container level but not individually, causing an unbounded memory accumulation in long-running processes that handle attacker-supplied GIF files.\n\n# Vulnerable source (gif2rgb.c)\n```c\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase EXTENSION_RECORD_TYPE:\n\t\t\t/* Skip any extension blocks in file: */\n\t\t\tif (DGifGetExtension(GifFile, &ExtCode, &Extension) ==\n\t\t\t GIF_ERROR) {\n\t\t\t\tPrintGifError(GifFile->Error);\n\t\t\t\texit(EXIT_FAILURE);\n\t\t\t}\n\t\t\twhile (Extension != NULL) {\n\t\t\t\tif (DGifGetExtensionNext(GifFile, &Extension) ==\n\t\t\t\t GIF_ERROR) {\n\t\t\t\t\tPrintGifError(GifFile->Error);\n\t\t\t\t\texit(EXIT_FAILURE);\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\tcase TERMINATE_RECORD_TYPE:\n\t\t\tbreak;\n\t\tdefault: /* Should be trapped by DGifGetRecordType. */\n\t\t\tbreak;\n\t\t}\n\t} while (RecordType != TERMINATE_RECORD_TYPE);\n\n\t/* Lets dump it - set the global variables required and do it: */\n\tColorMap = (GifFile->Image.ColorMap ? GifFile->Image.ColorMap\n\t : GifFile->SColorMap);\n\tif (ColorMap == NULL) {\n\t\tfprintf(stderr, \"Gif Image does not have a colormap\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\t/* check that the background color isn't garbage (SF bug #87) */\n\tif (GifFile->SBackGroundColor < 0 ||\n\t GifFile->SBackGroundColor >= ColorMap->ColorCount) {\n\t\tfprintf(stderr, \"Background color out of range for colormap\\n\");\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tDumpScreen2RGB(OutFileName, OneFileFlag, ColorMap, ScreenBuffer,\n\t GifFile->SWidth, GifFile->SHeight);\n\n\t(void)free(ScreenBuffer);\n\n\t{\n\t\tint Error;\n\t\tif (DGifCloseFile(GifFile, &Error) == GIF_ERROR) {\n\t\t\tPrintGifError(Error);\n\t\t\texit(EXIT_FAILURE);\n\t\t}\n\t}\n}\n\n/******************************************************************************\n * Interpret the command line and scan the given GIF file.\n ******************************************************************************/\nint main(int argc, char **argv) {\n\tbool Error, OutFileFlag = false, ColorFlag = false, SizeFlag = false,\n\t GifNoisyPrint = false;\n\tint NumFiles, Width = 0, Height = 0, ExpNumOfColors = 8;\n\tchar *OutFileName, **FileName = NULL;\n\tstatic bool OneFileFlag = false, HelpFlag = false;\n\n\tif ((Error = GAGetArgs(argc, argv, CtrlStr, &GifNoisyPrint, &ColorFlag,\n\t &ExpNumOfColors, &SizeFlag, &Width, &Height,\n\t &OneFileFlag, &OutFileFlag, &OutFileName,\n\t &HelpFlag, &NumFiles, &FileName)) != false ||\n\t (NumFiles > 1 && !HelpFlag)) {\n\t\tif (Error) {\n\t\t\tGAPrintErrMsg(Error);\n\t\t} else if (NumFiles > 1) {\n\t\t\tGIF_MESSAGE(\"Error in command line parsing - one input \"\n\t\t\t \"file please.\");\n\t\t}\n\t\tGAPrintHowTo(CtrlStr);\n\t\texit(EXIT_FAILURE);\n\t}\n\n\tif (HelpFlag) {\n\t\t(void)fprintf(stderr, VersionStr, GIFLIB_MAJOR, GIFLIB_MINOR);\n\t\tGAPrintHowTo(CtrlStr);\n\t\texit(EXIT_SUCCESS);\n\t}\n\tif (!OutFileFlag) {\n\t\tOutFileName = NULL;\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\tDumpScreen2RGB(OutFileName, OneFileFlag, ColorMap, ScreenBuffer,\n\t GifFile->SWidth, GifFile->SHeight);\n\n\t(void)free(ScreenBuffer);\n\n\t{\n=======\n\tDumpScreen2RGB(OutFileName, OneFileFlag, ColorMap, ScreenBuffer,\n\t GifFile->SWidth, GifFile->SHeight);\n\n\tfor (i = 0; i < GifFile->SHeight; i++) {\n \t(void)free(ScreenBuffer[i]);\n\t}\n\t(void)free(ScreenBuffer);\n\n\t{\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2021-41581: Stack buffer over-read (CWE-125) in LibreSSL 3.4.0 reachable through X.509 name-constraint email handling. x509_constraints_parse_mailbox() copies the mailbox address into a fixed 256-byte stack buffer one character at a time, but the per-character index guard is off by one, so a mailbox whose domain part is exactly 256 characters long fills the entire buffer with no room left for a terminating NUL byte. When the parser then calls strdup() on that buffer it scans past the end of the stack array looking for a NUL, reading adjacent stack memory beyond the object. This is triggered while validating a certificate or mailbox against email name constraints. Affects the libressl 3.4.0 package.\n\n# Vulnerable source (lib/libcrypto/x509/x509_constraints.c)\n```c\n\tint quoted = 0;\n\n\tif (candidate == NULL)\n\t\treturn 0;\n\n\t/* It can't be bigger than the local part, domain part and the '@' */\n\tif (len > LOCAL_PART_MAX_LEN + DOMAIN_PART_MAX_LEN + 1)\n\t\treturn 0;\n\n\tfor (i = 0; i < len; i++) {\n\t\tchar c = candidate[i];\n\t\t/* non ascii, cr, lf, or nul is never allowed */\n\t\tif (!isascii(c) || c == '\\r' || c == '\\n' || c == '\\0')\n\t\t\tgoto bad;\n\t\tif (i == 0) {\n\t\t\t/* local part is quoted part */\n\t\t\tif (c == '\"')\n\t\t\t\tquoted = 1;\n\t\t\t/* can not start with a . */\n\t\t\tif (c == '.')\n\t\t\t\tgoto bad;\n\t\t}\n\t\tif (wi > DOMAIN_PART_MAX_LEN)\n\t\t\tgoto bad;\n\t\tif (accept) {\n\t\t\tworking[wi++] = c;\n\t\t\taccept = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tif (candidate_local != NULL) {\n\t\t\t/* We are looking for the domain part */\n\t\t\tif (wi > DOMAIN_PART_MAX_LEN)\n\t\t\t\tgoto bad;\n\t\t\tworking[wi++] = c;\n\t\t\tif (i == len - 1) {\n\t\t\t\tif (wi == 0)\n\t\t\t\t\tgoto bad;\n\t\t\t\tif (candidate_domain != NULL)\n\t\t\t\t\tgoto bad;\n\t\t\t\tcandidate_domain = strdup(working);\n\t\t\t\tif (candidate_domain == NULL)\n\t\t\t\t\tgoto bad;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\t/* We are looking for the local part */\n\t\tif (wi > LOCAL_PART_MAX_LEN)\n\t\t\tbreak;\n\n\t\tif (quoted) {\n\t\t\tif (c == '\\\\') {\n\t\t\t\taccept = 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (c == '\"' && i != 0) {\n\t\t\t\t/* end the quoted part. @ must be next */\n\t\t\t\tif (i + 1 == len || candidate[i + 1] != '@')\n\t\t\t\t\tgoto bad;\n\t\t\t\tquoted = 0;\n\t\t\t}\n\t\t\t/*\n\t\t\t * XXX Go strangely permits sp but forbids ht\n\t\t\t * mimic that for now\n\t\t\t */\n\t\t\tif (c == 9)\n\t\t\t\tgoto bad;\n\t\t\tworking[wi++] = c;\n\t\t\tcontinue; /* all's good inside our quoted string */\n\t\t}\n\t\tif (c == '@') {\n\t\t\tif (wi == 0)\n\t\t\t\tgoto bad;;\n\t\t\tif (candidate_local != NULL)\n\t\t\t\tgoto bad;\n\t\t\tcandidate_local = strdup(working);\n\t\t\tif (candidate_local == NULL)\n\t\t\t\tgoto bad;\n\t\t\tmemset(working, 0, sizeof(working));\n\t\t\twi = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tif (c == '\\\\') {\n\t\t\t/*\n\t\t\t * RFC 3936 hints these can happen outside of\n\t\t\t * quotend string. don't include the \\ but\n\t\t\t * next character must be ok.\n\t\t\t */\n\t\t\tif (i + 1 == len)\n\t\t\t\tgoto bad;\n\t\t\tif (!local_part_ok(candidate[i + 1]))\n\t\t\t\tgoto bad;\n\t\t\taccept = 1;\n\t\t}\n\t\tif (!local_part_ok(c))\n\t\t\tgoto bad;\n\t\tworking[wi++] = c;\n\t}\n\tif (candidate_local == NULL || candidate_domain == NULL)\n\t\tgoto bad;\n\tif (!x509_constraints_valid_host(candidate_domain,\n\t strlen(candidate_domain)))\n\t\tgoto bad;\n\n\tname->local = candidate_local;\n\tname->name = candidate_domain;\n\tname->type = GEN_EMAIL;\n\treturn 1;\n bad:\n\tfree(candidate_local);\n\tfree(candidate_domain);\n\treturn 0;\n}\n\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\t\t\tif (c == '.')\n\t\t\t\tgoto bad;\n\t\t}\n\t\tif (wi > DOMAIN_PART_MAX_LEN)\n\t\t\tgoto bad;\n\t\tif (accept) {\n\t\t\tworking[wi++] = c;\n\t\t\taccept = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tif (candidate_local != NULL) {\n\t\t\t/* We are looking for the domain part */\n\t\t\tif (wi > DOMAIN_PART_MAX_LEN)\n\t\t\t\tgoto bad;\n\t\t\tworking[wi++] = c;\n\t\t\tif (i == len - 1) {\n=======\n\t\t\tif (c == '.')\n\t\t\t\tgoto bad;\n\t\t}\n\t\tif (accept) {\n\t\t\tif (wi >= DOMAIN_PART_MAX_LEN)\n\t\t\t\tgoto bad;\n\t\t\tworking[wi++] = c;\n\t\t\taccept = 0;\n\t\t\tcontinue;\n\t\t}\n\t\tif (candidate_local != NULL) {\n\t\t\t/* We are looking for the domain part */\n\t\t\tif (wi >= DOMAIN_PART_MAX_LEN)\n\t\t\t\tgoto bad;\n\t\t\tworking[wi++] = c;\n\t\t\tif (i == len - 1) {\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\t\t\tcontinue;\n\t\t}\n\t\t/* We are looking for the local part */\n\t\tif (wi > LOCAL_PART_MAX_LEN)\n\t\t\tbreak;\n\n\t\tif (quoted) {\n=======\n\t\t\tcontinue;\n\t\t}\n\t\t/* We are looking for the local part */\n\t\tif (wi >= LOCAL_PART_MAX_LEN)\n\t\t\tbreak;\n\n\t\tif (quoted) {\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\t\t\t */\n\t\t\tif (c == 9)\n\t\t\t\tgoto bad;\n\t\t\tworking[wi++] = c;\n\t\t\tcontinue; /* all's good inside our quoted string */\n\t\t}\n=======\n\t\t\t */\n\t\t\tif (c == 9)\n\t\t\t\tgoto bad;\n\t\t\tif (wi >= LOCAL_PART_MAX_LEN)\n\t\t\t\tgoto bad;\n\t\t\tworking[wi++] = c;\n\t\t\tcontinue; /* all's good inside our quoted string */\n\t\t}\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\t\t}\n\t\tif (!local_part_ok(c))\n\t\t\tgoto bad;\n\t\tworking[wi++] = c;\n\t}\n\tif (candidate_local == NULL || candidate_domain == NULL)\n=======\n\t\t}\n\t\tif (!local_part_ok(c))\n\t\t\tgoto bad;\n\t\tif (wi >= LOCAL_PART_MAX_LEN)\n\t\t\tgoto bad;\n\t\tworking[wi++] = c;\n\t}\n\tif (candidate_local == NULL || candidate_domain == NULL)\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2021-45340: When libsixel falls back to its built-in loader (load_with_builtin -> stbi__load_and_postprocess_8bit), a crafted Softimage PICT image is parsed by stbi__pic_load, which reads the image dimensions (e.g. 39168 x 5888) directly from the file. A remote attacker can therefore cause a denial of service by feeding img2sixel a malformed PICT file.\n\n# Vulnerable source (src/stb_image.h)\n```c\n// individual types do this automatically as much as possible (e.g. jpeg\n// does all cases internally since it needs to colorspace convert anyway,\n// and it never has alpha, so very few cases ). png can automatically\n// interleave an alpha=255 channel, but falls back to this for other cases\n//\n// assume data buffer is malloced, so malloc a new one and free that one\n// only failure mode is malloc failing\n\nstatic stbi_uc stbi__compute_y(int r, int g, int b)\n{\n return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8);\n}\n#endif\n\n#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM)\n// nothing\n#else\nstatic unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)\n{\n int i,j;\n unsigned char *good;\n\n if (req_comp == img_n) return data;\n STBI_ASSERT(req_comp >= 1 && req_comp <= 4);\n\n good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0);\n if (good == NULL) {\n STBI_FREE(data);\n return stbi__errpuc(\"outofmem\", \"Out of memory\");\n }\n\n for (j=0; j < (int) y; ++j) {\n unsigned char *src = data + j * x * img_n ;\n unsigned char *dest = good + j * x * req_comp;\n\n #define STBI__COMBO(a,b) ((a)*8+(b))\n #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)\n // convert source image with img_n components to one with req_comp components;\n // avoid switch per pixel, so use switch per scanline and massive macros\n switch (STBI__COMBO(img_n, req_comp)) {\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n int i,j;\n unsigned char *good;\n\n if (req_comp == img_n) return data;\n STBI_ASSERT(req_comp >= 1 && req_comp <= 4);\n=======\n int i,j;\n unsigned char *good;\n\n if (data == NULL) return data;\n if (req_comp == img_n) return data;\n STBI_ASSERT(req_comp >= 1 && req_comp <= 4);\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2022-28805: lua 5.2.4 parser has an out-of-bounds memory access in the variable lookup path: when resolving a global identifier inside a function block, the environment table reference was not promoted to a register or upvalue before being indexed, leaving the VM in an invalid state if the environment was stored as a literal, which a crafted Lua script can exploit to trigger a parser assertion failure or memory corruption.\n\n# Vulnerable source (src/lparser.c)\n```c\n BlockCnt *bl = fs->bl;\n while (bl->nactvar > level) bl = bl->previous;\n bl->upval = 1;\n}\n\n\n/*\n Find variable with given name 'n'. If it is an upvalue, add this\n upvalue into all intermediate functions.\n*/\nstatic int singlevaraux (FuncState *fs, TString *n, expdesc *var, int base) {\n if (fs == NULL) /* no more levels? */\n return VVOID; /* default is global */\n else {\n int v = searchvar(fs, n); /* look up locals at current level */\n if (v >= 0) { /* found? */\n init_exp(var, VLOCAL, v); /* variable is local */\n if (!base)\n markupval(fs, v); /* local will be used as an upval */\n return VLOCAL;\n }\n else { /* not found as local at current level; try upvalues */\n int idx = searchupvalue(fs, n); /* try existing upvalues */\n if (idx < 0) { /* not found? */\n if (singlevaraux(fs->prev, n, var, 0) == VVOID) /* try upper levels */\n return VVOID; /* not found; is a global */\n /* else was LOCAL or UPVAL */\n idx = newupvalue(fs, n, var); /* will be a new upvalue */\n }\n init_exp(var, VUPVAL, idx);\n return VUPVAL;\n }\n }\n}\n\n\nstatic void singlevar (LexState *ls, expdesc *var) {\n TString *varname = str_checkname(ls);\n FuncState *fs = ls->fs;\n if (singlevaraux(fs, varname, var, 1) == VVOID) { /* global name? */\n expdesc key;\n singlevaraux(fs, ls->envn, var, 1); /* get environment variable */\n lua_assert(var->k == VLOCAL || var->k == VUPVAL);\n codestring(ls, &key, varname); /* key is variable name */\n luaK_indexed(fs, var, &key); /* env[varname] */\n }\n}\n\n\nstatic void adjust_assign (LexState *ls, int nvars, int nexps, expdesc *e) {\n FuncState *fs = ls->fs;\n int extra = nvars - nexps;\n if (hasmultret(e->k)) {\n extra++; /* includes call itself */\n if (extra < 0) extra = 0;\n luaK_setreturns(fs, e, extra); /* last exp. provides the difference */\n if (extra > 1) luaK_reserveregs(fs, extra-1);\n }\n else {\n if (e->k != VVOID) luaK_exp2nextreg(fs, e); /* close last expression */\n if (extra > 0) {\n int reg = fs->freereg;\n luaK_reserveregs(fs, extra);\n luaK_nil(fs, reg, extra);\n }\n }\n}\n\n\nstatic void enterlevel (LexState *ls) {\n lua_State *L = ls->L;\n ++L->nCcalls;\n checklimit(ls->fs, L->nCcalls, LUAI_MAXCCALLS, \"C levels\");\n}\n\n\n#define leavelevel(ls)\t((ls)->L->nCcalls--)\n\n\nstatic void closegoto (LexState *ls, int g, Labeldesc *label) {\n int i;\n FuncState *fs = ls->fs;\n Labellist *gl = &ls->dyd->gt;\n Labeldesc *gt = &gl->arr[g];\n lua_assert(luaS_eqstr(gt->name, label->name));\n if (gt->nactvar < label->nactvar) {\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n expdesc key;\n singlevaraux(fs, ls->envn, var, 1); /* get environment variable */\n lua_assert(var->k == VLOCAL || var->k == VUPVAL);\n codestring(ls, &key, varname); /* key is variable name */\n luaK_indexed(fs, var, &key); /* env[varname] */\n }\n=======\n expdesc key;\n singlevaraux(fs, ls->envn, var, 1); /* get environment variable */\n lua_assert(var->k == VLOCAL || var->k == VUPVAL);\n luaK_exp2anyregup(fs, var); /* but could be a constant */\n codestring(ls, &key, varname); /* key is variable name */\n luaK_indexed(fs, var, &key); /* env[varname] */\n }\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2022-47016: Null pointer dereference (CWE-476) in tmux 3.3a. The upstream patch does not apply cleanly to tmux 3.3a; nixpkgs carries an adapted cherry-pick.\n\n# Vulnerable source (control.c, file.c, window.c)\n```c\n/* ==== file: control.c ==== */\n\n/* Initialize for control mode. */\nvoid\ncontrol_start(struct client *c)\n{\n\tstruct control_state\t*cs;\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tclose(c->out_fd);\n\t\tc->out_fd = -1;\n\t} else\n\t\tsetblocking(c->out_fd, 0);\n\tsetblocking(c->fd, 0);\n\n\tcs = c->control_state = xcalloc(1, sizeof *cs);\n\tRB_INIT(&cs->panes);\n\tTAILQ_INIT(&cs->pending_list);\n\tTAILQ_INIT(&cs->all_blocks);\n\tRB_INIT(&cs->subs);\n\n\tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n\t control_write_callback, control_error_callback, c);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL)\n\t\tcs->write_event = cs->read_event;\n\telse {\n\t\tcs->write_event = bufferevent_new(c->out_fd, NULL,\n\t\t control_write_callback, control_error_callback, c);\n\t}\n\tbufferevent_setwatermark(cs->write_event, EV_WRITE, CONTROL_BUFFER_LOW,\n\t 0);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL) {\n\t\tbufferevent_write(cs->write_event, \"\\033P1000p\", 7);\n\t\tbufferevent_enable(cs->write_event, EV_WRITE);\n\t}\n}\n\n/* Control client ready. */\nvoid\n\n/* ==== file: file.c ==== */\n\t}\n\n\tcf->fd = -1;\n\tif (msg->fd == -1)\n\t\tcf->fd = open(path, msg->flags|flags, 0644);\n\telse if (allow_streams) {\n\t\tif (msg->fd != STDOUT_FILENO && msg->fd != STDERR_FILENO)\n\t\t\terrno = EBADF;\n\t\telse {\n\t\t\tcf->fd = dup(msg->fd);\n\t\t\tif (close_received)\n\t\t\t\tclose(msg->fd); /* can only be used once */\n\t\t}\n\t} else\n\t errno = EBADF;\n\tif (cf->fd == -1) {\n\t\terror = errno;\n\t\tgoto reply;\n\t}\n\n\tcf->event = bufferevent_new(cf->fd, NULL, file_write_callback,\n\t file_write_error_callback, cf);\n\tbufferevent_enable(cf->event, EV_WRITE);\n\tgoto reply;\n\nreply:\n\treply.stream = msg->stream;\n\treply.error = error;\n\tproc_send(peer, MSG_WRITE_READY, -1, &reply, sizeof reply);\n}\n\n/* Handle a file write data message (client). */\nvoid\nfile_write_data(struct client_files *files, struct imsg *imsg)\n{\n\tstruct msg_write_data\t*msg = imsg->data;\n\tsize_t\t\t\t msglen = imsg->hdr.len - IMSG_HEADER_SIZE;\n\tstruct client_file\t find, *cf;\n\tsize_t\t\t\t size = msglen - sizeof *msg;\n\n /* ... */\n\t}\n\n\tcf->fd = -1;\n\tif (msg->fd == -1)\n\t\tcf->fd = open(path, flags);\n\telse if (allow_streams) {\n\t\tif (msg->fd != STDIN_FILENO)\n\t\t\terrno = EBADF;\n\t\telse {\n\t\t\tcf->fd = dup(msg->fd);\n\t\t\tif (close_received)\n\t\t\t\tclose(msg->fd); /* can only be used once */\n\t\t}\n\t} else\n\t\terrno = EBADF;\n\tif (cf->fd == -1) {\n\t\terror = errno;\n\t\tgoto reply;\n\t}\n\n\tcf->event = bufferevent_new(cf->fd, file_read_callback, NULL,\n\t file_read_error_callback, cf);\n\tbufferevent_enable(cf->event, EV_READ);\n\treturn;\n\nreply:\n\treply.stream = msg->stream;\n\treply.error = error;\n\tproc_send(peer, MSG_READ_DONE, -1, &reply, sizeof reply);\n}\n\n/* Handle a write ready message (server). */\nvoid\nfile_write_ready(struct client_files *files, struct imsg *imsg)\n{\n\tstruct msg_write_ready\t*msg = imsg->data;\n\tsize_t\t\t\t msglen = imsg->hdr.len - IMSG_HEADER_SIZE;\n\tstruct client_file\t find, *cf;\n\n\tif (msglen != sizeof *msg)\n\n/* ==== file: window.c ==== */\n}\n\nstatic void\nwindow_pane_error_callback(__unused struct bufferevent *bufev,\n __unused short what, void *data)\n{\n\tstruct window_pane *wp = data;\n\n\tlog_debug(\"%%%u error\", wp->id);\n\twp->flags |= PANE_EXITED;\n\n\tif (window_pane_destroy_ready(wp))\n\t\tserver_destroy_pane(wp, 1);\n}\n\nvoid\nwindow_pane_set_event(struct window_pane *wp)\n{\n\tsetblocking(wp->fd, 0);\n\n\twp->event = bufferevent_new(wp->fd, window_pane_read_callback,\n\t NULL, window_pane_error_callback, wp);\n\twp->ictx = input_init(wp, wp->event, &wp->palette);\n\n\tbufferevent_enable(wp->event, EV_READ|EV_WRITE);\n}\n\nvoid\nwindow_pane_resize(struct window_pane *wp, u_int sx, u_int sy)\n{\n\tstruct window_mode_entry\t*wme;\n\tstruct window_pane_resize\t*r;\n\n\tif (sx == wp->sx && sy == wp->sy)\n\t\treturn;\n\n\tr = xmalloc(sizeof *r);\n\tr->sx = sx;\n\tr->sy = sy;\n\tr->osx = wp->sx;\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\n\tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n\t control_write_callback, control_error_callback, c);\n\n\tif (c->flags & CLIENT_CONTROLCONTROL)\n\t\tcs->write_event = cs->read_event;\n\telse {\n\t\tcs->write_event = bufferevent_new(c->out_fd, NULL,\n\t\t control_write_callback, control_error_callback, c);\n\t}\n\tbufferevent_setwatermark(cs->write_event, EV_WRITE, CONTROL_BUFFER_LOW,\n\t 0);\n=======\n\n\tcs->read_event = bufferevent_new(c->fd, control_read_callback,\n\t control_write_callback, control_error_callback, c);\n\tif (cs->read_event == NULL)\n\t\tfatalx(\"out of memory\");\n\n\tif (c->flags & CLIENT_CONTROLCONTROL)\n\t\tcs->write_event = cs->read_event;\n\telse {\n\t\tcs->write_event = bufferevent_new(c->out_fd, NULL,\n\t\t control_write_callback, control_error_callback, c);\n\t\tif (cs->write_event == NULL)\n\t\t\tfatalx(\"out of memory\");\n\t}\n\tbufferevent_setwatermark(cs->write_event, EV_WRITE, CONTROL_BUFFER_LOW,\n\t 0);\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\n\tcf->event = bufferevent_new(cf->fd, NULL, file_write_callback,\n\t file_write_error_callback, cf);\n\tbufferevent_enable(cf->event, EV_WRITE);\n\tgoto reply;\n\n=======\n\n\tcf->event = bufferevent_new(cf->fd, NULL, file_write_callback,\n\t file_write_error_callback, cf);\n\tif (cf->event == NULL)\n\t\tfatalx(\"out of memory\");\n\tbufferevent_enable(cf->event, EV_WRITE);\n\tgoto reply;\n\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\n\tcf->event = bufferevent_new(cf->fd, file_read_callback, NULL,\n\t file_read_error_callback, cf);\n\tbufferevent_enable(cf->event, EV_READ);\n\treturn;\n\n=======\n\n\tcf->event = bufferevent_new(cf->fd, file_read_callback, NULL,\n\t file_read_error_callback, cf);\n\tif (cf->event == NULL)\n\t\tfatalx(\"out of memory\");\n\tbufferevent_enable(cf->event, EV_READ);\n\treturn;\n\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\n\twp->event = bufferevent_new(wp->fd, window_pane_read_callback,\n\t NULL, window_pane_error_callback, wp);\n\twp->ictx = input_init(wp, wp->event, &wp->palette);\n\n\tbufferevent_enable(wp->event, EV_READ|EV_WRITE);\n=======\n\n\twp->event = bufferevent_new(wp->fd, window_pane_read_callback,\n\t NULL, window_pane_error_callback, wp);\n\tif (wp->event == NULL)\n\t\tfatalx(\"out of memory\");\n\twp->ictx = input_init(wp, wp->event, &wp->palette);\n\n\tbufferevent_enable(wp->event, EV_READ|EV_WRITE);\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2023-28484: When xmlSchemaFixupComplexType() processes a complex type that derives by complexContent extension from a base type whose own content model is absent (a base declared with simpleContent carries no element content model), the fixup code that splices the base type's content model into the derived type reads the base type's content-model pointer without first checking that it is present. Affects the libxml2 2.10.3 package.\n\n# Vulnerable source (xmlschemas.c)\n```c\n\t\t\tNULL, NULL);\n\n\t\t} else if ((WXS_TYPE_PARTICLE(baseType) != NULL) &&\n\t\t (WXS_TYPE_PARTICLE_TERM(baseType) != NULL) &&\n\t\t ((WXS_TYPE_PARTICLE_TERM(baseType))->type ==\n\t\t\tXML_SCHEMA_TYPE_ALL))\n\t\t{\n\t\t /*\n\t\t * SPEC cos-all-limited (1)\n\t\t */\n\t\t xmlSchemaCustomErr(ACTXT_CAST pctxt,\n\t\t\t/* TODO: error code */\n\t\t\tXML_SCHEMAP_COS_ALL_LIMITED,\n\t\t\tWXS_ITEM_NODE(type), NULL,\n\t\t\t\"A type cannot be derived by extension from a type \"\n\t\t\t\"which has an 'all' model group in its \"\n\t\t\t\"{content type}, since this would produce a \"\n\t\t\t\"'sequence' model group containing the 'all' \"\n\t\t\t\"model group; 'all' model groups are not \"\n\t\t\t\"allowed to appear inside other model groups\",\n\t\t\tNULL, NULL);\n\n\t\t} else if (! dummySequence) {\n\t\t xmlSchemaTreeItemPtr effectiveContent =\n\t\t\t(xmlSchemaTreeItemPtr) type->subtypes;\n\t\t /*\n\t\t * Create the particle.\n\t\t */\n\t\t particle = xmlSchemaAddParticle(pctxt,\n\t\t\ttype->node, 1, 1);\n\t\t if (particle == NULL)\n\t\t\tgoto exit_failure;\n\t\t /*\n\t\t * Create the \"sequence\" model group.\n\t\t */\n\t\t particle->children = (xmlSchemaTreeItemPtr)\n\t\t\txmlSchemaAddModelGroup(pctxt, pctxt->schema,\n\t\t\tXML_SCHEMA_TYPE_SEQUENCE, type->node);\n\t\t if (particle->children == NULL)\n\t\t\tgoto exit_failure;\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\t\t\t\"allowed to appear inside other model groups\",\n\t\t\tNULL, NULL);\n\n\t\t} else if (! dummySequence) {\n\t\t xmlSchemaTreeItemPtr effectiveContent =\n\t\t\t(xmlSchemaTreeItemPtr) type->subtypes;\n\t\t /*\n=======\n\t\t\t\"allowed to appear inside other model groups\",\n\t\t\tNULL, NULL);\n\n\t\t} else if ((!dummySequence) && (baseType->subtypes != NULL)) {\n\t\t xmlSchemaTreeItemPtr effectiveContent =\n\t\t\t(xmlSchemaTreeItemPtr) type->subtypes;\n\t\t /*\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2023-40890: Stack-based buffer overflow in zbar 0.23.92: the lookup_sequence() function in databar.c uses an unbounded loop counter variable that can exceed the seq[] array capacity when scanning DataBar encoded barcodes, allowing a crafted barcode to trigger out-of-bounds memory access.\n\n# Vulnerable source (zbar/decoder/databar.c)\n```c\n * This file is part of the ZBar Bar Code Reader.\n *\n * The ZBar Bar Code Reader is free software; you can redistribute it\n * and/or modify it under the terms of the GNU Lesser Public License as\n * published by the Free Software Foundation; either version 2.1 of\n * the License, or (at your option) any later version.\n *\n * The ZBar Bar Code Reader is distributed in the hope that it will be\n * useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser Public License for more details.\n *\n * You should have received a copy of the GNU Lesser Public License\n * along with the ZBar Bar Code Reader; if not, write to the Free\n * Software Foundation, Inc., 51 Franklin St, Fifth Floor,\n * Boston, MA 02110-1301 USA\n *\n * http://sourceforge.net/projects/zbar\n *------------------------------------------------------------------------*/\n\n#include <config.h>\n#include <zbar.h>\n\n#ifdef DEBUG_DATABAR\n# define DEBUG_LEVEL (DEBUG_DATABAR)\n#endif\n#include \"debug.h\"\n#include \"decoder.h\"\n\n#define GS ('\\035')\n\nenum { SCH_NUM, SCH_ALNUM, SCH_ISO646 };\n\nstatic const signed char finder_hash[0x20] = {\n 0x16, 0x1f, 0x02, 0x00, 0x03, 0x00, 0x06, 0x0b,\n 0x1f, 0x0e, 0x17, 0x0c, 0x0b, 0x14, 0x11, 0x0c,\n 0x1f, 0x03, 0x13, 0x08, 0x00, 0x0a, -1, 0x16,\n 0x0c, 0x09, -1, 0x1a, 0x1f, 0x1c, 0x00, -1,\n};\n\n /* ... */\n const unsigned char *p;\n i = (n + 1) / 2 + 1;\n n += 4;\n i = (i * i) / 4;\n dbprintf(2, \" {%d,%d:\", i, n);\n p = exp_sequences + i;\n\n fixed >>= 1;\n seq[0] = 0;\n seq[1] = 1;\n for(i = 2; i < n; ) {\n int s = *p;\n if(!(i & 2)) {\n p++;\n s >>= 4;\n }\n else\n s &= 0xf;\n if(s == fixed)\n fixed = -1;\n s <<= 1;\n dbprintf(2, \"%x\", s);\n seq[i++] = s++;\n seq[i++] = s;\n }\n dbprintf(2, \"}\");\n seq[n] = -1;\n return(fixed < 1);\n}\n\n#define IDX(s) \\\n (((s)->finder << 2) | ((s)->color << 1) | ((s)->color ^ (s)->side))\n\nstatic inline zbar_symbol_type_t\nmatch_segment_exp (zbar_decoder_t *dcode,\n databar_segment_t *seg,\n int dir)\n{\n databar_decoder_t *db = &dcode->databar;\n int bestsegs[22], i = 0, segs[22], seq[22];\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\n#include <config.h>\n#include <zbar.h>\n\n#ifdef DEBUG_DATABAR\n# define DEBUG_LEVEL (DEBUG_DATABAR)\n=======\n\n#include <config.h>\n#include <zbar.h>\n#include <stdlib.h>\n#include <stdio.h>\n\n#ifdef DEBUG_DATABAR\n# define DEBUG_LEVEL (DEBUG_DATABAR)\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n fixed = -1;\n s <<= 1;\n dbprintf(2, \"%x\", s);\n seq[i++] = s++;\n seq[i++] = s;\n }\n=======\n fixed = -1;\n s <<= 1;\n dbprintf(2, \"%x\", s);\n\n if (i > 20) {\n fprintf(stderr, \"Bug: Out-of-bounds condition detected\\n\");\n exit(99);\n }\n\n seq[i++] = s++;\n seq[i++] = s;\n }\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2023-49502: At setup bwdif checked a frame overall width and height (requiring at least 3 wide and 4 tall) but not the size of the smaller chroma-subsampled component buffers. For a subsampled pixel layout such as yuv420p the chroma components are half size, so a frame whose overall width and height satisfy the check can still carry a chroma component smaller than the interpolation kernel; bwdif accepted such a frame and read beyond the edges of that undersized chroma component while deinterlacing. Reachable from an attacker-supplied clip. Affects the ffmpeg 5.1.x branch.\n\n# Vulnerable source (libavfilter/vf_bwdif.c)\n```c\n AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA444P10,\n AV_PIX_FMT_YUVA420P16, AV_PIX_FMT_YUVA422P16, AV_PIX_FMT_YUVA444P16,\n AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10,\n AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14, AV_PIX_FMT_GBRP16,\n AV_PIX_FMT_GBRAP, AV_PIX_FMT_GBRAP16,\n AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY16,\n AV_PIX_FMT_NONE\n};\n\nstatic int config_props(AVFilterLink *link)\n{\n AVFilterContext *ctx = link->src;\n BWDIFContext *s = link->src->priv;\n YADIFContext *yadif = &s->yadif;\n\n link->time_base = av_mul_q(ctx->inputs[0]->time_base, (AVRational){1, 2});\n link->w = link->src->inputs[0]->w;\n link->h = link->src->inputs[0]->h;\n\n if(yadif->mode&1)\n link->frame_rate = av_mul_q(link->src->inputs[0]->frame_rate, (AVRational){2,1});\n\n if (link->w < 3 || link->h < 4) {\n av_log(ctx, AV_LOG_ERROR, \"Video of less than 3 columns or 4 lines is not supported\\n\");\n return AVERROR(EINVAL);\n }\n\n yadif->csp = av_pix_fmt_desc_get(link->format);\n yadif->filter = filter;\n if (yadif->csp->comp[0].depth > 8) {\n s->filter_intra = filter_intra_16bit;\n s->filter_line = filter_line_c_16bit;\n s->filter_edge = filter_edge_16bit;\n } else {\n s->filter_intra = filter_intra;\n s->filter_line = filter_line_c;\n s->filter_edge = filter_edge;\n }\n\n#if ARCH_X86\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n if(yadif->mode&1)\n link->frame_rate = av_mul_q(link->src->inputs[0]->frame_rate, (AVRational){2,1});\n\n if (link->w < 3 || link->h < 4) {\n av_log(ctx, AV_LOG_ERROR, \"Video of less than 3 columns or 4 lines is not supported\\n\");\n return AVERROR(EINVAL);\n }\n\n yadif->csp = av_pix_fmt_desc_get(link->format);\n yadif->filter = filter;\n if (yadif->csp->comp[0].depth > 8) {\n s->filter_intra = filter_intra_16bit;\n s->filter_line = filter_line_c_16bit;\n=======\n if(yadif->mode&1)\n link->frame_rate = av_mul_q(link->src->inputs[0]->frame_rate, (AVRational){2,1});\n\n yadif->csp = av_pix_fmt_desc_get(link->format);\n yadif->filter = filter;\n\n if (AV_CEIL_RSHIFT(link->w, yadif->csp->log2_chroma_w) < 3 || AV_CEIL_RSHIFT(link->h, yadif->csp->log2_chroma_h) < 4) {\n av_log(ctx, AV_LOG_ERROR, \"Video with planes less than 3 columns or 4 lines is not supported\\n\");\n return AVERROR(EINVAL);\n }\n\n if (yadif->csp->comp[0].depth > 8) {\n s->filter_intra = filter_intra_16bit;\n s->filter_line = filter_line_c_16bit;\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2024-12254: Memory-exhaustion denial of service (CWE-400 uncontrolled resource consumption) in CPython's asyncio. The _SelectorSocketTransport.writelines() method, when the socket accepts only part of the data and leaves a residual buffer, registers a write handler but does not apply the transport's write-buffer back-pressure step that the byte-oriented write() path performs. As a result the connected protocol is never told to stop producing while a slow-reading or stalled peer drains the socket, so the transport's outgoing buffer can grow without bound and exhaust process memory (gh-127655). Affects applications that send via writelines() over an asyncio selector transport. nixpkgs ships an affected python3 (3.12.8).\n\n# Vulnerable source (Lib/asyncio/selector_events.py)\n```python\n elif self._eof:\n self._sock.shutdown(socket.SHUT_WR)\n\n def write_eof(self):\n if self._closing or self._eof:\n return\n self._eof = True\n if not self._buffer:\n self._sock.shutdown(socket.SHUT_WR)\n\n def writelines(self, list_of_data):\n if self._eof:\n raise RuntimeError('Cannot call writelines() after write_eof()')\n if self._empty_waiter is not None:\n raise RuntimeError('unable to writelines; sendfile is in progress')\n if not list_of_data:\n return\n self._buffer.extend([memoryview(data) for data in list_of_data])\n self._write_ready()\n # If the entire buffer couldn't be written, register a write handler\n if self._buffer:\n self._loop._add_writer(self._sock_fd, self._write_ready)\n\n def can_write_eof(self):\n return True\n\n def _call_connection_lost(self, exc):\n super()._call_connection_lost(exc)\n if self._empty_waiter is not None:\n self._empty_waiter.set_exception(\n ConnectionError(\"Connection is closed by peer\"))\n\n def _make_empty_waiter(self):\n if self._empty_waiter is not None:\n raise RuntimeError(\"Empty waiter is already set\")\n self._empty_waiter = self._loop.create_future()\n if not self._buffer:\n self._empty_waiter.set_result(None)\n return self._empty_waiter\n\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n # If the entire buffer couldn't be written, register a write handler\n if self._buffer:\n self._loop._add_writer(self._sock_fd, self._write_ready)\n\n def can_write_eof(self):\n return True\n=======\n # If the entire buffer couldn't be written, register a write handler\n if self._buffer:\n self._loop._add_writer(self._sock_fd, self._write_ready)\n self._maybe_pause_protocol()\n\n def can_write_eof(self):\n return True\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2024-33664: CWE-400 in python3Packages.python-jose 3.3.0. The jose.jwe.decrypt function accepts a compact-serialized encryption string of any length and forwards it to the internal segment-splitter before performing any validation. No upper bound on the input string is checked before deserialization begins. An attacker with access to the decryption endpoint can submit a multi-megabyte compact-form payload, causing the runtime to allocate proportional heap memory while splitting and base64-decoding each segment. The absence of an early-exit guard means resource consumption is bounded only by the caller patience and the process memory limit.\n\n# Vulnerable source (jose/jwe.py)\n```python\ndef decrypt(jwe_str, key):\n \"\"\"Decrypts a JWE compact serialized string and returns the plaintext.\n\n Args:\n jwe_str (str): A JWE to be decrypt.\n key (str or dict): A key to attempt to decrypt the payload with. Can be\n individual JWK or JWK set.\n\n Returns:\n bytes: The plaintext bytes, assuming the authentication tag is valid.\n\n Raises:\n JWEError: If there is an exception verifying the token.\n\n Examples:\n >>> from jose import jwe\n >>> jwe.decrypt(jwe_string, 'asecret128bitkey')\n 'Hello, World!'\n \"\"\"\n header, encoded_header, encrypted_key, iv, cipher_text, auth_tag = _jwe_compact_deserialize(jwe_str)\n\n # Verify that the implementation understands and can process all\n # fields that it is required to support, whether required by this\n # specification, by the algorithms being used, or by the \"crit\"\n # Header Parameter value, and that the values of those parameters\n # are also understood and supported.\n\n try:\n # Determine the Key Management Mode employed by the algorithm\n # specified by the \"alg\" (algorithm) Header Parameter.\n alg = header[\"alg\"]\n enc = header[\"enc\"]\n if alg not in ALGORITHMS.SUPPORTED:\n raise JWEError(\"Algorithm %s not supported.\" % alg)\n if enc not in ALGORITHMS.SUPPORTED:\n raise JWEError(\"Algorithm %s not supported.\" % enc)\n\n except KeyError:\n raise JWEParseError(\"alg and enc headers are required!\")\n\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n >>> jwe.decrypt(jwe_string, 'asecret128bitkey')\n 'Hello, World!'\n \"\"\"\n header, encoded_header, encrypted_key, iv, cipher_text, auth_tag = _jwe_compact_deserialize(jwe_str)\n=======\n >>> jwe.decrypt(jwe_string, 'asecret128bitkey')\n 'Hello, World!'\n \"\"\"\n\n # limit the token size to 250 KB\n if len(jwe_str) > 250 * 1024:\n raise JWEError(\"JWE string exceeds 250 KB\")\n\n header, encoded_header, encrypted_key, iv, cipher_text, auth_tag = _jwe_compact_deserialize(jwe_str)\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2024-41671: Twisted's HTTP server failed to correctly enforce the chunk trailer size limit when incoming data arrived in multiple TCP segments, allowing a connection to feed arbitrarily large trailer data without triggering the configured guard. A separate ordering defect caused the channel to signal that all request content had been received before the final data segment was passed to the pending request, enabling an attacker to smuggle an additional pipelined HTTP request into the same connection.\n\n# Vulnerable source (src/twisted/web/http.py)\n```python\n if ext and ext.translate(None, _chunkExtChars) != b\"\":\n raise _MalformedChunkedDataError(\n f\"Invalid characters in chunk extensions: {ext!r}.\"\n )\n\n if length == 0:\n self.state = \"TRAILER\"\n else:\n self.state = \"BODY\"\n\n self.length = length\n del self._buffer[0 : eolIndex + 2]\n self._start = 0\n return True\n\n def _dataReceived_CRLF(self) -> bool:\n \"\"\"\n Await the carriage return and line feed characters that are the end of\n chunk marker that follow the chunk data.\n\n @returns: C{True} when the CRLF have been read, otherwise C{False}.\n\n @raises _MalformedChunkedDataError: when anything other than CRLF are\n received.\n \"\"\"\n if len(self._buffer) < 2:\n return False\n\n if not self._buffer.startswith(b\"\\r\\n\"):\n raise _MalformedChunkedDataError(\"Chunk did not end with CRLF\")\n\n self.state = \"CHUNK_LENGTH\"\n del self._buffer[0:2]\n return True\n\n def _dataReceived_TRAILER(self) -> bool:\n \"\"\"\n Collect trailer headers if received and finish at the terminal zero-length\n chunk. Then invoke C{finishCallback} and switch to state C{'FINISHED'}.\n\n @returns: C{False}, as there is either insufficient data to continue,\n or no data remains.\n \"\"\"\n if (\n self._receivedTrailerHeadersSize + len(self._buffer)\n > self._maxTrailerHeadersSize\n ):\n raise _MalformedChunkedDataError(\"Trailer headers data is too long.\")\n\n eolIndex = self._buffer.find(b\"\\r\\n\", self._start)\n\n if eolIndex == -1:\n # Still no end of network line marker found.\n # Continue processing more data.\n return False\n\n if eolIndex > 0:\n # A trailer header was detected.\n self._trailerHeaders.append(self._buffer[0:eolIndex])\n del self._buffer[0 : eolIndex + 2]\n self._start = 0\n self._receivedTrailerHeadersSize += eolIndex + 2\n return True\n\n # eolIndex in this part of code is equal to 0\n\n data = memoryview(self._buffer)[2:].tobytes()\n\n del self._buffer[:]\n self.state = \"FINISHED\"\n self.finishCallback(data)\n return False\n\n def _dataReceived_BODY(self) -> bool:\n \"\"\"\n Deliver any available chunk data to the C{dataCallback}. When all the\n remaining data for the chunk arrives, switch to state C{'CRLF'}.\n\n @returns: C{True} to continue processing of any buffered data.\n \"\"\"\n if len(self._buffer) >= self.length:\n chunk = memoryview(self._buffer)[: self.length].tobytes()\n del self._buffer[: self.length]\n self.state = \"CRLF\"\n self.dataCallback(chunk)\n else:\n chunk = bytes(self._buffer)\n self.length -= len(chunk)\n del self._buffer[:]\n self.dataCallback(chunk)\n return True\n\n def _dataReceived_FINISHED(self) -> bool:\n \"\"\"\n Once C{finishCallback} has been invoked receipt of additional data\n raises L{RuntimeError} because it represents a programming error in\n the caller.\n \"\"\"\n raise RuntimeError(\n \"_ChunkedTransferDecoder.dataReceived called after last \"\n \"chunk was processed\"\n )\n\n def dataReceived(self, data: bytes) -> None:\n \"\"\"\n Interpret data from a request or response body which uses the\n I{chunked} Transfer-Encoding.\n \"\"\"\n self._buffer += data\n goOn = True\n while goOn and self._buffer:\n goOn = getattr(self, \"_dataReceived_\" + self.state)()\n\n def noMoreData(self) -> None:\n \"\"\"\n Verify that all data has been received. If it has not been, raise\n L{_DataLoss}.\n \"\"\"\n if self.state != \"FINISHED\":\n raise _DataLoss(\n \"Chunked decoder in %r state, still expecting more data to \"\n \"get to 'FINISHED' state.\" % (self.state,)\n )\n\n\n@implementer(interfaces.IPushProducer)\nclass _NoPushProducer:\n \"\"\"\n A no-op version of L{interfaces.IPushProducer}, used to abstract over the\n possibility that a L{HTTPChannel} transport does not provide\n L{IPushProducer}.\n \"\"\"\n\n def pauseProducing(self):\n \"\"\"\n Pause producing data.\n\n Tells a producer that it has produced too much data to process for\n the time being, and to stop until resumeProducing() is called.\n \"\"\"\n\n def resumeProducing(self):\n \"\"\"\n Resume producing data.\n\n This tells a producer to re-add itself to the main loop and produce\n more data for its consumer.\n \"\"\"\n\n def registerProducer(self, producer, streaming):\n \"\"\"\n Register to receive data from a producer.\n\n @param producer: The producer to register.\n @param streaming: Whether this is a streaming producer or not.\n \"\"\"\n\n def unregisterProducer(self):\n \"\"\"\n Stop consuming data from a producer, without disconnecting.\n \"\"\"\n\n def stopProducing(self):\n \"\"\"\n IProducer.stopProducing\n \"\"\"\n\n\n@implementer(interfaces.ITransport, interfaces.IPushProducer, interfaces.IConsumer)\nclass HTTPChannel(basic.LineReceiver, policies.TimeoutMixin):\n \"\"\"\n A receiver for HTTP requests.\n\n The L{HTTPChannel} provides L{interfaces.ITransport} and\n L{interfaces.IConsumer} to the L{Request} objects it creates. It also\n implements L{interfaces.IPushProducer} to C{self.transport}, allowing the\n transport to pause it.\n\n @ivar MAX_LENGTH: Maximum length for initial request line and each line\n from the header.\n\n @ivar _transferDecoder: L{None} or a decoder instance if the request body\n uses the I{chunked} Transfer-Encoding.\n @type _transferDecoder: L{_ChunkedTransferDecoder}\n\n @ivar maxHeaders: Maximum number of headers allowed per request.\n @type maxHeaders: C{int}\n\n @ivar totalHeadersSize: Maximum bytes for request line plus all headers\n from the request.\n @type totalHeadersSize: C{int}\n\n @ivar _receivedHeaderSize: Bytes received so far for the header.\n @type _receivedHeaderSize: C{int}\n\n @ivar _handlingRequest: Whether a request is currently being processed.\n @type _handlingRequest: L{bool}\n\n @ivar _dataBuffer: Any data that has been received from the connection\n while processing an outstanding request.\n @type _dataBuffer: L{list} of L{bytes}\n\n @ivar _networkProducer: Either the transport, if it provides\n L{interfaces.IPushProducer}, or a null implementation of\n L{interfaces.IPushProducer}. Used to attempt to prevent the transport\n from producing excess data when we're responding to a request.\n @type _networkProducer: L{interfaces.IPushProducer}\n\n @ivar _requestProducer: If the L{Request} object or anything it calls\n registers itself as an L{interfaces.IProducer}, it will be stored here.\n This is used to create a producing pipeline: pause/resume producing\n methods will be propagated from the C{transport}, through the\n L{HTTPChannel} instance, to the c{_requestProducer}.\n\n The reason we proxy through the producing methods rather than the old\n behaviour (where we literally just set the L{Request} object as the\n producer on the transport) is because we want to be able to exert\n backpressure on the client to prevent it from sending in arbitrarily\n many requests without ever reading responses. Essentially, if the\n client never reads our responses we will eventually stop reading its\n requests.\n\n @type _requestProducer: L{interfaces.IPushProducer}\n\n @ivar _requestProducerStreaming: A boolean that tracks whether the producer\n on the L{Request} side of this channel has registered itself as a\n L{interfaces.IPushProducer} or an L{interfaces.IPullProducer}.\n @type _requestProducerStreaming: L{bool} or L{None}\n\n @ivar _waitingForTransport: A boolean that tracks whether the transport has\n asked us to stop producing. This is used to keep track of what we're\n waiting for: if the transport has asked us to stop producing then we\n don't want to unpause the transport until it asks us to produce again.\n @type _waitingForTransport: L{bool}\n\n @ivar abortTimeout: The number of seconds to wait after we attempt to shut\n the transport down cleanly to give up and forcibly terminate it. This\n is only used when we time a connection out, to prevent errors causing\n the FD to get leaked. If this is L{None}, we will wait forever.\n @type abortTimeout: L{int}\n\n @ivar _abortingCall: The L{twisted.internet.base.DelayedCall} that will be\n used to forcibly close the transport if it doesn't close cleanly.\n @type _abortingCall: L{twisted.internet.base.DelayedCall}\n\n @ivar _optimisticEagerReadSize: When a resource takes a long time to answer\n a request (via L{twisted.web.server.NOT_DONE_YET}, hopefully one day by\n a L{Deferred}), we would like to be able to let that resource know\n about the underlying transport disappearing as promptly as possible,\n via L{Request.notifyFinish}, and therefore via\n C{self.requests[...].connectionLost()} on this L{HTTPChannel}.\n\n However, in order to simplify application logic, we implement\n head-of-line blocking, and do not relay pipelined requests to the\n application until the previous request has been answered. This means\n that said application cannot dispose of any entity-body that comes in\n from those subsequent requests, which may be arbitrarily large, and it\n may need to be buffered in memory.\n\n To implement this tradeoff between prompt notification when possible\n (in the most frequent case of non-pipelined requests) and correct\n behavior when not (say, if a client sends a very long-running GET\n request followed by a PUT request with a very large body) we will\n continue reading pipelined requests into C{self._dataBuffer} up to a\n given limit.\n\n C{_optimisticEagerReadSize} is the number of bytes we will accept from\n the client and buffer before pausing the transport.\n\n This behavior has been in place since Twisted 17.9.0 .\n\n @type _optimisticEagerReadSize: L{int}\n \"\"\"\n\n maxHeaders = 500\n totalHeadersSize = 16384\n abortTimeout = 15\n\n length = 0\n persistent = 1\n __header = b\"\"\n __first_line = 1\n __content = None\n\n # set in instances or subclasses\n requestFactory = Request\n\n _savedTimeOut = None\n _receivedHeaderCount = 0\n _receivedHeaderSize = 0\n _requestProducer = None\n _requestProducerStreaming = None\n _waitingForTransport = False\n _abortingCall = None\n _optimisticEagerReadSize = 0x4000\n _log = Logger()\n\n def __init__(self):\n # the request queue\n self.requests = []\n self._handlingRequest = False\n self._dataBuffer = []\n self._transferDecoder = None\n\n def connectionMade(self):\n self.setTimeout(self.timeOut)\n self._networkProducer = interfaces.IPushProducer(\n self.transport, _NoPushProducer()\n )\n self._networkProducer.registerProducer(self, True)\n\n def lineReceived(self, line):\n \"\"\"\n Called for each line from request until the end of headers when\n it enters binary mode.\n \"\"\"\n self.resetTimeout()\n\n self._receivedHeaderSize += len(line)\n if self._receivedHeaderSize > self.totalHeadersSize:\n self._respondToBadRequestAndDisconnect()\n return\n\n if self.__first_line:\n # if this connection is not persistent, drop any data which\n # the client (illegally) sent after the last request.\n if not self.persistent:\n self.dataReceived = self.lineReceived = lambda *args: None\n return\n\n # IE sends an extraneous empty line (\\r\\n) after a POST request;\n # eat up such a line, but only ONCE\n if not line and self.__first_line == 1:\n self.__first_line = 2\n return\n\n # create a new Request object\n if INonQueuedRequestFactory.providedBy(self.requestFactory):\n request = self.requestFactory(self)\n else:\n request = self.requestFactory(self, len(self.requests))\n self.requests.append(request)\n\n self.__first_line = 0\n\n parts = line.split()\n if len(parts) != 3:\n self._respondToBadRequestAndDisconnect()\n return\n command, request, version = parts\n try:\n command.decode(\"ascii\")\n except UnicodeDecodeError:\n self._respondToBadRequestAndDisconnect()\n return\n\n self._command = command\n self._path = request\n self._version = version\n elif line == b\"\":\n # End of headers.\n if self.__header:\n ok = self.headerReceived(self.__header)\n # If the last header we got is invalid, we MUST NOT proceed\n # with processing. We'll have sent a 400 anyway, so just stop.\n if not ok:\n return\n self.__header = b\"\"\n self.allHeadersReceived()\n if self.length == 0:\n self.allContentReceived()\n else:\n self.setRawMode()\n elif line[0] in b\" \\t\":\n # Continuation of a multi line header.\n self.__header += b\" \" + line.lstrip(b\" \\t\")\n # Regular header line.\n # Processing of header line is delayed to allow accumulating multi\n # line headers.\n else:\n if self.__header:\n self.headerReceived(self.__header)\n self.__header = line\n\n def _finishRequestBody(self, data):\n self.allContentReceived()\n self._dataBuffer.append(data)\n\n def _maybeChooseTransferDecoder(self, header, data):\n \"\"\"\n If the provided header is C{content-length} or\n C{transfer-encoding}, choose the appropriate decoder if any.\n\n Returns L{True} if the request can proceed and L{False} if not.\n \"\"\"\n\n def fail():\n self._respondToBadRequestAndDisconnect()\n self.length = None\n return False\n\n # Can this header determine the length?\n if header == b\"content-length\":\n if not data.isdigit():\n return fail()\n try:\n length = int(data)\n except ValueError:\n return fail()\n newTransferDecoder = _IdentityTransferDecoder(\n length, self.requests[-1].handleContentChunk, self._finishRequestBody\n )\n elif header == b\"transfer-encoding\":\n # XXX Rather poorly tested code block, apparently only exercised by\n # test_chunkedEncoding\n if data.lower() == b\"chunked\":\n length = None\n newTransferDecoder = _ChunkedTransferDecoder(\n self.requests[-1].handleContentChunk, self._finishRequestBody\n )\n elif data.lower() == b\"identity\":\n return True\n else:\n return fail()\n else:\n # It's not a length related header, so exit\n return True\n\n if self._transferDecoder is not None:\n return fail()\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n @returns: C{False}, as there is either insufficient data to continue,\n or no data remains.\n \"\"\"\n if (\n self._receivedTrailerHeadersSize + len(self._buffer)\n > self._maxTrailerHeadersSize\n ):\n raise _MalformedChunkedDataError(\"Trailer headers data is too long.\")\n\n eolIndex = self._buffer.find(b\"\\r\\n\", self._start)\n\n if eolIndex == -1:\n # Still no end of network line marker found.\n # Continue processing more data.\n return False\n\n=======\n @returns: C{False}, as there is either insufficient data to continue,\n or no data remains.\n \"\"\"\n eolIndex = self._buffer.find(b\"\\r\\n\", self._start)\n\n if eolIndex == -1:\n # Still no end of network line marker found.\n #\n # Check if we've run up against the trailer size limit: if the next\n # read contains the terminating CRLF then we'll have this many bytes\n # of trailers (including the CRLFs).\n minTrailerSize = (\n self._receivedTrailerHeadersSize\n + len(self._buffer)\n + (1 if self._buffer.endswith(b\"\\r\") else 2)\n )\n if minTrailerSize > self._maxTrailerHeadersSize:\n raise _MalformedChunkedDataError(\"Trailer headers data is too long.\")\n # Continue processing more data.\n return False\n\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n del self._buffer[0 : eolIndex + 2]\n self._start = 0\n self._receivedTrailerHeadersSize += eolIndex + 2\n return True\n\n # eolIndex in this part of code is equal to 0\n=======\n del self._buffer[0 : eolIndex + 2]\n self._start = 0\n self._receivedTrailerHeadersSize += eolIndex + 2\n if self._receivedTrailerHeadersSize > self._maxTrailerHeadersSize:\n raise _MalformedChunkedDataError(\"Trailer headers data is too long.\")\n return True\n\n # eolIndex in this part of code is equal to 0\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n self.__header = line\n\n def _finishRequestBody(self, data):\n self.allContentReceived()\n self._dataBuffer.append(data)\n\n def _maybeChooseTransferDecoder(self, header, data):\n \"\"\"\n=======\n self.__header = line\n\n def _finishRequestBody(self, data):\n self._dataBuffer.append(data)\n self.allContentReceived()\n\n def _maybeChooseTransferDecoder(self, header, data):\n \"\"\"\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2024-41810: Reflected cross-site scripting (CWE-79) in Twisted's web redirect helper. Any twisted.web Resource that returns redirectTo(request.args[...], request) (a common redirect pattern) is exploitable.\n\n# Vulnerable source (src/twisted/web/_template_util.py)\n```python\n response code. This is intended to be returned from a render method,\n eg::\n\n def render_GET(self, request):\n return redirectTo(b\"http://example.com/\", request)\n \"\"\"\n if not isinstance(URL, bytes):\n raise TypeError(\"URL must be bytes\")\n request.setHeader(b\"Content-Type\", b\"text/html; charset=utf-8\")\n request.redirect(URL)\n # FIXME: The URL should be HTML-escaped.\n # https://twistedmatrix.com/trac/ticket/9839\n content = b\"\"\"\n<html>\n <head>\n <meta http-equiv=\\\"refresh\\\" content=\\\"0;URL=%(url)s\\\">\n </head>\n <body bgcolor=\\\"#FFFFFF\\\" text=\\\"#000000\\\">\n <a href=\\\"%(url)s\\\">click here</a>\n </body>\n</html>\n\"\"\" % {\n b\"url\": URL\n }\n return content\n\n\nclass Redirect(resource.Resource):\n \"\"\"\n Resource that redirects to a specific URL.\n\n @ivar url: Redirect target URL to put in the I{Location} response header.\n @type url: L{bytes}\n \"\"\"\n\n isLeaf = True\n\n def __init__(self, url: bytes):\n super().__init__()\n self.url = url\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n </body>\n</html>\n\"\"\" % {\n b\"url\": URL\n }\n return content\n=======\n </body>\n</html>\n\"\"\" % {\n b\"url\": escape(URL.decode(\"utf-8\")).encode(\"utf-8\")\n }\n return content\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2024-45781: GRUB2 copies symbolic link strings from UFS filesystem images into a heap-allocated buffer without verifying that the string fits in the buffer. When a filesystem image contains a link whose path is longer than the buffer, the copy writes past the buffer end into adjacent heap memory, potentially enabling arbitrary code execution during boot.\n\n# Vulnerable source (grub-core/fs/ufs.c)\n```c\n grpblk += grub_ufs_to_cpu32 (sblock->cylg_offset)\n * (group & (~grub_ufs_to_cpu32 (sblock->cylg_mask)));\n#endif\n\n if (!inode)\n {\n inode = (char *) &data->inode;\n data->ino = ino;\n }\n\n grub_disk_read (data->disk,\n\t\t ((grub_ufs_to_cpu32 (sblock->inoblk_offs) + grpblk)\n\t\t << grub_ufs_to_cpu32 (data->sblock.log2_blksz))\n\t\t + grpino / UFS_INODE_PER_BLOCK,\n\t\t (grpino % UFS_INODE_PER_BLOCK)\n\t\t * sizeof (struct grub_ufs_inode),\n\t\t sizeof (struct grub_ufs_inode),\n\t\t inode);\n\n return grub_errno;\n}\n\n\n/* Lookup the symlink the current inode points to. INO is the inode\n number of the directory the symlink is relative to. */\nstatic grub_err_t\ngrub_ufs_lookup_symlink (struct grub_ufs_data *data, int ino)\n{\n char *symlink;\n grub_size_t sz = INODE_SIZE (data);\n\n if (++data->linknest > GRUB_UFS_MAX_SYMLNK_CNT)\n return grub_error (GRUB_ERR_SYMLINK_LOOP, N_(\"too deep nesting of symlinks\"));\n\n symlink = grub_malloc (sz + 1);\n if (!symlink)\n return grub_errno;\n /* Normally we should just check that data->inode.nblocks == 0.\n However old Linux doesn't maintain nblocks correctly and so it's always\n 0. If size is bigger than inline space then the symlink is surely not\n inline. */\n /* Check against zero is paylindromic, no need to swap. */\n if (data->inode.nblocks == 0\n && INODE_SIZE (data) <= sizeof (data->inode.symlink))\n grub_strcpy (symlink, (char *) data->inode.symlink);\n else\n {\n if (grub_ufs_read_file (data, 0, 0, 0, sz, symlink) < 0)\n\t{\n\t grub_free(symlink);\n\t return grub_errno;\n\t}\n }\n symlink[sz] = '\\0';\n\n /* The symlink is an absolute path, go back to the root inode. */\n if (symlink[0] == '/')\n ino = GRUB_UFS_INODE;\n\n /* Now load in the old inode. */\n if (grub_ufs_read_inode (data, ino, 0))\n {\n grub_free (symlink);\n return grub_errno;\n }\n\n grub_ufs_find_file (data, symlink);\n\n grub_free (symlink);\n\n return grub_errno;\n}\n\n\n/* Find the file with the pathname PATH on the filesystem described by\n DATA. */\nstatic grub_err_t\ngrub_ufs_find_file (struct grub_ufs_data *data, const char *path)\n{\n const char *name;\n const char *next = path;\n unsigned int pos = 0;\n int dirino;\n char *filename;\n\n /* We reject filenames longer than the one we're looking\n for without reading, so this allocation is enough. */\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n /* Check against zero is paylindromic, no need to swap. */\n if (data->inode.nblocks == 0\n && INODE_SIZE (data) <= sizeof (data->inode.symlink))\n grub_strcpy (symlink, (char *) data->inode.symlink);\n else\n {\n if (grub_ufs_read_file (data, 0, 0, 0, sz, symlink) < 0)\n=======\n /* Check against zero is paylindromic, no need to swap. */\n if (data->inode.nblocks == 0\n && INODE_SIZE (data) <= sizeof (data->inode.symlink))\n grub_strlcpy (symlink, (char *) data->inode.symlink, sz);\n else\n {\n if (grub_ufs_read_file (data, 0, 0, 0, sz, symlink) < 0)\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2024-45782: GRUB2 through 2.12 reads HFS volume names from disk images and copies them into a bounded stack buffer without verifying that the name fits. An attacker with a crafted HFS disk image can provide a volume name that overflows the buffer.\n\n# Vulnerable source (grub-core/fs/hfs.c)\n```c\n grub_error (GRUB_ERR_BAD_FS, \"not an HFS filesystem\");\n goto fail;\n }\n\n /* Check if this is an embedded HFS+ filesystem. */\n if (grub_be_to_cpu16 (data->sblock.embed_sig) == GRUB_HFS_EMBED_HFSPLUS_SIG)\n {\n grub_error (GRUB_ERR_BAD_FS, \"embedded HFS+ filesystem\");\n goto fail;\n }\n\n data->blksz = grub_be_to_cpu32 (data->sblock.blksz);\n data->disk = disk;\n\n /* Lookup the root node of the extent overflow tree. */\n first_block = ((grub_be_to_cpu16 (data->sblock.extent_recs[0].first_block)\n\t\t * GRUB_HFS_BLKS)\n\t\t + grub_be_to_cpu16 (data->sblock.first_block));\n\n if (grub_disk_read (data->disk, first_block, 0,\n\t\t sizeof (treehead), &treehead))\n goto fail;\n data->ext_root = grub_be_to_cpu32 (treehead.head.root_node);\n data->ext_size = grub_be_to_cpu16 (treehead.head.node_size);\n\n /* Lookup the root node of the catalog tree. */\n first_block = ((grub_be_to_cpu16 (data->sblock.catalog_recs[0].first_block)\n\t\t * GRUB_HFS_BLKS)\n\t\t + grub_be_to_cpu16 (data->sblock.first_block));\n if (grub_disk_read (data->disk, first_block, 0,\n\t\t sizeof (treehead), &treehead))\n goto fail;\n data->cat_root = grub_be_to_cpu32 (treehead.head.root_node);\n data->cat_size = grub_be_to_cpu16 (treehead.head.node_size);\n\n if (data->cat_size == 0\n || data->blksz < data->cat_size\n || data->blksz < data->ext_size)\n goto fail;\n\n /* Lookup the root directory node in the catalog tree using the\n volume name. */\n key.parent_dir = grub_cpu_to_be32_compile_time (1);\n key.strlen = data->sblock.volname[0];\n grub_strcpy ((char *) key.str, (char *) (data->sblock.volname + 1));\n\n if (grub_hfs_find_node (data, (char *) &key, data->cat_root,\n\t\t\t 0, (char *) &dir, sizeof (dir)) == 0)\n {\n grub_error (GRUB_ERR_BAD_FS, \"cannot find the HFS root directory\");\n goto fail;\n }\n\n if (grub_errno)\n goto fail;\n\n data->rootdir = grub_be_to_cpu32 (dir.dirid);\n\n return data;\n fail:\n grub_free (data);\n\n if (grub_errno == GRUB_ERR_OUT_OF_RANGE)\n grub_error (GRUB_ERR_BAD_FS, \"not a HFS filesystem\");\n\n return 0;\n}\n\n/* Compare the K1 and K2 catalog file keys using HFS character ordering. */\nstatic int\ngrub_hfs_cmp_catkeys (const struct grub_hfs_catalog_key *k1,\n\t\t const struct grub_hfs_catalog_key *k2)\n{\n /* Taken from hfsutils 3.2.6 and converted to a readable form */\n static const unsigned char hfs_charorder[256] = {\n [0x00] = 0,\n [0x01] = 1,\n [0x02] = 2,\n [0x03] = 3,\n [0x04] = 4,\n [0x05] = 5,\n [0x06] = 6,\n [0x07] = 7,\n [0x08] = 8,\n [0x09] = 9,\n [0x0A] = 10,\n [0x0B] = 11,\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n volume name. */\n key.parent_dir = grub_cpu_to_be32_compile_time (1);\n key.strlen = data->sblock.volname[0];\n grub_strcpy ((char *) key.str, (char *) (data->sblock.volname + 1));\n\n if (grub_hfs_find_node (data, (char *) &key, data->cat_root,\n\t\t\t 0, (char *) &dir, sizeof (dir)) == 0)\n=======\n volume name. */\n key.parent_dir = grub_cpu_to_be32_compile_time (1);\n key.strlen = data->sblock.volname[0];\n grub_strlcpy ((char *) key.str, (char *) (data->sblock.volname + 1), sizeof (key.str));\n\n if (grub_hfs_find_node (data, (char *) &key, data->cat_root,\n\t\t\t 0, (char *) &dir, sizeof (dir)) == 0)\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2024-5535: OpenSSL's SSL_select_next_proto function failed to validate that its protocol list arguments were correctly formed before processing them. The function accepted a zero-length or malformed list and would access memory beyond the end of the provided buffer while iterating over protocol names. Code that called this function with an NPN (Next Protocol Negotiation) list that was not properly validated upstream could trigger an out-of-bounds read, potentially leading to application crashes or information disclosure.\n\n# Vulnerable source (ssl/ssl_lib.c)\n```c\n return sc->session->ext.hostname;\n } else {\n if (!SSL_CONNECTION_IS_TLS13(sc) && sc->hit\n && sc->session->ext.hostname != NULL)\n return sc->session->ext.hostname;\n }\n }\n\n return sc->ext.hostname;\n}\n\nint SSL_get_servername_type(const SSL *s)\n{\n if (SSL_get_servername(s, TLSEXT_NAMETYPE_host_name) != NULL)\n return TLSEXT_NAMETYPE_host_name;\n return -1;\n}\n\n/*\n * SSL_select_next_proto implements the standard protocol selection. It is\n * expected that this function is called from the callback set by\n * SSL_CTX_set_next_proto_select_cb. The protocol data is assumed to be a\n * vector of 8-bit, length prefixed byte strings. The length byte itself is\n * not included in the length. A byte string of length 0 is invalid. No byte\n * string may be truncated. The current, but experimental algorithm for\n * selecting the protocol is: 1) If the server doesn't support NPN then this\n * is indicated to the callback. In this case, the client application has to\n * abort the connection or have a default application level protocol. 2) If\n * the server supports NPN, but advertises an empty list then the client\n * selects the first protocol in its list, but indicates via the API that this\n * fallback case was enacted. 3) Otherwise, the client finds the first\n * protocol in the server's list that it supports and selects this protocol.\n * This is because it's assumed that the server has better information about\n * which protocol a client should use. 4) If the client doesn't support any\n * of the server's advertised protocols, then this is treated the same as\n * case 2. It returns either OPENSSL_NPN_NEGOTIATED if a common protocol was\n * found, or OPENSSL_NPN_NO_OVERLAP if the fallback case was reached.\n */\nint SSL_select_next_proto(unsigned char **out, unsigned char *outlen,\n const unsigned char *server,\n unsigned int server_len,\n const unsigned char *client, unsigned int client_len)\n{\n unsigned int i, j;\n const unsigned char *result;\n int status = OPENSSL_NPN_UNSUPPORTED;\n\n /*\n * For each protocol in server preference order, see if we support it.\n */\n for (i = 0; i < server_len;) {\n for (j = 0; j < client_len;) {\n if (server[i] == client[j] &&\n memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {\n /* We found a match */\n result = &server[i];\n status = OPENSSL_NPN_NEGOTIATED;\n goto found;\n }\n j += client[j];\n j++;\n }\n i += server[i];\n i++;\n }\n\n /* There's no overlap between our protocols and the server's list. */\n result = client;\n status = OPENSSL_NPN_NO_OVERLAP;\n\n found:\n *out = (unsigned char *)result + 1;\n *outlen = result[0];\n return status;\n}\n\n#ifndef OPENSSL_NO_NEXTPROTONEG\n/*\n * SSL_get0_next_proto_negotiated sets *data and *len to point to the\n * client's requested protocol for this connection and returns 0. If the\n * client didn't request any protocol, then *data is set to NULL. Note that\n * the client can request any protocol it chooses. The value returned from\n * this function need not be a member of the list of supported protocols\n * provided by the callback.\n */\nvoid SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,\n unsigned *len)\n{\n const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);\n\n if (sc == NULL) {\n /* We have no other way to indicate error */\n *data = NULL;\n *len = 0;\n return;\n }\n\n *data = sc->ext.npn;\n if (*data == NULL) {\n *len = 0;\n } else {\n *len = (unsigned int)sc->ext.npn_len;\n }\n}\n\n/*\n * SSL_CTX_set_npn_advertised_cb sets a callback that is called when\n * a TLS server needs a list of supported protocols for Next Protocol\n * Negotiation. The returned list must be in wire format. The list is\n * returned by setting |out| to point to it and |outlen| to its length. This\n * memory will not be modified, but one should assume that the SSL* keeps a\n * reference to it. The callback should return SSL_TLSEXT_ERR_OK if it\n * wishes to advertise. Otherwise, no such extension will be included in the\n * ServerHello.\n */\nvoid SSL_CTX_set_npn_advertised_cb(SSL_CTX *ctx,\n SSL_CTX_npn_advertised_cb_func cb,\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n unsigned int server_len,\n const unsigned char *client, unsigned int client_len)\n{\n unsigned int i, j;\n const unsigned char *result;\n int status = OPENSSL_NPN_UNSUPPORTED;\n\n /*\n * For each protocol in server preference order, see if we support it.\n */\n for (i = 0; i < server_len;) {\n for (j = 0; j < client_len;) {\n if (server[i] == client[j] &&\n memcmp(&server[i + 1], &client[j + 1], server[i]) == 0) {\n /* We found a match */\n result = &server[i];\n status = OPENSSL_NPN_NEGOTIATED;\n goto found;\n }\n j += client[j];\n j++;\n }\n i += server[i];\n i++;\n }\n\n /* There's no overlap between our protocols and the server's list. */\n result = client;\n status = OPENSSL_NPN_NO_OVERLAP;\n\n found:\n *out = (unsigned char *)result + 1;\n *outlen = result[0];\n return status;\n}\n\n#ifndef OPENSSL_NO_NEXTPROTONEG\n=======\n unsigned int server_len,\n const unsigned char *client, unsigned int client_len)\n{\n PACKET cpkt, csubpkt, spkt, ssubpkt;\n\n if (!PACKET_buf_init(&cpkt, client, client_len)\n || !PACKET_get_length_prefixed_1(&cpkt, &csubpkt)\n || PACKET_remaining(&csubpkt) == 0) {\n *out = NULL;\n *outlen = 0;\n return OPENSSL_NPN_NO_OVERLAP;\n }\n\n /*\n * Set the default opportunistic protocol. Will be overwritten if we find\n * a match.\n */\n *out = (unsigned char *)PACKET_data(&csubpkt);\n *outlen = (unsigned char)PACKET_remaining(&csubpkt);\n\n /*\n * For each protocol in server preference order, see if we support it.\n */\n if (PACKET_buf_init(&spkt, server, server_len)) {\n while (PACKET_get_length_prefixed_1(&spkt, &ssubpkt)) {\n if (PACKET_remaining(&ssubpkt) == 0)\n continue; /* Invalid - ignore it */\n if (PACKET_buf_init(&cpkt, client, client_len)) {\n while (PACKET_get_length_prefixed_1(&cpkt, &csubpkt)) {\n if (PACKET_equal(&csubpkt, PACKET_data(&ssubpkt),\n PACKET_remaining(&ssubpkt))) {\n /* We found a match */\n *out = (unsigned char *)PACKET_data(&ssubpkt);\n *outlen = (unsigned char)PACKET_remaining(&ssubpkt);\n return OPENSSL_NPN_NEGOTIATED;\n }\n }\n /* Ignore spurious trailing bytes in the client list */\n } else {\n /* This should never happen */\n return OPENSSL_NPN_NO_OVERLAP;\n }\n }\n /* Ignore spurious trailing bytes in the server list */\n }\n\n /*\n * There's no overlap between our protocols and the server's list. We use\n * the default opportunistic protocol selected earlier\n */\n return OPENSSL_NPN_NO_OVERLAP;\n}\n\n#ifndef OPENSSL_NO_NEXTPROTONEG\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2024-8096: curl's GnuTLS TLS backend failed to correctly enforce certificate revocation validation through OCSP stapling. When a connection was initiated, the server could suppress the stapled proof that its certificate had not been revoked, and curl would not detect the absence or flag the handshake as invalid. A man-in-the-middle attacker could exploit this gap to present a revoked certificate without triggering an alert.\n\n# Vulnerable source (lib/vtls/gtls.c)\n```c\n sni = FALSE; /* SSLv3 has no SNI */\n\n /* allocate a shared creds struct */\n result = Curl_gtls_shared_creds_create(data, &gtls->shared_creds);\n if(result)\n return result;\n\n#ifdef USE_GNUTLS_SRP\n if(config->username && Curl_auth_allowed_to_host(data)) {\n infof(data, \"Using TLS-SRP username: %s\", config->username);\n\n rc = gnutls_srp_allocate_client_credentials(&gtls->srp_client_cred);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_srp_allocate_client_cred() failed: %s\",\n gnutls_strerror(rc));\n return CURLE_OUT_OF_MEMORY;\n }\n\n rc = gnutls_srp_set_client_credentials(gtls->srp_client_cred,\n config->username,\n config->password);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_srp_set_client_cred() failed: %s\",\n gnutls_strerror(rc));\n return CURLE_BAD_FUNCTION_ARGUMENT;\n }\n }\n#endif\n\n ssl_config->certverifyresult = 0;\n\n /* Initialize TLS session as a client */\n init_flags = GNUTLS_CLIENT;\n\n#if defined(GNUTLS_FORCE_CLIENT_CERT)\n init_flags |= GNUTLS_FORCE_CLIENT_CERT;\n#endif\n\n#if defined(GNUTLS_NO_TICKETS)\n /* Disable TLS session tickets */\n init_flags |= GNUTLS_NO_TICKETS;\n#endif\n\n rc = gnutls_init(&gtls->session, init_flags);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_init() failed: %d\", rc);\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n if(sni && peer->sni) {\n if(gnutls_server_name_set(gtls->session, GNUTLS_NAME_DNS,\n peer->sni, strlen(peer->sni)) < 0) {\n failf(data, \"Failed to set SNI\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n /* Use default priorities */\n rc = gnutls_set_default_priority(gtls->session);\n if(rc != GNUTLS_E_SUCCESS)\n return CURLE_SSL_CONNECT_ERROR;\n\n /* \"In GnuTLS 3.6.5, TLS 1.3 is enabled by default\" */\n tls13support = gnutls_check_version(\"3.6.5\");\n\n /* Ensure +SRP comes at the *end* of all relevant strings so that it can be\n * removed if a runtime error indicates that SRP is not supported by this\n * GnuTLS version */\n\n if(config->version == CURL_SSLVERSION_SSLv2 ||\n config->version == CURL_SSLVERSION_SSLv3) {\n failf(data, \"GnuTLS does not support SSLv2 or SSLv3\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n if(config->version == CURL_SSLVERSION_TLSv1_3) {\n if(!tls13support) {\n failf(data, \"This GnuTLS installation does not support TLS 1.3\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n /* At this point we know we have a supported TLS version, so set it */\n result = set_ssl_version_min_max(data, peer,\n config, &prioritylist, tls13support);\n if(result)\n return result;\n\n#ifdef USE_GNUTLS_SRP\n /* Only add SRP to the cipher list if SRP is requested. Otherwise\n * GnuTLS will disable TLS 1.3 support. */\n if(config->username) {\n char *prioritysrp = aprintf(\"%s:\" GNUTLS_SRP, prioritylist);\n if(!prioritysrp)\n return CURLE_OUT_OF_MEMORY;\n rc = gnutls_priority_set_direct(gtls->session, prioritysrp, &err);\n free(prioritysrp);\n\n if((rc == GNUTLS_E_INVALID_REQUEST) && err) {\n infof(data, \"This GnuTLS does not support SRP\");\n }\n }\n else {\n#endif\n infof(data, \"GnuTLS ciphers: %s\", prioritylist);\n rc = gnutls_priority_set_direct(gtls->session, prioritylist, &err);\n#ifdef USE_GNUTLS_SRP\n }\n#endif\n\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"Error %d setting GnuTLS cipher list starting with %s\",\n rc, err);\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n if(config->clientcert) {\n if(!gtls->shared_creds->trust_setup) {\n result = Curl_gtls_client_trust_setup(cf, data, gtls);\n if(result)\n return result;\n }\n if(ssl_config->key_passwd) {\n const unsigned int supported_key_encryption_algorithms =\n GNUTLS_PKCS_USE_PKCS12_3DES | GNUTLS_PKCS_USE_PKCS12_ARCFOUR |\n GNUTLS_PKCS_USE_PKCS12_RC2_40 | GNUTLS_PKCS_USE_PBES2_3DES |\n GNUTLS_PKCS_USE_PBES2_AES_128 | GNUTLS_PKCS_USE_PBES2_AES_192 |\n GNUTLS_PKCS_USE_PBES2_AES_256;\n rc = gnutls_certificate_set_x509_key_file2(\n gtls->shared_creds->creds,\n config->clientcert,\n ssl_config->key ? ssl_config->key : config->clientcert,\n do_file_type(ssl_config->cert_type),\n ssl_config->key_passwd,\n supported_key_encryption_algorithms);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data,\n \"error reading X.509 potentially-encrypted key file: %s\",\n gnutls_strerror(rc));\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n else {\n if(gnutls_certificate_set_x509_key_file(\n gtls->shared_creds->creds,\n config->clientcert,\n ssl_config->key ? ssl_config->key : config->clientcert,\n do_file_type(ssl_config->cert_type) ) !=\n GNUTLS_E_SUCCESS) {\n failf(data, \"error reading X.509 key or certificate file\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n }\n\n#ifdef USE_GNUTLS_SRP\n /* put the credentials to the current session */\n if(config->username) {\n rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_SRP,\n gtls->srp_client_cred);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_credentials_set() failed: %s\", gnutls_strerror(rc));\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n else\n#endif\n {\n rc = gnutls_credentials_set(gtls->session, GNUTLS_CRD_CERTIFICATE,\n gtls->shared_creds->creds);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_credentials_set() failed: %s\", gnutls_strerror(rc));\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n if(config->verifystatus) {\n rc = gnutls_ocsp_status_request_enable_client(gtls->session,\n NULL, 0, NULL);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_ocsp_status_request_enable_client() failed: %d\", rc);\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n return CURLE_OK;\n}\n\nstatic int keylog_callback(gnutls_session_t session, const char *label,\n const gnutls_datum_t *secret)\n{\n gnutls_datum_t crandom;\n gnutls_datum_t srandom;\n\n gnutls_session_get_random(session, &crandom, &srandom);\n if(crandom.size != 32) {\n return -1;\n }\n\n Curl_tls_keylog_write(label, crandom.data, secret->data, secret->size);\n return 0;\n}\n\nCURLcode Curl_gtls_ctx_init(struct gtls_ctx *gctx,\n struct Curl_cfilter *cf,\n struct Curl_easy *data,\n struct ssl_peer *peer,\n const unsigned char *alpn, size_t alpn_len,\n Curl_gtls_ctx_setup_cb *cb_setup,\n void *cb_user_data,\n void *ssl_user_data)\n{\n struct ssl_primary_config *conn_config = Curl_ssl_cf_get_primary_config(cf);\n CURLcode result;\n\n DEBUGASSERT(gctx);\n\n result = gtls_client_init(cf, data, peer, gctx);\n if(result)\n return result;\n\n gnutls_session_set_ptr(gctx->session, ssl_user_data);\n\n if(cb_setup) {\n result = cb_setup(cf, data, cb_user_data);\n if(result)\n return result;\n }\n\n /* Open the file if a TLS or QUIC backend has not done this before. */\n Curl_tls_keylog_open();\n if(Curl_tls_keylog_enabled()) {\n gnutls_session_set_keylog_function(gctx->session, keylog_callback);\n }\n\n /* convert the ALPN string from our arguments to a list of strings\n * that gnutls wants and will convert internally back to this very\n * string for sending to the server. nice. */\n if(alpn && alpn_len) {\n gnutls_datum_t alpns[5];\n size_t i, alen = alpn_len;\n unsigned char *s = (unsigned char *)alpn;\n unsigned char slen;\n for(i = 0; (i < ARRAYSIZE(alpns)) && alen; ++i) {\n slen = s[0];\n if(slen >= alen)\n return CURLE_FAILED_INIT;\n alpns[i].data = s + 1;\n alpns[i].size = slen;\n s += slen + 1;\n alen -= (size_t)slen + 1;\n }\n if(alen) /* not all alpn chars used, wrong format or too many */\n return CURLE_FAILED_INIT;\n if(i && gnutls_alpn_set_protocols(gctx->session,\n alpns, (unsigned int)i,\n GNUTLS_ALPN_MANDATORY)) {\n failf(data, \"failed setting ALPN\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n /* This might be a reconnect, so we check for a session ID in the cache\n to speed up things */\n if(conn_config->cache_session) {\n void *ssl_sessionid;\n size_t ssl_idsize;\n\n Curl_ssl_sessionid_lock(data);\n if(!Curl_ssl_getsessionid(cf, data, peer, &ssl_sessionid, &ssl_idsize)) {\n /* we got a session id, use it! */\n int rc;\n\n rc = gnutls_session_set_data(gctx->session, ssl_sessionid, ssl_idsize);\n if(rc < 0)\n infof(data, \"SSL failed to set session ID\");\n else\n infof(data, \"SSL reusing session ID (size=%zu)\", ssl_idsize);\n }\n Curl_ssl_sessionid_unlock(data);\n }\n return CURLE_OK;\n}\n\nstatic CURLcode\ngtls_connect_step1(struct Curl_cfilter *cf, struct Curl_easy *data)\n{\n struct ssl_connect_data *connssl = cf->ctx;\n struct gtls_ssl_backend_data *backend =\n (struct gtls_ssl_backend_data *)connssl->backend;\n struct alpn_proto_buf proto;\n CURLcode result;\n\n DEBUGASSERT(backend);\n DEBUGASSERT(ssl_connect_1 == connssl->connecting_state);\n\n if(connssl->state == ssl_connection_complete)\n /* to make us tolerant against being called more than once for the\n same connection */\n return CURLE_OK;\n\n memset(&proto, 0, sizeof(proto));\n if(connssl->alpn) {\n result = Curl_alpn_to_proto_buf(&proto, connssl->alpn);\n if(result) {\n failf(data, \"Error determining ALPN\");\n return CURLE_SSL_CONNECT_ERROR;\n }\n }\n\n result = Curl_gtls_ctx_init(&backend->gtls, cf, data, &connssl->peer,\n proto.data, proto.len, NULL, NULL, cf);\n if(result)\n return result;\n\n gnutls_handshake_set_hook_function(backend->gtls.session,\n GNUTLS_HANDSHAKE_ANY, GNUTLS_HOOK_POST,\n gtls_handshake_cb);\n\n /* register callback functions and handle to send and receive data. */\n gnutls_transport_set_ptr(backend->gtls.session, cf);\n gnutls_transport_set_push_function(backend->gtls.session, gtls_push);\n gnutls_transport_set_pull_function(backend->gtls.session, gtls_pull);\n\n return CURLE_OK;\n}\n\nstatic CURLcode pkp_pin_peer_pubkey(struct Curl_easy *data,\n gnutls_x509_crt_t cert,\n const char *pinnedpubkey)\n{\n /* Scratch */\n size_t len1 = 0, len2 = 0;\n unsigned char *buff1 = NULL;\n\n gnutls_pubkey_t key = NULL;\n\n /* Result is returned to caller */\n CURLcode result = CURLE_SSL_PINNEDPUBKEYNOTMATCH;\n\n /* if a path was not specified, do not pin */\n if(!pinnedpubkey)\n return CURLE_OK;\n\n if(!cert)\n return result;\n\n do {\n int ret;\n\n /* Begin Gyrations to get the public key */\n gnutls_pubkey_init(&key);\n\n ret = gnutls_pubkey_import_x509(key, cert, 0);\n if(ret < 0)\n break; /* failed */\n\n ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, NULL, &len1);\n if(ret != GNUTLS_E_SHORT_MEMORY_BUFFER || len1 == 0)\n break; /* failed */\n\n buff1 = malloc(len1);\n if(!buff1)\n break; /* failed */\n\n len2 = len1;\n\n ret = gnutls_pubkey_export(key, GNUTLS_X509_FMT_DER, buff1, &len2);\n if(ret < 0 || len1 != len2)\n break; /* failed */\n\n /* End Gyrations */\n\n /* The one good exit point */\n result = Curl_pin_peer_pubkey(data, pinnedpubkey, buff1, len1);\n } while(0);\n\n if(key)\n gnutls_pubkey_deinit(key);\n\n Curl_safefree(buff1);\n\n return result;\n}\n\nCURLcode\nCurl_gtls_verifyserver(struct Curl_easy *data,\n gnutls_session_t session,\n struct ssl_primary_config *config,\n struct ssl_config_data *ssl_config,\n struct ssl_peer *peer,\n const char *pinned_key)\n{\n unsigned int cert_list_size;\n const gnutls_datum_t *chainp;\n unsigned int verify_status = 0;\n gnutls_x509_crt_t x509_cert, x509_issuer;\n gnutls_datum_t issuerp;\n gnutls_datum_t certfields;\n char certname[65] = \"\"; /* limited to 64 chars by ASN.1 */\n size_t size;\n time_t certclock;\n int rc;\n CURLcode result = CURLE_OK;\n#ifndef CURL_DISABLE_VERBOSE_STRINGS\n const char *ptr;\n int algo;\n unsigned int bits;\n gnutls_protocol_t version = gnutls_protocol_get_version(session);\n#endif\n long * const certverifyresult = &ssl_config->certverifyresult;\n\n#ifndef CURL_DISABLE_VERBOSE_STRINGS\n /* the name of the cipher suite used, e.g. ECDHE_RSA_AES_256_GCM_SHA384. */\n ptr = gnutls_cipher_suite_get_name(gnutls_kx_get(session),\n gnutls_cipher_get(session),\n gnutls_mac_get(session));\n\n infof(data, \"SSL connection using %s / %s\",\n gnutls_protocol_get_name(version), ptr);\n#endif\n\n /* This function will return the peer's raw certificate (chain) as sent by\n the peer. These certificates are in raw format (DER encoded for\n X.509). In case of a X.509 then a certificate list may be present. The\n first certificate in the list is the peer's certificate, following the\n issuer's certificate, then the issuer's issuer etc. */\n\n chainp = gnutls_certificate_get_peers(session, &cert_list_size);\n if(!chainp) {\n if(config->verifypeer ||\n config->verifyhost ||\n config->issuercert) {\n#ifdef USE_GNUTLS_SRP\n if(ssl_config->primary.username && !config->verifypeer &&\n gnutls_cipher_get(session)) {\n /* no peer cert, but auth is ok if we have SRP user and cipher and no\n peer verify */\n }\n else {\n#endif\n failf(data, \"failed to get server cert\");\n *certverifyresult = GNUTLS_E_NO_CERTIFICATE_FOUND;\n return CURLE_PEER_FAILED_VERIFICATION;\n#ifdef USE_GNUTLS_SRP\n }\n#endif\n }\n infof(data, \" common name: WARNING could not obtain\");\n }\n\n if(data->set.ssl.certinfo && chainp) {\n unsigned int i;\n\n result = Curl_ssl_init_certinfo(data, (int)cert_list_size);\n if(result)\n return result;\n\n for(i = 0; i < cert_list_size; i++) {\n const char *beg = (const char *) chainp[i].data;\n const char *end = beg + chainp[i].size;\n\n result = Curl_extract_certinfo(data, (int)i, beg, end);\n if(result)\n return result;\n }\n }\n\n if(config->verifypeer) {\n /* This function will try to verify the peer's certificate and return its\n status (trusted, invalid etc.). The value of status should be one or\n more of the gnutls_certificate_status_t enumerated elements bitwise\n or'd. To avoid denial of service attacks some default upper limits\n regarding the certificate key size and chain size are set. To override\n them use gnutls_certificate_set_verify_limits(). */\n\n rc = gnutls_certificate_verify_peers2(session, &verify_status);\n if(rc < 0) {\n failf(data, \"server cert verify failed: %d\", rc);\n *certverifyresult = rc;\n return CURLE_SSL_CONNECT_ERROR;\n }\n\n *certverifyresult = verify_status;\n\n /* verify_status is a bitmask of gnutls_certificate_status bits */\n if(verify_status & GNUTLS_CERT_INVALID) {\n if(config->verifypeer) {\n failf(data, \"server certificate verification failed. CAfile: %s \"\n \"CRLfile: %s\", config->CAfile ? config->CAfile:\n \"none\",\n ssl_config->primary.CRLfile ?\n ssl_config->primary.CRLfile : \"none\");\n return CURLE_PEER_FAILED_VERIFICATION;\n }\n else\n infof(data, \" server certificate verification FAILED\");\n }\n else\n infof(data, \" server certificate verification OK\");\n }\n else\n infof(data, \" server certificate verification SKIPPED\");\n\n if(config->verifystatus) {\n if(gnutls_ocsp_status_request_is_checked(session, 0) == 0) {\n gnutls_datum_t status_request;\n gnutls_ocsp_resp_t ocsp_resp;\n\n gnutls_ocsp_cert_status_t status;\n gnutls_x509_crl_reason_t reason;\n\n rc = gnutls_ocsp_status_request_get(session, &status_request);\n\n infof(data, \" server certificate status verification FAILED\");\n\n if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {\n failf(data, \"No OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n if(rc < 0) {\n failf(data, \"Invalid OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n gnutls_ocsp_resp_init(&ocsp_resp);\n\n rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request);\n if(rc < 0) {\n failf(data, \"Invalid OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL,\n &status, NULL, NULL, NULL, &reason);\n\n switch(status) {\n case GNUTLS_OCSP_CERT_GOOD:\n break;\n\n case GNUTLS_OCSP_CERT_REVOKED: {\n const char *crl_reason;\n\n switch(reason) {\n default:\n case GNUTLS_X509_CRLREASON_UNSPECIFIED:\n crl_reason = \"unspecified reason\";\n break;\n\n case GNUTLS_X509_CRLREASON_KEYCOMPROMISE:\n crl_reason = \"private key compromised\";\n break;\n\n case GNUTLS_X509_CRLREASON_CACOMPROMISE:\n crl_reason = \"CA compromised\";\n break;\n\n case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED:\n crl_reason = \"affiliation has changed\";\n break;\n\n case GNUTLS_X509_CRLREASON_SUPERSEDED:\n crl_reason = \"certificate superseded\";\n break;\n\n case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION:\n crl_reason = \"operation has ceased\";\n break;\n\n case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD:\n crl_reason = \"certificate is on hold\";\n break;\n\n case GNUTLS_X509_CRLREASON_REMOVEFROMCRL:\n crl_reason = \"will be removed from delta CRL\";\n break;\n\n case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN:\n crl_reason = \"privilege withdrawn\";\n break;\n\n case GNUTLS_X509_CRLREASON_AACOMPROMISE:\n crl_reason = \"AA compromised\";\n break;\n }\n\n failf(data, \"Server certificate was revoked: %s\", crl_reason);\n break;\n }\n\n default:\n case GNUTLS_OCSP_CERT_UNKNOWN:\n failf(data, \"Server certificate status is unknown\");\n break;\n }\n\n gnutls_ocsp_resp_deinit(ocsp_resp);\n\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n else\n infof(data, \" server certificate status verification OK\");\n }\n else\n infof(data, \" server certificate status verification SKIPPED\");\n\n /* initialize an X.509 certificate structure. */\n gnutls_x509_crt_init(&x509_cert);\n\n if(chainp)\n /* convert the given DER or PEM encoded Certificate to the native\n gnutls_x509_crt_t format */\n gnutls_x509_crt_import(x509_cert, chainp, GNUTLS_X509_FMT_DER);\n\n if(config->issuercert) {\n gnutls_x509_crt_init(&x509_issuer);\n issuerp = load_file(config->issuercert);\n gnutls_x509_crt_import(x509_issuer, &issuerp, GNUTLS_X509_FMT_PEM);\n rc = (int)gnutls_x509_crt_check_issuer(x509_cert, x509_issuer);\n gnutls_x509_crt_deinit(x509_issuer);\n unload_file(issuerp);\n if(rc <= 0) {\n failf(data, \"server certificate issuer check failed (IssuerCert: %s)\",\n config->issuercert?config->issuercert:\"none\");\n gnutls_x509_crt_deinit(x509_cert);\n return CURLE_SSL_ISSUER_ERROR;\n }\n infof(data, \" server certificate issuer check OK (Issuer Cert: %s)\",\n config->issuercert?config->issuercert:\"none\");\n }\n\n size = sizeof(certname);\n rc = gnutls_x509_crt_get_dn_by_oid(x509_cert, GNUTLS_OID_X520_COMMON_NAME,\n 0, /* the first and only one */\n FALSE,\n certname,\n &size);\n if(rc) {\n infof(data, \"error fetching CN from cert:%s\",\n gnutls_strerror(rc));\n }\n\n /* This function will check if the given certificate's subject matches the\n given hostname. This is a basic implementation of the matching described\n in RFC2818 (HTTPS), which takes into account wildcards, and the subject\n alternative name PKIX extension. Returns non zero on success, and zero on\n failure. */\n\n /* This function does not handle trailing dots, so if we have an SNI name\n use that and fallback to the hostname only if there is no SNI (like for\n IP addresses) */\n rc = (int)gnutls_x509_crt_check_hostname(x509_cert,\n peer->sni ? peer->sni :\n peer->hostname);\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n init_flags |= GNUTLS_NO_TICKETS;\n#endif\n\n rc = gnutls_init(&gtls->session, init_flags);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_init() failed: %d\", rc);\n=======\n init_flags |= GNUTLS_NO_TICKETS;\n#endif\n\n#if defined(GNUTLS_NO_STATUS_REQUEST)\n if(!config->verifystatus)\n /* Disable the \"status_request\" TLS extension, enabled by default since\n GnuTLS 3.8.0. */\n init_flags |= GNUTLS_NO_STATUS_REQUEST;\n#endif\n\n rc = gnutls_init(&gtls->session, init_flags);\n if(rc != GNUTLS_E_SUCCESS) {\n failf(data, \"gnutls_init() failed: %d\", rc);\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n infof(data, \" server certificate verification SKIPPED\");\n\n if(config->verifystatus) {\n if(gnutls_ocsp_status_request_is_checked(session, 0) == 0) {\n gnutls_datum_t status_request;\n gnutls_ocsp_resp_t ocsp_resp;\n\n gnutls_ocsp_cert_status_t status;\n gnutls_x509_crl_reason_t reason;\n\n rc = gnutls_ocsp_status_request_get(session, &status_request);\n\n infof(data, \" server certificate status verification FAILED\");\n\n if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {\n failf(data, \"No OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n if(rc < 0) {\n failf(data, \"Invalid OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n gnutls_ocsp_resp_init(&ocsp_resp);\n\n rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request);\n if(rc < 0) {\n failf(data, \"Invalid OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL,\n &status, NULL, NULL, NULL, &reason);\n\n switch(status) {\n case GNUTLS_OCSP_CERT_GOOD:\n break;\n\n case GNUTLS_OCSP_CERT_REVOKED: {\n const char *crl_reason;\n\n switch(reason) {\n default:\n case GNUTLS_X509_CRLREASON_UNSPECIFIED:\n crl_reason = \"unspecified reason\";\n break;\n\n case GNUTLS_X509_CRLREASON_KEYCOMPROMISE:\n crl_reason = \"private key compromised\";\n break;\n\n case GNUTLS_X509_CRLREASON_CACOMPROMISE:\n crl_reason = \"CA compromised\";\n break;\n\n case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED:\n crl_reason = \"affiliation has changed\";\n break;\n\n case GNUTLS_X509_CRLREASON_SUPERSEDED:\n crl_reason = \"certificate superseded\";\n break;\n\n case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION:\n crl_reason = \"operation has ceased\";\n break;\n\n case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD:\n crl_reason = \"certificate is on hold\";\n break;\n\n case GNUTLS_X509_CRLREASON_REMOVEFROMCRL:\n crl_reason = \"will be removed from delta CRL\";\n break;\n\n case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN:\n crl_reason = \"privilege withdrawn\";\n break;\n\n case GNUTLS_X509_CRLREASON_AACOMPROMISE:\n crl_reason = \"AA compromised\";\n break;\n }\n\n failf(data, \"Server certificate was revoked: %s\", crl_reason);\n break;\n }\n\n default:\n case GNUTLS_OCSP_CERT_UNKNOWN:\n failf(data, \"Server certificate status is unknown\");\n break;\n }\n\n gnutls_ocsp_resp_deinit(ocsp_resp);\n\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n else\n infof(data, \" server certificate status verification OK\");\n }\n else\n infof(data, \" server certificate status verification SKIPPED\");\n=======\n infof(data, \" server certificate verification SKIPPED\");\n\n if(config->verifystatus) {\n gnutls_datum_t status_request;\n gnutls_ocsp_resp_t ocsp_resp;\n gnutls_ocsp_cert_status_t status;\n gnutls_x509_crl_reason_t reason;\n\n rc = gnutls_ocsp_status_request_get(session, &status_request);\n\n if(rc == GNUTLS_E_REQUESTED_DATA_NOT_AVAILABLE) {\n failf(data, \"No OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n if(rc < 0) {\n failf(data, \"Invalid OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n gnutls_ocsp_resp_init(&ocsp_resp);\n\n rc = gnutls_ocsp_resp_import(ocsp_resp, &status_request);\n if(rc < 0) {\n failf(data, \"Invalid OCSP response received\");\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n\n (void)gnutls_ocsp_resp_get_single(ocsp_resp, 0, NULL, NULL, NULL, NULL,\n &status, NULL, NULL, NULL, &reason);\n\n switch(status) {\n case GNUTLS_OCSP_CERT_GOOD:\n break;\n\n case GNUTLS_OCSP_CERT_REVOKED: {\n const char *crl_reason;\n\n switch(reason) {\n default:\n case GNUTLS_X509_CRLREASON_UNSPECIFIED:\n crl_reason = \"unspecified reason\";\n break;\n\n case GNUTLS_X509_CRLREASON_KEYCOMPROMISE:\n crl_reason = \"private key compromised\";\n break;\n\n case GNUTLS_X509_CRLREASON_CACOMPROMISE:\n crl_reason = \"CA compromised\";\n break;\n\n case GNUTLS_X509_CRLREASON_AFFILIATIONCHANGED:\n crl_reason = \"affiliation has changed\";\n break;\n\n case GNUTLS_X509_CRLREASON_SUPERSEDED:\n crl_reason = \"certificate superseded\";\n break;\n\n case GNUTLS_X509_CRLREASON_CESSATIONOFOPERATION:\n crl_reason = \"operation has ceased\";\n break;\n\n case GNUTLS_X509_CRLREASON_CERTIFICATEHOLD:\n crl_reason = \"certificate is on hold\";\n break;\n\n case GNUTLS_X509_CRLREASON_REMOVEFROMCRL:\n crl_reason = \"will be removed from delta CRL\";\n break;\n\n case GNUTLS_X509_CRLREASON_PRIVILEGEWITHDRAWN:\n crl_reason = \"privilege withdrawn\";\n break;\n\n case GNUTLS_X509_CRLREASON_AACOMPROMISE:\n crl_reason = \"AA compromised\";\n break;\n }\n\n failf(data, \"Server certificate was revoked: %s\", crl_reason);\n break;\n }\n\n default:\n case GNUTLS_OCSP_CERT_UNKNOWN:\n failf(data, \"Server certificate status is unknown\");\n break;\n }\n\n gnutls_ocsp_resp_deinit(ocsp_resp);\n if(status != GNUTLS_OCSP_CERT_GOOD)\n return CURLE_SSL_INVALIDCERTSTATUS;\n }\n else\n infof(data, \" server certificate status verification SKIPPED\");\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-0622: GRUB2 through version 2.12 performs string copy operations without enforcing destination buffer size limits, allowing unchecked overflows when processing crafted inputs during boot configuration parsing or device path handling. Multiple functions in the grub utility library lack bounds checking on string copies, which can lead to heap buffer overflows and potential execution of arbitrary code during system boot when processing malicious configuration data.\n\n# Vulnerable source (include/grub/misc.h)\n```c\n#include <grub/types.h>\n#include <grub/symbol.h>\n#include <grub/err.h>\n#include <grub/i18n.h>\n#include <grub/compiler.h>\n\n#define ALIGN_UP(addr, align) \\\n\t(((addr) + (typeof (addr)) (align) - 1) & ~((typeof (addr)) (align) - 1))\n#define ALIGN_UP_OVERHEAD(addr, align) ((-(addr)) & ((typeof (addr)) (align) - 1))\n#define ALIGN_DOWN(addr, align) \\\n\t((addr) & ~((typeof (addr)) (align) - 1))\n#define ARRAY_SIZE(array) (sizeof (array) / sizeof (array[0]))\n#define COMPILE_TIME_ASSERT(cond) switch (0) { case 1: case !(cond): ; }\n\n#define grub_dprintf(condition, ...) grub_real_dprintf(GRUB_FILE, __LINE__, condition, __VA_ARGS__)\n\nvoid *EXPORT_FUNC(grub_memmove) (void *dest, const void *src, grub_size_t n);\nchar *EXPORT_FUNC(grub_strcpy) (char *dest, const char *src);\n\nstatic inline char *\ngrub_strncpy (char *dest, const char *src, int c)\n{\n char *p = dest;\n\n while ((*p++ = *src++) != '\\0' && --c)\n ;\n\n return dest;\n}\n\nstatic inline char *\ngrub_stpcpy (char *dest, const char *src)\n{\n char *d = dest;\n const char *s = src;\n\n do\n *d++ = *s;\n while (*s++ != '\\0');\n\n return d - 1;\n}\n\n/* XXX: If grub_memmove is too slow, we must implement grub_memcpy. */\nstatic inline void *\ngrub_memcpy (void *dest, const void *src, grub_size_t n)\n{\n return grub_memmove (dest, src, n);\n}\n\n#if defined(__x86_64__) && !defined (GRUB_UTIL)\n#if defined (__MINGW32__) || defined (__CYGWIN__) || defined (__MINGW64__)\n#define GRUB_ASM_ATTR __attribute__ ((sysv_abi))\n#else\n#define GRUB_ASM_ATTR\n#endif\n#endif\n\nint EXPORT_FUNC(grub_memcmp) (const void *s1, const void *s2, grub_size_t n);\nint EXPORT_FUNC(grub_strcmp) (const char *s1, const char *s2);\nint EXPORT_FUNC(grub_strncmp) (const char *s1, const char *s2, grub_size_t n);\n\nchar *EXPORT_FUNC(grub_strchr) (const char *s, int c);\nchar *EXPORT_FUNC(grub_strrchr) (const char *s, int c);\nint EXPORT_FUNC(grub_strword) (const char *s, const char *w);\n\n/* Copied from gnulib.\n Written by Bruno Haible <bruno@clisp.org>, 2005. */\nstatic inline char *\ngrub_strstr (const char *haystack, const char *needle)\n{\n /* Be careful not to look at the entire extent of haystack or needle\n until needed. This is useful because of these two cases:\n - haystack may be very long, and a match of needle found early,\n - needle may be very long, and not even a short initial segment of\n needle may be found in haystack. */\n if (*needle != '\\0')\n {\n /* Speed up the following searches of needle by caching its first\n\t character. */\n char b = *needle++;\n\n for (;; haystack++)\n\t{\n\t if (*haystack == '\\0')\n\t /* No match. */\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n return d - 1;\n}\n\n/* XXX: If grub_memmove is too slow, we must implement grub_memcpy. */\nstatic inline void *\ngrub_memcpy (void *dest, const void *src, grub_size_t n)\n=======\n return d - 1;\n}\n\nstatic inline grub_size_t\ngrub_strlcpy (char *dest, const char *src, grub_size_t size)\n{\n char *d = dest;\n grub_size_t res = 0;\n /*\n * We do not subtract one from size here to avoid dealing with underflowing\n * the value, which is why to_copy is always checked to be greater than one\n * throughout this function.\n */\n grub_size_t to_copy = size;\n\n /* Copy size - 1 bytes to dest. */\n if (to_copy > 1)\n while ((*d++ = *src++) != '\\0' && ++res && --to_copy > 1)\n ;\n\n /*\n * NUL terminate if size != 0. The previous step may have copied a NUL byte\n * if it reached the end of the string, but we know dest[size - 1] must always\n * be a NUL byte.\n */\n if (size != 0)\n dest[size - 1] = '\\0';\n\n /* If there is still space in dest, but are here, we reached the end of src. */\n if (to_copy > 1)\n return res;\n\n /*\n * If we haven't reached the end of the string, iterate through to determine\n * the strings total length.\n */\n while (*src++ != '\\0' && ++res)\n ;\n\n return res;\n}\n\n/* XXX: If grub_memmove is too slow, we must implement grub_memcpy. */\nstatic inline void *\ngrub_memcpy (void *dest, const void *src, grub_size_t n)\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-0938: Host-parsing confusion (CWE-20 improper input validation) in CPython's urllib.parse. nixpkgs ships an affected python3 (3.11.x).\n\n# Vulnerable source (Lib/urllib/parse.py)\n```python\n if wdelim >= 0: # if found\n delim = min(delim, wdelim) # use earliest delim position\n return url[start:delim], url[delim:] # return (domain, rest)\n\ndef _checknetloc(netloc):\n if not netloc or netloc.isascii():\n return\n # looking for characters like \\u2100 that expand to 'a/c'\n # IDNA uses NFKC equivalence, so normalize for this check\n import unicodedata\n n = netloc.replace('@', '') # ignore characters already included\n n = n.replace(':', '') # but not the surrounding text\n n = n.replace('#', '')\n n = n.replace('?', '')\n netloc2 = unicodedata.normalize('NFKC', n)\n if n == netloc2:\n return\n for c in '/?#@:':\n if c in netloc2:\n raise ValueError(\"netloc '\" + netloc + \"' contains invalid \" +\n \"characters under NFKC normalization\")\n\n# Valid bracketed hosts are defined in\n# https://www.rfc-editor.org/rfc/rfc3986#page-49 and https://url.spec.whatwg.org/\ndef _check_bracketed_host(hostname):\n if hostname.startswith('v'):\n if not re.match(r\"\\Av[a-fA-F0-9]+\\..+\\Z\", hostname):\n raise ValueError(f\"IPvFuture address is invalid\")\n else:\n ip = ipaddress.ip_address(hostname) # Throws Value Error if not IPv6 or IPv4\n if isinstance(ip, ipaddress.IPv4Address):\n raise ValueError(f\"An IPv4 address cannot be in brackets\")\n\n# typed=True avoids BytesWarnings being emitted during cache key\n# comparison since this API supports both bytes and str input.\n@functools.lru_cache(typed=True)\ndef urlsplit(url, scheme='', allow_fragments=True):\n \"\"\"Parse a URL into 5 components:\n <scheme>://<netloc>/<path>?<query>#<fragment>\n\n /* ... */\n for b in _UNSAFE_URL_BYTES_TO_REMOVE:\n url = url.replace(b, \"\")\n if scheme is not None:\n scheme = scheme.strip(_WHATWG_C0_CONTROL_OR_SPACE)\n for b in _UNSAFE_URL_BYTES_TO_REMOVE:\n scheme = scheme.replace(b, \"\")\n\n allow_fragments = bool(allow_fragments)\n netloc = query = fragment = None\n i = url.find(':')\n if i > 0 and url[0].isascii() and url[0].isalpha():\n for c in url[:i]:\n if c not in scheme_chars:\n break\n else:\n scheme, url = url[:i].lower(), url[i+1:]\n if url[:2] == '//':\n netloc, url = _splitnetloc(url, 2)\n if (('[' in netloc and ']' not in netloc) or\n (']' in netloc and '[' not in netloc)):\n raise ValueError(\"Invalid IPv6 URL\")\n if '[' in netloc and ']' in netloc:\n bracketed_host = netloc.partition('[')[2].partition(']')[0]\n _check_bracketed_host(bracketed_host)\n if allow_fragments and '#' in url:\n url, fragment = url.split('#', 1)\n if '?' in url:\n url, query = url.split('?', 1)\n _checknetloc(netloc)\n return (scheme, netloc, url, query, fragment)\n\ndef urlunparse(components):\n \"\"\"Put a parsed URL back together again. This may result in a\n slightly different, but equivalent URL, if the URL that was parsed\n originally had redundant delimiters, e.g. a ? with an empty query\n (the draft states that these are equivalent).\"\"\"\n scheme, netloc, url, params, query, fragment, _coerce_result = (\n _coerce_args(*components))\n if not netloc:\n if scheme and scheme in uses_netloc and (not url or url[:1] == '/'):\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n raise ValueError(\"netloc '\" + netloc + \"' contains invalid \" +\n \"characters under NFKC normalization\")\n\n# Valid bracketed hosts are defined in\n# https://www.rfc-editor.org/rfc/rfc3986#page-49 and https://url.spec.whatwg.org/\ndef _check_bracketed_host(hostname):\n=======\n raise ValueError(\"netloc '\" + netloc + \"' contains invalid \" +\n \"characters under NFKC normalization\")\n\ndef _check_bracketed_netloc(netloc):\n # Note that this function must mirror the splitting\n # done in NetlocResultMixins._hostinfo().\n hostname_and_port = netloc.rpartition('@')[2]\n before_bracket, have_open_br, bracketed = hostname_and_port.partition('[')\n if have_open_br:\n # No data is allowed before a bracket.\n if before_bracket:\n raise ValueError(\"Invalid IPv6 URL\")\n hostname, _, port = bracketed.partition(']')\n # No data is allowed after the bracket but before the port delimiter.\n if port and not port.startswith(\":\"):\n raise ValueError(\"Invalid IPv6 URL\")\n else:\n hostname, _, port = hostname_and_port.partition(':')\n _check_bracketed_host(hostname)\n\n# Valid bracketed hosts are defined in\n# https://www.rfc-editor.org/rfc/rfc3986#page-49 and https://url.spec.whatwg.org/\ndef _check_bracketed_host(hostname):\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n (']' in netloc and '[' not in netloc)):\n raise ValueError(\"Invalid IPv6 URL\")\n if '[' in netloc and ']' in netloc:\n bracketed_host = netloc.partition('[')[2].partition(']')[0]\n _check_bracketed_host(bracketed_host)\n if allow_fragments and '#' in url:\n url, fragment = url.split('#', 1)\n if '?' in url:\n=======\n (']' in netloc and '[' not in netloc)):\n raise ValueError(\"Invalid IPv6 URL\")\n if '[' in netloc and ']' in netloc:\n _check_bracketed_netloc(netloc)\n if allow_fragments and '#' in url:\n url, fragment = url.split('#', 1)\n if '?' in url:\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-10911: This allows an attacker to trigger use-after-free via a crafted XSL stylesheet that causes expired pointers to be dereferenced.\n\n# Vulnerable source (libxslt/xsltInternals.h)\n```c\n const xmlChar *stype; /* sort */\n int has_stype;\t\t/* sort */\n int number;\t\t/* sort */\n const xmlChar *order;\t/* sort */\n int has_order;\t\t/* sort */\n int descending;\t/* sort */\n const xmlChar *lang;\t/* sort */\n int has_lang;\t\t/* sort */\n const xmlChar *case_order;\t/* sort */\n int lower_first;\t/* sort */\n\n const xmlChar *use;\t\t/* copy, element */\n int has_use;\t\t/* copy, element */\n\n int noescape;\t\t/* text */\n\n const xmlChar *name;\t/* element, attribute, pi */\n int has_name;\t\t/* element, attribute, pi */\n const xmlChar *ns;\t\t/* element */\n int has_ns;\t\t/* element */\n\n const xmlChar *mode;\t/* apply-templates */\n const xmlChar *modeURI;\t/* apply-templates */\n\n const xmlChar *test;\t/* if */\n\n xsltTemplatePtr templ;\t/* call-template */\n\n const xmlChar *select;\t/* sort, copy-of, value-of, apply-templates */\n\n int ver11;\t\t/* document */\n const xmlChar *filename;\t/* document URL */\n int has_filename;\t/* document */\n\n xsltNumberData numdata;\t/* number */\n\n xmlXPathCompExprPtr comp;\t/* a precompiled XPath expression */\n xmlNsPtr *nsList;\t\t/* the namespaces in scope */\n int nsNr;\t\t\t/* the number of namespaces in scope */\n};\n\n#endif /* XSLT_REFACTORED */\n\n\n/*\n * The in-memory structure corresponding to an XSLT Variable\n * or Param.\n */\ntypedef struct _xsltStackElem xsltStackElem;\ntypedef xsltStackElem *xsltStackElemPtr;\nstruct _xsltStackElem {\n struct _xsltStackElem *next;/* chained list */\n xsltStylePreCompPtr comp; /* the compiled form */\n int computed;\t\t/* was the evaluation done */\n const xmlChar *name;\t/* the local part of the name QName */\n const xmlChar *nameURI;\t/* the URI part of the name QName */\n const xmlChar *select;\t/* the eval string */\n xmlNodePtr tree;\t\t/* the sequence constructor if no eval\n\t\t\t\t string or the location */\n xmlXPathObjectPtr value;\t/* The value if computed */\n xmlDocPtr fragment;\t\t/* The Result Tree Fragments (needed for XSLT 1.0)\n\t\t\t\t which are bound to the variable's lifetime. */\n int level; /* the depth in the tree;\n -1 if persistent (e.g. a given xsl:with-param) */\n xsltTransformContextPtr context; /* The transformation context; needed to cache\n the variables */\n int flags;\n};\n\n#ifdef XSLT_REFACTORED\n\nstruct _xsltPrincipalStylesheetData {\n /*\n * Namespace dictionary for ns-prefixes and ns-names:\n * TODO: Shared between stylesheets, and XPath mechanisms.\n * Not used yet.\n */\n xmlDictPtr namespaceDict;\n /*\n * Global list of in-scope namespaces.\n */\n xsltPointerListPtr inScopeNamespaces;\n /*\n * Global list of information for [xsl:]excluded-result-prefixes.\n */\n xsltPointerListPtr exclResultNamespaces;\n /*\n * Global list of information for [xsl:]extension-element-prefixes.\n */\n xsltPointerListPtr extElemNamespaces;\n xsltEffectiveNsPtr effectiveNs;\n#ifdef XSLT_REFACTORED_XSLT_NSCOMP\n /*\n * Namespace name map to get rid of string comparison of namespace names.\n */\n xsltNsMapPtr nsMap;\n#endif\n};\n\n\n#endif\n/*\n * Note that we added a @compCtxt field to anchor an stylesheet compilation\n * context, since, due to historical reasons, various compile-time function\n * take only the stylesheet as argument and not a compilation context.\n */\nstruct _xsltStylesheet {\n /*\n * The stylesheet import relation is kept as a tree.\n */\n struct _xsltStylesheet *parent;\n struct _xsltStylesheet *next;\n struct _xsltStylesheet *imports;\n\n xsltDocumentPtr docList;\t\t/* the include document list */\n\n /*\n * General data on the style sheet document.\n */\n xmlDocPtr doc;\t\t/* the parsed XML stylesheet */\n xmlHashTablePtr stripSpaces;/* the hash table of the strip-space and\n\t\t\t\t preserve space elements */\n int stripAll;\t/* strip-space * (1) preserve-space * (-1) */\n xmlHashTablePtr cdataSection;/* the hash table of the cdata-section */\n\n /*\n * Global variable or parameters.\n */\n xsltStackElemPtr variables; /* linked list of param and variables */\n\n /*\n * Template descriptions.\n */\n xsltTemplatePtr templates; /* the ordered list of templates */\n xmlHashTablePtr templatesHash; /* hash table or wherever compiled\n templates information is stored */\n struct _xsltCompMatch *rootMatch; /* template based on / */\n struct _xsltCompMatch *keyMatch; /* template based on key() */\n struct _xsltCompMatch *elemMatch; /* template based on * */\n struct _xsltCompMatch *attrMatch; /* template based on @* */\n struct _xsltCompMatch *parentMatch; /* template based on .. */\n struct _xsltCompMatch *textMatch; /* template based on text() */\n struct _xsltCompMatch *piMatch; /* template based on\n processing-instruction() */\n struct _xsltCompMatch *commentMatch; /* template based on comment() */\n\n /*\n * Namespace aliases.\n * NOTE: Not used in the refactored code.\n */\n xmlHashTablePtr nsAliases;\t/* the namespace alias hash tables */\n\n /*\n * Attribute sets.\n */\n xmlHashTablePtr attributeSets;/* the attribute sets hash tables */\n\n /*\n * Namespaces.\n * TODO: Eliminate this.\n */\n xmlHashTablePtr nsHash; /* the set of namespaces in use:\n ATTENTION: This is used for\n execution of XPath expressions; unfortunately\n it restricts the stylesheet to have distinct\n prefixes.\n\t\t\t\t TODO: We need to get rid of this.\n\t\t\t\t */\n void *nsDefs; /* ATTENTION TODO: This is currently used to store\n\t\t\t\t xsltExtDefPtr (in extensions.c) and\n *not* xmlNsPtr.\n\t\t\t\t */\n\n /*\n * Key definitions.\n */\n void *keys;\t\t\t/* key definitions */\n\n /*\n * Output related stuff.\n */\n xmlChar *method;\t\t/* the output method */\n xmlChar *methodURI;\t\t/* associated namespace if any */\n xmlChar *version;\t\t/* version string */\n xmlChar *encoding;\t\t/* encoding string */\n int omitXmlDeclaration; /* omit-xml-declaration = \"yes\" | \"no\" */\n\n /*\n * Number formatting.\n */\n xsltDecimalFormatPtr decimalFormat;\n int standalone; /* standalone = \"yes\" | \"no\" */\n xmlChar *doctypePublic; /* doctype-public string */\n xmlChar *doctypeSystem; /* doctype-system string */\n int indent;\t\t\t/* should output being indented */\n xmlChar *mediaType;\t\t/* media-type string */\n\n /*\n * Precomputed blocks.\n */\n xsltElemPreCompPtr preComps;/* list of precomputed blocks */\n int warnings;\t\t/* number of warnings found at compilation */\n int errors;\t\t\t/* number of errors found at compilation */\n\n xmlChar *exclPrefix;\t/* last excluded prefixes */\n xmlChar **exclPrefixTab;\t/* array of excluded prefixes */\n int exclPrefixNr;\t/* number of excluded prefixes in scope */\n int exclPrefixMax;\t/* size of the array */\n\n void *_private;\t\t/* user defined data */\n\n /*\n * Extensions.\n */\n xmlHashTablePtr extInfos;\t/* the extension data */\n int\t\t extrasNr;\t/* the number of extras required */\n\n /*\n * For keeping track of nested includes\n */\n xsltDocumentPtr includes;\t/* points to last nested include */\n\n /*\n * dictionary: shared between stylesheet, context and documents.\n */\n xmlDictPtr dict;\n /*\n * precompiled attribute value templates.\n */\n void *attVTs;\n /*\n * if namespace-alias has an alias for the default stylesheet prefix\n * NOTE: Not used in the refactored code.\n */\n const xmlChar *defaultAlias;\n /*\n * bypass pre-processing (already done) (used in imports)\n */\n int nopreproc;\n /*\n * all document text strings were internalized\n */\n int internalized;\n /*\n * Literal Result Element as Stylesheet c.f. section 2.3\n */\n int literal_result;\n /*\n * The principal stylesheet\n */\n xsltStylesheetPtr principal;\n#ifdef XSLT_REFACTORED\n /*\n * Compilation context used during compile-time.\n */\n xsltCompilerCtxtPtr compCtxt; /* TODO: Change this to (void *). */\n\n xsltPrincipalStylesheetDataPtr principalData;\n#endif\n /*\n * Forwards-compatible processing\n */\n int forwards_compatible;\n\n xmlHashTablePtr namedTemplates; /* hash table of named templates */\n\n xmlXPathContextPtr xpathCtxt;\n\n unsigned long opLimit;\n unsigned long opCount;\n};\n\ntypedef struct _xsltTransformCache xsltTransformCache;\ntypedef xsltTransformCache *xsltTransformCachePtr;\nstruct _xsltTransformCache {\n xmlDocPtr RVT;\n int nbRVT;\n xsltStackElemPtr stackItems;\n int nbStackItems;\n#ifdef XSLT_DEBUG_PROFILE_CACHE\n int dbgCachedRVTs;\n int dbgReusedRVTs;\n int dbgCachedVars;\n int dbgReusedVars;\n#endif\n};\n\n/*\n * The in-memory structure corresponding to an XSLT Transformation.\n */\ntypedef enum {\n XSLT_OUTPUT_XML = 0,\n XSLT_OUTPUT_HTML,\n XSLT_OUTPUT_TEXT\n} xsltOutputType;\n\ntypedef void *\n(*xsltNewLocaleFunc)(const xmlChar *lang, int lowerFirst);\ntypedef void\n(*xsltFreeLocaleFunc)(void *locale);\ntypedef xmlChar *\n(*xsltGenSortKeyFunc)(void *locale, const xmlChar *lang);\n\ntypedef enum {\n XSLT_STATE_OK = 0,\n XSLT_STATE_ERROR,\n XSLT_STATE_STOPPED\n} xsltTransformState;\n\nstruct _xsltTransformContext {\n xsltStylesheetPtr style;\t\t/* the stylesheet used */\n xsltOutputType type;\t\t/* the type of output */\n\n xsltTemplatePtr templ;\t\t/* the current template */\n int templNr;\t\t/* Nb of templates in the stack */\n int templMax;\t\t/* Size of the templtes stack */\n xsltTemplatePtr *templTab;\t\t/* the template stack */\n\n xsltStackElemPtr vars;\t\t/* the current variable list */\n int varsNr;\t\t/* Nb of variable list in the stack */\n int varsMax;\t\t/* Size of the variable list stack */\n xsltStackElemPtr *varsTab;\t\t/* the variable list stack */\n int varsBase;\t\t/* the var base for current templ */\n\n /*\n * Extensions\n */\n xmlHashTablePtr extFunctions;\t/* the extension functions */\n xmlHashTablePtr extElements;\t/* the extension elements */\n xmlHashTablePtr extInfos;\t\t/* the extension data */\n\n const xmlChar *mode;\t\t/* the current mode */\n const xmlChar *modeURI;\t\t/* the current mode URI */\n\n xsltDocumentPtr docList;\t\t/* the document list */\n\n xsltDocumentPtr document;\t\t/* the current source document; can be NULL if an RTF */\n xmlNodePtr node;\t\t\t/* the current node being processed */\n xmlNodeSetPtr nodeList;\t\t/* the current node list */\n /* xmlNodePtr current;\t\t\tthe node */\n\n xmlDocPtr output;\t\t\t/* the resulting document */\n xmlNodePtr insert;\t\t\t/* the insertion node */\n\n xmlXPathContextPtr xpathCtxt;\t/* the XPath context */\n xsltTransformState state;\t\t/* the current state */\n\n /*\n * Global variables\n */\n xmlHashTablePtr globalVars;\t/* the global variables and params */\n\n xmlNodePtr inst;\t\t\t/* the instruction in the stylesheet */\n\n int xinclude;\t\t\t/* should XInclude be processed */\n\n const char * outputFile;\t/* the output URI if known */\n\n int profile; /* is this run profiled */\n long prof;\t\t/* the current profiled value */\n int profNr;\t\t/* Nb of templates in the stack */\n int profMax;\t\t/* Size of the templtaes stack */\n long *profTab;\t\t/* the profile template stack */\n\n void *_private;\t\t/* user defined data */\n\n int extrasNr;\t\t/* the number of extras used */\n int extrasMax;\t\t/* the number of extras allocated */\n xsltRuntimeExtraPtr extras;\t\t/* extra per runtime information */\n\n xsltDocumentPtr styleList;\t\t/* the stylesheet docs list */\n void * sec;\t\t/* the security preferences if any */\n\n xmlGenericErrorFunc error;\t\t/* a specific error handler */\n void * errctx;\t\t/* context for the error handler */\n\n xsltSortFunc sortfunc;\t\t/* a ctxt specific sort routine */\n\n /*\n * handling of temporary Result Value Tree\n * (XSLT 1.0 term: \"Result Tree Fragment\")\n */\n xmlDocPtr tmpRVT;\t\t/* list of RVT without persistance */\n xmlDocPtr persistRVT;\t\t/* list of persistant RVTs */\n int ctxtflags; /* context processing flags */\n\n /*\n * Speed optimization when coalescing text nodes\n */\n const xmlChar *lasttext;\t\t/* last text node content */\n int lasttsize;\t\t/* last text node size */\n int lasttuse;\t\t/* last text node use */\n /*\n * Per Context Debugging\n */\n int debugStatus;\t\t\t/* the context level debug status */\n unsigned long* traceCode;\t\t/* pointer to the variable holding the mask */\n\n int parserOptions;\t\t\t/* parser options xmlParserOption */\n\n /*\n * dictionary: shared between stylesheet, context and documents.\n */\n xmlDictPtr dict;\n xmlDocPtr\t\ttmpDoc; /* Obsolete; not used in the library. */\n /*\n * all document text strings are internalized\n */\n int internalized;\n int nbKeys;\n int hasTemplKeyPatterns;\n xsltTemplatePtr currentTemplateRule; /* the Current Template Rule */\n xmlNodePtr initialContextNode;\n xmlDocPtr initialContextDoc;\n xsltTransformCachePtr cache;\n void *contextVariable; /* the current variable item */\n xmlDocPtr localRVT; /* list of local tree fragments; will be freed when\n\t\t\t the instruction which created the fragment\n exits */\n xmlDocPtr localRVTBase; /* Obsolete */\n int keyInitLevel; /* Needed to catch recursive keys issues */\n int depth; /* Needed to catch recursions */\n int maxTemplateDepth;\n int maxTemplateVars;\n unsigned long opLimit;\n unsigned long opCount;\n int sourceDocDirty;\n unsigned long currentId; /* For generate-id() */\n\n xsltNewLocaleFunc newLocale;\n xsltFreeLocaleFunc freeLocale;\n xsltGenSortKeyFunc genSortKey;\n};\n\n/**\n * CHECK_STOPPED:\n *\n * Macro to check if the XSLT processing should be stopped.\n * Will return from the function.\n */\n#define CHECK_STOPPED if (ctxt->state == XSLT_STATE_STOPPED) return;\n\n/**\n * CHECK_STOPPEDE:\n *\n * Macro to check if the XSLT processing should be stopped.\n * Will goto the error: label.\n */\n#define CHECK_STOPPEDE if (ctxt->state == XSLT_STATE_STOPPED) goto error;\n\n/**\n * CHECK_STOPPED0:\n *\n * Macro to check if the XSLT processing should be stopped.\n * Will return from the function with a 0 value.\n */\n#define CHECK_STOPPED0 if (ctxt->state == XSLT_STATE_STOPPED) return(0);\n\n/*\n * The macro XML_CAST_FPTR is a hack to avoid a gcc warning about\n * possible incompatibilities between function pointers and object\n * pointers. It is defined in libxml/hash.h within recent versions\n * of libxml2, but is put here for compatibility.\n */\n#ifndef XML_CAST_FPTR\n/**\n * XML_CAST_FPTR:\n * @fptr: pointer to a function\n *\n * Macro to do a casting from an object pointer to a\n * function pointer without encountering a warning from\n * gcc\n *\n * #define XML_CAST_FPTR(fptr) (*(void **)(&fptr))\n * This macro violated ISO C aliasing rules (gcc4 on s390 broke)\n * so it is disabled now\n */\n\n#define XML_CAST_FPTR(fptr) fptr\n#endif\n/*\n * Functions associated to the internal types\nxsltDecimalFormatPtr\txsltDecimalFormatGetByName(xsltStylesheetPtr sheet,\n\t\t\t\t\t\t xmlChar *name);\n */\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltNewStylesheet\t(void);\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltParseStylesheetFile\t(const xmlChar* filename);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltFreeStylesheet\t(xsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltIsBlank\t\t(xmlChar *str);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltFreeStackElemList\t(xsltStackElemPtr elem);\nXSLTPUBFUN xsltDecimalFormatPtr XSLTCALL\n\t\t\txsltDecimalFormatGetByName(xsltStylesheetPtr style,\n\t\t\t\t\t\t xmlChar *name);\nXSLTPUBFUN xsltDecimalFormatPtr XSLTCALL\n\t\t\txsltDecimalFormatGetByQName(xsltStylesheetPtr style,\n\t\t\t\t\t\t const xmlChar *nsUri,\n const xmlChar *name);\n\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltParseStylesheetProcess(xsltStylesheetPtr ret,\n\t\t\t\t\t\t xmlDocPtr doc);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltParseStylesheetOutput(xsltStylesheetPtr style,\n\t\t\t\t\t\t xmlNodePtr cur);\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltParseStylesheetDoc\t(xmlDocPtr doc);\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltParseStylesheetImportedDoc(xmlDocPtr doc,\n\t\t\t\t\t\txsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltParseStylesheetUser(xsltStylesheetPtr style,\n\t\t\t\t\t\txmlDocPtr doc);\nXSLTPUBFUN xsltStylesheetPtr XSLTCALL\n\t\t\txsltLoadStylesheetPI\t(xmlDocPtr doc);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltNumberFormat\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xsltNumberDataPtr data,\n\t\t\t\t\t\t xmlNodePtr node);\nXSLTPUBFUN xmlXPathError XSLTCALL\n\t\t\txsltFormatNumberConversion(xsltDecimalFormatPtr self,\n\t\t\t\t\t\t xmlChar *format,\n\t\t\t\t\t\t double number,\n\t\t\t\t\t\t xmlChar **result);\n\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltParseTemplateContent(xsltStylesheetPtr style,\n\t\t\t\t\t\t xmlNodePtr templ);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltAllocateExtra\t(xsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltAllocateExtraCtxt\t(xsltTransformContextPtr ctxt);\n/*\n * Extra functions for Result Value Trees\n */\nXSLTPUBFUN xmlDocPtr XSLTCALL\n\t\t\txsltCreateRVT\t\t(xsltTransformContextPtr ctxt);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltRegisterTmpRVT\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlDocPtr RVT);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltRegisterLocalRVT\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlDocPtr RVT);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltRegisterPersistRVT\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlDocPtr RVT);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltExtensionInstructionResultRegister(\n\t\t\t\t\t\t xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlXPathObjectPtr obj);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltExtensionInstructionResultFinalize(\n\t\t\t\t\t\t xsltTransformContextPtr ctxt);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltFlagRVTs(\n\t\t\t\t\t\t xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlXPathObjectPtr obj,\n\t\t\t\t\t\t int val);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltFreeRVTs\t\t(xsltTransformContextPtr ctxt);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltReleaseRVT\t\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlDocPtr RVT);\n/*\n * Extra functions for Attribute Value Templates\n */\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltCompileAttr\t\t(xsltStylesheetPtr style,\n\t\t\t\t\t\t xmlAttrPtr attr);\nXSLTPUBFUN xmlChar * XSLTCALL\n\t\t\txsltEvalAVT\t\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t void *avt,\n\t\t\t\t\t\t xmlNodePtr node);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltFreeAVTList\t\t(void *avt);\n\n/*\n * Extra function for successful xsltCleanupGlobals / xsltInit sequence.\n */\n\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltUninit\t\t(void);\n\n/************************************************************************\n *\t\t\t\t\t\t\t\t\t*\n * Compile-time functions for *internal* use only *\n *\t\t\t\t\t\t\t\t\t*\n ************************************************************************/\n\n#ifdef XSLT_REFACTORED\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltParseSequenceConstructor(\n\t\t\t\t\t\t xsltCompilerCtxtPtr cctxt,\n\t\t\t\t\t\t xmlNodePtr start);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltParseAnyXSLTElem\t(xsltCompilerCtxtPtr cctxt,\n\t\t\t\t\t\t xmlNodePtr elem);\n#ifdef XSLT_REFACTORED_XSLT_NSCOMP\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltRestoreDocumentNamespaces(\n\t\t\t\t\t\t xsltNsMapPtr ns,\n\t\t\t\t\t\t xmlDocPtr doc);\n#endif\n#endif /* XSLT_REFACTORED */\n\n/************************************************************************\n *\t\t\t\t\t\t\t\t\t*\n * Transformation-time functions for *internal* use only *\n *\t\t\t\t\t\t\t\t\t*\n ************************************************************************/\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltInitCtxtKey\t\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xsltDocumentPtr doc,\n\t\t\t\t\t\t xsltKeyDefPtr keyd);\nXSLTPUBFUN int XSLTCALL\n\t\t\txsltInitAllDocKeys\t(xsltTransformContextPtr ctxt);\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* __XML_XSLT_H__ */\n\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\n#endif /* XSLT_REFACTORED */\n\n\n/*\n * The in-memory structure corresponding to an XSLT Variable\n=======\n\n#endif /* XSLT_REFACTORED */\n\ntypedef struct _xsltRVTList xsltRVTList;\ntypedef xsltRVTList *xsltRVTListPtr;\n\n/*\n * The in-memory structure corresponding to an XSLT Variable\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n xmlNodePtr tree;\t\t/* the sequence constructor if no eval\n\t\t\t\t string or the location */\n xmlXPathObjectPtr value;\t/* The value if computed */\n xmlDocPtr fragment;\t\t/* The Result Tree Fragments (needed for XSLT 1.0)\n\t\t\t\t which are bound to the variable's lifetime. */\n int level; /* the depth in the tree;\n -1 if persistent (e.g. a given xsl:with-param) */\n=======\n xmlNodePtr tree;\t\t/* the sequence constructor if no eval\n\t\t\t\t string or the location */\n xmlXPathObjectPtr value;\t/* The value if computed */\n xsltRVTListPtr fragment;\t/* The Result Tree Fragments (needed for XSLT 1.0)\n\t\t\t\t which are bound to the variable's lifetime. */\n int level; /* the depth in the tree;\n -1 if persistent (e.g. a given xsl:with-param) */\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n unsigned long opCount;\n};\n\ntypedef struct _xsltTransformCache xsltTransformCache;\ntypedef xsltTransformCache *xsltTransformCachePtr;\nstruct _xsltTransformCache {\n xmlDocPtr RVT;\n int nbRVT;\n xsltStackElemPtr stackItems;\n int nbStackItems;\n=======\n unsigned long opCount;\n};\n\nstruct _xsltRVTList {\n xmlDocPtr RVT;\n xsltRVTListPtr next;\n};\n\ntypedef struct _xsltTransformCache xsltTransformCache;\ntypedef xsltTransformCache *xsltTransformCachePtr;\nstruct _xsltTransformCache {\n xsltRVTListPtr rvtList;\n int nbRVT;\n xsltStackElemPtr stackItems;\n int nbStackItems;\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n * handling of temporary Result Value Tree\n * (XSLT 1.0 term: \"Result Tree Fragment\")\n */\n xmlDocPtr tmpRVT;\t\t/* list of RVT without persistance */\n xmlDocPtr persistRVT;\t\t/* list of persistant RVTs */\n int ctxtflags; /* context processing flags */\n\n /*\n=======\n * handling of temporary Result Value Tree\n * (XSLT 1.0 term: \"Result Tree Fragment\")\n */\n xsltRVTListPtr tmpRVTList;\t /* list of RVT without persistance */\n xsltRVTListPtr persistRVTList; /* list of persistant RVTs */\n int ctxtflags; /* context processing flags */\n\n /*\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n xmlDocPtr initialContextDoc;\n xsltTransformCachePtr cache;\n void *contextVariable; /* the current variable item */\n xmlDocPtr localRVT; /* list of local tree fragments; will be freed when\n\t\t\t the instruction which created the fragment\n exits */\n xmlDocPtr localRVTBase; /* Obsolete */\n=======\n xmlDocPtr initialContextDoc;\n xsltTransformCachePtr cache;\n void *contextVariable; /* the current variable item */\n xsltRVTListPtr localRVTList; /* list of local tree fragments; will be freed when\n\t\t\t the instruction which created the fragment\n exits */\n xmlDocPtr localRVTBase; /* Obsolete */\n>>>>>>> REPLACE\n<<<<<<< SEARCH\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltFreeRVTs\t\t(xsltTransformContextPtr ctxt);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltReleaseRVT\t\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlDocPtr RVT);\n/*\n * Extra functions for Attribute Value Templates\n */\n=======\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltFreeRVTs\t\t(xsltTransformContextPtr ctxt);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltReleaseRVT (xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xmlDocPtr RVT);\nXSLTPUBFUN void XSLTCALL\n\t\t\txsltReleaseRVTList\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t xsltRVTListPtr list);\n/*\n * Extra functions for Attribute Value Templates\n */\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n#endif\n\n#endif /* __XML_XSLT_H__ */\n\n=======\n#endif\n\n#endif /* __XML_XSLT_H__ */\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-11230: Algorithmic complexity denial-of-service (CWE-407) in HAProxy 3.2.5 and earlier via the bundled mjson library. The custom `mystrtod()` function in `src/mjson.c` computes the exponential part of a floating-point number using a linear O(n) loop (`for (i = 0; i < e; i++) d *= 10`), where `e` is the unvalidated exponent from the JSON input. An attacker submitting a specially crafted JSON value with a large positive exponent (e.g. `1e99999`) forces HAProxy to execute a proportionally large number of multiplications, consuming unbounded CPU time. Although HAProxy's internal watchdog will terminate a runaway process, the repeated triggering causes denial of service. Reported by Oula Kivalo.\n\n# Vulnerable source (src/mjson.c)\n```c\n d *= sign;\n\n /* fraction part */\n if (*p == '.') {\n double f = 0.0;\n double base = 0.1;\n ++p;\n\n if (is_digit(*p)) {\n while (*p && is_digit(*p)) {\n f += base * (*p - '0');\n base /= 10.0;\n ++p;\n ++n;\n }\n }\n d += f * sign;\n a = p;\n }\n\n /* exponential part */\n if ((*p == 'E') || (*p == 'e')) {\n int i, e = 0, neg = 0;\n p++;\n if (*p == '-') p++, neg++;\n if (*p == '+') p++;\n while (is_digit(*p)) e = e * 10 + *p++ - '0';\n if (neg) e = -e;\n#if 0\n if (d == 2.2250738585072011 && e == -308) {\n d = 0.0;\n a = p;\n goto done;\n }\n if (d == 2.2250738585072012 && e <= -308) {\n d *= 1.0e-308;\n a = p;\n goto done;\n }\n#endif\n for (i = 0; i < e; i++) d *= 10;\n for (i = 0; i < -e; i++) d /= 10;\n a = p;\n } else if (p > str && !is_digit(*(p - 1))) {\n a = str;\n goto done;\n }\n\ndone:\n if (end) *end = (char *) a;\n return d;\n}\n\n#if MJSON_ENABLE_MERGE\nint mjson_merge(const char *s, int n, const char *s2, int n2,\n mjson_print_fn_t fn, void *userdata) {\n int koff, klen, voff, vlen, t, t2, k, off = 0, len = 0, comma = 0;\n if (n < 2) return len;\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\n /* exponential part */\n if ((*p == 'E') || (*p == 'e')) {\n int i, e = 0, neg = 0;\n p++;\n if (*p == '-') p++, neg++;\n if (*p == '+') p++;\n while (is_digit(*p)) e = e * 10 + *p++ - '0';\n if (neg) e = -e;\n#if 0\n if (d == 2.2250738585072011 && e == -308) {\n=======\n\n /* exponential part */\n if ((*p == 'E') || (*p == 'e')) {\n double exp, f;\n int i, e = 0, neg = 0;\n p++;\n if (*p == '-') p++, neg++;\n if (*p == '+') p++;\n while (is_digit(*p)) e = e * 10 + *p++ - '0';\n i = e;\n if (neg) e = -e;\n#if 0\n if (d == 2.2250738585072011 && e == -308) {\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n goto done;\n }\n#endif\n for (i = 0; i < e; i++) d *= 10;\n for (i = 0; i < -e; i++) d /= 10;\n a = p;\n } else if (p > str && !is_digit(*(p - 1))) {\n a = str;\n=======\n goto done;\n }\n#endif\n /* calculate f = 10^i */\n exp = 10;\n f = 1;\n while (i > 0) {\n if (i & 1) f *= exp;\n exp *= exp;\n i >>= 1;\n }\n if (e > 0) d *= f;\n else if (e < 0) d /= f;\n a = p;\n } else if (p > str && !is_digit(*(p - 1))) {\n a = str;\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-14905: 389 Directory Server allocates a buffer for serializing LDAP attribute type definitions by summing component widths without accounting for all literal prefix strings in the output format, allowing a crafted LDAP client to trigger a heap overflow when the server emits its attribute type schema.\n\n# Vulnerable source (ldap/servers/slapd/schema.c)\n```c\n\n if (rc == 0) { /* all matched so far */\n /* get rid of trailing ignored strings (if any) */\n if (NULL != ignorestr) {\n if (sa1[i1] != NULL && 0 == strcmp(sa1[i1], ignorestr)) {\n ++i1;\n }\n if (sa2[i2] != NULL && 0 == strcmp(sa2[i2], ignorestr)) {\n ++i2;\n }\n }\n\n /* check for differing array lengths */\n if (sa2[i2] != NULL) {\n rc = -1; /* sa1 < sa2 -- fewer elements */\n } else if (sa1[i1] != NULL) {\n rc = 1; /* sa1 > sa2 -- more elements */\n }\n }\n\n return rc;\n}\n\n\nstruct attr_enum_wrapper\n{\n Slapi_Attr **attrs;\n int enquote_sup_oc;\n struct sizedbuffer *psbAttrTypes;\n int user_defined_only;\n int schema_ds4x_compat;\n};\n\nstatic int\nschema_attr_enum_callback(struct asyntaxinfo *asip, void *arg)\n{\n struct attr_enum_wrapper *aew = (struct attr_enum_wrapper *)arg;\n int aliaslen = 0;\n struct berval val;\n struct berval *vals[2] = {0, 0};\n const char *attr_desc, *syntaxoid;\n char *outp, syntaxlengthbuf[128];\n int i;\n\n vals[0] = &val;\n\n if (!asip) {\n slapi_log_err(SLAPI_LOG_ERR, \"schema_attr_enum_callback\",\n \"Error: no attribute types in schema_attr_enum_callback\\n\");\n return ATTR_SYNTAX_ENUM_NEXT;\n }\n\n if (aew->user_defined_only &&\n (asip->asi_flags & SLAPI_ATTR_FLAG_STD_ATTR)) {\n return ATTR_SYNTAX_ENUM_NEXT; /* not user defined */\n }\n\n if (aew->schema_ds4x_compat) {\n attr_desc = (asip->asi_flags & SLAPI_ATTR_FLAG_STD_ATTR)\n ? ATTR_STANDARD_STRING\n : ATTR_USERDEF_STRING;\n } else {\n attr_desc = asip->asi_desc;\n }\n\n if (asip->asi_aliases != NULL) {\n for (i = 0; asip->asi_aliases[i] != NULL; ++i) {\n aliaslen += strlen(asip->asi_aliases[i]);\n }\n }\n\n syntaxoid = asip->asi_plugin->plg_syntax_oid;\n\n if (!aew->schema_ds4x_compat &&\n asip->asi_syntaxlength != SLAPI_SYNTAXLENGTH_NONE) {\n /* sprintf() is safe because syntaxlengthbuf is large enough */\n sprintf(syntaxlengthbuf, \"{%d}\", asip->asi_syntaxlength);\n } else {\n *syntaxlengthbuf = '\\0';\n }\n\n /*\n * XXX: 256 is a magic number... it must be big enough to account for\n * all of the fixed sized items we output.\n */\n sizedbuffer_allocate(aew->psbAttrTypes, 256 + strlen(asip->asi_oid) +\n strlen(asip->asi_name) +\n aliaslen + strlen_null_ok(attr_desc) +\n strlen(syntaxoid) +\n strlen_null_ok(asip->asi_superior) +\n strlen_null_ok(asip->asi_mr_equality) +\n strlen_null_ok(asip->asi_mr_ordering) +\n strlen_null_ok(asip->asi_mr_substring) +\n strcat_extensions(NULL, asip->asi_extensions));\n\n /*\n * Overall strategy is to maintain a pointer to the next location in\n * the output buffer so we can do simple strcpy's, sprintf's, etc.\n * That pointer is `outp'. Each item that is output includes a trailing\n * space, so there is no need to include a leading one in the next item.\n */\n outp = aew->psbAttrTypes->buffer;\n outp += sprintf(outp, \"( %s NAME \", asip->asi_oid);\n if (asip->asi_aliases == NULL || asip->asi_aliases[0] == NULL) {\n /* only one name */\n outp += sprintf(outp, \"'%s' \", asip->asi_name);\n } else {\n /* several names */\n outp += sprintf(outp, \"( '%s' \", asip->asi_name);\n for (i = 0; asip->asi_aliases[i] != NULL; ++i) {\n outp += sprintf(outp, \"'%s' \", asip->asi_aliases[i]);\n }\n outp += strcpy_count(outp, \") \");\n }\n\n /* DESC is optional */\n if (attr_desc && *attr_desc) {\n outp += sprintf(outp, \"DESC '%s'\", attr_desc);\n }\n if (!aew->schema_ds4x_compat &&\n (asip->asi_flags & SLAPI_ATTR_FLAG_OBSOLETE)) {\n outp += strcpy_count(outp, schema_obsolete_with_spaces);\n } else {\n outp += strcpy_count(outp, \" \");\n }\n\n if (!aew->schema_ds4x_compat) {\n /*\n * These values in quotes are not supported by the openldap parser.\n * Even if nsslapd-enquote-sup-oc is on, quotes should not be added.\n */\n outp += put_tagged_oid(outp, \"SUP \", asip->asi_superior, NULL, 0);\n outp += put_tagged_oid(outp, \"EQUALITY \", asip->asi_mr_equality, NULL, 0);\n outp += put_tagged_oid(outp, \"ORDERING \", asip->asi_mr_ordering, NULL, 0);\n outp += put_tagged_oid(outp, \"SUBSTR \", asip->asi_mr_substring, NULL, 0);\n }\n\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n const char *attr_desc, *syntaxoid;\n char *outp, syntaxlengthbuf[128];\n int i;\n\n vals[0] = &val;\n\n=======\n const char *attr_desc, *syntaxoid;\n char *outp, syntaxlengthbuf[128];\n int i;\n int nb_aliases = 0;\n\n vals[0] = &val;\n\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n if (asip->asi_aliases != NULL) {\n for (i = 0; asip->asi_aliases[i] != NULL; ++i) {\n aliaslen += strlen(asip->asi_aliases[i]);\n }\n }\n\n=======\n if (asip->asi_aliases != NULL) {\n for (i = 0; asip->asi_aliases[i] != NULL; ++i) {\n aliaslen += strlen(asip->asi_aliases[i]);\n nb_aliases++;\n }\n }\n\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n * XXX: 256 is a magic number... it must be big enough to account for\n * all of the fixed sized items we output.\n */\n sizedbuffer_allocate(aew->psbAttrTypes, 256 + strlen(asip->asi_oid) +\n strlen(asip->asi_name) +\n aliaslen + strlen_null_ok(attr_desc) +\n strlen(syntaxoid) +\n strlen_null_ok(asip->asi_superior) +\n strlen_null_ok(asip->asi_mr_equality) +\n strlen_null_ok(asip->asi_mr_ordering) +\n strlen_null_ok(asip->asi_mr_substring) +\n strcat_extensions(NULL, asip->asi_extensions));\n\n /*\n * Overall strategy is to maintain a pointer to the next location in\n=======\n * XXX: 256 is a magic number... it must be big enough to account for\n * all of the fixed sized items we output.\n */\n {\n int asi_oid_strlen = strlen(asip->asi_oid) + 8; /* \"( %s NAME \" */\n int asi_name_strlen = strlen(asip->asi_name) + 6; /* \"( '%s' ...)\" */\n int asi_aliases_strlen = aliaslen + nb_aliases * 3; /* \"'%s' \" */\n int asi_desc_strlen = strlen_null_ok(attr_desc) + 7; /* \"DESC '%s'\" */\n int asi_syntaxoid_strlen = strlen(\"SYNTAX \") + strlen(syntaxoid) + strlen(syntaxlengthbuf);\n int asi_superior_strlen = strlen(\"SUP \") + strlen_null_ok(asip->asi_superior);\n int asi_mr_equality_strlen = strlen(\"EQUALITY \") + strlen_null_ok(asip->asi_mr_equality);\n int asi_mr_ordering_strlen = strlen(\"ORDERING \") + strlen_null_ok(asip->asi_mr_ordering);\n int asi_mr_substring_strlen = strlen(\"SUBSTR \") + strlen_null_ok(asip->asi_mr_substring);\n int asi_flags_strlen = strlen(\"SINGLE-VALUE \") +\n strlen(schema_obsolete_with_spaces) +\n strlen(schema_collective_with_spaces) +\n strlen(schema_nousermod_with_spaces) +\n strlen(\"USAGE distributedOperation \") +\n strlen(\"USAGE dSAOperation \") +\n strlen(\"USAGE directoryOperation \");\n int asi_extension_strlen = strcat_extensions(NULL, asip->asi_extensions);\n\n if (aew->enquote_sup_oc) {\n /* it enquote the syntax oid */\n asi_syntaxoid_strlen += 2;\n }\n\n sizedbuffer_allocate(aew->psbAttrTypes, 256 + asi_oid_strlen +\n asi_name_strlen +\n asi_aliases_strlen +\n asi_desc_strlen +\n asi_syntaxoid_strlen +\n asi_superior_strlen +\n asi_mr_equality_strlen +\n asi_mr_ordering_strlen +\n asi_mr_substring_strlen +\n asi_extension_strlen +\n asi_flags_strlen);\n }\n\n /*\n * Overall strategy is to maintain a pointer to the next location in\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-31344: Heap-buffer-overflow (out-of-bounds read, CWE-125) in giflib 5.2.2's gif2rgb utility. A crafted GIF whose raster contains a color index >= the global/local palette size therefore reads past the Colors[] allocation (and the read bytes are written into the RGB output). Fix pulled into nixpkgs from the OpenMandriva patch giflib-5.2.2-cve-2025-31344 (in-tree pkgs/by-name/gi/giflib/CVE-2025-31344.patch); no upstream giflib release carries it yet, so a version bump is not possible.\n\n# Vulnerable source (gif2rgb.c)\n```c\n\n\t\tfree((char *)Buffer);\n\t\tfclose(rgbfp[0]);\n\t} else {\n\t\tunsigned char *Buffers[3];\n\n\t\tif ((Buffers[0] = (unsigned char *)malloc(ScreenWidth)) ==\n\t\t NULL ||\n\t\t (Buffers[1] = (unsigned char *)malloc(ScreenWidth)) ==\n\t\t NULL ||\n\t\t (Buffers[2] = (unsigned char *)malloc(ScreenWidth)) ==\n\t\t NULL) {\n\t\t\tGIF_EXIT(\n\t\t\t \"Failed to allocate memory required, aborted.\");\n\t\t}\n\n\t\tfor (i = 0; i < ScreenHeight; i++) {\n\t\t\tGifRow = ScreenBuffer[i];\n\t\t\tGifQprintf(\"\\b\\b\\b\\b%-4d\", ScreenHeight - i);\n\t\t\tfor (j = 0; j < ScreenWidth; j++) {\n\t\t\t\tColorMapEntry = &ColorMap->Colors[GifRow[j]];\n\t\t\t\tBuffers[0][j] = ColorMapEntry->Red;\n\t\t\t\tBuffers[1][j] = ColorMapEntry->Green;\n\t\t\t\tBuffers[2][j] = ColorMapEntry->Blue;\n\t\t\t}\n\t\t\tif (fwrite(Buffers[0], ScreenWidth, 1, rgbfp[0]) != 1 ||\n\t\t\t fwrite(Buffers[1], ScreenWidth, 1, rgbfp[1]) != 1 ||\n\t\t\t fwrite(Buffers[2], ScreenWidth, 1, rgbfp[2]) != 1) {\n\t\t\t\tGIF_EXIT(\"Write to file(s) failed.\");\n\t\t\t}\n\t\t}\n\n\t\tfree((char *)Buffers[0]);\n\t\tfree((char *)Buffers[1]);\n\t\tfree((char *)Buffers[2]);\n\t\tfclose(rgbfp[0]);\n\t\tfclose(rgbfp[1]);\n\t\tfclose(rgbfp[2]);\n\t}\n}\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\t\t\tGifRow = ScreenBuffer[i];\n\t\t\tGifQprintf(\"\\b\\b\\b\\b%-4d\", ScreenHeight - i);\n\t\t\tfor (j = 0; j < ScreenWidth; j++) {\n\t\t\t\tColorMapEntry = &ColorMap->Colors[GifRow[j]];\n\t\t\t\tBuffers[0][j] = ColorMapEntry->Red;\n\t\t\t\tBuffers[1][j] = ColorMapEntry->Green;\n=======\n\t\t\tGifRow = ScreenBuffer[i];\n\t\t\tGifQprintf(\"\\b\\b\\b\\b%-4d\", ScreenHeight - i);\n\t\t\tfor (j = 0; j < ScreenWidth; j++) {\n\t\t\t\t/* Check if color is within color palete */\n\t\t\t\tif (GifRow[j] >= ColorMap->ColorCount) {\n\t\t\t\t\tGIF_EXIT(GifErrorString(\n\t\t\t\t\t D_GIF_ERR_IMAGE_DEFECT));\n\t\t\t\t}\n\t\t\t\tColorMapEntry = &ColorMap->Colors[GifRow[j]];\n\t\t\t\tBuffers[0][j] = ColorMapEntry->Red;\n\t\t\t\tBuffers[1][j] = ColorMapEntry->Green;\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-34451: Stack-based buffer overflow (CWE-121) in rofl0r/proxychains-ng <= 4.17 via `proxy_from_string()` in `src/libproxychains.c`. When parsing a proxy configuration line with an HTTP proxy that has a username or password exceeding 255 bytes, the code copies the credential into a fixed 256-byte stack buffer (`user_buf[]` / `pass_buf[]`) without bounds checking. The public PoC: run `proxychains4 -f evil.conf -- /bin/true` with evil.conf containing `http AAAA...AAA:pass@127.0.0.1 8080` where the username is >255 characters.\n\n# Vulnerable source (src/libproxychains.c)\n```c\n\t\t\tcase '5': proxytype = RS_PT_SOCKS5; break;\n\t\t\tcase '4': proxytype = RS_PT_SOCKS4; break;\n\t\t\tdefault: goto inv_string;\n\t\t}\n\t} else if(*proxystring == 'h') {\n\t\tproxytype = RS_PT_HTTP;\n\t\tnext_token = 4;\n\t} else goto inv_string;\n\tif(\n\t proxystring[next_token++] != ':' ||\n\t proxystring[next_token++] != '/' ||\n\t proxystring[next_token++] != '/') goto inv_string;\n\tconst char *at = strrchr(proxystring+next_token, '@');\n\tif(at) {\n\t\tif(proxytype == RS_PT_SOCKS4)\n\t\t\treturn 0;\n\t\tp = strchr(proxystring+next_token, ':');\n\t\tif(!p || p >= at) goto inv_string;\n\t\tconst char *u = proxystring+next_token;\n\t\tul = p-u;\n\t\tp++;\n\t\tpl = at-p;\n\t\tif(proxytype == RS_PT_SOCKS5 && (ul > 255 || pl > 255))\n\t\t\treturn 0;\n\t\tmemcpy(user_buf, u, ul);\n\t\tuser_buf[ul]=0;\n\t\tmemcpy(pass_buf, p, pl);\n\t\tpass_buf[pl]=0;\n\t\tnext_token += 2+ul+pl;\n\t} else {\n\t\tuser_buf[0]=0;\n\t\tpass_buf[0]=0;\n\t}\n\tconst char* h = proxystring+next_token;\n\tp = strchr(h, ':');\n\tif(!p) goto inv_string;\n\thl = p-h;\n\tif(hl > 255)\n\t\treturn 0;\n\tmemcpy(host_buf, h, hl);\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\t\tul = p-u;\n\t\tp++;\n\t\tpl = at-p;\n\t\tif(proxytype == RS_PT_SOCKS5 && (ul > 255 || pl > 255))\n\t\t\treturn 0;\n\t\tmemcpy(user_buf, u, ul);\n\t\tuser_buf[ul]=0;\n=======\n\t\tul = p-u;\n\t\tp++;\n\t\tpl = at-p;\n\t\tif(ul > 255 || pl > 255)\n\t\t\treturn 0;\n\t\tmemcpy(user_buf, u, ul);\n\t\tuser_buf[ul]=0;\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-46836: corosync through 3.1.9 does not validate the size of an orf_token message against the size of the preallocated storage buffer before endian conversion. A remote attacker on the corosync network segment can send a crafted oversized orf_token message, causing an out-of-bounds write into a fixed-size stack buffer and crashing the corosync daemon.\n\n# Vulnerable source (exec/totemsrp.c)\n```c\n\n\treturn (transmits_allowed);\n}\n\n/*\n * don't overflow the RTR sort queue\n */\nstatic void fcc_rtr_limit (\n\tstruct totemsrp_instance *instance,\n\tstruct orf_token *token,\n\tunsigned int *transmits_allowed)\n{\n\tint check = QUEUE_RTR_ITEMS_SIZE_MAX;\n\tcheck -= (*transmits_allowed + instance->totem_config->window_size);\n\tassert (check >= 0);\n\tif (sq_lt_compare (instance->last_released +\n\t\tQUEUE_RTR_ITEMS_SIZE_MAX - *transmits_allowed -\n\t\tinstance->totem_config->window_size,\n\n\t\t\ttoken->seq)) {\n\n\t\t\t*transmits_allowed = 0;\n\t}\n}\n\nstatic void fcc_token_update (\n\tstruct totemsrp_instance *instance,\n\tstruct orf_token *token,\n\tunsigned int msgs_transmitted)\n{\n\ttoken->fcc += msgs_transmitted - instance->my_trc;\n\ttoken->backlog += instance->my_cbl - instance->my_pbl;\n\tinstance->my_trc = msgs_transmitted;\n\tinstance->my_pbl = instance->my_cbl;\n}\n\n/*\n * Sanity checkers\n */\nstatic int check_orf_token_sanity(\n\tconst struct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\tint rtr_entries;\n\tconst struct orf_token *token = (const struct orf_token *)msg;\n\tsize_t required_len;\n\n\tif (msg_len < sizeof(struct orf_token)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received orf_token message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\tif (endian_conversion_needed) {\n\t\trtr_entries = swab32(token->rtr_list_entries);\n\t} else {\n\t\trtr_entries = token->rtr_list_entries;\n\t}\n\n\trequired_len = sizeof(struct orf_token) + rtr_entries * sizeof(struct rtr_item);\n\tif (msg_len < required_len) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received orf_token message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\nstatic int check_mcast_sanity(\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\n\tif (msg_len < sizeof(struct mcast)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received mcast message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\nstatic int check_memb_merge_detect_sanity(\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\n\tif (msg_len < sizeof(struct memb_merge_detect)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received memb_merge_detect message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\nstatic int check_memb_join_sanity(\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\tconst struct memb_join *mj_msg = (const struct memb_join *)msg;\n\tunsigned int proc_list_entries;\n\tunsigned int failed_list_entries;\n\tsize_t required_len;\n\n\tif (msg_len < sizeof(struct memb_join)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received memb_join message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\tproc_list_entries = mj_msg->proc_list_entries;\n\tfailed_list_entries = mj_msg->failed_list_entries;\n\n\tif (endian_conversion_needed) {\n\t\tproc_list_entries = swab32(proc_list_entries);\n\t\tfailed_list_entries = swab32(failed_list_entries);\n\t}\n\n\trequired_len = sizeof(struct memb_join) + ((proc_list_entries + failed_list_entries) * sizeof(struct srp_addr));\n\tif (msg_len < required_len) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received memb_join message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\nstatic int check_memb_commit_token_sanity(\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\tconst struct memb_commit_token *mct_msg = (const struct memb_commit_token *)msg;\n\tunsigned int addr_entries;\n\tsize_t required_len;\n\n\tif (msg_len < sizeof(struct memb_commit_token)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received memb_commit_token message is too short... ignoring.\");\n\n\t\treturn (0);\n\t}\n\n\taddr_entries= mct_msg->addr_entries;\n\tif (endian_conversion_needed) {\n\t\taddr_entries = swab32(addr_entries);\n\t}\n\n\trequired_len = sizeof(struct memb_commit_token) +\n\t (addr_entries * (sizeof(struct srp_addr) + sizeof(struct memb_commit_token_memb_entry)));\n\tif (msg_len < required_len) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received memb_commit_token message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\nstatic int check_token_hold_cancel_sanity(\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\n\tif (msg_len < sizeof(struct token_hold_cancel)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received token_hold_cancel message is too short... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\treturn (0);\n}\n\n/*\n * Message Handlers\n */\n\n#ifdef GIVEINFO\nuint64_t tv_old;\n#endif\n/*\n * message handler called when TOKEN message type received\n */\nstatic int message_handler_orf_token (\n\tstruct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\tchar token_storage[1500];\n\tchar token_convert[1500];\n\tstruct orf_token *token = NULL;\n\tint forward_token;\n\tunsigned int transmits_allowed;\n\tunsigned int mcasted_retransmit;\n\tunsigned int mcasted_regular;\n\tunsigned int last_aru;\n\n#ifdef GIVEINFO\n\tuint64_t tv_current;\n\tuint64_t tv_diff;\n\n\ttv_current = qb_util_nano_current_get ();\n\ttv_diff = tv_current - tv_old;\n\ttv_old = tv_current;\n\n\tlog_printf (instance->totemsrp_log_level_debug,\n\t \"Time since last token %0.4f ms\", tv_diff / (float)QB_TIME_NS_IN_MSEC);\n#endif\n\n\tif (check_orf_token_sanity(instance, msg, msg_len, endian_conversion_needed) == -1) {\n\t\treturn (0);\n\t}\n\n\tif (instance->orf_token_discard) {\n\t\treturn (0);\n\t}\n#ifdef TEST_DROP_ORF_TOKEN_PERCENTAGE\n\tif (random()%100 < TEST_DROP_ORF_TOKEN_PERCENTAGE) {\n\t\treturn (0);\n\t}\n#endif\n\n\tif (endian_conversion_needed) {\n\t\torf_token_endian_convert ((struct orf_token *)msg,\n\t\t\t(struct orf_token *)token_convert);\n\t\tmsg = (struct orf_token *)token_convert;\n\t}\n\n\t/*\n\t * Make copy of token and retransmit list in case we have\n\t * to flush incoming messages from the kernel queue\n\t */\n\ttoken = (struct orf_token *)token_storage;\n\tmemcpy (token, msg, sizeof (struct orf_token));\n\tmemcpy (&token->rtr_list[0], (char *)msg + sizeof (struct orf_token),\n\t\tsizeof (struct rtr_item) * RETRANSMIT_ENTRIES_MAX);\n\n\n\t/*\n\t * Handle merge detection timeout\n\t */\n\tif (token->seq == instance->my_last_seq) {\n\t\tstart_merge_detect_timeout (instance);\n\t\tinstance->my_seq_unchanged += 1;\n\t} else {\n\t\tcancel_merge_detect_timeout (instance);\n\t\tcancel_token_hold_retransmit_timeout (instance);\n\t\tinstance->my_seq_unchanged = 0;\n\t}\n\n\tinstance->my_last_seq = token->seq;\n\n#ifdef TEST_RECOVERY_MSG_COUNT\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\tconst struct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tint endian_conversion_needed)\n{\n\tint rtr_entries;\n\tconst struct orf_token *token = (const struct orf_token *)msg;\n\tsize_t required_len;\n\n\tif (msg_len < sizeof(struct orf_token)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received orf_token message is too short... ignoring.\");\n=======\n\tconst struct totemsrp_instance *instance,\n\tconst void *msg,\n\tsize_t msg_len,\n\tsize_t max_msg_len,\n\tint endian_conversion_needed)\n{\n\tint rtr_entries;\n\tconst struct orf_token *token = (const struct orf_token *)msg;\n\tsize_t required_len;\n\n\tif (msg_len > max_msg_len) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received orf_token message is too long... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\tif (msg_len < sizeof(struct orf_token)) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received orf_token message is too short... ignoring.\");\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\t\trtr_entries = token->rtr_list_entries;\n\t}\n\n\trequired_len = sizeof(struct orf_token) + rtr_entries * sizeof(struct rtr_item);\n\tif (msg_len < required_len) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n=======\n\t\trtr_entries = token->rtr_list_entries;\n\t}\n\n\tif (rtr_entries > RETRANSMIT_ENTRIES_MAX) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n\t\t \"Received orf_token message rtr_entries is corrupted... ignoring.\");\n\n\t\treturn (-1);\n\t}\n\n\trequired_len = sizeof(struct orf_token) + rtr_entries * sizeof(struct rtr_item);\n\tif (msg_len < required_len) {\n\t\tlog_printf (instance->totemsrp_log_level_security,\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\t \"Time since last token %0.4f ms\", tv_diff / (float)QB_TIME_NS_IN_MSEC);\n#endif\n\n\tif (check_orf_token_sanity(instance, msg, msg_len, endian_conversion_needed) == -1) {\n\t\treturn (0);\n\t}\n=======\n\t \"Time since last token %0.4f ms\", tv_diff / (float)QB_TIME_NS_IN_MSEC);\n#endif\n\n\tif (check_orf_token_sanity(instance, msg, msg_len, sizeof(token_storage),\n\t endian_conversion_needed) == -1) {\n\t\treturn (0);\n\t}\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-47256: Stack-based buffer underwrite (CWE-191 integer underflow \u2192 CWE-121 stack buffer overflow) in libxmp's Pha Packer loader. In loaders/prowizard/pha.c, the depack_pha() function iterates over compressed blocks using a counter ocpt whose value comes directly from the module file. When ocpt is sufficiently large, the expression used as an array subscript wraps below zero (signed integer underflow), causing writes to memory below the dest buffer's base \u2014 a stack buffer underwrite. A crafted .mod file with an overflowed ocpt field triggers a SIGSEGV on any caller of xmp_load_module(). Upstream ships test fixtures: test-dev/data/f/prowizard_pha_invalid_ocpt and prowizard_pha_invalid_ocpt2.\n\n# Vulnerable source (src/loaders/prowizard/pha.c)\n```c\n/* ProWizard\n * Copyright (C) 1996-1999 Asle / ReDoX\n * Modified in 2006,2007,2014 by Claudio Matsuoka\n * Modified in 2021 by Alice Rowan\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n /* ... */\n\t\t\t\tpaddr1[j] = paddr1[i];\n\t\t\t\tpaddr1[i] = tmp;\n\t\t\t\tgoto restart;\n\t\t\t}\n\t\t}\n\t}\n\n\tj = 0;\n\tfor (i = 0; i < 128; i++) {\n\t\tif (i == 0) {\n\t\t\tpaddr2[j] = paddr1[i];\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (paddr1[i] == paddr2[j])\n\t\t\tcontinue;\n\t\tpaddr2[++j] = paddr1[i];\n\t}\n\n\t/* try to take care of unused patterns ... HARRRRRRD */\n\tmemset(paddr1, 0, sizeof(paddr1));\n\tj = 0;\n\tk = paddr[0];\n\t/* 120 ... leaves 8 unused ptk_tableible patterns .. */\n\tfor (i = 0; i < 120; i++) {\n\t\tpaddr1[j] = paddr2[i];\n\t\tj += 1;\n\t\tif (j >= 128)\n\t\t\tbreak;\n\n\t\tif ((paddr2[i + 1] - paddr2[i]) > 1024) {\n\t\t\tpaddr1[j] = paddr2[i] + 1024;\n\t\t\tj += 1;\n\t\t\tif (j >= 128)\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tfor (c1 = 0; c1 < 128; c1++) {\n\t\tfor (c2 = 0; c2 < 128; c2++) {\n /* ... */\n#if 0\n\tj = ftell (in);\n\tfseek (in, 0, 2);\t/* SEEK_END */\n\tpsize = ftell (in) - j;\n\tfseek (in, j, 0);\t/* SEEK_SET */\n#endif\n\t/* This value should be larger than the actual size of the\n\t * pattern data and will probably set the error flag, so\n\t * clear it after reading.\n\t */\n\tpsize = npat * 1024;\n\tif ((pdata = (uint8 *)malloc(psize)) == NULL)\n\t\treturn -1;\n\n\tpsize = hio_read(pdata, 1, psize, in);\n\thio_error(in);\n\n\tsize = npat * 1024;\n\tif ((pat = (uint8 *)calloc(1, size)) == NULL)\n\t\tgoto err;\n\n\tj = 0;\n\tfor (i = 0; i < psize && j < size; i++) {\n\t\tif (pdata[i] == 0xff) {\n\t\t\ti += 1;\n\t\t\tif (i >= psize)\n\t\t\t\tgoto err;\n\n\t\t\tocpt[(k + 3) % 4] = 0xff - pdata[i];\n\t\t\tcontinue;\n\t\t}\n\t\tif (ocpt[k % 4] != 0) {\n\t\t\tins = onote[k % 4][0];\n\t\t\tnote = onote[k % 4][1];\n\t\t\tfxt = onote[k % 4][2];\n\t\t\tfxp = onote[k % 4][3];\n\t\t\tocpt[k % 4] -= 1;\n\n\t\t\tpat[j] = ins & 0xf0;\n\t\t\tif (PTK_IS_VALID_NOTE(note / 2)) {\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n/* ProWizard\n * Copyright (C) 1996-1999 Asle / ReDoX\n * Modified in 2006,2007,2014 by Claudio Matsuoka\n * Modified in 2021 by Alice Rowan\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n=======\n/* ProWizard\n * Copyright (C) 1996-1999 Asle / ReDoX\n * Modified in 2006,2007,2014 by Claudio Matsuoka\n * Modified in 2021, 2025 by Alice Rowan\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\t/* try to take care of unused patterns ... HARRRRRRD */\n\tmemset(paddr1, 0, sizeof(paddr1));\n\tj = 0;\n\tk = paddr[0];\n\t/* 120 ... leaves 8 unused ptk_tableible patterns .. */\n\tfor (i = 0; i < 120; i++) {\n\t\tpaddr1[j] = paddr2[i];\n=======\n\t/* try to take care of unused patterns ... HARRRRRRD */\n\tmemset(paddr1, 0, sizeof(paddr1));\n\tj = 0;\n\t/* 120 ... leaves 8 unused ptk_tableible patterns .. */\n\tfor (i = 0; i < 120; i++) {\n\t\tpaddr1[j] = paddr2[i];\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\t\tgoto err;\n\n\tj = 0;\n\tfor (i = 0; i < psize && j < size; i++) {\n\t\tif (pdata[i] == 0xff) {\n\t\t\ti += 1;\n=======\n\t\tgoto err;\n\n\tj = 0;\n\tk = 0;\n\tfor (i = 0; i < psize && j < size; i++) {\n\t\tif (pdata[i] == 0xff) {\n\t\t\ti += 1;\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-48060: Heap buffer overflow (CWE-122) in jq 1.7.1 and earlier in the string-formatting path. via `0[[]|implode]`) reads one byte past the allocation boundary, causing a heap buffer overflow. A crafted jq program or input that triggers the `implode`-of-empty-array path can crash jq or, under adversarial heap layout, leak or corrupt adjacent heap memory.\n\n# Vulnerable source (src/jv.c)\n```c\n length = out - s->data;\n s->data[length] = 0;\n s->length_hashed = length << 1;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n/* Assumes valid UTF8 */\nstatic jv jvp_string_new(const char* data, uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = length << 1;\n if (data != NULL)\n memcpy(s->data, data, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\nstatic jv jvp_string_empty_new(uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n\nstatic void jvp_string_free(jv js) {\n jvp_string* s = jvp_string_ptr(js);\n if (jvp_refcnt_dec(&s->refcnt)) {\n jv_mem_free(s);\n }\n}\n\nstatic uint32_t jvp_string_length(jvp_string* s) {\n return s->length_hashed >> 1;\n}\n\nstatic uint32_t jvp_string_remaining_space(jvp_string* s) {\n assert(s->alloc_length >= jvp_string_length(s));\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n=======\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-49466: This could be exploited to cause a denial of service when the intermediate directory was absent, or to write files outside the intended temporary folder.\n\n# Vulnerable source (commands/msgview/open.go)\n```go\npackage msgview\n\nimport (\n\t\"errors\"\n\t\"io\"\n\t\"mime\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"git.sr.ht/~rjarry/aerc/app\"\n\t\"git.sr.ht/~rjarry/aerc/commands\"\n\t\"git.sr.ht/~rjarry/aerc/lib\"\n\t\"git.sr.ht/~rjarry/aerc/lib/log\"\n)\n\ntype Open struct {\n\tDelete bool `opt:\"-d\" desc:\"Delete temp file after the opener exits.\"`\n\tCmd string `opt:\"...\" required:\"false\"`\n}\n\nfunc init() {\n\tcommands.Register(Open{})\n}\n\nfunc (Open) Description() string {\n\treturn \"Save the current message part to a temporary file, then open it.\"\n}\n\nfunc (Open) Context() commands.CommandContext {\n\treturn commands.MESSAGE_VIEWER\n}\n\nfunc (Open) Aliases() []string {\n\treturn []string{\"open\"}\n}\n\nfunc (o Open) Execute(args []string) error {\n\tmv := app.SelectedTabContent().(*app.MessageViewer)\n\tif mv == nil {\n\t\treturn errors.New(\"open only supported selected message parts\")\n\t}\n\tp := mv.SelectedMessagePart()\n\n\tmv.MessageView().FetchBodyPart(p.Index, func(reader io.Reader) {\n\t\tmimeType := \"\"\n\n\t\tpart, err := mv.MessageView().BodyStructure().PartAtIndex(p.Index)\n\t\tif err != nil {\n\t\t\tapp.PushError(err.Error())\n\t\t\treturn\n\t\t}\n\t\tmimeType = part.FullMIMEType()\n\n\t\ttmpDir, err := os.MkdirTemp(os.TempDir(), \"aerc-*\")\n\t\tif err != nil {\n\t\t\tapp.PushError(err.Error())\n\t\t\treturn\n\t\t}\n\t\tfilename := part.FileName()\n\t\tvar tmpFile *os.File\n\t\tif filename == \"\" {\n\t\t\textension := \"\"\n\t\t\tif exts, _ := mime.ExtensionsByType(mimeType); len(exts) > 0 {\n\t\t\t\textension = exts[0]\n\t\t\t}\n\t\t\ttmpFile, err = os.CreateTemp(tmpDir, \"aerc-*\"+extension)\n\t\t} else {\n\t\t\ttmpFile, err = os.Create(filepath.Join(tmpDir, filename))\n\t\t}\n\t\tif err != nil {\n\t\t\tapp.PushError(err.Error())\n\t\t\treturn\n\t\t}\n\n\t\t_, err = io.Copy(tmpFile, reader)\n\t\ttmpFile.Close()\n\t\tif err != nil {\n\t\t\tapp.PushError(err.Error())\n\t\t\treturn\n\t\t}\n\n\t\tgo func() {\n\t\t\tdefer log.PanicHandler()\n\t\t\tif o.Delete {\n\t\t\t\tdefer os.RemoveAll(tmpDir)\n\t\t\t}\n\t\t\terr = lib.XDGOpenMime(tmpFile.Name(), mimeType, o.Cmd)\n\t\t\tif err != nil {\n\t\t\t\tapp.PushError(\"open: \" + err.Error())\n\t\t\t}\n\t\t}()\n\t})\n\n\treturn nil\n}\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\t\"io\"\n\t\"mime\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"git.sr.ht/~rjarry/aerc/app\"\n=======\n\t\"io\"\n\t\"mime\"\n\t\"os\"\n\t\"path\"\n\t\"path/filepath\"\n\n\t\"git.sr.ht/~rjarry/aerc/app\"\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\t\t\tapp.PushError(err.Error())\n\t\t\treturn\n\t\t}\n\t\tfilename := part.FileName()\n\t\tvar tmpFile *os.File\n\t\tif filename == \"\" {\n\t\t\textension := \"\"\n=======\n\t\t\tapp.PushError(err.Error())\n\t\t\treturn\n\t\t}\n\t\tfilename := path.Base(part.FileName())\n\t\tvar tmpFile *os.File\n\t\tif filename == \"\" {\n\t\t\textension := \"\"\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-5278: Heap-buffer-overflow (out-of-bounds read, CWE-127/CWE-823) in GNU coreutils 9.7 `sort`. PoC (from coreutils NEWS): `sort +0.18446744073709551615R input` on 64-bit systems induces a read 1 byte before an allocated heap buffer.\n\n# Vulnerable source (src/sort.c)\n```c\n {\n while (ptr < lim && *ptr != tab)\n ++ptr;\n if (ptr < lim)\n ++ptr;\n }\n else\n while (ptr < lim && sword--)\n {\n while (ptr < lim && blanks[to_uchar (*ptr)])\n ++ptr;\n while (ptr < lim && !blanks[to_uchar (*ptr)])\n ++ptr;\n }\n\n /* If we're ignoring leading blanks when computing the Start\n of the field, skip past them here. */\n if (key->skipsblanks)\n while (ptr < lim && blanks[to_uchar (*ptr)])\n ++ptr;\n\n /* Advance PTR by SCHAR (if possible), but no further than LIM. */\n ptr = MIN (lim, ptr + schar);\n\n return ptr;\n}\n\n/* Return the limit of (a pointer to the first character after) the field\n in LINE specified by KEY. */\n\nATTRIBUTE_PURE\nstatic char *\nlimfield (struct line const *line, struct keyfield const *key)\n{\n char *ptr = line->text, *lim = ptr + line->length - 1;\n size_t eword = key->eword, echar = key->echar;\n\n if (echar == 0)\n eword++; /* Skip all of end field. */\n\n /* ... */\n }\n else\n {\n char *newlim;\n newlim = ptr;\n while (newlim < lim && blanks[to_uchar (*newlim)])\n ++newlim;\n while (newlim < lim && !blanks[to_uchar (*newlim)])\n ++newlim;\n lim = newlim;\n }\n#endif\n\n if (echar != 0) /* We need to skip over a portion of the end field. */\n {\n /* If we're ignoring leading blanks when computing the End\n of the field, skip past them here. */\n if (key->skipeblanks)\n while (ptr < lim && blanks[to_uchar (*ptr)])\n ++ptr;\n\n /* Advance PTR by ECHAR (if possible), but no further than LIM. */\n ptr = MIN (lim, ptr + echar);\n }\n\n return ptr;\n}\n\n/* Fill BUF reading from FP, moving buf->left bytes from the end\n of buf->buf to the beginning first. If EOF is reached and the\n file wasn't terminated by a newline, supply one. Set up BUF's line\n table too. FILE is the name of the file corresponding to FP.\n Return true if some input was read. */\n\nstatic bool\nfillbuf (struct buffer *buf, FILE *fp, char const *file)\n{\n struct keyfield const *key = keylist;\n char eol = eolchar;\n size_t line_bytes = buf->line_bytes;\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n ++ptr;\n\n /* Advance PTR by SCHAR (if possible), but no further than LIM. */\n ptr = MIN (lim, ptr + schar);\n\n return ptr;\n}\n=======\n ++ptr;\n\n /* Advance PTR by SCHAR (if possible), but no further than LIM. */\n size_t remaining_bytes = lim - ptr;\n if (schar < remaining_bytes)\n ptr += schar;\n else\n ptr = lim;\n\n return ptr;\n}\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n ++ptr;\n\n /* Advance PTR by ECHAR (if possible), but no further than LIM. */\n ptr = MIN (lim, ptr + echar);\n }\n\n return ptr;\n=======\n ++ptr;\n\n /* Advance PTR by ECHAR (if possible), but no further than LIM. */\n size_t remaining_bytes = lim - ptr;\n if (echar < remaining_bytes)\n ptr += echar;\n else\n ptr = lim;\n }\n\n return ptr;\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-57812: Processing such TIFF files triggers out-of-bounds memory access and heap buffer overflows in the TIFF reading code, exploitable via crafted print jobs sent to a CUPS server.\n\n# Vulnerable source (cupsfilters/image-tiff.c)\n```c\n# include <tiff.h>\t// TIFF image definitions\n# include <tiffio.h>\n# include <unistd.h>\n\n\n//\n// '_cfImageReadTIFF()' - Read a TIFF image file.\n//\n\nint\t\t\t\t\t// O - Read status\n_cfImageReadTIFF(\n cf_image_t *img,\t\t// IO - Image\n FILE *fp,\t\t// I - Image file\n cf_icspace_t primary,\t\t// I - Primary choice for colorspace\n cf_icspace_t secondary,\t\t// I - Secondary choice for colorspace\n int saturation,\t\t// I - Color saturation (%)\n int hue,\t\t// I - Color hue (degrees)\n const cf_ib_t *lut)\t\t// I - Lookup table for gamma/brightness\n{\n TIFF\t\t*tif;\t\t\t// TIFF file\n uint32_t\twidth, height;\t\t// Size of image\n uint16_t\tphotometric,\t\t// Colorspace\n\t\tcompression,\t\t// Type of compression\n\t\torientation,\t\t// Orientation\n\t\tresunit,\t\t// Units for resolution\n\t\tsamples,\t\t// Number of samples/pixel\n\t\tbits,\t\t\t// Number of bits/pixel\n\t\tinkset,\t\t\t// Ink set for color separations\n\t\tnuminks;\t\t// Number of inks in set\n float\t\txres,\t\t\t// Horizontal resolution\n\t\tyres;\t\t\t// Vertical resolution\n uint16_t\t*redcmap,\t\t// Red colormap information\n\t\t*greencmap,\t\t// Green colormap information\n\t\t*bluecmap;\t\t// Blue colormap information\n int\t\tc,\t\t\t// Color index\n\t\tnum_colors,\t\t// Number of colors\n\t\tbpp,\t\t\t// Bytes per pixel\n\t\tx, y,\t\t\t// Current x & y\n\t\trow,\t\t\t// Current row in image\n\t\txstart, ystart,\t\t// Starting x & y\n /* ... */\n DEBUG_puts(\"DEBUG: No image width tag in the file!\\n\");\n TIFFClose(tif);\n fclose(fp);\n return (-1);\n }\n\n if (!TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &height))\n {\n DEBUG_puts(\"DEBUG: No image height tag in the file!\\n\");\n TIFFClose(tif);\n fclose(fp);\n return (-1);\n }\n\n if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometric))\n {\n DEBUG_puts(\"DEBUG: No photometric tag in the file!\\n\");\n TIFFClose(tif);\n fclose(fp);\n return (-1);\n }\n\n if (!TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression))\n {\n DEBUG_puts(\"DEBUG: No compression tag in the file!\\n\");\n TIFFClose(tif);\n fclose(fp);\n return (-1);\n }\n\n if (!TIFFGetField(tif, TIFFTAG_SAMPLESPERPIXEL, &samples))\n samples = 1;\n\n if (!TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits))\n bits = 1;\n\n //\n // Get the image orientation...\n //\n\n if (!TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation))\n orientation = 0;\n\n //\n // Get the image resolution...\n //\n \n int temp = -1;\n\n#ifdef HAVE_EXIF\n //\n // Scan image file for EXIF data\n //\n\n /* ... */\n\n if (img->xppi == 0 || img->yppi == 0)\n {\n DEBUG_puts(\"DEBUG: Bad TIFF resolution.\\n\");\n img->xppi = img->yppi = 128;\n }\n\n DEBUG_printf((\"DEBUG: TIFF resolution = %fx%f, units=%d\\n\",\n\t\t xres, yres, resunit));\n DEBUG_printf((\"DEBUG: Stored resolution = %dx%d PPI\\n\",\n\t\t img->xppi, img->yppi));\n }\n\n //\n // See if the image has an alpha channel...\n //\n\n if (samples == 2 || (samples == 4 && photometric == PHOTOMETRIC_RGB))\n alpha = 1;\n else\n alpha = 0;\n\n //\n // Check the size of the image...\n //\n\n if (width == 0 || width > CF_IMAGE_MAX_WIDTH ||\n height == 0 || height > CF_IMAGE_MAX_HEIGHT ||\n (bits != 1 && bits != 2 && bits != 4 && bits != 8) ||\n samples < 1 || samples > 4)\n {\n DEBUG_printf((\"DEBUG: Bad TIFF dimensions %ux%ux%ux%u!\\n\",\n\t\t (unsigned)width, (unsigned)height, (unsigned)bits,\n\t\t (unsigned)samples));\n TIFFClose(tif);\n fclose(fp);\n return (1);\n }\n\n //\n /* ... */\n break;\n default :\n case ORIENTATION_TOPLEFT :\n DEBUG_puts(\"DEBUG: orientation = top-left\\n\");\n break;\n case ORIENTATION_LEFTTOP :\n DEBUG_puts(\"DEBUG: orientation = left-top\\n\");\n break;\n case ORIENTATION_BOTLEFT :\n DEBUG_puts(\"DEBUG: orientation = bottom-left\\n\");\n break;\n case ORIENTATION_LEFTBOT :\n DEBUG_puts(\"DEBUG: orientation = left-bottom\\n\");\n break;\n case ORIENTATION_BOTRIGHT :\n DEBUG_puts(\"DEBUG: orientation = bottom-right\\n\");\n break;\n case ORIENTATION_RIGHTBOT :\n DEBUG_puts(\"DEBUG: orientation = right-bottom\\n\");\n break;\n }\n\n switch (orientation)\n {\n case ORIENTATION_TOPRIGHT :\n case ORIENTATION_RIGHTTOP :\n xstart = img->xsize - 1;\n xdir = -1;\n ystart = 0;\n ydir = 1;\n break;\n default :\n case ORIENTATION_TOPLEFT :\n case ORIENTATION_LEFTTOP :\n xstart = 0;\n xdir = 1;\n ystart = 0;\n ydir = 1;\n break;\n case ORIENTATION_BOTLEFT :\n /* ... */\n\t {\n\t\tdefault :\n\t\t break;\n\n\t\tcase CF_IMAGE_WHITE :\n\t\t cfImageRGBToWhite(in, out, img->xsize);\n\t\t break;\n\t\tcase CF_IMAGE_RGB :\n\t\t cfImageRGBToRGB(in, out, img->xsize);\n\t\t break;\n\t\tcase CF_IMAGE_BLACK :\n\t\t cfImageRGBToBlack(in, out, img->xsize);\n\t\t break;\n\t\tcase CF_IMAGE_CMY :\n\t\t cfImageRGBToCMY(in, out, img->xsize);\n\t\t break;\n\t\tcase CF_IMAGE_CMYK :\n\t\t cfImageRGBToCMYK(in, out, img->xsize);\n\t\t break;\n\t }\n\n\t if (lut)\n\t cfImageLut(out, img->xsize * 3, lut);\n\n _cfImagePutRow(img, 0, y, img->xsize, out);\n }\n }\n else\n {\n\t //\n\t // Column major order...\n\t //\n\n for (x = xstart, xcount = img->xsize, row = 0;\n \t xcount > 0;\n \t xcount --, x += xdir, row ++)\n {\n if (bits == 1)\n {\n \tTIFFReadScanline(tif, scanline, row, 0);\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n TIFF\t\t*tif;\t\t\t// TIFF file\n uint32_t\twidth, height;\t\t// Size of image\n uint16_t\tphotometric,\t\t// Colorspace\n\t\tcompression,\t\t// Type of compression\n\t\torientation,\t\t// Orientation\n\t\tresunit,\t\t// Units for resolution\n=======\n TIFF\t\t*tif;\t\t\t// TIFF file\n uint32_t\twidth, height;\t\t// Size of image\n uint16_t\tphotometric,\t\t// Colorspace\n planar, // Color components in separate planes\n\t\tcompression,\t\t// Type of compression\n\t\torientation,\t\t// Orientation\n\t\tresunit,\t\t// Units for resolution\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n return (-1);\n }\n\n if (!TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression))\n {\n DEBUG_puts(\"DEBUG: No compression tag in the file!\\n\");\n=======\n return (-1);\n }\n\n if (TIFFGetField(tif, TIFFTAG_PLANARCONFIG, &planar) &&\n planar == PLANARCONFIG_SEPARATE)\n {\n fputs(\"DEBUG: Images with planar color configuration are not supported!\\n\", stderr);\n TIFFClose(tif);\n fclose(fp);\n return (1);\n }\n\n if (!TIFFGetField(tif, TIFFTAG_COMPRESSION, &compression))\n {\n DEBUG_puts(\"DEBUG: No compression tag in the file!\\n\");\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n if (!TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits))\n bits = 1;\n\n //\n // Get the image orientation...\n //\n=======\n if (!TIFFGetField(tif, TIFFTAG_BITSPERSAMPLE, &bits))\n bits = 1;\n\n if (bits == 1 && samples > 1)\n {\n fprintf(stderr, \"ERROR: Color images with 1 bit per sample not supported! \"\n \"Samples per pixel: %d; Bits per sample: %d\\n\", samples, bits);\n TIFFClose(tif);\n fclose(fp);\n return (1);\n }\n\n //\n // Get the image orientation...\n //\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n else\n alpha = 0;\n\n //\n // Check the size of the image...\n //\n=======\n else\n alpha = 0;\n\n //\n // Check whether number of samples per pixel corresponds with color space\n //\n\n if ((photometric == PHOTOMETRIC_RGB && (samples < 3 || samples > 4)) ||\n (photometric == PHOTOMETRIC_SEPARATED && samples != 4))\n {\n fprintf(stderr, \"DEBUG: Number of samples per pixel does not correspond to color space! \"\n \"Color space: %s; Samples per pixel: %d\\n\",\n (photometric == PHOTOMETRIC_RGB ? \"RGB\" :\n (photometric == PHOTOMETRIC_SEPARATED ? \"CMYK\" : \"Unknown\")),\n samples);\n TIFFClose(tif);\n fclose(fp);\n return (1);\n }\n\n //\n // Check the size of the image...\n //\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n break;\n }\n\n switch (orientation)\n {\n case ORIENTATION_TOPRIGHT :\n=======\n break;\n }\n\n if (orientation >= ORIENTATION_LEFTTOP)\n {\n fputs(\"ERROR: TIFF files with vertical scanlines are not supported!\\n\", stderr);\n TIFFClose(tif);\n fclose(fp);\n return (-1);\n }\n\n switch (orientation)\n {\n case ORIENTATION_TOPRIGHT :\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\t }\n\n\t if (lut)\n\t cfImageLut(out, img->xsize * 3, lut);\n\n _cfImagePutRow(img, 0, y, img->xsize, out);\n }\n=======\n\t }\n\n\t if (lut)\n\t cfImageLut(out, img->xsize * bpp, lut);\n\n _cfImagePutRow(img, 0, y, img->xsize, out);\n }\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-60876: HTTP header injection in BusyBox 1.37.0 wget: the networking/wget.c URL parsing function accepts URLs containing ASCII control characters and space characters, allowing a server or redirect to craft a URL that injects arbitrary headers into subsequent HTTP requests.\n\n# Vulnerable source (networking/wget.c)\n```c\n\t\t\tfprintf(stderr, \"--> %s%s\\n\\n\", s1, s2);\n\t\tfflush(fp);\n\t\tlog_io(\"> %s%s\", s1, s2);\n\t}\n\n\t/* Read until \"Nxx something\" is received */\n\tG.wget_buf[3] = 0;\n\tdo {\n\t\tfgets_trim_sanitize(fp, \"%s\\n\");\n\t} while (!isdigit(G.wget_buf[0]) || G.wget_buf[3] != ' ');\n\n\tG.wget_buf[3] = '\\0';\n\tresult = xatoi_positive(G.wget_buf);\n\tG.wget_buf[3] = ' ';\n\treturn result;\n}\n#endif\n\nstatic void parse_url(const char *src_url, struct host_info *h)\n{\n\tchar *url, *p, *sp;\n\n\tfree(h->allocated);\n\th->allocated = url = xstrdup(src_url);\n\n\th->protocol = P_HTTP;\n\tp = strstr(url, \"://\");\n\tif (p) {\n\t\t*p = '\\0';\n\t\th->host = p + 3;\n#if ENABLE_FEATURE_WGET_FTP\n\t\tif (strcmp(url, P_FTP) == 0) {\n\t\t\th->port = bb_lookup_std_port(P_FTP, \"tcp\", 21);\n\t\t\th->protocol = P_FTP;\n\t\t} else\n#endif\n#if FTPS_SUPPORTED\n\t\tif (strcmp(url, P_FTPS) == 0) {\n\t\t\th->port = bb_lookup_std_port(P_FTPS, \"tcp\", 990);\n\t\t\th->protocol = P_FTPS;\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n{\n\tchar *url, *p, *sp;\n\n\tfree(h->allocated);\n\th->allocated = url = xstrdup(src_url);\n=======\n{\n\tchar *url, *p, *sp;\n\n\t/* Fix for CVE-2025-60876 - don't allow control characters or spaces in the URL */\n\t/* otherwise a malicious URL can be used to inject HTTP headers in the request */\n\tconst unsigned char *u = (void *) src_url;\n\twhile (*u) {\n\t\tif (*u <= ' ')\n\t\t\tbb_simple_error_msg_and_die(\"Unencoded control character found in the URL!\");\n\t\tu++;\n\t}\n\n\tfree(h->allocated);\n\th->allocated = url = xstrdup(src_url);\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-6170: Stack-buffer-overflow (CWE-787 out-of-bounds write) in libxml2's xmllint interactive shell. Affects the 2.13.x series; nixpkgs carries it as the libxml2_13 compat attr.\n\n# Vulnerable source (debugXML.c, xmllint.c)\n```c\n/* ==== file: debugXML.c ==== */\n if ((node == NULL) || (buffer == NULL))\n return (-1);\n\n path = xmlGetNodePath(node);\n if (path == NULL)\n\treturn (-1);\n\n /*\n * This test prevents buffer overflow, because this routine\n * is only called by xmlShell, in which the second argument is\n * 500 chars long.\n * It is a dirty hack before a cleaner solution is found.\n * Documentation should mention that the second argument must\n * be at least 500 chars long, and could be stripped if too long.\n */\n snprintf(buffer, 499, \"%s\", path);\n buffer[499] = '0';\n xmlFree(path);\n\n return (0);\n}\n\n/**\n * xmlShell:\n * @doc: the initial document\n * @filename: the output buffer\n * @input: the line reading function\n * @output: the output FILE*, defaults to stdout if NULL\n *\n * Implements the XML shell\n * This allow to load, validate, view, modify and save a document\n * using a environment similar to a UNIX commandline.\n */\nvoid\nxmlShell(xmlDocPtr doc, const char *filename, xmlShellReadlineFunc input,\n FILE * output)\n{\n char prompt[500] = \"/ > \";\n char *cmdline = NULL, *cur;\n char command[100];\n char arg[400];\n int i;\n xmlShellCtxtPtr ctxt;\n xmlXPathObjectPtr list;\n\n if (doc == NULL)\n return;\n if (filename == NULL)\n return;\n if (input == NULL)\n return;\n if (output == NULL)\n output = stdout;\n ctxt = (xmlShellCtxtPtr) xmlMalloc(sizeof(xmlShellCtxt));\n if (ctxt == NULL)\n /* ... */\n (ctxt->node->ns->prefix), ctxt->node->name);\n else if ((ctxt->node != NULL) && (ctxt->node->name))\n snprintf(prompt, sizeof(prompt), \"%s > \", ctxt->node->name);\n else\n snprintf(prompt, sizeof(prompt), \"? > \");\n prompt[sizeof(prompt) - 1] = 0;\n\n /*\n * Get a new command line\n */\n cmdline = ctxt->input(prompt);\n if (cmdline == NULL)\n break;\n\n /*\n * Parse the command itself\n */\n cur = cmdline;\n while ((*cur == ' ') || (*cur == '\\t'))\n cur++;\n i = 0;\n while ((*cur != ' ') && (*cur != '\\t') &&\n (*cur != '\\n') && (*cur != '\\r')) {\n if (*cur == 0)\n break;\n command[i++] = *cur++;\n }\n command[i] = 0;\n if (i == 0)\n continue;\n\n /*\n * Parse the argument\n */\n while ((*cur == ' ') || (*cur == '\\t'))\n cur++;\n i = 0;\n while ((*cur != '\\n') && (*cur != '\\r') && (*cur != 0)) {\n if (*cur == 0)\n break;\n arg[i++] = *cur++;\n }\n arg[i] = 0;\n\n /*\n * start interpreting the command\n */\n if (!strcmp(command, \"exit\"))\n break;\n if (!strcmp(command, \"quit\"))\n break;\n if (!strcmp(command, \"bye\"))\n break;\n\t\tif (!strcmp(command, \"help\")) {\n\t\t fprintf(ctxt->output, \"\\tbase display XML base of the node\\n\");\n\n/* ==== file: xmllint.c ==== */\n\n xmlHTMLPrintFileInfo(input);\n\n fprintf(ERR_STREAM, \"<b>validity warning</b>: \");\n va_start(args, msg);\n len = strlen(buffer);\n vsnprintf(&buffer[len], sizeof(buffer) - len, msg, args);\n va_end(args);\n xmlHTMLEncodeSend();\n fprintf(ERR_STREAM, \"</p>\\n\");\n\n xmlHTMLPrintFileContext(input);\n xmlHTMLEncodeSend();\n}\n\n/************************************************************************\n *\t\t\t\t\t\t\t\t\t*\n *\t\t\tShell Interface\t\t\t\t\t*\n *\t\t\t\t\t\t\t\t\t*\n ************************************************************************/\n#ifdef LIBXML_DEBUG_ENABLED\n#ifdef LIBXML_XPATH_ENABLED\n/**\n * xmlShellReadline:\n * @prompt: the prompt value\n *\n * Read a string\n *\n * Returns a pointer to it or NULL on EOF the caller is expected to\n * free the returned string.\n */\nstatic char *\nxmlShellReadline(char *prompt) {\n#ifdef HAVE_LIBREADLINE\n char *line_read;\n\n /* Get a line from the user. */\n line_read = readline (prompt);\n\n /* If the line has any text in it, save it on the history. */\n if (line_read && *line_read)\n\tadd_history (line_read);\n\n return (line_read);\n#else\n char line_read[501];\n char *ret;\n int len;\n\n if (prompt != NULL)\n\tfprintf(stdout, \"%s\", prompt);\n fflush(stdout);\n if (!fgets(line_read, 500, stdin))\n return(NULL);\n line_read[500] = 0;\n len = strlen(line_read);\n ret = (char *) malloc(len + 1);\n if (ret != NULL) {\n\tmemcpy (ret, line_read, len + 1);\n }\n return(ret);\n#endif\n}\n#endif /* LIBXML_XPATH_ENABLED */\n#endif /* LIBXML_DEBUG_ENABLED */\n\n/************************************************************************\n *\t\t\t\t\t\t\t\t\t*\n *\t\t\tI/O Interfaces\t\t\t\t\t*\n *\t\t\t\t\t\t\t\t\t*\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n return (0);\n}\n\n/**\n * xmlShell:\n * @doc: the initial document\n=======\n return (0);\n}\n\n#define MAX_PROMPT_SIZE 500\n#define MAX_ARG_SIZE 400\n#define MAX_COMMAND_SIZE 100\n\n/**\n * xmlShell:\n * @doc: the initial document\n>>>>>>> REPLACE\n<<<<<<< SEARCH\nxmlShell(xmlDocPtr doc, const char *filename, xmlShellReadlineFunc input,\n FILE * output)\n{\n char prompt[500] = \"/ > \";\n char *cmdline = NULL, *cur;\n char command[100];\n char arg[400];\n int i;\n xmlShellCtxtPtr ctxt;\n xmlXPathObjectPtr list;\n=======\nxmlShell(xmlDocPtr doc, const char *filename, xmlShellReadlineFunc input,\n FILE * output)\n{\n char prompt[MAX_PROMPT_SIZE] = \"/ > \";\n char *cmdline = NULL, *cur;\n char command[MAX_COMMAND_SIZE];\n char arg[MAX_ARG_SIZE];\n int i;\n xmlShellCtxtPtr ctxt;\n xmlXPathObjectPtr list;\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n cur++;\n i = 0;\n while ((*cur != ' ') && (*cur != '\\t') &&\n (*cur != '\\n') && (*cur != '\\r')) {\n if (*cur == 0)\n break;\n command[i++] = *cur++;\n=======\n cur++;\n i = 0;\n while ((*cur != ' ') && (*cur != '\\t') &&\n (*cur != '\\n') && (*cur != '\\r') &&\n (i < (MAX_COMMAND_SIZE - 1))) {\n if (*cur == 0)\n break;\n command[i++] = *cur++;\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n while ((*cur == ' ') || (*cur == '\\t'))\n cur++;\n i = 0;\n while ((*cur != '\\n') && (*cur != '\\r') && (*cur != 0)) {\n if (*cur == 0)\n break;\n arg[i++] = *cur++;\n=======\n while ((*cur == ' ') || (*cur == '\\t'))\n cur++;\n i = 0;\n while ((*cur != '\\n') && (*cur != '\\r') && (*cur != 0) && (i < (MAX_ARG_SIZE-1))) {\n if (*cur == 0)\n break;\n arg[i++] = *cur++;\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n ************************************************************************/\n#ifdef LIBXML_DEBUG_ENABLED\n#ifdef LIBXML_XPATH_ENABLED\n/**\n * xmlShellReadline:\n * @prompt: the prompt value\n=======\n ************************************************************************/\n#ifdef LIBXML_DEBUG_ENABLED\n#ifdef LIBXML_XPATH_ENABLED\n\n#define MAX_PROMPT_SIZE 500\n\n/**\n * xmlShellReadline:\n * @prompt: the prompt value\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n if (prompt != NULL)\n\tfprintf(stdout, \"%s\", prompt);\n fflush(stdout);\n if (!fgets(line_read, 500, stdin))\n return(NULL);\n line_read[500] = 0;\n len = strlen(line_read);\n ret = (char *) malloc(len + 1);\n if (ret != NULL) {\n=======\n if (prompt != NULL)\n\tfprintf(stdout, \"%s\", prompt);\n fflush(stdout);\n if (!fgets(line_read, MAX_PROMPT_SIZE, stdin))\n return(NULL);\n line_read[MAX_PROMPT_SIZE] = 0;\n len = strlen(line_read);\n ret = (char *) malloc(len + 1);\n if (ret != NULL) {\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-64503: Out-of-bounds write (CWE-787) in libcupsfilters 2.1.1 cfFilterPDFToRaster() via the bundled PDF-to-raster filter. Reported as GHSA-893j-2wr2-wrh9.\n\n# Vulnerable source (cupsfilters/pdftoraster.c)\n```c\n \"cfFilterPDFToRaster: cropbox = [ %f %f %f %f ]; rotate = %d\",\n cropBox.x1, cropBox.x2, cropBox.y1, cropBox.y2,\n rotate);\n \n // Enter input page dimensions in header, so that if no page size got\n // specified for the job, the input size gets used via the header\n l = cropBox.x2 - cropBox.x1;\n if (l<0)\n l = -l;\n\n if (rotate == 90 || rotate == 270)\n doc->header.cupsPageSize[1] = l;\n else\n doc->header.cupsPageSize[0] = l;\n\n l = cropBox.y2 - cropBox.y1;\n if (l < 0)\n l = -l;\n if (rotate == 90 || rotate == 270)\n doc->header.cupsPageSize[0] = l;\n else\n doc->header.cupsPageSize[1] = l;\n if (rotate == 90 || rotate == 270)\n {\n doc->header.cupsImagingBBox[0] =\n doc->header.cupsPageSize[0] - cropBox.y1;\n doc->header.cupsImagingBBox[1] = cropBox.x2;\n doc->header.cupsImagingBBox[2] =\n doc->header.cupsPageSize[0] - cropBox.y2;\n doc->header.cupsImagingBBox[3] = cropBox.x1;\n }\n else\n {\n doc->header.cupsImagingBBox[0] = cropBox.x1;\n doc->header.cupsImagingBBox[1] =\n doc->header.cupsPageSize[1] - cropBox.y1;\n doc->header.cupsImagingBBox[2] = cropBox.x2;\n doc->header.cupsImagingBBox[3] =\n doc->header.cupsPageSize[1] - cropBox.y2;\n }\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n doc->header.cupsPageSize[0] = l;\n else\n doc->header.cupsPageSize[1] = l;\n if (rotate == 90 || rotate == 270)\n {\n doc->header.cupsImagingBBox[0] =\n=======\n doc->header.cupsPageSize[0] = l;\n else\n doc->header.cupsPageSize[1] = l;\n\n //\n // Maximum allowed page size for PDF is 200x200 inches (~ 5x5 m), or 14400x14400 pt\n // https://community.adobe.com/t5/indesign-discussions/maximum-width-of-a-pdf/td-p/9217372\n //\n if (doc->header.cupsPageSize[0] > 14400) {\n fprintf(stderr, \"ERROR: Page width is %.2fpt, too large, cropping to 14400pt\\n\", doc->header.cupsPageSize[0]);\n doc->header.cupsPageSize[0] = 14400;\n }\n if (doc->header.cupsPageSize[1] > 14400) {\n fprintf(stderr, \"ERROR: Page height is %.2fpt, too large, cropping to 14400pt\\n\", doc->header.cupsPageSize[1]);\n doc->header.cupsPageSize[1] = 14400;\n }\n\n if (rotate == 90 || rotate == 270)\n {\n doc->header.cupsImagingBBox[0] =\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2025-7424: libxslt 1.1.43 and earlier is vulnerable to CVE-2025-7424, a type confusion that can lead to heap corruption. The psvi memory field is shared between stylesheet and input data without proper type tracking, causing confusion during XSLT transformations when the library attempts to read data stored by one code path using assumptions from another. An attacker can exploit this by crafting a malicious XSL stylesheet to corrupt memory and potentially execute arbitrary code.\n\n# Vulnerable source (libxslt/xsltutils.h)\n```c\n\n/*\n * Output, reuse libxml I/O buffers.\n */\nXSLTPUBFUN int XSLTCALL\n\t\txsltSaveResultTo\t\t(xmlOutputBufferPtr buf,\n\t\t\t\t\t\t xmlDocPtr result,\n\t\t\t\t\t\t xsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\txsltSaveResultToFilename\t(const char *URI,\n\t\t\t\t\t\t xmlDocPtr result,\n\t\t\t\t\t\t xsltStylesheetPtr style,\n\t\t\t\t\t\t int compression);\nXSLTPUBFUN int XSLTCALL\n\t\txsltSaveResultToFile\t\t(FILE *file,\n\t\t\t\t\t\t xmlDocPtr result,\n\t\t\t\t\t\t xsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\txsltSaveResultToFd\t\t(int fd,\n\t\t\t\t\t\t xmlDocPtr result,\n\t\t\t\t\t\t xsltStylesheetPtr style);\nXSLTPUBFUN int XSLTCALL\n\t\txsltSaveResultToString (xmlChar **doc_txt_ptr,\n int * doc_txt_len,\n xmlDocPtr result,\n xsltStylesheetPtr style);\n\n/*\n * XPath interface\n */\nXSLTPUBFUN xmlXPathCompExprPtr XSLTCALL\n\t\txsltXPathCompile\t\t(xsltStylesheetPtr style,\n\t\t\t\t\t\t const xmlChar *str);\nXSLTPUBFUN xmlXPathCompExprPtr XSLTCALL\n\t\txsltXPathCompileFlags\t\t(xsltStylesheetPtr style,\n\t\t\t\t\t\t const xmlChar *str,\n\t\t\t\t\t\t int flags);\n\n#ifdef IN_LIBXSLT\n/** DOC_DISABLE */\n#define XSLT_SOURCE_NODE_MASK 15u\n#define XSLT_SOURCE_NODE_HAS_KEY 1u\n#define XSLT_SOURCE_NODE_HAS_ID 2u\nint\nxsltGetSourceNodeFlags(xmlNodePtr node);\nint\nxsltSetSourceNodeFlags(xsltTransformContextPtr ctxt, xmlNodePtr node,\n int flags);\nint\nxsltClearSourceNodeFlags(xmlNodePtr node, int flags);\nvoid **\nxsltGetPSVIPtr(xmlNodePtr cur);\n/** DOC_ENABLE */\n#endif\n\n#ifdef WITH_PROFILER\n/*\n * Profiling.\n */\nXSLTPUBFUN void XSLTCALL\n\t\txsltSaveProfiling\t\t(xsltTransformContextPtr ctxt,\n\t\t\t\t\t\t FILE *output);\nXSLTPUBFUN xmlDocPtr XSLTCALL\n\t\txsltGetProfileInformation\t(xsltTransformContextPtr ctxt);\n\nXSLTPUBFUN long XSLTCALL\n\t\txsltTimestamp\t\t\t(void);\nXSLTPUBFUN void XSLTCALL\n\t\txsltCalibrateAdjust\t\t(long delta);\n#endif\n\n/**\n * XSLT_TIMESTAMP_TICS_PER_SEC:\n *\n * Sampling precision for profiling\n */\n#define XSLT_TIMESTAMP_TICS_PER_SEC 100000l\n\n/*\n * Hooks for the debugger.\n */\n\ntypedef enum {\n XSLT_DEBUG_NONE = 0, /* no debugging allowed */\n XSLT_DEBUG_INIT,\n XSLT_DEBUG_STEP,\n XSLT_DEBUG_STEPOUT,\n XSLT_DEBUG_NEXT,\n XSLT_DEBUG_STOP,\n XSLT_DEBUG_CONT,\n XSLT_DEBUG_RUN,\n XSLT_DEBUG_RUN_RESTART,\n XSLT_DEBUG_QUIT\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n#define XSLT_SOURCE_NODE_MASK 15u\n#define XSLT_SOURCE_NODE_HAS_KEY 1u\n#define XSLT_SOURCE_NODE_HAS_ID 2u\nint\nxsltGetSourceNodeFlags(xmlNodePtr node);\nint\n=======\n#define XSLT_SOURCE_NODE_MASK 15u\n#define XSLT_SOURCE_NODE_HAS_KEY 1u\n#define XSLT_SOURCE_NODE_HAS_ID 2u\n#define XSLT_SOURCE_NODE_SHIFT_16 12u\n#define XSLT_SOURCE_NODE_SHIFT_32 28u\n#define XSLT_SOURCE_NODE_VALUE_MASK ((1 << XSLT_SOURCE_NODE_SHIFT_32) - 1)\n#define XSLT_SOURCE_NODE_VALUE_MAX XSLT_SOURCE_NODE_VALUE_MASK\nint\nxsltGetSourceNodeFlags(xmlNodePtr node);\nint\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n int flags);\nint\nxsltClearSourceNodeFlags(xmlNodePtr node, int flags);\nvoid **\nxsltGetPSVIPtr(xmlNodePtr cur);\n/** DOC_ENABLE */\n=======\n int flags);\nint\nxsltClearSourceNodeFlags(xmlNodePtr node, int flags);\nint\nxsltSetSourceNodeValue(xmlNodePtr node, int value);\nint\nxsltGetSourceNodeValue(xmlNodePtr node);\nvoid **\nxsltGetPSVIPtr(xmlNodePtr cur);\n/** DOC_ENABLE */\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-0989: Stack overflow via unbounded recursion when parsing a RelaxNG schema in libxml2 2.13.9 (CWE-674, uncontrolled recursion / denial of service). A crafted .rng schema whose definitions reference other sub-schemas in a deeply nested chain makes the parser recurse without any depth bound while resolving each referenced sub-grammar, exhausting the call stack. Triggered by schema input alone during validation setup; no network or special privileges are required.\n\n# Vulnerable source (relaxng.c, include/libxml/relaxng.h)\n```c\n/* ==== file: relaxng.c ==== */\n *\n * Author: Daniel Veillard\n */\n\n/**\n * TODO:\n * - add support for DTD compatibility spec\n * http://www.oasis-open.org/committees/relax-ng/compatibility-20011203.html\n * - report better mem allocations pbms at runtime and abort immediately.\n */\n\n#define IN_LIBXML\n#include \"libxml.h\"\n\n#ifdef LIBXML_RELAXNG_ENABLED\n\n#include <string.h>\n#include <stdio.h>\n#include <stddef.h>\n#include <libxml/xmlmemory.h>\n#include <libxml/parser.h>\n#include <libxml/parserInternals.h>\n#include <libxml/hash.h>\n#include <libxml/uri.h>\n\n#include <libxml/relaxng.h>\n\n#include <libxml/xmlautomata.h>\n#include <libxml/xmlregexp.h>\n#include <libxml/xmlschemastypes.h>\n\n#include \"private/error.h\"\n#include \"private/regexp.h\"\n#include \"private/string.h\"\n#include \"private/threads.h\"\n\n/*\n * The Relax-NG namespace\n */\nstatic const xmlChar *xmlRelaxNGNs = (const xmlChar *)\n \"http://relaxng.org/ns/structure/1.0\";\n\n#define IS_RELAXNG(node, typ)\t\t\t\t\t\t\\\n ((node != NULL) && (node->ns != NULL) &&\t\t\t\t\\\n (node->type == XML_ELEMENT_NODE) &&\t\t\t\t\t\\\n (xmlStrEqual(node->name, (const xmlChar *) typ)) &&\t\t\\\n (xmlStrEqual(node->ns->href, xmlRelaxNGNs)))\n\n\n#define MAX_ERROR 5\n\ntypedef struct _xmlRelaxNGSchema xmlRelaxNGSchema;\ntypedef xmlRelaxNGSchema *xmlRelaxNGSchemaPtr;\n\n /* ... */\n xmlRelaxNGDefinePtr *defTab; /* pointer to the allocated definitions */\n\n const char *buffer;\n int size;\n\n /* the document stack */\n xmlRelaxNGDocumentPtr doc; /* Current parsed external ref */\n int docNr; /* Depth of the parsing stack */\n int docMax; /* Max depth of the parsing stack */\n xmlRelaxNGDocumentPtr *docTab; /* array of docs */\n\n /* the include stack */\n xmlRelaxNGIncludePtr inc; /* Current parsed include */\n int incNr; /* Depth of the include parsing stack */\n int incMax; /* Max depth of the parsing stack */\n xmlRelaxNGIncludePtr *incTab; /* array of incs */\n\n int idref; /* requires idref checking */\n\n /* used to compile content models */\n xmlAutomataPtr am; /* the automata */\n xmlAutomataStatePtr state; /* used to build the automata */\n\n int crng;\t\t\t/* compact syntax and other flags */\n int freedoc;\t\t/* need to free the document */\n\n xmlResourceLoader resourceLoader;\n void *resourceCtxt;\n /* ... */\nint\nxmlRelaxParserSetFlag(xmlRelaxNGParserCtxt *ctxt, int flags)\n{\n if (ctxt == NULL) return(-1);\n if (flags & XML_RELAXNGP_FREE_DOC) {\n ctxt->crng |= XML_RELAXNGP_FREE_DOC;\n\tflags -= XML_RELAXNGP_FREE_DOC;\n }\n if (flags & XML_RELAXNGP_CRNG) {\n ctxt->crng |= XML_RELAXNGP_CRNG;\n\tflags -= XML_RELAXNGP_CRNG;\n }\n if (flags != 0) return(-1);\n return(0);\n}\n\n/************************************************************************\n *\t\t\t\t\t\t\t\t\t*\n *\t\t\tDocument functions\t\t\t\t*\n *\t\t\t\t\t\t\t\t\t*\n ************************************************************************/\nstatic xmlDocPtr xmlRelaxNGCleanupDoc(xmlRelaxNGParserCtxtPtr ctxt,\n xmlDocPtr doc);\n\nstatic xmlDoc *\nxmlRelaxReadFile(xmlRelaxNGParserCtxtPtr ctxt, const char *filename) {\n xmlParserCtxtPtr pctxt;\n xmlDocPtr doc;\n /* ... */\n if (ctxt->serror != NULL)\n xmlCtxtSetErrorHandler(pctxt, ctxt->serror, ctxt->userData);\n if (ctxt->resourceLoader != NULL)\n xmlCtxtSetResourceLoader(pctxt, ctxt->resourceLoader,\n ctxt->resourceCtxt);\n doc = xmlCtxtReadMemory(pctxt, buf, size, NULL, NULL, 0);\n xmlFreeParserCtxt(pctxt);\n\n return(doc);\n}\n\n/**\n * Pushes a new include on top of the include stack\n *\n * @param ctxt the parser context\n * @param value the element doc\n * @returns 0 in case of error, the index in the stack otherwise\n */\nstatic int\nxmlRelaxNGIncludePush(xmlRelaxNGParserCtxtPtr ctxt,\n xmlRelaxNGIncludePtr value)\n{\n if (ctxt->incTab == NULL) {\n ctxt->incMax = 4;\n ctxt->incNr = 0;\n ctxt->incTab =\n (xmlRelaxNGIncludePtr *) xmlMalloc(ctxt->incMax *\n sizeof(ctxt->incTab[0]));\n if (ctxt->incTab == NULL) {\n xmlRngPErrMemory(ctxt);\n return (0);\n }\n }\n if (ctxt->incNr >= ctxt->incMax) {\n ctxt->incMax *= 2;\n ctxt->incTab =\n (xmlRelaxNGIncludePtr *) xmlRealloc(ctxt->incTab,\n ctxt->incMax *\n sizeof(ctxt->incTab[0]));\n if (ctxt->incTab == NULL) {\n xmlRngPErrMemory(ctxt);\n return (0);\n }\n }\n ctxt->incTab[ctxt->incNr] = value;\n ctxt->inc = value;\n return (ctxt->incNr++);\n}\n\n/**\n * Pops the top include from the include stack\n *\n * @param ctxt the parser context\n /* ... */\n\n /*\n * transmit the ns if needed\n */\n if (ns != NULL) {\n root = xmlDocGetRootElement(doc);\n if (root != NULL) {\n if (xmlHasProp(root, BAD_CAST \"ns\") == NULL) {\n xmlSetProp(root, BAD_CAST \"ns\", ns);\n }\n }\n }\n\n /*\n * push it on the stack\n */\n xmlRelaxNGIncludePush(ctxt, ret);\n\n /*\n * Some preprocessing of the document content, this include recursing\n * in the include stack.\n */\n\n doc = xmlRelaxNGCleanupDoc(ctxt, doc);\n if (doc == NULL) {\n ctxt->inc = NULL;\n return (NULL);\n }\n /* ... */\n\n/**\n * parse a schema definition resource and build an internal\n * XML Schema structure which can be used to validate instances.\n *\n * @param ctxt a Relax-NG parser context\n * @returns the internal XML RelaxNG structure built from the resource or\n * NULL in case of error\n */\nxmlRelaxNG *\nxmlRelaxNGParse(xmlRelaxNGParserCtxt *ctxt)\n{\n xmlRelaxNGPtr ret = NULL;\n xmlDocPtr doc;\n xmlNodePtr root;\n\n xmlRelaxNGInitTypes();\n\n if (ctxt == NULL)\n return (NULL);\n\n /*\n * First step is to parse the input document into an DOM/Infoset\n */\n if (ctxt->URL != NULL) {\n doc = xmlRelaxReadFile(ctxt, (const char *) ctxt->URL);\n if (doc == NULL) {\n xmlRngPErr(ctxt, NULL, XML_RNGP_PARSE_ERROR,\n\n/* ==== file: include/libxml/relaxng.h ==== */\n\n/*\n * Interfaces for parsing.\n */\nXMLPUBFUN xmlRelaxNGParserCtxt *\n\t\t xmlRelaxNGNewParserCtxt\t(const char *URL);\nXMLPUBFUN xmlRelaxNGParserCtxt *\n\t\t xmlRelaxNGNewMemParserCtxt\t(const char *buffer,\n\t\t\t\t\t\t int size);\nXMLPUBFUN xmlRelaxNGParserCtxt *\n\t\t xmlRelaxNGNewDocParserCtxt\t(xmlDoc *doc);\n\nXMLPUBFUN int\n\t\t xmlRelaxParserSetFlag\t(xmlRelaxNGParserCtxt *ctxt,\n\t\t\t\t\t\t int flag);\n\nXMLPUBFUN void\n\t\t xmlRelaxNGFreeParserCtxt\t(xmlRelaxNGParserCtxt *ctxt);\nXMLPUBFUN void\n\t\t xmlRelaxNGSetParserErrors(xmlRelaxNGParserCtxt *ctxt,\n\t\t\t\t\t xmlRelaxNGValidityErrorFunc err,\n\t\t\t\t\t xmlRelaxNGValidityWarningFunc warn,\n\t\t\t\t\t void *ctx);\nXMLPUBFUN int\n\t\t xmlRelaxNGGetParserErrors(xmlRelaxNGParserCtxt *ctxt,\n\t\t\t\t\t xmlRelaxNGValidityErrorFunc *err,\n\t\t\t\t\t xmlRelaxNGValidityWarningFunc *warn,\n\t\t\t\t\t void **ctx);\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\t\t xmlRelaxParserSetFlag\t(xmlRelaxNGParserCtxt *ctxt,\n\t\t\t\t\t\t int flag);\n\nXMLPUBFUN void\n\t\t xmlRelaxNGFreeParserCtxt\t(xmlRelaxNGParserCtxt *ctxt);\nXMLPUBFUN void\n=======\n\t\t xmlRelaxParserSetFlag\t(xmlRelaxNGParserCtxt *ctxt,\n\t\t\t\t\t\t int flag);\n\nXMLPUBFUN int\n\t\t xmlRelaxParserSetIncLImit\t(xmlRelaxNGParserCtxt *ctxt,\n\t\t\t\t\t\t int limit);\n\nXMLPUBFUN void\n\t\t xmlRelaxNGFreeParserCtxt\t(xmlRelaxNGParserCtxt *ctxt);\nXMLPUBFUN void\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\n#ifdef LIBXML_RELAXNG_ENABLED\n\n#include <string.h>\n#include <stdio.h>\n#include <stddef.h>\n=======\n\n#ifdef LIBXML_RELAXNG_ENABLED\n\n#include <errno.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdio.h>\n#include <stddef.h>\n>>>>>>> REPLACE\n<<<<<<< SEARCH\nstatic const xmlChar *xmlRelaxNGNs = (const xmlChar *)\n \"http://relaxng.org/ns/structure/1.0\";\n\n#define IS_RELAXNG(node, typ)\t\t\t\t\t\t\\\n ((node != NULL) && (node->ns != NULL) &&\t\t\t\t\\\n (node->type == XML_ELEMENT_NODE) &&\t\t\t\t\t\\\n=======\nstatic const xmlChar *xmlRelaxNGNs = (const xmlChar *)\n \"http://relaxng.org/ns/structure/1.0\";\n\n/*\n * Default include limit, this can be override with RNG_INCLUDE_LIMIT\n * env variable\n */\nstatic const int _xmlRelaxNGIncludeLimit = 1000;\n\n#define IS_RELAXNG(node, typ)\t\t\t\t\t\t\\\n ((node != NULL) && (node->ns != NULL) &&\t\t\t\t\\\n (node->type == XML_ELEMENT_NODE) &&\t\t\t\t\t\\\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n int incNr; /* Depth of the include parsing stack */\n int incMax; /* Max depth of the parsing stack */\n xmlRelaxNGIncludePtr *incTab; /* array of incs */\n\n int idref; /* requires idref checking */\n\n=======\n int incNr; /* Depth of the include parsing stack */\n int incMax; /* Max depth of the parsing stack */\n xmlRelaxNGIncludePtr *incTab; /* array of incs */\n int incLimit; /* Include limit, to avoid stack-overflow on parse */\n\n int idref; /* requires idref checking */\n\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n return(0);\n}\n\n/************************************************************************\n *\t\t\t\t\t\t\t\t\t*\n *\t\t\tDocument functions\t\t\t\t*\n=======\n return(0);\n}\n\n/**\n * Semi private function used to set the include recursion limit to a\n * parser context. Set to 0 to use the default value.\n *\n * @param ctxt a RelaxNG parser context\n * @param limit the new include depth limit\n * @returns 0 if success and -1 in case of error\n */\nint\nxmlRelaxParserSetIncLImit(xmlRelaxNGParserCtxt *ctxt, int limit)\n{\n if (ctxt == NULL) return(-1);\n if (limit < 0) return(-1);\n ctxt->incLimit = limit;\n return(0);\n}\n\n/************************************************************************\n *\t\t\t\t\t\t\t\t\t*\n *\t\t\tDocument functions\t\t\t\t*\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n *\n * @param ctxt the parser context\n * @param value the element doc\n * @returns 0 in case of error, the index in the stack otherwise\n */\nstatic int\nxmlRelaxNGIncludePush(xmlRelaxNGParserCtxtPtr ctxt,\n=======\n *\n * @param ctxt the parser context\n * @param value the element doc\n * @returns -1 in case of error, the index in the stack otherwise\n */\nstatic int\nxmlRelaxNGIncludePush(xmlRelaxNGParserCtxtPtr ctxt,\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n sizeof(ctxt->incTab[0]));\n if (ctxt->incTab == NULL) {\n xmlRngPErrMemory(ctxt);\n return (0);\n }\n }\n if (ctxt->incNr >= ctxt->incMax) {\n ctxt->incMax *= 2;\n ctxt->incTab =\n=======\n sizeof(ctxt->incTab[0]));\n if (ctxt->incTab == NULL) {\n xmlRngPErrMemory(ctxt);\n return (-1);\n }\n }\n if (ctxt->incNr >= ctxt->incLimit) {\n xmlRngPErr(ctxt, (xmlNodePtr)value->doc, XML_RNGP_PARSE_ERROR,\n \"xmlRelaxNG: inclusion recursion limit reached\\n\", NULL, NULL);\n return(-1);\n }\n\n if (ctxt->incNr >= ctxt->incMax) {\n ctxt->incMax *= 2;\n ctxt->incTab =\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n sizeof(ctxt->incTab[0]));\n if (ctxt->incTab == NULL) {\n xmlRngPErrMemory(ctxt);\n return (0);\n }\n }\n ctxt->incTab[ctxt->incNr] = value;\n=======\n sizeof(ctxt->incTab[0]));\n if (ctxt->incTab == NULL) {\n xmlRngPErrMemory(ctxt);\n return (-1);\n }\n }\n ctxt->incTab[ctxt->incNr] = value;\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n /*\n * push it on the stack\n */\n xmlRelaxNGIncludePush(ctxt, ret);\n\n /*\n * Some preprocessing of the document content, this include recursing\n=======\n /*\n * push it on the stack\n */\n if (xmlRelaxNGIncludePush(ctxt, ret) < 0) {\n return (NULL);\n }\n\n /*\n * Some preprocessing of the document content, this include recursing\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n xmlDocPtr doc;\n xmlNodePtr root;\n\n xmlRelaxNGInitTypes();\n\n if (ctxt == NULL)\n return (NULL);\n\n /*\n * First step is to parse the input document into an DOM/Infoset\n */\n=======\n xmlDocPtr doc;\n xmlNodePtr root;\n\n const char *include_limit_env = getenv(\"RNG_INCLUDE_LIMIT\");\n\n xmlRelaxNGInitTypes();\n\n if (ctxt == NULL)\n return (NULL);\n\n if (ctxt->incLimit == 0) {\n ctxt->incLimit = _xmlRelaxNGIncludeLimit;\n if (include_limit_env != NULL) {\n char *strEnd;\n unsigned long val = 0;\n errno = 0;\n val = strtoul(include_limit_env, &strEnd, 10);\n if (errno != 0 || *strEnd != 0 || val > INT_MAX) {\n xmlRngPErr(ctxt, NULL, XML_RNGP_PARSE_ERROR,\n \"xmlRelaxNGParse: invalid RNG_INCLUDE_LIMIT %s\\n\",\n (const xmlChar*)include_limit_env,\n NULL);\n return(NULL);\n }\n if (val)\n ctxt->incLimit = val;\n }\n }\n\n /*\n * First step is to parse the input document into an DOM/Infoset\n */\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-0992: Denial-of-service vulnerability (CWE-400) in libxml2 2.13.9 XML catalog processing. This causes O(n^2) growth in catalog lookup cost when the resulting list is traversed repeatedly, enabling an attacker who controls catalog file content to cause unbounded CPU or memory consumption.\n\n# Vulnerable source (catalog.c)\n```c\n\t\tBAD_CAST \"rewritePrefix\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"delegatePublic\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_DELEGATE_PUBLIC,\n\t\tBAD_CAST \"delegatePublic\", BAD_CAST \"publicIdStartString\",\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"delegateSystem\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_DELEGATE_SYSTEM,\n\t\tBAD_CAST \"delegateSystem\", BAD_CAST \"systemIdStartString\",\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"uri\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_URI,\n\t\tBAD_CAST \"uri\", BAD_CAST \"name\",\n\t\tBAD_CAST \"uri\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"rewriteURI\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_REWRITE_URI,\n\t\tBAD_CAST \"rewriteURI\", BAD_CAST \"uriStartString\",\n\t\tBAD_CAST \"rewritePrefix\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"delegateURI\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_DELEGATE_URI,\n\t\tBAD_CAST \"delegateURI\", BAD_CAST \"uriStartString\",\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"nextCatalog\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_NEXT_CATALOG,\n\t\tBAD_CAST \"nextCatalog\", NULL,\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n }\n if (entry != NULL) {\n if (parent != NULL) {\n\t entry->parent = parent;\n\t if (parent->children == NULL)\n\t\tparent->children = entry;\n\t else {\n\t\txmlCatalogEntryPtr prev;\n\n\t\tprev = parent->children;\n\t\twhile (prev->next != NULL)\n\t\t prev = prev->next;\n\t\tprev->next = entry;\n\t }\n\t}\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\t\tBAD_CAST \"delegateURI\", BAD_CAST \"uriStartString\",\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"nextCatalog\")) {\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_NEXT_CATALOG,\n\t\tBAD_CAST \"nextCatalog\", NULL,\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n }\n if (entry != NULL) {\n if (parent != NULL) {\n=======\n\t\tBAD_CAST \"delegateURI\", BAD_CAST \"uriStartString\",\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n } else if (xmlStrEqual(cur->name, BAD_CAST \"nextCatalog\")) {\n\txmlCatalogEntryPtr prev = parent->children;\n\n\tentry = xmlParseXMLCatalogOneNode(cur, XML_CATA_NEXT_CATALOG,\n\t\tBAD_CAST \"nextCatalog\", NULL,\n\t\tBAD_CAST \"catalog\", prefer, cgroup);\n\t/* Avoid duplication of nextCatalog */\n\twhile (prev != NULL) {\n\t if ((prev->type == XML_CATA_NEXT_CATALOG) &&\n\t\t(xmlStrEqual (prev->URL, entry->URL)) &&\n\t\t(xmlStrEqual (prev->value, entry->value)) &&\n\t\t(prev->prefer == entry->prefer) &&\n\t\t(prev->group == entry->group)) {\n\t\t if (xmlDebugCatalogs)\n\t\t\txmlCatalogPrintDebug(\n\t\t\t \"Ignoring repeated nextCatalog %s\\n\", entry->URL);\n\t\t xmlFreeCatalogEntry(entry, NULL);\n\t\t entry = NULL;\n\t\t break;\n\t }\n\t prev = prev->next;\n\t}\n }\n if (entry != NULL) {\n if (parent != NULL) {\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-10275: Buffer overflow (CWE-122) in OpenSC 0.27.1 pkcs11-tool.\n\n# Vulnerable source (src/tools/pkcs11-tool.c)\n```c\n\t\t\tif (strcmp(opt_uri->type, \"cert\") == 0) {\n\t\t\t\topt_object_class = CKO_CERTIFICATE;\n\t\t\t\topt_object_class_str = \"cert\";\n\t\t\t} else if (strcmp(opt_uri->type, \"private\") == 0) {\n\t\t\t\topt_object_class = CKO_PRIVATE_KEY;\n\t\t\t\topt_object_class_str = \"privkey\";\n\t\t\t} else if (strcmp(opt_uri->type, \"secret-key\") == 0) {\n\t\t\t\topt_object_class = CKO_SECRET_KEY;\n\t\t\t\topt_object_class_str = \"secrkey\";\n\t\t\t} else if (strcmp(opt_uri->type, \"public\") == 0) {\n\t\t\t\topt_object_class = CKO_PUBLIC_KEY;\n\t\t\t\topt_object_class_str = \"pubkey,\";\n\t\t\t} else if (strcmp(opt_uri->type, \"data\") == 0) {\n\t\t\t\topt_object_class = CKO_DATA;\n\t\t\t\topt_object_class_str = \"data\";\n\t\t\t} else {\n\t\t\t\tfprintf(stderr, \"Unsupported object type \\\"%s\\\" specified in PKCS#11 URI\\n\", opt_uri->type);\n\t\t\t\tutil_print_usage_and_die(app_name, options, option_help, NULL);\n\t\t\t}\n\t\t}\n\t\tif (opt_uri->id) {\n\t\t\topt_object_id_len = opt_uri->id_len;\n\t\t\tmemcpy(opt_object_id, opt_uri->id, opt_object_id_len);\n\t\t}\n\t}\n\n\tif (!opt_module) {\n\t\topt_module = DEFAULT_PKCS11_PROVIDER;\n\t}\n#ifdef _WIN32\n\texpanded_len = PATH_MAX;\n\texpanded_len = ExpandEnvironmentStringsA(opt_module, expanded_val, expanded_len);\n\tif (0 < expanded_len && expanded_len < sizeof expanded_val)\n\t\topt_module = expanded_val;\n#endif\n\n#ifndef ENABLE_SHARED\n\tif (strcmp(opt_module, DEFAULT_PKCS11_PROVIDER) == 0)\n\t\tp11 = &pkcs11_function_list_3_0;\n\telse\n /* ... */\n\tf = fopen(opt_file_to_write, \"rb\");\n\tif (f == NULL)\n\t\tutil_fatal(\"Couldn't open file \\\"%s\\\"\", opt_file_to_write);\n\tfclose(f);\n\n\t/* Get for a not-yet-existing ID */\n\twhile(find_object(session, CKO_PRIVATE_KEY, &priv_key, id, id_len, NULL, 0))\n\t\tid[0]++;\n\n\tprintf(\"\\n*** Generating a %s key pair ***\\n\", opt_key_type);\n\n\tif (!gen_keypair(slot, session, &pub_key, &priv_key, opt_key_type)) {\n\t\tprintf(\"ERR: cannot generate new key pair\\n\");\n\t\treturn session;\n\t}\n\n\ttmp = getID(session, priv_key, &i);\n\tif (i == 0) {\n\t\tfprintf(stderr, \"ERR: newly generated private key has no (or an empty) CKA_ID\\n\");\n\t\treturn session;\n\t}\n\topt_object_id_len = (size_t) i;\n\tmemcpy(opt_object_id, tmp, opt_object_id_len);\n\n\t/* This is done in NSS */\n\tgetMODULUS(session, priv_key, &mod_len);\n\tif (mod_len < 5 || mod_len > 10000) { /* should be reasonable limits */\n\t\tfprintf(stderr, \"ERR: GetAttribute(privkey, CKA_MODULUS) doesn't seem to work\\n\");\n\t\treturn session;\n\t}\n\n\tprintf(\"\\n*** Changing the CKA_ID of private and public key into one of 20 bytes ***\\n\");\n\n\trv = p11->C_SetAttributeValue(session, priv_key, attribs, 1);\n\tif (rv != CKR_OK)\n\t\tp11_fatal(\"C_SetAttributeValue(priv_key)\", rv);\n\n\trv = p11->C_SetAttributeValue(session, pub_key, attribs, 1);\n\tif (rv != CKR_OK)\n\t\tp11_fatal(\"C_SetAttributeValue(pub_key)\", rv);\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\t\t}\n\t\tif (opt_uri->id) {\n\t\t\topt_object_id_len = opt_uri->id_len;\n\t\t\tmemcpy(opt_object_id, opt_uri->id, opt_object_id_len);\n\t\t}\n\t}\n=======\n\t\t}\n\t\tif (opt_uri->id) {\n\t\t\topt_object_id_len = opt_uri->id_len;\n\t\t\tif (opt_object_id_len > sizeof(opt_object_id))\n\t\t\t\tutil_fatal(\"URI's object ID too long\");\n\t\t\tmemcpy(opt_object_id, opt_uri->id, opt_object_id_len);\n\t\t}\n\t}\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\t\treturn session;\n\t}\n\topt_object_id_len = (size_t) i;\n\tmemcpy(opt_object_id, tmp, opt_object_id_len);\n\n\t/* This is done in NSS */\n=======\n\t\treturn session;\n\t}\n\topt_object_id_len = (size_t) i;\n\tif (opt_object_id_len > sizeof(opt_object_id)) {\n\t\tfprintf(stderr, \"ERR: object ID too long\\n\");\n\t\treturn session;\n\t}\n\tmemcpy(opt_object_id, tmp, opt_object_id_len);\n\n\t/* This is done in NSS */\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-11625: The Bytes::Random::Secure Perl module does not detect when a process has been forked. After a fork, the child process inherits the parent's pseudorandom number generator (PRNG) state and will produce the same sequence of bytes as the parent, breaking the cryptographic security guarantees the module is meant to provide. An attacker who can observe the output of both parent and child processes can recover the full PRNG state.\n\n# Vulnerable source (lib/Bytes/Random/Secure.pm)\n```perl\n }\n }\n return %args;\n}\n\n\n# Round bits parameter to nearest greater or equal 32-bit \"long\".\nsub _round_bits_to_ge_32 {\n my( $self, $bits ) = @_;\n my $remainder = $bits % 32;\n return $bits if $remainder == 0;\n carp \"Bits field must be a multiple of 32. Rounding up.\";\n return $bits + 32 - $remainder;\n}\n\n\n# Constrain bits argument to a reasonable range.\nsub _constrain_bits {\n my( $self, $bits, $min, $max ) = @_;\n\n if( $bits < $min ) {\n carp \"Bits field must be >= 64 (two longs). Rounding up.\";\n $bits = $min;\n }\n elsif( $bits > $max ) {\n carp \"Bits field must be <= 8192 (256 longs). Rounding down.\";\n $bits = $max;\n }\n # No need for an 'else' here.\n \n return $bits;\n}\n\n\n# Build attributes set by new(). Any not explicitly set will use defaults\n# as described in the constant OO_ATTRIBS.\nsub _build_attributes {\n my ( $self, $args ) = @_;\n\n while ( my ( $arg, $default ) = each %{ OO_ATTRIBS() } ) {\n $self->{$arg} = exists $args->{$arg} ? $args->{$arg} : $default;\n }\n\n $self->{_RNG} = undef; # Lazy initialization.\n return $self;\n}\n\n\n# Get a seed and use it to instantiate a RNG.\n# Note: Currently we specify only Math::Random::ISAAC. However, the PRNG\n# object attribute may be used in the future to specify alternate RNG's.\nsub _instantiate_rng {\n my $self = shift;\n\n my ( %seed_opts ) = $self->_build_seed_options;\n my @seeds = $self->_generate_seed( %seed_opts );\n $self->{_RNG} = Math::Random::ISAAC->new(@seeds);\n\n return $self->{_RNG};\n}\n\n\n# Set up seed options for Crypt::Random::Seed\nsub _build_seed_options {\n my( $self ) = @_;\n\n my %crs_opts;\n\n # CRYPT_RANDOM_SEED_OPTS enumerates the options that Crypt::Random::Seed\n # supports. We have already built object attributes for those options.\n foreach my $opt ( @{ CRYPT_RANDOM_SEED_OPTS() } ) {\n $crs_opts{$opt} = $self->{$opt} if defined $self->{$opt};\n }\n\n return %crs_opts;\n}\n\n\n# Use Crypt::Random::Seed to generate some high-quality long int\n# seeds for Math::Random::ISAAC.\nsub _generate_seed {\n my ( $self, %options_hash ) = @_;\n\n my $seed_size = $self->{Bits} / 32;\n my $source = Crypt::Random::Seed->new(%options_hash);\n\n croak 'Unable to obtain a strong seed source from Crypt::Random::Seed.'\n unless defined $source;\n\n return $source->random_values($seed_size); # List of unsigned longs.\n}\n\n\n# Validate that we are getting an integer >= 0.\n# If not, throw an exception.\nsub _validate_int {\n my( $self, $input ) = @_;\n croak \"Byte count must be a positive integer.\"\n unless looks_like_number( $input )\n && $input == int( $input )\n && $input >= 0;\n return 1;\n}\n\n\n# Random bytes string.\nsub bytes {\n my( $self, $bytes ) = @_;\n $bytes = defined $bytes ? $bytes : 0; # Default to zero bytes.\n $self->_validate_int( $bytes ); # Throws on violation.\n\n $self->_instantiate_rng unless defined $self->{_RNG};\n\n my $str = '';\n\n while ( $bytes >= 4 ) { # Utilize irand()'s 32 bits.\n $str .= pack( \"L\", $self->{_RNG}->irand );\n $bytes -= 4;\n }\n\n if ( $bytes > 0 ) {\n my $rval = $self->{_RNG}->irand;\n\n $str .= pack( \"S\", ( $rval >> 8 ) & 0xFFFF )\n if $bytes >= 2; # 16 bits.\n $str .= pack( \"C\", $rval & 0xFF ) if $bytes % 2; # 8 bits.\n\n }\n return $str;\n}\n\n# Base64 encoding of random byte string.\nsub bytes_base64 {\n my ( $self, $bytes, $eol ) = @_;\n return encode_base64( $self->bytes($bytes), defined($eol) ? $eol : qq{\\n} );\n}\n\n# Hex digits representing random byte string (No whitespace, no '0x').\nsub bytes_hex {\n my ( $self, $bytes ) = @_;\n return unpack 'H*', $self->bytes($bytes);\n}\n\n# Quoted Printable representation of random byte string.\nsub bytes_qp {\n my ( $self, $bytes, $eol ) = @_;\n return encode_qp $self->bytes($bytes), defined($eol) ? $eol : qq{\\n}, 1;\n}\n\n\nsub string_from {\n my( $self, $bag, $bytes ) = @_;\n $bag = defined $bag ? $bag : '';\n $bytes = defined $bytes ? $bytes : 0;\n my $range = length $bag;\n \n $self->_validate_int( $bytes );\n \n croak \"Bag's size must be at least 1 character.\"\n if $range < 1;\n\n my $rand_bytes = q{}; # We need an empty (and defined) string.\n \n for my $random ( $self->_ranged_randoms( $range, $bytes ) ) {\n $rand_bytes .= substr( $bag, $random, 1 );\n }\n\n return $rand_bytes;\n}\n\n\nsub shuffle {\n my($self, $aref) = @_;\n croak 'Argument must be an array reference.' unless 'ARRAY' eq ref $aref;\n return $aref unless @$aref;\n for (my $i = @$aref; --$i;) {\n my $r = ($self->_ranged_randoms($i+1, 1))[0];\n ($aref->[$i],$aref->[$r]) = ($aref->[$r], $aref->[$i]);\n }\n return $aref;\n}\n\n# Helpers for string_from() and shuffle.\n\nsub _ranged_randoms {\n my ( $self, $range, $count ) = @_;\n $count = defined $count ? $count : 0;\n\n # Lazily seed the RNG so we don't waste available strong entropy.\n $self->_instantiate_rng unless defined $self->{_RNG};\n\n my $divisor = $self->_closest_divisor($range);\n\n my @randoms;\n \n $#randoms = $count - 1; # Pre-extend the @randoms array so 'push' avoids\n # copy on resize.\n @randoms = (); # Then purge it, but its memory won't be released.\n\n for my $n ( 1 .. $count ) {\n my $random;\n\n # The loop rolls, and re-rolls if the random number is out of the bag's\n # range. This is to avoid a solution that would introduce modulo bias.\n do {\n $random = $self->{_RNG}->irand % $divisor;\n } while ( $random >= $range );\n\n push @randoms, $random;\n }\n\n return @randoms;\n}\n\n\n# Find nearest factor of 2**32 >= $range.\n\nsub _closest_divisor {\n my ( $self, $range ) = @_;\n $range = defined $range ? $range : 0;\n\n croak \"$range must be positive.\" if $range < 0;\n croak \"$range exceeds irand max limit of 2**32.\" if $range > 2**32;\n\n my $n = 0;\n my $d;\n while ( $n <= 32 ) {\n $d = 2 ** $n++;\n last if $d >= $range;\n }\n \n return $d;\n}\n\n\n\n# irand, so that people who don't need \"bytes\" can enjoy B::R::S's convenience\n# without jumping through \"unpack\" hoops. (A suggestion from Dana Jacobsen.)\n\nsub irand {\n my( $self ) = @_;\n $self->_instantiate_rng unless defined $self->{_RNG};\n return $self->{_RNG}->irand;\n}\n\n\n################################################################################\n## Functions interface ##\n################################################################################\n\n# Instantiate our random number generator(s) inside of a lexical closure,\n# limiting the scope of the RNG object so it can't be tampered with.\n\n{\n my $RNG_object = undef;\n\n\n # Lazily, instantiate the RNG object, but only once.\n my $fetch_RNG = sub {\n $RNG_object = Bytes::Random::Secure->new( FUNC_STD )\n unless defined $RNG_object;\n return $RNG_object;\n };\n\n\n sub random_bytes {\n return $fetch_RNG->()->bytes( @_ );\n }\n\n\n sub random_string_from {\n return $fetch_RNG->()->string_from( @_ );\n }\n\n}\n\n\n# Base64 encoded random bytes functions\n\nsub random_bytes_base64 {\n my ( $bytes, $eof ) = @_;\n return encode_base64 random_bytes($bytes), defined($eof) ? $eof : qq{\\n};\n}\n\n\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n $self->{$arg} = exists $args->{$arg} ? $args->{$arg} : $default;\n }\n\n $self->{_RNG} = undef; # Lazy initialization.\n return $self;\n}\n=======\n $self->{$arg} = exists $args->{$arg} ? $args->{$arg} : $default;\n }\n\n $self->{_pid} = $$;\n $self->{_RNG} = undef; # Lazy initialization.\n return $self;\n}\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n my @seeds = $self->_generate_seed( %seed_opts );\n $self->{_RNG} = Math::Random::ISAAC->new(@seeds);\n\n return $self->{_RNG};\n}\n\n=======\n my @seeds = $self->_generate_seed( %seed_opts );\n $self->{_RNG} = Math::Random::ISAAC->new(@seeds);\n\n $self->{_pid} = $$;\n\n return $self->{_RNG};\n}\n\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n $bytes = defined $bytes ? $bytes : 0; # Default to zero bytes.\n $self->_validate_int( $bytes ); # Throws on violation.\n\n $self->_instantiate_rng unless defined $self->{_RNG};\n\n my $str = '';\n\n=======\n $bytes = defined $bytes ? $bytes : 0; # Default to zero bytes.\n $self->_validate_int( $bytes ); # Throws on violation.\n\n $self->_instantiate_rng unless $$ == $self->{_pid} && defined $self->{_RNG};\n\n my $str = '';\n\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n $count = defined $count ? $count : 0;\n\n # Lazily seed the RNG so we don't waste available strong entropy.\n $self->_instantiate_rng unless defined $self->{_RNG};\n\n my $divisor = $self->_closest_divisor($range);\n\n=======\n $count = defined $count ? $count : 0;\n\n # Lazily seed the RNG so we don't waste available strong entropy.\n $self->_instantiate_rng unless $$ == $self->{_pid} && defined $self->{_RNG};\n\n my $divisor = $self->_closest_divisor($range);\n\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\nsub irand {\n my( $self ) = @_;\n $self->_instantiate_rng unless defined $self->{_RNG};\n return $self->{_RNG}->irand;\n}\n=======\n\nsub irand {\n my( $self ) = @_;\n $self->_instantiate_rng unless $$ == $self->{_pid} && defined $self->{_RNG};\n return $self->{_RNG}->irand;\n}\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-31842: HTTP request handling defect in tinyproxy 1.11.3: the transfer-encoding detection in src/reqs.c uses case-sensitive string comparison when checking for chunked encoding, causing tinyproxy to mishandle HTTP requests where the Transfer-Encoding header value uses non-lowercase casing.\n\n# Vulnerable source (src/reqs.c)\n```c\n * -1.\n */\nstatic long get_content_length (pseudomap *hashofheaders)\n{\n char *data;\n long content_length = -1;\n\n data = pseudomap_find (hashofheaders, \"content-length\");\n\n if (data)\n content_length = atol (data);\n\n return content_length;\n}\n\nstatic int is_chunked_transfer (pseudomap *hashofheaders)\n{\n char *data;\n data = pseudomap_find (hashofheaders, \"transfer-encoding\");\n return data ? !strcmp (data, \"chunked\") : 0;\n}\n\n/*\n * Search for Via header in a hash of headers and either write a new Via\n * header, or append our information to the end of an existing Via header.\n *\n * FIXME: Need to add code to \"hide\" our internal information for security\n * purposes.\n */\nstatic int\nwrite_via_header (int fd, pseudomap *hashofheaders,\n unsigned int major, unsigned int minor)\n{\n char hostname[512];\n char *data;\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n{\n char *data;\n data = pseudomap_find (hashofheaders, \"transfer-encoding\");\n return data ? !strcmp (data, \"chunked\") : 0;\n}\n=======\n{\n char *data;\n data = pseudomap_find (hashofheaders, \"transfer-encoding\");\n return data ? !strcasecmp (data, \"chunked\") : 0;\n}\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-32316: jq 1.8.1 jv.c has two heap buffer overflows in text handling functions: in the bad-byte replacement function, the buffer size calculation could overflow a 32-bit integer when processing a sufficiently large input, resulting in a tiny buffer with a large write beyond it; in the append function, the same wrap-around applies when appending data that pushes the combined total beyond the 32-bit maximum, causing an out-of-bounds write.\n\n# Vulnerable source (src/jv.c)\n```c\n }\n if (idx > -1)\n res = jv_array_append(res, jv_number(idx));\n idx = -1;\n }\n jv_free(a);\n jv_free(b);\n return res;\n}\n\n/*\n * Strings (internal helpers)\n */\n\n#define JVP_FLAGS_STRING JVP_MAKE_FLAGS(JV_KIND_STRING, JVP_PAYLOAD_ALLOCATED)\n\ntypedef struct {\n jv_refcnt refcnt;\n uint32_t hash;\n // high 31 bits are length, low bit is a flag\n // indicating whether hash has been computed.\n uint32_t length_hashed;\n uint32_t alloc_length;\n char data[];\n} jvp_string;\n\nstatic jvp_string* jvp_string_ptr(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_STRING));\n return (jvp_string*)a.u.ptr;\n}\n\nstatic jvp_string* jvp_string_alloc(uint32_t size) {\n jvp_string* s = jv_mem_alloc(sizeof(jvp_string) + size + 1);\n s->refcnt.count = 1;\n s->alloc_length = size;\n return s;\n}\n\n/* Copy a UTF8 string, replacing all badly encoded points with U+FFFD */\nstatic jv jvp_string_copy_replace_bad(const char* data, uint32_t length) {\n const char* end = data + length;\n const char* i = data;\n\n uint32_t maxlength = length * 3 + 1; // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n jvp_string* s = jvp_string_alloc(maxlength);\n char* out = s->data;\n int c = 0;\n\n while ((i = jvp_utf8_next(i, end, &c))) {\n if (c == -1) {\n c = 0xFFFD; // U+FFFD REPLACEMENT CHARACTER\n }\n out += jvp_utf8_encode(c, out);\n assert(out < s->data + maxlength);\n }\n length = out - s->data;\n s->data[length] = 0;\n s->length_hashed = length << 1;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n/* Assumes valid UTF8 */\nstatic jv jvp_string_new(const char* data, uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = length << 1;\n if (data != NULL)\n memcpy(s->data, data, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\nstatic jv jvp_string_empty_new(uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n\nstatic void jvp_string_free(jv js) {\n jvp_string* s = jvp_string_ptr(js);\n if (jvp_refcnt_dec(&s->refcnt)) {\n jv_mem_free(s);\n }\n}\n\nstatic uint32_t jvp_string_length(jvp_string* s) {\n return s->length_hashed >> 1;\n}\n\nstatic uint32_t jvp_string_remaining_space(jvp_string* s) {\n assert(s->alloc_length >= jvp_string_length(s));\n uint32_t r = s->alloc_length - jvp_string_length(s);\n return r;\n}\n\nstatic jv jvp_string_append(jv string, const char* data, uint32_t len) {\n jvp_string* s = jvp_string_ptr(string);\n uint32_t currlen = jvp_string_length(s);\n\n if (jvp_refcnt_unshared(string.u.ptr) &&\n jvp_string_remaining_space(s) >= len) {\n // the next string fits at the end of a\n memcpy(s->data + currlen, data, len);\n s->data[currlen + len] = 0;\n s->length_hashed = (currlen + len) << 1;\n return string;\n } else {\n // allocate a bigger buffer and copy\n uint32_t allocsz = (currlen + len) * 2;\n if (allocsz < 32) allocsz = 32;\n jvp_string* news = jvp_string_alloc(allocsz);\n news->length_hashed = (currlen + len) << 1;\n memcpy(news->data, s->data, currlen);\n memcpy(news->data + currlen, data, len);\n news->data[currlen + len] = 0;\n jvp_string_free(string);\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&news->refcnt}};\n return r;\n }\n}\n\nstatic const uint32_t HASH_SEED = 0x432A9843;\n\nstatic uint32_t rotl32 (uint32_t x, int8_t r){\n return (x << r) | (x >> (32 - r));\n}\n\nstatic uint32_t jvp_string_hash(jv jstr) {\n jvp_string* str = jvp_string_ptr(jstr);\n if (str->length_hashed & 1)\n return str->hash;\n\n /* The following is based on MurmurHash3.\n MurmurHash3 was written by Austin Appleby, and is placed\n in the public domain. */\n\n const uint8_t* data = (const uint8_t*)str->data;\n int len = (int)jvp_string_length(str);\n const int nblocks = len / 4;\n\n uint32_t h1 = HASH_SEED;\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n const char* end = data + length;\n const char* i = data;\n\n uint32_t maxlength = length * 3 + 1; // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n jvp_string* s = jvp_string_alloc(maxlength);\n char* out = s->data;\n int c = 0;\n=======\n const char* end = data + length;\n const char* i = data;\n\n // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n uint64_t maxlength = (uint64_t)length * 3 + 1;\n if (maxlength >= INT_MAX) {\n return jv_invalid_with_msg(jv_string(\"String too long\"));\n }\n\n jvp_string* s = jvp_string_alloc(maxlength);\n char* out = s->data;\n int c = 0;\n>>>>>>> REPLACE\n<<<<<<< SEARCH\nstatic jv jvp_string_append(jv string, const char* data, uint32_t len) {\n jvp_string* s = jvp_string_ptr(string);\n uint32_t currlen = jvp_string_length(s);\n\n if (jvp_refcnt_unshared(string.u.ptr) &&\n jvp_string_remaining_space(s) >= len) {\n=======\nstatic jv jvp_string_append(jv string, const char* data, uint32_t len) {\n jvp_string* s = jvp_string_ptr(string);\n uint32_t currlen = jvp_string_length(s);\n if ((uint64_t)currlen + len >= INT_MAX) {\n jv_free(string);\n return jv_invalid_with_msg(jv_string(\"String too long\"));\n }\n\n if (jvp_refcnt_unshared(string.u.ptr) &&\n jvp_string_remaining_space(s) >= len) {\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-32746: GNU inetutils includes a telnetd server that passes certain environment variables from clients to the spawned login process. The util-linux login utility, since version 2.40, reads the CREDENTIALS_DIRECTORY environment variable: if a directory at that path contains a 'login.noauth' file set to 'yes', the utility bypasses password authentication. Because telnetd relays client-supplied environment variables directly to login, a remote attacker can supply a path they control as CREDENTIALS_DIRECTORY and place the 'login.noauth' bypass file there, gaining unauthenticated access as any user including root.\n\n# Vulnerable source (telnetd/pty.c)\n```c\n * Remove a few things from the environment that\n * don't need to be there.\n *\n * Security fix included in telnet-95.10.23.NE of David Borman <deb@cray.com>.\n */\nstatic void\nscrub_env (void)\n{\n char **cpp, **cpp2;\n\n for (cpp2 = cpp = environ; *cpp; cpp++)\n {\n if (strncmp (*cpp, \"LD_\", 3)\n\t && strncmp (*cpp, \"_RLD_\", 5)\n\t && strncmp (*cpp, \"LIBPATH=\", 8) && strncmp (*cpp, \"IFS=\", 4))\n\t*cpp2++ = *cpp;\n }\n *cpp2 = 0;\n}\n\nvoid\nstart_login (char *host, int autologin, char *name)\n{\n char *cmd;\n int argc;\n char **argv;\n\n (void) host;\t\t\t/* Silence warnings. Diagnostic use? */\n (void) autologin;\n (void) name;\n\n scrub_env ();\n\n /* Set the environment variable \"LINEMODE\" to indicate our linemode */\n if (lmodetype == REAL_LINEMODE)\n setenv (\"LINEMODE\", \"real\", 1);\n else if (lmodetype == KLUDGE_LINEMODE || lmodetype == KLUDGE_OK)\n setenv (\"LINEMODE\", \"kludge\", 1);\n\n cmd = expand_line (login_invocation);\n if (!cmd)\n fatal (net, \"can't expand login command line\");\n argcv_get (cmd, \"\", &argc, &argv);\n execv (argv[0], argv);\n syslog (LOG_ERR, \"%s: %m\\n\", cmd);\n fatalperror (net, cmd);\n}\n\n/* SIG is generally naught every time the server itself\n * decides to close the connection out of an error condition.\n * In response to TELOPT_LOGOUT from the client, SIG is set\n * to SIGHUP, so we consider the exit as a success. In other\n * cases, when the forked client process is caught exiting,\n * then SIG will be SIGCHLD. Then we deliver the clients's\n * reported exit code.\n */\nvoid\ncleanup (int sig)\n{\n int status = EXIT_FAILURE;\n char *p;\n\n if (sig == SIGCHLD)\n {\n pid_t pid = waitpid ((pid_t) - 1, &status, WNOHANG);\n syslog (LOG_INFO, \"child process %ld exited: %d\",\n\t (long) pid, WEXITSTATUS (status));\n\n status = WEXITSTATUS (status);\n }\n else if (sig == SIGHUP)\n status = EXIT_SUCCESS;\t/* Response to TELOPT_LOGOUT. */\n\n p = line + sizeof (PATH_TTY_PFX) - 1;\n utmp_logout (p);\n chmod (line, 0644);\n chown (line, 0, 0);\n shutdown (net, 2);\n exit (status);\n}\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n if (!cmd)\n fatal (net, \"can't expand login command line\");\n argcv_get (cmd, \"\", &argc, &argv);\n execv (argv[0], argv);\n syslog (LOG_ERR, \"%s: %m\\n\", cmd);\n fatalperror (net, cmd);\n=======\n if (!cmd)\n fatal (net, \"can't expand login command line\");\n argcv_get (cmd, \"\", &argc, &argv);\n\n /* util-linux's \"login\" introduced an authentication bypass method\n * via environment variable \"CREDENTIALS_DIRECTORY\" in version 2.40.\n * Clear it from the environment before executing \"login\" to prevent\n * abuse via Telnet.\n */\n unsetenv (\"CREDENTIALS_DIRECTORY\");\n\n execv (argv[0], argv);\n syslog (LOG_ERR, \"%s: %m\\n\", cmd);\n fatalperror (net, cmd);\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-33236: CWE-22 in python3Packages.nltk 3.9.2. The NLTK corpus fetch engine reads package catalog data from a CDN endpoint (https://raw.githubusercontent.com/nltk/nltk_data/gh-pages/packages.xml). Each catalog entry specifies a data-category value (e.g. corpora) and a resource identifier (e.g. punkt). Both strings pass directly into os.path.join() when constructing the target disk path, with no sanitization for path-escape sequences. An attacker able to serve a hostile catalog via MITM, CDN compromise, or rogue mirror can embed sequences of two-dot path elements in either field, directing corpus file writes to arbitrary OS paths beyond the NLTK data root.\n\n# Vulnerable source (nltk/downloader.py)\n```python\n author=\"Unknown\",\n unzip=True,\n **kw,\n ):\n self.id = id\n \"\"\"A unique identifier for this package.\"\"\"\n\n self.name = name or id\n \"\"\"A string name for this package.\"\"\"\n\n self.subdir = subdir\n \"\"\"The subdirectory where this package should be installed.\n E.g., ``'corpora'`` or ``'taggers'``.\"\"\"\n\n self.url = url\n \"\"\"A URL that can be used to download this package's file.\"\"\"\n\n self.size = int(size)\n \"\"\"The filesize (in bytes) of the package file.\"\"\"\n\n self.unzipped_size = int(unzipped_size)\n \"\"\"The total filesize of the files contained in the package's\n zipfile.\"\"\"\n\n self.checksum = checksum\n \"\"\"The MD-5 checksum of the package file.\"\"\"\n\n self.svn_revision = svn_revision\n \"\"\"A subversion revision number for this package.\"\"\"\n\n\n/* ... */\n\n\n # Check for (and remove) any old/stale version.\n filepath = os.path.join(download_dir, info.filename)\n if os.path.exists(filepath):\n if status == self.STALE:\n yield StaleMessage(info)\n os.remove(filepath)\n\n # Ensure the download_dir exists\n os.makedirs(download_dir, exist_ok=True)\n os.makedirs(os.path.join(download_dir, info.subdir), exist_ok=True)\n\n # Download the file. This will raise an IOError if the url\n # is not found.\n\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n self.name = name or id\n \"\"\"A string name for this package.\"\"\"\n\n self.subdir = subdir\n \"\"\"The subdirectory where this package should be installed.\n E.g., ``'corpora'`` or ``'taggers'``.\"\"\"\n\n self.url = url\n \"\"\"A URL that can be used to download this package's file.\"\"\"\n\n=======\n self.name = name or id\n \"\"\"A string name for this package.\"\"\"\n\n # Validate subdir to prevent path traversal from malicious XML index\n if os.path.isabs(subdir) or \"..\" in subdir.replace(\"\\\\\", \"/\").split(\"/\"):\n raise ValueError(\n f\"Invalid package subdir {subdir!r}: must be a relative path \"\n f\"without parent directory references\"\n )\n self.subdir = subdir\n \"\"\"The subdirectory where this package should be installed.\n E.g., ``'corpora'`` or ``'taggers'``.\"\"\"\n\n # Validate id to prevent path traversal\n if os.sep in id or \"/\" in id or \"\\\\\" in id or \"..\" in id:\n raise ValueError(\n f\"Invalid package id {id!r}: must not contain path separators\"\n )\n\n self.url = url\n \"\"\"A URL that can be used to download this package's file.\"\"\"\n\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\n # Check for (and remove) any old/stale version.\n filepath = os.path.join(download_dir, info.filename)\n if os.path.exists(filepath):\n if status == self.STALE:\n yield StaleMessage(info)\n=======\n\n # Check for (and remove) any old/stale version.\n filepath = os.path.join(download_dir, info.filename)\n\n # Defense-in-depth: verify filepath stays within download_dir\n real_download = os.path.realpath(os.path.abspath(download_dir))\n real_filepath = os.path.realpath(os.path.abspath(filepath))\n if not real_filepath.startswith(real_download + os.sep):\n yield ErrorMessage(\n info,\n f\"Path traversal blocked: package '{info.id}' attempted to \"\n f\"write outside download directory (subdir='{info.subdir}')\",\n )\n return\n\n if os.path.exists(filepath):\n if status == self.STALE:\n yield StaleMessage(info)\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-33947: jq through 1.8.1 allows deeply nested path arrays to cause unbounded recursion in jv_setpath, jv_getpath, and jv_delpaths, leading to stack overflow. A crafted input document with paths exceeding ten thousand levels of nesting triggers the vulnerability when processed with path manipulation filters.\n\n# Vulnerable source (src/jv_aux.c)\n```c\n }\n if (i < delidx) {\n break;\n }\n neg_idx++;\n }\n while (nonneg_idx < jv_array_length(jv_copy(nonneg_keys))) {\n int delidx = (int)jv_number_get_value_and_consume(jv_array_get(jv_copy(nonneg_keys), nonneg_idx));\n if (i == delidx) {\n del = 1;\n }\n if (i < delidx) {\n break;\n }\n nonneg_idx++;\n }\n for (int sidx=0; !del && sidx<jv_array_length(jv_copy(starts)); sidx++) {\n if ((int)jv_number_get_value_and_consume(jv_array_get(jv_copy(starts), sidx)) <= i &&\n i < (int)jv_number_get_value_and_consume(jv_array_get(jv_copy(ends), sidx))) {\n del = 1;\n }\n }\n if (!del)\n new_array = jv_array_append(new_array, jv_array_get(jv_copy(t), i));\n }\n arr_out:\n jv_free(neg_keys);\n jv_free(nonneg_keys);\n jv_free(starts);\n jv_free(ends);\n jv_free(t);\n t = new_array;\n } else if (jv_get_kind(t) == JV_KIND_OBJECT) {\n jv_array_foreach(keys, i, k) {\n if (jv_get_kind(k) != JV_KIND_STRING) {\n jv_free(t);\n t = jv_invalid_with_msg(jv_string_fmt(\"Cannot delete %s field of object\",\n jv_kind_name(jv_get_kind(k))));\n jv_free(k);\n break;\n }\n t = jv_object_delete(t, k);\n }\n } else {\n jv err = jv_invalid_with_msg(jv_string_fmt(\"Cannot delete fields from %s\",\n jv_kind_name(jv_get_kind(t))));\n jv_free(t);\n t = err;\n }\n jv_free(keys);\n return t;\n}\n\njv jv_setpath(jv root, jv path, jv value) {\n if (jv_get_kind(path) != JV_KIND_ARRAY) {\n jv_free(value);\n jv_free(root);\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n if (!jv_is_valid(root)){\n jv_free(value);\n jv_free(path);\n return root;\n }\n if (jv_array_length(jv_copy(path)) == 0) {\n jv_free(path);\n jv_free(root);\n return value;\n }\n jv pathcurr = jv_array_get(jv_copy(path), 0);\n jv pathrest = jv_array_slice(path, 1, jv_array_length(jv_copy(path)));\n\n /*\n * We need to be careful not to make extra copies since that leads to\n * quadratic behavior (e.g., when growing large data structures in a\n * reduction with `setpath/2`, i.e., with `|=`.\n */\n if (jv_get_kind(pathcurr) == JV_KIND_OBJECT) {\n // Assignment to slice -- dunno yet how to avoid the extra copy\n return jv_set(root, pathcurr,\n jv_setpath(jv_get(jv_copy(root), jv_copy(pathcurr)), pathrest, value));\n }\n\n jv subroot = jv_get(jv_copy(root), jv_copy(pathcurr));\n if (!jv_is_valid(subroot)) {\n jv_free(root);\n jv_free(pathcurr);\n jv_free(pathrest);\n jv_free(value);\n return subroot;\n }\n\n // To avoid the extra copy we drop the reference from `root` by setting that\n // to null first.\n root = jv_set(root, jv_copy(pathcurr), jv_null());\n if (!jv_is_valid(root)) {\n jv_free(subroot);\n jv_free(pathcurr);\n jv_free(pathrest);\n jv_free(value);\n return root;\n }\n return jv_set(root, pathcurr, jv_setpath(subroot, pathrest, value));\n}\n\njv jv_getpath(jv root, jv path) {\n if (jv_get_kind(path) != JV_KIND_ARRAY) {\n jv_free(root);\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n if (!jv_is_valid(root)) {\n jv_free(path);\n return root;\n }\n if (jv_array_length(jv_copy(path)) == 0) {\n jv_free(path);\n return root;\n }\n jv pathcurr = jv_array_get(jv_copy(path), 0);\n jv pathrest = jv_array_slice(path, 1, jv_array_length(jv_copy(path)));\n return jv_getpath(jv_get(root, pathcurr), pathrest);\n}\n\n// assumes paths is a sorted array of arrays\nstatic jv delpaths_sorted(jv object, jv paths, int start) {\n jv delkeys = jv_array();\n for (int i=0; i<jv_array_length(jv_copy(paths));) {\n int j = i;\n assert(jv_array_length(jv_array_get(jv_copy(paths), i)) > start);\n int delkey = jv_array_length(jv_array_get(jv_copy(paths), i)) == start + 1;\n jv key = jv_array_get(jv_array_get(jv_copy(paths), i), start);\n while (j < jv_array_length(jv_copy(paths)) &&\n jv_equal(jv_copy(key), jv_array_get(jv_array_get(jv_copy(paths), j), start)))\n j++;\n // if i <= entry < j, then entry starts with key\n if (delkey) {\n // deleting this entire key, we don't care about any more specific deletions\n delkeys = jv_array_append(delkeys, key);\n } else {\n // deleting certain sub-parts of this key\n jv subobject = jv_get(jv_copy(object), jv_copy(key));\n if (!jv_is_valid(subobject)) {\n jv_free(key);\n jv_free(object);\n object = subobject;\n break;\n } else if (jv_get_kind(subobject) == JV_KIND_NULL) {\n jv_free(key);\n jv_free(subobject);\n } else {\n jv newsubobject = delpaths_sorted(subobject, jv_array_slice(jv_copy(paths), i, j), start+1);\n if (!jv_is_valid(newsubobject)) {\n jv_free(key);\n jv_free(object);\n object = newsubobject;\n break;\n }\n object = jv_set(object, key, newsubobject);\n }\n if (!jv_is_valid(object)) break;\n }\n i = j;\n }\n jv_free(paths);\n if (jv_is_valid(object))\n object = jv_dels(object, delkeys);\n else\n jv_free(delkeys);\n return object;\n}\n\njv jv_delpaths(jv object, jv paths) {\n if (jv_get_kind(paths) != JV_KIND_ARRAY) {\n jv_free(object);\n jv_free(paths);\n return jv_invalid_with_msg(jv_string(\"Paths must be specified as an array\"));\n }\n paths = jv_sort(paths, jv_copy(paths));\n jv_array_foreach(paths, i, elem) {\n if (jv_get_kind(elem) != JV_KIND_ARRAY) {\n jv_free(object);\n jv_free(paths);\n jv err = jv_invalid_with_msg(jv_string_fmt(\"Path must be specified as array, not %s\",\n jv_kind_name(jv_get_kind(elem))));\n jv_free(elem);\n return err;\n }\n jv_free(elem);\n }\n if (jv_array_length(jv_copy(paths)) == 0) {\n // nothing is being deleted\n jv_free(paths);\n return object;\n }\n if (jv_array_length(jv_array_get(jv_copy(paths), 0)) == 0) {\n // everything is being deleted\n jv_free(paths);\n jv_free(object);\n return jv_null();\n }\n return delpaths_sorted(object, paths, 0);\n}\n\n\nstatic int string_cmp(const void* pa, const void* pb){\n const jv* a = pa;\n const jv* b = pb;\n int lena = jv_string_length_bytes(jv_copy(*a));\n int lenb = jv_string_length_bytes(jv_copy(*b));\n int minlen = lena < lenb ? lena : lenb;\n int r = memcmp(jv_string_value(*a), jv_string_value(*b), minlen);\n if (r == 0) r = lena - lenb;\n return r;\n}\n\njv jv_keys_unsorted(jv x) {\n if (jv_get_kind(x) != JV_KIND_OBJECT)\n return jv_keys(x);\n jv answer = jv_array_sized(jv_object_length(jv_copy(x)));\n jv_object_foreach(x, key, value) {\n answer = jv_array_append(answer, key);\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n return t;\n}\n\njv jv_setpath(jv root, jv path, jv value) {\n if (jv_get_kind(path) != JV_KIND_ARRAY) {\n jv_free(value);\n=======\n return t;\n}\n\n#ifndef MAX_PATH_DEPTH\n#define MAX_PATH_DEPTH (10000)\n#endif\n\njv jv_setpath(jv root, jv path, jv value) {\n if (jv_get_kind(path) != JV_KIND_ARRAY) {\n jv_free(value);\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n if (!jv_is_valid(root)){\n jv_free(value);\n jv_free(path);\n=======\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n if (jv_array_length(jv_copy(path)) > MAX_PATH_DEPTH) {\n jv_free(value);\n jv_free(root);\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n }\n if (!jv_is_valid(root)){\n jv_free(value);\n jv_free(path);\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n if (!jv_is_valid(root)) {\n jv_free(path);\n return root;\n=======\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path must be specified as an array\"));\n }\n if (jv_array_length(jv_copy(path)) > MAX_PATH_DEPTH) {\n jv_free(root);\n jv_free(path);\n return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n }\n if (!jv_is_valid(root)) {\n jv_free(path);\n return root;\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n jv_free(elem);\n return err;\n }\n jv_free(elem);\n }\n if (jv_array_length(jv_copy(paths)) == 0) {\n=======\n jv_free(elem);\n return err;\n }\n if (jv_array_length(jv_copy(elem)) > MAX_PATH_DEPTH) {\n jv_free(object);\n jv_free(paths);\n jv_free(elem);\n return jv_invalid_with_msg(jv_string(\"Path too deep\"));\n }\n jv_free(elem);\n }\n if (jv_array_length(jv_copy(paths)) == 0) {\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-33948: Input like '{}\\x00{}' was thus parsed as only '{}' and jq exited 0, dropping the trailing bytes after the NUL \u2014 so jq and another NUL-aware consumer could disagree on the document. Affects jq 1.8.x.\n\n# Vulnerable source (src/util.c)\n```c\n\n state->buf[0] = 0;\n state->buf_valid_len = 0;\n if (state->current_input) {\n char *res;\n memset(state->buf, 0xff, sizeof(state->buf));\n\n const int max_utf8_len = 4;\n const int max_gets_len = sizeof(state->buf) - max_utf8_len;\n while (!(res = fgets(state->buf, max_gets_len, state->current_input)) &&\n ferror(state->current_input) && errno == EINTR)\n clearerr(state->current_input);\n if (res == NULL) {\n state->buf[0] = 0;\n if (ferror(state->current_input))\n state->failures++;\n } else {\n const char *p = memchr(state->buf, '\\n', max_gets_len);\n\n if (p != NULL)\n state->current_line++;\n\n if (p == NULL && state->parser != NULL) {\n /*\n * There should be no NULs in JSON texts (but JSON text\n * sequences are another story).\n */\n state->buf_valid_len = strlen(state->buf);\n } else if (p == NULL && feof(state->current_input)) {\n size_t i;\n\n /*\n * XXX We don't know how many bytes we've read!\n *\n * We can't use getline() because there need not be any newlines\n * in the input. The only entirely correct choices are: use\n * fgetc() or fread(). Using fread() will complicate buffer\n * management here.\n *\n * For now we check how much fgets() read by scanning backwards for the\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n if (p != NULL)\n state->current_line++;\n\n if (p == NULL && state->parser != NULL) {\n /*\n * There should be no NULs in JSON texts (but JSON text\n * sequences are another story).\n */\n state->buf_valid_len = strlen(state->buf);\n } else if (p == NULL && feof(state->current_input)) {\n size_t i;\n\n /*\n=======\n if (p != NULL)\n state->current_line++;\n\n if (p == NULL && feof(state->current_input)) {\n size_t i;\n\n /*\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-39979: jq 1.8.1 jv_parse_sized_custom_flags function has an out-of-bounds read when a parse error is reported: the error message formatter used the input pointer with a plain format specifier that reads until NUL rather than stopping at the declared input boundary, allowing a crafted JSON input without a terminating NUL to trigger reads past the allocated buffer.\n\n# Vulnerable source (src/jv_parse.c)\n```c\n value = p->next;\n }\n p->next = jv_invalid();\n if ((p->flags & JV_PARSE_SEQ) && !p->last_ch_was_ws && jv_get_kind(value) == JV_KIND_NUMBER) {\n jv_free(value);\n return make_error(p, \"Potentially truncated top-level numeric value at EOF at line %d, column %d\", p->line, p->column);\n }\n return value;\n }\n}\n\njv jv_parse_sized_custom_flags(const char* string, int length, int flags) {\n struct jv_parser parser;\n parser_init(&parser, flags);\n jv_parser_set_buf(&parser, string, length, 0);\n jv value = jv_parser_next(&parser);\n if (jv_is_valid(value)) {\n jv next = jv_parser_next(&parser);\n if (jv_is_valid(next)) {\n // multiple JSON values, we only wanted one\n jv_free(value);\n jv_free(next);\n value = jv_invalid_with_msg(jv_string(\"Unexpected extra JSON values\"));\n } else if (jv_invalid_has_msg(jv_copy(next))) {\n // parser error after the first JSON value\n jv_free(value);\n value = next;\n } else {\n // a single valid JSON value\n jv_free(next);\n }\n } else if (jv_invalid_has_msg(jv_copy(value))) {\n // parse error, we'll return it\n } else {\n // no value at all\n jv_free(value);\n value = jv_invalid_with_msg(jv_string(\"Expected JSON value\"));\n }\n parser_free(&parser);\n\n if (!jv_is_valid(value) && jv_invalid_has_msg(jv_copy(value))) {\n jv msg = jv_invalid_get_msg(value);\n value = jv_invalid_with_msg(jv_string_fmt(\"%s (while parsing '%s')\",\n jv_string_value(msg),\n string));\n jv_free(msg);\n }\n return value;\n}\n\njv jv_parse_sized(const char* string, int length) {\n return jv_parse_sized_custom_flags(string, length, 0);\n}\n\njv jv_parse(const char* string) {\n return jv_parse_sized(string, strlen(string));\n}\n\njv jv_parse_custom_flags(const char* string, int flags) {\n return jv_parse_sized_custom_flags(string, strlen(string), flags);\n}\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\n if (!jv_is_valid(value) && jv_invalid_has_msg(jv_copy(value))) {\n jv msg = jv_invalid_get_msg(value);\n value = jv_invalid_with_msg(jv_string_fmt(\"%s (while parsing '%s')\",\n jv_string_value(msg),\n string));\n jv_free(msg);\n }\n=======\n\n if (!jv_is_valid(value) && jv_invalid_has_msg(jv_copy(value))) {\n jv msg = jv_invalid_get_msg(value);\n value = jv_invalid_with_msg(jv_string_fmt(\"%s (while parsing '%.*s')\",\n jv_string_value(msg),\n length,\n string));\n jv_free(msg);\n }\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-40164: An attacker can craft a JSON object whose keys all map to the same hash bucket, causing worst-case O(n^2) collision-chain traversal during parsing and evaluation. Processing a sufficiently large crafted object causes excessive CPU consumption and service unavailability.\n\n# Vulnerable source (src/jv.c)\n```c\n/*\n * Portions Copyright (c) 2016 Kungliga Tekniska H\u00f6gskolan\n * (Royal Institute of Technology, Stockholm, Sweden).\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n */\n\n\n#include <stdint.h>\n#include <stddef.h>\n#include <assert.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <stdarg.h>\n#include <limits.h>\n#include <math.h>\n#include <float.h>\n\n#include \"jv_alloc.h\"\n#include \"jv.h\"\n#include \"jv_unicode.h\"\n#include \"util.h\"\n\n/*\n * Internal refcounting helpers\n */\n\ntypedef struct jv_refcnt {\n int count;\n} jv_refcnt;\n\nstatic const jv_refcnt JV_REFCNT_INIT = {1};\n\nstatic void jvp_refcnt_inc(jv_refcnt* c) {\n c->count++;\n}\n\nstatic int jvp_refcnt_dec(jv_refcnt* c) {\n c->count--;\n return c->count == 0;\n}\n\nstatic int jvp_refcnt_unshared(jv_refcnt* c) {\n assert(c->count > 0);\n return c->count == 1;\n}\n\n#define KIND_MASK 0xF\n#define PFLAGS_MASK 0xF0\n#define PTYPE_MASK 0x70\n\ntypedef enum {\n JVP_PAYLOAD_NONE = 0,\n JVP_PAYLOAD_ALLOCATED = 0x80,\n} payload_flags;\n\n#define JVP_MAKE_PFLAGS(ptype, allocated) ((((ptype) << 4) & PTYPE_MASK) | ((allocated) ? JVP_PAYLOAD_ALLOCATED : 0))\n#define JVP_MAKE_FLAGS(kind, pflags) ((kind & KIND_MASK) | (pflags & PFLAGS_MASK))\n\n#define JVP_FLAGS(j) ((j).kind_flags)\n#define JVP_KIND(j) (JVP_FLAGS(j) & KIND_MASK)\n\n#define JVP_HAS_FLAGS(j, flags) (JVP_FLAGS(j) == flags)\n#define JVP_HAS_KIND(j, kind) (JVP_KIND(j) == kind)\n\n#define JVP_IS_ALLOCATED(j) (j.kind_flags & JVP_PAYLOAD_ALLOCATED)\n\n#define JVP_FLAGS_NULL JVP_MAKE_FLAGS(JV_KIND_NULL, JVP_PAYLOAD_NONE)\n#define JVP_FLAGS_INVALID JVP_MAKE_FLAGS(JV_KIND_INVALID, JVP_PAYLOAD_NONE)\n#define JVP_FLAGS_FALSE JVP_MAKE_FLAGS(JV_KIND_FALSE, JVP_PAYLOAD_NONE)\n#define JVP_FLAGS_TRUE JVP_MAKE_FLAGS(JV_KIND_TRUE, JVP_PAYLOAD_NONE)\n\njv_kind jv_get_kind(jv x) {\n return JVP_KIND(x);\n}\n\nconst char* jv_kind_name(jv_kind k) {\n switch (k) {\n case JV_KIND_INVALID: return \"<invalid>\";\n case JV_KIND_NULL: return \"null\";\n case JV_KIND_FALSE: return \"boolean\";\n case JV_KIND_TRUE: return \"boolean\";\n case JV_KIND_NUMBER: return \"number\";\n case JV_KIND_STRING: return \"string\";\n case JV_KIND_ARRAY: return \"array\";\n case JV_KIND_OBJECT: return \"object\";\n }\n assert(0 && \"invalid kind\");\n return \"<unknown>\";\n}\n\nconst jv JV_NULL = {JVP_FLAGS_NULL, 0, 0, 0, {0}};\nconst jv JV_INVALID = {JVP_FLAGS_INVALID, 0, 0, 0, {0}};\nconst jv JV_FALSE = {JVP_FLAGS_FALSE, 0, 0, 0, {0}};\nconst jv JV_TRUE = {JVP_FLAGS_TRUE, 0, 0, 0, {0}};\n\njv jv_true(void) {\n return JV_TRUE;\n}\n\njv jv_false(void) {\n return JV_FALSE;\n}\n\njv jv_null(void) {\n return JV_NULL;\n}\n\njv jv_bool(int x) {\n return x ? JV_TRUE : JV_FALSE;\n}\n\n/*\n * Invalid objects, with optional error messages\n */\n\n#define JVP_FLAGS_INVALID_MSG JVP_MAKE_FLAGS(JV_KIND_INVALID, JVP_PAYLOAD_ALLOCATED)\n\ntypedef struct {\n jv_refcnt refcnt;\n jv errmsg;\n} jvp_invalid;\n\njv jv_invalid_with_msg(jv err) {\n jvp_invalid* i = jv_mem_alloc(sizeof(jvp_invalid));\n i->refcnt = JV_REFCNT_INIT;\n i->errmsg = err;\n\n jv x = {JVP_FLAGS_INVALID_MSG, 0, 0, 0, {&i->refcnt}};\n return x;\n}\n\njv jv_invalid(void) {\n return JV_INVALID;\n}\n\njv jv_invalid_get_msg(jv inv) {\n assert(JVP_HAS_KIND(inv, JV_KIND_INVALID));\n\n jv x;\n if (JVP_HAS_FLAGS(inv, JVP_FLAGS_INVALID_MSG)) {\n x = jv_copy(((jvp_invalid*)inv.u.ptr)->errmsg);\n }\n else {\n x = jv_null();\n }\n\n jv_free(inv);\n return x;\n}\n\nint jv_invalid_has_msg(jv inv) {\n assert(JVP_HAS_KIND(inv, JV_KIND_INVALID));\n int r = JVP_HAS_FLAGS(inv, JVP_FLAGS_INVALID_MSG);\n jv_free(inv);\n return r;\n}\n\nstatic void jvp_invalid_free(jv x) {\n assert(JVP_HAS_KIND(x, JV_KIND_INVALID));\n if (JVP_HAS_FLAGS(x, JVP_FLAGS_INVALID_MSG) && jvp_refcnt_dec(x.u.ptr)) {\n jv_free(((jvp_invalid*)x.u.ptr)->errmsg);\n jv_mem_free(x.u.ptr);\n }\n}\n\n/*\n * Numbers\n */\n\n#ifdef USE_DECNUM\n#include \"jv_dtoa.h\"\n#include \"jv_dtoa_tsd.h\"\n\n// we will manage the space for the struct\n#define DECNUMDIGITS 1\n#include \"decNumber/decNumber.h\"\n\nenum {\n JVP_NUMBER_NATIVE = 0,\n JVP_NUMBER_DECIMAL = 1\n};\n\n#define JVP_FLAGS_NUMBER_NATIVE JVP_MAKE_FLAGS(JV_KIND_NUMBER, JVP_MAKE_PFLAGS(JVP_NUMBER_NATIVE, 0))\n#define JVP_FLAGS_NUMBER_LITERAL JVP_MAKE_FLAGS(JV_KIND_NUMBER, JVP_MAKE_PFLAGS(JVP_NUMBER_DECIMAL, 1))\n\n// the decimal precision of binary double\n#define DEC_NUMBER_DOUBLE_PRECISION (17)\n#define DEC_NUMBER_STRING_GUARD (14)\n#define DEC_NUMBER_DOUBLE_EXTRA_UNITS ((DEC_NUMBER_DOUBLE_PRECISION - DECNUMDIGITS + DECDPUN - 1)/DECDPUN)\n\n#include \"jv_thread.h\"\n#ifdef WIN32\n#ifndef __MINGW32__\n/* Copied from Heimdal: thread-specific keys; see lib/base/dll.c in Heimdal */\n\n/*\n * This is an implementation of thread-specific storage with\n * destructors. WIN32 doesn't quite have this. Instead it has\n * DllMain(), an entry point in every DLL that gets called to notify the\n * DLL of thread/process \"attach\"/\"detach\" events.\n *\n * We use __thread (or __declspec(thread)) for the thread-local itself\n * and DllMain() DLL_THREAD_DETACH events to drive destruction of\n * thread-local values.\n *\n * When building in maintainer mode on non-Windows pthread systems this\n * uses a single pthread key instead to implement multiple keys. This\n * keeps the code from rotting when modified by non-Windows developers.\n */\n\n/* Logical array of keys that grows lock-lessly */\ntypedef struct tls_keys tls_keys;\nstruct tls_keys {\n void (**keys_dtors)(void *); /* array of destructors */\n size_t keys_start_idx; /* index of first destructor */\n size_t keys_num;\n tls_keys *keys_next;\n};\n\n/*\n * Well, not quite locklessly. We need synchronization primitives to do\n * this locklessly. An atomic CAS will do.\n */\nstatic pthread_mutex_t tls_key_defs_lock = PTHREAD_MUTEX_INITIALIZER;\nstatic tls_keys *tls_key_defs;\n\n/* Logical array of values (per-thread; no locking needed here) */\nstruct tls_values {\n void **values; /* realloc()ed */\n size_t values_num;\n};\n\n#ifdef _MSC_VER\nstatic __declspec(thread) struct nomem_handler nomem_handler;\n#else\nstatic __thread struct tls_values values;\n#endif\n\n#define DEAD_KEY ((void *)8)\n\nstatic void\nw32_service_thread_detach(void *unused)\n{\n tls_keys *key_defs;\n void (*dtor)(void*);\n size_t i;\n\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = tls_key_defs;\n pthread_mutex_unlock(&tls_key_defs_lock);\n\n if (key_defs == NULL)\n return;\n\n for (i = 0; i < values.values_num; i++) {\n assert(i >= key_defs->keys_start_idx);\n if (i >= key_defs->keys_start_idx + key_defs->keys_num) {\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = key_defs->keys_next;\n pthread_mutex_unlock(&tls_key_defs_lock);\n\n assert(key_defs != NULL);\n assert(i >= key_defs->keys_start_idx);\n assert(i < key_defs->keys_start_idx + key_defs->keys_num);\n }\n dtor = key_defs->keys_dtors[i - key_defs->keys_start_idx];\n if (values.values[i] != NULL && dtor != NULL && dtor != DEAD_KEY)\n dtor(values.values[i]);\n values.values[i] = NULL;\n }\n}\n\nextern void jv_tsd_dtoa_ctx_init();\nextern void jv_tsd_dtoa_ctx_fini();\nvoid jv_tsd_dec_ctx_fini();\nvoid jv_tsd_dec_ctx_init();\n\nBOOL WINAPI DllMain(HINSTANCE hinstDLL,\n DWORD fdwReason,\n LPVOID lpvReserved)\n{\n switch (fdwReason) {\n case DLL_PROCESS_ATTACH:\n\t/*create_pt_key();*/\n\tjv_tsd_dtoa_ctx_init();\n\tjv_tsd_dec_ctx_init();\n\treturn TRUE;\n case DLL_PROCESS_DETACH:\n\tjv_tsd_dtoa_ctx_fini();\n\tjv_tsd_dec_ctx_fini();\n\treturn TRUE;\n case DLL_THREAD_ATTACH: return 0;\n case DLL_THREAD_DETACH:\n w32_service_thread_detach(NULL);\n return TRUE;\n default: return TRUE;\n }\n}\n\nint\npthread_key_create(pthread_key_t *key, void (*dtor)(void *))\n{\n tls_keys *key_defs, *new_key_defs;\n size_t i, k;\n int ret = ENOMEM;\n\n pthread_mutex_lock(&tls_key_defs_lock);\n if (tls_key_defs == NULL) {\n /* First key */\n new_key_defs = calloc(1, sizeof(*new_key_defs));\n if (new_key_defs == NULL) {\n pthread_mutex_unlock(&tls_key_defs_lock);\n return ENOMEM;\n }\n new_key_defs->keys_num = 8;\n new_key_defs->keys_dtors = calloc(new_key_defs->keys_num,\n sizeof(*new_key_defs->keys_dtors));\n if (new_key_defs->keys_dtors == NULL) {\n pthread_mutex_unlock(&tls_key_defs_lock);\n free(new_key_defs);\n return ENOMEM;\n }\n tls_key_defs = new_key_defs;\n new_key_defs->keys_dtors[0] = dtor;\n for (i = 1; i < new_key_defs->keys_num; i++)\n new_key_defs->keys_dtors[i] = NULL;\n pthread_mutex_unlock(&tls_key_defs_lock);\n return 0;\n }\n\n for (key_defs = tls_key_defs;\n key_defs != NULL;\n key_defs = key_defs->keys_next) {\n k = key_defs->keys_start_idx;\n for (i = 0; i < key_defs->keys_num; i++, k++) {\n if (key_defs->keys_dtors[i] == NULL) {\n /* Found free slot; use it */\n key_defs->keys_dtors[i] = dtor;\n *key = k;\n pthread_mutex_unlock(&tls_key_defs_lock);\n return 0;\n }\n }\n if (key_defs->keys_next != NULL)\n continue;\n\n /* Grow the registration array */\n /* XXX DRY */\n new_key_defs = calloc(1, sizeof(*new_key_defs));\n if (new_key_defs == NULL)\n break;\n\n new_key_defs->keys_dtors =\n calloc(key_defs->keys_num + key_defs->keys_num / 2,\n sizeof(*new_key_defs->keys_dtors));\n if (new_key_defs->keys_dtors == NULL) {\n free(new_key_defs);\n break;\n }\n new_key_defs->keys_start_idx = key_defs->keys_start_idx +\n key_defs->keys_num;\n new_key_defs->keys_num = key_defs->keys_num + key_defs->keys_num / 2;\n new_key_defs->keys_dtors[i] = dtor;\n for (i = 1; i < new_key_defs->keys_num; i++)\n new_key_defs->keys_dtors[i] = NULL;\n key_defs->keys_next = new_key_defs;\n ret = 0;\n break;\n }\n pthread_mutex_unlock(&tls_key_defs_lock);\n return ret;\n}\n\nstatic void\nkey_lookup(pthread_key_t key, tls_keys **kd,\n size_t *dtor_idx, void (**dtor)(void *))\n{\n tls_keys *key_defs;\n\n if (kd != NULL)\n *kd = NULL;\n if (dtor_idx != NULL)\n *dtor_idx = 0;\n if (dtor != NULL)\n *dtor = NULL;\n\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = tls_key_defs;\n pthread_mutex_unlock(&tls_key_defs_lock);\n\n while (key_defs != NULL) {\n if (key >= key_defs->keys_start_idx &&\n key < key_defs->keys_start_idx + key_defs->keys_num) {\n if (kd != NULL)\n *kd = key_defs;\n if (dtor_idx != NULL)\n *dtor_idx = key - key_defs->keys_start_idx;\n if (dtor != NULL)\n *dtor = key_defs->keys_dtors[key - key_defs->keys_start_idx];\n return;\n }\n\n pthread_mutex_lock(&tls_key_defs_lock);\n key_defs = key_defs->keys_next;\n pthread_mutex_unlock(&tls_key_defs_lock);\n assert(key_defs != NULL);\n assert(key >= key_defs->keys_start_idx);\n }\n}\n\nint\npthread_setspecific(pthread_key_t key, void *value)\n{\n void **new_values;\n size_t new_num;\n void (*dtor)(void *);\n size_t i;\n\n key_lookup(key, NULL, NULL, &dtor);\n if (dtor == NULL)\n return EINVAL;\n\n if (key >= values.values_num) {\n if (values.values_num == 0) {\n values.values = NULL;\n new_num = 8;\n } else {\n new_num = (values.values_num + values.values_num / 2);\n }\n new_values = realloc(values.values, sizeof(void *) * new_num);\n if (new_values == NULL)\n return ENOMEM;\n for (i = values.values_num; i < new_num; i++)\n new_values[i] = NULL;\n values.values = new_values;\n values.values_num = new_num;\n }\n\n assert(key < values.values_num);\n\n if (values.values[key] != NULL && dtor != NULL && dtor != DEAD_KEY)\n dtor(values.values[key]);\n\n values.values[key] = value;\n return 0;\n}\n\nvoid *\npthread_getspecific(pthread_key_t key)\n{\n if (key >= values.values_num)\n return NULL;\n return values.values[key];\n}\n#else\n#include <pthread.h>\n#endif\n#else\n#include <pthread.h>\n#endif\n\nstatic pthread_key_t dec_ctx_key;\nstatic pthread_once_t dec_ctx_once = PTHREAD_ONCE_INIT;\n\n#define DEC_CONTEXT() tsd_dec_ctx_get(&dec_ctx_key)\n\n// atexit finalizer to clean up the tsd dec contexts if main() exits\n// without having called pthread_exit()\nvoid jv_tsd_dec_ctx_fini(void) {\n jv_mem_free(pthread_getspecific(dec_ctx_key));\n pthread_setspecific(dec_ctx_key, NULL);\n}\n\nvoid jv_tsd_dec_ctx_init(void) {\n if (pthread_key_create(&dec_ctx_key, jv_mem_free) != 0) {\n fprintf(stderr, \"error: cannot create thread specific key\");\n abort();\n }\n atexit(jv_tsd_dec_ctx_fini);\n}\n\nstatic decContext* tsd_dec_ctx_get(pthread_key_t *key) {\n pthread_once(&dec_ctx_once, jv_tsd_dec_ctx_init); // cannot fail\n decContext *ctx = (decContext*)pthread_getspecific(*key);\n if (ctx) {\n return ctx;\n }\n\n ctx = malloc(sizeof(decContext));\n if (ctx) {\n if (key == &dec_ctx_key)\n {\n decContextDefault(ctx, DEC_INIT_BASE);\n // make sure (Int)D2U(rhs->exponent-lhs->exponent) does not overflow\n ctx->digits = MIN(DEC_MAX_DIGITS,\n INT32_MAX - (DECDPUN - 1) - (ctx->emax - ctx->emin - 1));\n ctx->traps = 0; /*no errors*/\n }\n if (pthread_setspecific(*key, ctx) != 0) {\n fprintf(stderr, \"error: cannot store thread specific data\");\n abort();\n }\n }\n return ctx;\n}\n\ntypedef struct {\n jv_refcnt refcnt;\n double num_double;\n char * literal_data;\n decNumber num_decimal; // must be the last field in the structure for memory management\n} jvp_literal_number;\n\ntypedef struct {\n decNumber number;\n decNumberUnit units[DEC_NUMBER_DOUBLE_EXTRA_UNITS];\n} decNumberDoublePrecision;\n\n\nstatic inline int jvp_number_is_literal(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n return JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL);\n}\n\nstatic jvp_literal_number* jvp_literal_number_ptr(jv j) {\n assert(JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL));\n return (jvp_literal_number*)j.u.ptr;\n}\n\nstatic decNumber* jvp_dec_number_ptr(jv j) {\n assert(JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL));\n return &(((jvp_literal_number*)j.u.ptr)->num_decimal);\n}\n\nstatic jvp_literal_number* jvp_literal_number_alloc(unsigned literal_length) {\n /* The number of units needed is ceil(DECNUMDIGITS/DECDPUN) */\n int units = ((literal_length+DECDPUN-1)/DECDPUN);\n\n jvp_literal_number* n = jv_mem_alloc(\n sizeof(jvp_literal_number)\n + sizeof(decNumberUnit) * units\n );\n\n n->refcnt = JV_REFCNT_INIT;\n n->num_double = NAN;\n n->literal_data = NULL;\n return n;\n}\n\nstatic jv jvp_literal_number_new(const char * literal) {\n jvp_literal_number* n = jvp_literal_number_alloc(strlen(literal));\n\n decContext *ctx = DEC_CONTEXT();\n decContextClearStatus(ctx, DEC_Conversion_syntax);\n decNumberFromString(&n->num_decimal, literal, ctx);\n\n if (ctx->status & DEC_Conversion_syntax) {\n jv_mem_free(n);\n return JV_INVALID;\n }\n if (decNumberIsNaN(&n->num_decimal)) {\n // Reject NaN with payload.\n if (n->num_decimal.digits > 1 || *n->num_decimal.lsu != 0) {\n jv_mem_free(n);\n return JV_INVALID;\n }\n jv_mem_free(n);\n return jv_number(NAN);\n }\n\n jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, 0, {&n->refcnt}};\n return r;\n}\n\nstatic double jvp_literal_number_to_double(jv j) {\n assert(JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL));\n decContext dblCtx;\n\n // init as decimal64 but change digits to allow conversion to binary64 (double)\n decContextDefault(&dblCtx, DEC_INIT_DECIMAL64);\n dblCtx.digits = DEC_NUMBER_DOUBLE_PRECISION;\n\n decNumber *p_dec_number = jvp_dec_number_ptr(j);\n decNumberDoublePrecision dec_double;\n char literal[DEC_NUMBER_DOUBLE_PRECISION + DEC_NUMBER_STRING_GUARD + 1];\n\n // reduce the number to the shortest possible form\n // that fits into the 64 bit floating point representation\n decNumberReduce(&dec_double.number, p_dec_number, &dblCtx);\n\n decNumberToString(&dec_double.number, literal);\n\n char *end;\n return jvp_strtod(tsd_dtoa_context_get(), literal, &end);\n}\n\nstatic const char* jvp_literal_number_literal(jv n) {\n assert(JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL));\n decNumber *pdec = jvp_dec_number_ptr(n);\n jvp_literal_number* plit = jvp_literal_number_ptr(n);\n\n if (decNumberIsNaN(pdec)) {\n return \"null\";\n }\n\n if (decNumberIsInfinite(pdec)) {\n // We cannot preserve the literal data of numbers outside the limited\n // range of exponent. Since `decNumberToString` returns \"Infinity\"\n // (or \"-Infinity\"), and to reduce stack allocations as possible, we\n // normalize infinities in the callers instead of printing the maximum\n // (or minimum) double here.\n return NULL;\n }\n\n if (plit->literal_data == NULL) {\n int len = jvp_dec_number_ptr(n)->digits + 15 /* 14 + NUL */;\n plit->literal_data = jv_mem_alloc(len);\n\n // Preserve the actual precision as we have parsed it\n // don't do decNumberTrim(pdec);\n\n decNumberToString(pdec, plit->literal_data);\n }\n\n return plit->literal_data;\n}\n\nint jv_number_has_literal(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n return JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL);\n}\n\nconst char* jv_number_get_literal(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n return jvp_literal_number_literal(n);\n } else {\n return NULL;\n }\n}\n\njv jv_number_with_literal(const char * literal) {\n return jvp_literal_number_new(literal);\n}\n#endif /* USE_DECNUM */\n\njv jv_number(double x) {\n jv j = {\n#ifdef USE_DECNUM\n JVP_FLAGS_NUMBER_NATIVE,\n#else\n JV_KIND_NUMBER,\n#endif\n 0, 0, 0, {.number = x}\n };\n return j;\n}\n\nstatic void jvp_number_free(jv j) {\n assert(JVP_HAS_KIND(j, JV_KIND_NUMBER));\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL) && jvp_refcnt_dec(j.u.ptr)) {\n jvp_literal_number* n = jvp_literal_number_ptr(j);\n if (n->literal_data) {\n jv_mem_free(n->literal_data);\n }\n jv_mem_free(n);\n }\n#endif\n}\n\ndouble jv_number_value(jv j) {\n assert(JVP_HAS_KIND(j, JV_KIND_NUMBER));\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(j, JVP_FLAGS_NUMBER_LITERAL)) {\n jvp_literal_number* n = jvp_literal_number_ptr(j);\n\n if (isnan(n->num_double)) {\n n->num_double = jvp_literal_number_to_double(j);\n }\n\n return n->num_double;\n }\n#endif\n return j.u.number;\n}\n\nint jv_is_integer(jv j){\n if (!JVP_HAS_KIND(j, JV_KIND_NUMBER)){\n return 0;\n }\n\n double x = jv_number_value(j);\n\n double ipart;\n double fpart = modf(x, &ipart);\n\n return fabs(fpart) < DBL_EPSILON;\n}\n\nint jvp_number_is_nan(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n decNumber *pdec = jvp_dec_number_ptr(n);\n return decNumberIsNaN(pdec);\n }\n#endif\n return isnan(n.u.number);\n}\n\njv jv_number_abs(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n jvp_literal_number* m = jvp_literal_number_alloc(jvp_dec_number_ptr(n)->digits);\n\n decNumberAbs(&m->num_decimal, jvp_dec_number_ptr(n), DEC_CONTEXT());\n jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, 0, {&m->refcnt}};\n return r;\n }\n#endif\n return jv_number(fabs(jv_number_value(n)));\n}\n\njv jv_number_negate(jv n) {\n assert(JVP_HAS_KIND(n, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(n, JVP_FLAGS_NUMBER_LITERAL)) {\n jvp_literal_number* m = jvp_literal_number_alloc(jvp_dec_number_ptr(n)->digits);\n\n decNumberMinus(&m->num_decimal, jvp_dec_number_ptr(n), DEC_CONTEXT());\n jv r = {JVP_FLAGS_NUMBER_LITERAL, 0, 0, 0, {&m->refcnt}};\n return r;\n }\n#endif\n return jv_number(-jv_number_value(n));\n}\n\nint jvp_number_cmp(jv a, jv b) {\n assert(JVP_HAS_KIND(a, JV_KIND_NUMBER));\n assert(JVP_HAS_KIND(b, JV_KIND_NUMBER));\n\n#ifdef USE_DECNUM\n if (JVP_HAS_FLAGS(a, JVP_FLAGS_NUMBER_LITERAL) && JVP_HAS_FLAGS(b, JVP_FLAGS_NUMBER_LITERAL)) {\n struct {\n decNumber number;\n decNumberUnit units[1];\n } res;\n\n decNumberCompare(&res.number,\n jvp_dec_number_ptr(a),\n jvp_dec_number_ptr(b),\n DEC_CONTEXT()\n );\n if (decNumberIsZero(&res.number)) {\n return 0;\n } else if (decNumberIsNegative(&res.number)) {\n return -1;\n } else {\n return 1;\n }\n }\n#endif\n double da = jv_number_value(a), db = jv_number_value(b);\n if (da < db) {\n return -1;\n } else if (da == db) {\n return 0;\n } else {\n return 1;\n }\n}\n\nstatic int jvp_number_equal(jv a, jv b) {\n return jvp_number_cmp(a, b) == 0;\n}\n\n/*\n * Arrays (internal helpers)\n */\n\n#define ARRAY_SIZE_ROUND_UP(n) (((n)*3)/2)\n#define JVP_FLAGS_ARRAY JVP_MAKE_FLAGS(JV_KIND_ARRAY, JVP_PAYLOAD_ALLOCATED)\n\nstatic int imax(int a, int b) {\n if (a>b) return a;\n else return b;\n}\n\n//FIXME signed vs unsigned\ntypedef struct {\n jv_refcnt refcnt;\n int length, alloc_length;\n jv elements[];\n} jvp_array;\n\nstatic jvp_array* jvp_array_ptr(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n return (jvp_array*)a.u.ptr;\n}\n\nstatic jvp_array* jvp_array_alloc(unsigned size) {\n jvp_array* a = jv_mem_alloc(sizeof(jvp_array) + sizeof(jv) * size);\n a->refcnt.count = 1;\n a->length = 0;\n a->alloc_length = size;\n return a;\n}\n\nstatic jv jvp_array_new(unsigned size) {\n jv r = {JVP_FLAGS_ARRAY, 0, 0, 0, {&jvp_array_alloc(size)->refcnt}};\n return r;\n}\n\nstatic void jvp_array_free(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n if (jvp_refcnt_dec(a.u.ptr)) {\n jvp_array* array = jvp_array_ptr(a);\n for (int i=0; i<array->length; i++) {\n jv_free(array->elements[i]);\n }\n jv_mem_free(array);\n }\n}\n\nstatic int jvp_array_length(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n return a.size;\n}\n\nstatic int jvp_array_offset(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n return a.offset;\n}\n\nstatic jv* jvp_array_read(jv a, int i) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n if (i >= 0 && i < jvp_array_length(a)) {\n jvp_array* array = jvp_array_ptr(a);\n assert(i + jvp_array_offset(a) < array->length);\n return &array->elements[i + jvp_array_offset(a)];\n } else {\n return 0;\n }\n}\n\nstatic jv* jvp_array_write(jv* a, int i) {\n assert(i >= 0);\n jvp_array* array = jvp_array_ptr(*a);\n\n int pos = i + jvp_array_offset(*a);\n if (pos < array->alloc_length && jvp_refcnt_unshared(a->u.ptr)) {\n // use existing array space\n for (int j = array->length; j <= pos; j++) {\n array->elements[j] = JV_NULL;\n }\n array->length = imax(pos + 1, array->length);\n a->size = imax(i + 1, a->size);\n return &array->elements[pos];\n } else {\n // allocate a new array\n int new_length = imax(i + 1, jvp_array_length(*a));\n jvp_array* new_array = jvp_array_alloc(ARRAY_SIZE_ROUND_UP(new_length));\n int j;\n for (j = 0; j < jvp_array_length(*a); j++) {\n new_array->elements[j] =\n jv_copy(array->elements[j + jvp_array_offset(*a)]);\n }\n for (; j < new_length; j++) {\n new_array->elements[j] = JV_NULL;\n }\n new_array->length = new_length;\n jvp_array_free(*a);\n jv new_jv = {JVP_FLAGS_ARRAY, 0, 0, new_length, {&new_array->refcnt}};\n *a = new_jv;\n return &new_array->elements[i];\n }\n}\n\nstatic int jvp_array_equal(jv a, jv b) {\n if (jvp_array_length(a) != jvp_array_length(b))\n return 0;\n if (jvp_array_ptr(a) == jvp_array_ptr(b) &&\n jvp_array_offset(a) == jvp_array_offset(b))\n return 1;\n for (int i=0; i<jvp_array_length(a); i++) {\n if (!jv_equal(jv_copy(*jvp_array_read(a, i)),\n jv_copy(*jvp_array_read(b, i))))\n return 0;\n }\n return 1;\n}\n\nstatic void jvp_clamp_slice_params(int len, int *pstart, int *pend)\n{\n if (*pstart < 0) *pstart = len + *pstart;\n if (*pend < 0) *pend = len + *pend;\n\n if (*pstart < 0) *pstart = 0;\n if (*pstart > len) *pstart = len;\n if (*pend > len) *pend = len;\n if (*pend < *pstart) *pend = *pstart;\n}\n\n\nstatic int jvp_array_contains(jv a, jv b) {\n int r = 1;\n jv_array_foreach(b, bi, belem) {\n int ri = 0;\n jv_array_foreach(a, ai, aelem) {\n if (jv_contains(aelem, jv_copy(belem))) {\n ri = 1;\n break;\n }\n }\n jv_free(belem);\n if (!ri) {\n r = 0;\n break;\n }\n }\n return r;\n}\n\n\n/*\n * Public\n */\n\nstatic jv jvp_array_slice(jv a, int start, int end) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n int len = jvp_array_length(a);\n jvp_clamp_slice_params(len, &start, &end);\n assert(0 <= start && start <= end && end <= len);\n\n // FIXME: maybe slice should reallocate if the slice is small enough\n if (start == end) {\n jv_free(a);\n return jv_array();\n }\n\n if (a.offset + start >= 1 << (sizeof(a.offset) * CHAR_BIT)) {\n jv r = jv_array_sized(end - start);\n for (int i = start; i < end; i++)\n r = jv_array_append(r, jv_array_get(jv_copy(a), i));\n jv_free(a);\n return r;\n } else {\n a.offset += start;\n a.size = end - start;\n return a;\n }\n}\n\n/*\n * Arrays (public interface)\n */\n\njv jv_array_sized(int n) {\n return jvp_array_new(n);\n}\n\njv jv_array(void) {\n return jv_array_sized(16);\n}\n\nint jv_array_length(jv j) {\n assert(JVP_HAS_KIND(j, JV_KIND_ARRAY));\n int len = jvp_array_length(j);\n jv_free(j);\n return len;\n}\n\njv jv_array_get(jv j, int idx) {\n assert(JVP_HAS_KIND(j, JV_KIND_ARRAY));\n jv* slot = jvp_array_read(j, idx);\n jv val;\n if (slot) {\n val = jv_copy(*slot);\n } else {\n val = jv_invalid();\n }\n jv_free(j);\n return val;\n}\n\njv jv_array_set(jv j, int idx, jv val) {\n assert(JVP_HAS_KIND(j, JV_KIND_ARRAY));\n\n if (idx < 0)\n idx = jvp_array_length(j) + idx;\n if (idx < 0) {\n jv_free(j);\n jv_free(val);\n return jv_invalid_with_msg(jv_string(\"Out of bounds negative array index\"));\n }\n if (idx > (INT_MAX >> 2) - jvp_array_offset(j)) {\n jv_free(j);\n jv_free(val);\n return jv_invalid_with_msg(jv_string(\"Array index too large\"));\n }\n // copy/free of val,j coalesced\n jv* slot = jvp_array_write(&j, idx);\n jv_free(*slot);\n *slot = val;\n return j;\n}\n\njv jv_array_append(jv j, jv val) {\n // copy/free of val,j coalesced\n return jv_array_set(j, jv_array_length(jv_copy(j)), val);\n}\n\njv jv_array_concat(jv a, jv b) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n assert(JVP_HAS_KIND(b, JV_KIND_ARRAY));\n\n // FIXME: could be faster\n jv_array_foreach(b, i, elem) {\n a = jv_array_append(a, elem);\n if (!jv_is_valid(a)) break;\n }\n jv_free(b);\n return a;\n}\n\njv jv_array_slice(jv a, int start, int end) {\n assert(JVP_HAS_KIND(a, JV_KIND_ARRAY));\n // copy/free of a coalesced\n return jvp_array_slice(a, start, end);\n}\n\njv jv_array_indexes(jv a, jv b) {\n jv res = jv_array();\n int idx = -1;\n int alen = jv_array_length(jv_copy(a));\n for (int ai = 0; ai < alen; ++ai) {\n jv_array_foreach(b, bi, belem) {\n if (!jv_equal(jv_array_get(jv_copy(a), ai + bi), belem))\n idx = -1;\n else if (bi == 0 && idx == -1)\n idx = ai;\n }\n if (idx > -1)\n res = jv_array_append(res, jv_number(idx));\n idx = -1;\n }\n jv_free(a);\n jv_free(b);\n return res;\n}\n\n/*\n * Strings (internal helpers)\n */\n\n#define JVP_FLAGS_STRING JVP_MAKE_FLAGS(JV_KIND_STRING, JVP_PAYLOAD_ALLOCATED)\n\ntypedef struct {\n jv_refcnt refcnt;\n uint32_t hash;\n // high 31 bits are length, low bit is a flag\n // indicating whether hash has been computed.\n uint32_t length_hashed;\n uint32_t alloc_length;\n char data[];\n} jvp_string;\n\nstatic jvp_string* jvp_string_ptr(jv a) {\n assert(JVP_HAS_KIND(a, JV_KIND_STRING));\n return (jvp_string*)a.u.ptr;\n}\n\nstatic jvp_string* jvp_string_alloc(uint32_t size) {\n jvp_string* s = jv_mem_alloc(sizeof(jvp_string) + size + 1);\n s->refcnt.count = 1;\n s->alloc_length = size;\n return s;\n}\n\n/* Copy a UTF8 string, replacing all badly encoded points with U+FFFD */\nstatic jv jvp_string_copy_replace_bad(const char* data, uint32_t length) {\n const char* end = data + length;\n const char* i = data;\n\n uint32_t maxlength = length * 3 + 1; // worst case: all bad bytes, each becomes a 3-byte U+FFFD\n jvp_string* s = jvp_string_alloc(maxlength);\n char* out = s->data;\n int c = 0;\n\n while ((i = jvp_utf8_next(i, end, &c))) {\n if (c == -1) {\n c = 0xFFFD; // U+FFFD REPLACEMENT CHARACTER\n }\n out += jvp_utf8_encode(c, out);\n assert(out < s->data + maxlength);\n }\n length = out - s->data;\n s->data[length] = 0;\n s->length_hashed = length << 1;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n/* Assumes valid UTF8 */\nstatic jv jvp_string_new(const char* data, uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = length << 1;\n if (data != NULL)\n memcpy(s->data, data, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\nstatic jv jvp_string_empty_new(uint32_t length) {\n jvp_string* s = jvp_string_alloc(length);\n s->length_hashed = 0;\n memset(s->data, 0, length);\n s->data[length] = 0;\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&s->refcnt}};\n return r;\n}\n\n\nstatic void jvp_string_free(jv js) {\n jvp_string* s = jvp_string_ptr(js);\n if (jvp_refcnt_dec(&s->refcnt)) {\n jv_mem_free(s);\n }\n}\n\nstatic uint32_t jvp_string_length(jvp_string* s) {\n return s->length_hashed >> 1;\n}\n\nstatic uint32_t jvp_string_remaining_space(jvp_string* s) {\n assert(s->alloc_length >= jvp_string_length(s));\n uint32_t r = s->alloc_length - jvp_string_length(s);\n return r;\n}\n\nstatic jv jvp_string_append(jv string, const char* data, uint32_t len) {\n jvp_string* s = jvp_string_ptr(string);\n uint32_t currlen = jvp_string_length(s);\n\n if (jvp_refcnt_unshared(string.u.ptr) &&\n jvp_string_remaining_space(s) >= len) {\n // the next string fits at the end of a\n memcpy(s->data + currlen, data, len);\n s->data[currlen + len] = 0;\n s->length_hashed = (currlen + len) << 1;\n return string;\n } else {\n // allocate a bigger buffer and copy\n uint32_t allocsz = (currlen + len) * 2;\n if (allocsz < 32) allocsz = 32;\n jvp_string* news = jvp_string_alloc(allocsz);\n news->length_hashed = (currlen + len) << 1;\n memcpy(news->data, s->data, currlen);\n memcpy(news->data + currlen, data, len);\n news->data[currlen + len] = 0;\n jvp_string_free(string);\n jv r = {JVP_FLAGS_STRING, 0, 0, 0, {&news->refcnt}};\n return r;\n }\n}\n\nstatic const uint32_t HASH_SEED = 0x432A9843;\n\nstatic uint32_t rotl32 (uint32_t x, int8_t r){\n return (x << r) | (x >> (32 - r));\n}\n\nstatic uint32_t jvp_string_hash(jv jstr) {\n jvp_string* str = jvp_string_ptr(jstr);\n if (str->length_hashed & 1)\n return str->hash;\n\n /* The following is based on MurmurHash3.\n MurmurHash3 was written by Austin Appleby, and is placed\n in the public domain. */\n\n const uint8_t* data = (const uint8_t*)str->data;\n int len = (int)jvp_string_length(str);\n const int nblocks = len / 4;\n\n uint32_t h1 = HASH_SEED;\n\n const uint32_t c1 = 0xcc9e2d51;\n const uint32_t c2 = 0x1b873593;\n const uint32_t* blocks = (const uint32_t *)(data + nblocks*4);\n\n for(int i = -nblocks; i; i++) {\n uint32_t k1 = blocks[i]; //FIXME: endianness/alignment\n\n k1 *= c1;\n k1 = rotl32(k1,15);\n k1 *= c2;\n\n h1 ^= k1;\n h1 = rotl32(h1,13);\n h1 = h1*5+0xe6546b64;\n }\n\n const uint8_t* tail = (const uint8_t*)(data + nblocks*4);\n\n uint32_t k1 = 0;\n\n switch(len & 3) {\n case 3: k1 ^= tail[2] << 16;\n JQ_FALLTHROUGH;\n case 2: k1 ^= tail[1] << 8;\n JQ_FALLTHROUGH;\n case 1: k1 ^= tail[0];\n k1 *= c1; k1 = rotl32(k1,15); k1 *= c2; h1 ^= k1;\n }\n\n h1 ^= len;\n\n h1 ^= h1 >> 16;\n h1 *= 0x85ebca6b;\n h1 ^= h1 >> 13;\n h1 *= 0xc2b2ae35;\n h1 ^= h1 >> 16;\n\n str->length_hashed |= 1;\n str->hash = h1;\n\n return h1;\n}\n\n\nstatic int jvp_string_equal(jv a, jv b) {\n assert(JVP_HAS_KIND(a, JV_KIND_STRING));\n assert(JVP_HAS_KIND(b, JV_KIND_STRING));\n jvp_string* stra = jvp_string_ptr(a);\n jvp_string* strb = jvp_string_ptr(b);\n if (jvp_string_length(stra) != jvp_string_length(strb)) return 0;\n return memcmp(stra->data, strb->data, jvp_string_length(stra)) == 0;\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n#include <limits.h>\n#include <math.h>\n#include <float.h>\n\n#include \"jv_alloc.h\"\n#include \"jv.h\"\n=======\n#include <limits.h>\n#include <math.h>\n#include <float.h>\n#include <time.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <pthread.h>\n\n#include \"jv_alloc.h\"\n#include \"jv.h\"\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n }\n}\n\nstatic const uint32_t HASH_SEED = 0x432A9843;\n\nstatic uint32_t rotl32 (uint32_t x, int8_t r){\n return (x << r) | (x >> (32 - r));\n=======\n }\n}\n\nstatic uint32_t hash_seed;\nstatic pthread_once_t hash_seed_once = PTHREAD_ONCE_INIT;\n\nstatic void jvp_hash_seed_init(void) {\n uint32_t seed;\n#if defined(HAVE_ARC4RANDOM)\n seed = arc4random();\n#elif defined(HAVE_GETENTROPY)\n if (getentropy(&seed, sizeof(seed)) != 0)\n seed = (uint32_t)getpid() ^ (uint32_t)time(NULL);\n#else\n int fd = open(\"/dev/urandom\", O_RDONLY);\n if (fd >= 0) {\n if (read(fd, &seed, sizeof(seed)) != 4)\n seed = (uint32_t)getpid() ^ (uint32_t)time(NULL);\n close(fd);\n } else {\n seed = (uint32_t)getpid() ^ (uint32_t)time(NULL);\n }\n#endif\n hash_seed = seed;\n}\n\nstatic uint32_t jvp_hash_seed(void) {\n pthread_once(&hash_seed_once, jvp_hash_seed_init);\n return hash_seed;\n}\n\nstatic uint32_t rotl32 (uint32_t x, int8_t r){\n return (x << r) | (x >> (32 - r));\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n int len = (int)jvp_string_length(str);\n const int nblocks = len / 4;\n\n uint32_t h1 = HASH_SEED;\n\n const uint32_t c1 = 0xcc9e2d51;\n const uint32_t c2 = 0x1b873593;\n=======\n int len = (int)jvp_string_length(str);\n const int nblocks = len / 4;\n\n uint32_t h1 = jvp_hash_seed();\n\n const uint32_t c1 = 0xcc9e2d51;\n const uint32_t c2 = 0x1b873593;\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-40198: Improper input validation / incorrect computation (CWE-20) in the Perl module Net::CIDR::Lite. The IPv6 packer accepted an uncompressed address that had fewer than the eight groups a full IPv6 address requires and carried no compression marker, for example a seven-group string. Such an address has no valid 128-bit interpretation, but the module produced a packed value for it anyway, which corrupts the subsequent network-mask and range-comparison so a range or membership test operates on the wrong bytes. A CIDR allow-list or deny-list built from attacker-influenced IPv6 input therefore admits or blocks the wrong addresses, an IP access-control bypass via find(). Affects Net::CIDR::Lite before 0.23.\n\n# Vulnerable source (Lite.pm)\n```perl\n}\n\nsub _unpack_ipv4 {\n join(\".\", unpack(\"xC*\", shift));\n}\n\nsub _pack_ipv6 {\n my $ip = shift;\n $ip =~ s/^::$/::0/;\n return if $ip =~ /^:/ and $ip !~ s/^::/:/;\n return if $ip =~ /:$/ and $ip !~ s/::$/:/;\n my @nums = split /:/, $ip, -1;\n return unless @nums <= 8;\n my ($empty, $ipv4, $str) = (0,'','');\n for (@nums) {\n return if $ipv4;\n $str .= \"0\" x (4-length) . $_, next if /^[a-fA-F\\d]{1,4}$/;\n do { return if $empty++ }, $str .= \"X\", next if $_ eq '';\n next if $ipv4 = _pack_ipv4($_);\n return;\n }\n return if $ipv4 and @nums > 6;\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n pack(\"H*\", \"00\" . $str).$ipv4;\n}\n\nsub _unpack_ipv6 {\n _compress_ipv6(join(\":\", unpack(\"xH*\", shift) =~ /..../g)),\n}\n\n# Replace longest run of null blocks with a double colon\nsub _compress_ipv6 {\n my $ip = shift;\n if (my @runs = $ip =~ /((?:(?:^|:)(?:0000))+:?)/g ) {\n my $max = $runs[0];\n for (@runs[1..$#runs]) {\n $max = $_ if length($max) < length;\n }\n $ip =~ s/$max/::/;\n }\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n return;\n }\n return if $ipv4 and @nums > 6;\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n pack(\"H*\", \"00\" . $str).$ipv4;\n}\n=======\n return;\n }\n return if $ipv4 and @nums > 6;\n return unless $empty or @nums == ($ipv4 ? 6 : 8);\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n pack(\"H*\", \"00\" . $str).$ipv4;\n}\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-40199: Improper input validation / incorrect computation (CWE-20) in the Perl module Net::CIDR::Lite. When packing an IPv4-mapped IPv6 address such as ::ffff:192.168.1.0, the module appended the full result of its IPv4 packer, which carries an extra leading sentinel byte, instead of the address bytes alone. The packed value was therefore one byte too long, which corrupts the subsequent network-mask and range-comparison so a membership test returns the wrong answer: an address outside an IPv4-mapped allow-list range is reported as inside it. A CIDR allow-list or deny-list built over IPv4-mapped IPv6 ranges consequently admits or blocks the wrong addresses, an IP access-control bypass via find(). Affects Net::CIDR::Lite before 0.23.\n\n# Vulnerable source (Lite.pm)\n```perl\nsub _unpack_ipv4 {\n join(\".\", unpack(\"xC*\", shift));\n}\n\nsub _pack_ipv6 {\n my $ip = shift;\n $ip =~ s/^::$/::0/;\n return if $ip =~ /^:/ and $ip !~ s/^::/:/;\n return if $ip =~ /:$/ and $ip !~ s/::$/:/;\n my @nums = split /:/, $ip, -1;\n return unless @nums <= 8;\n my ($empty, $ipv4, $str) = (0,'','');\n for (@nums) {\n return if $ipv4;\n $str .= \"0\" x (4-length) . $_, next if /^[a-fA-F\\d]{1,4}$/;\n do { return if $empty++ }, $str .= \"X\", next if $_ eq '';\n next if $ipv4 = _pack_ipv4($_);\n return;\n }\n return if $ipv4 and @nums > 6;\n return unless $empty or @nums == ($ipv4 ? 6 : 8);\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n pack(\"H*\", \"00\" . $str).$ipv4;\n}\n\nsub _unpack_ipv6 {\n _compress_ipv6(join(\":\", unpack(\"xH*\", shift) =~ /..../g)),\n}\n\n# Replace longest run of null blocks with a double colon\nsub _compress_ipv6 {\n my $ip = shift;\n if (my @runs = $ip =~ /((?:(?:^|:)(?:0000))+:?)/g ) {\n my $max = $runs[0];\n for (@runs[1..$#runs]) {\n $max = $_ if length($max) < length;\n }\n $ip =~ s/$max/::/;\n }\n $ip =~ s/:0{1,3}/:/g;\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n return if $ipv4 and @nums > 6;\n return unless $empty or @nums == ($ipv4 ? 6 : 8);\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n pack(\"H*\", \"00\" . $str).$ipv4;\n}\n\nsub _unpack_ipv6 {\n=======\n return if $ipv4 and @nums > 6;\n return unless $empty or @nums == ($ipv4 ? 6 : 8);\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n pack(\"H*\", \"00\" . $str).substr($ipv4, 1);\n}\n\nsub _unpack_ipv6 {\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-40355: Null pointer dereference in MIT krb5 1.22.2 NegoEx message parsing: the parse_nego_message() function in src/lib/gssapi/spnego/negoex_util.c obtains a pointer via vector_base() to an extension table in the message payload but does not verify whether the pointer is non-null before indexing into the extension table, allowing an unauthenticated remote attacker to crash any GSS application that accepts NegoEx context tokens.\n\n# Vulnerable source (src/lib/gssapi/spnego/negoex_util.c)\n```c\nstatic OM_uint32\nparse_nego_message(OM_uint32 *minor, struct k5input *in,\n const uint8_t *msg_base, size_t msg_len,\n struct nego_message *msg)\n{\n const uint8_t *p;\n uint64_t protocol_version;\n uint32_t extension_type;\n size_t offset, count, i;\n\n p = k5_input_get_bytes(in, sizeof(msg->random));\n if (p != NULL)\n memcpy(msg->random, p, sizeof(msg->random));\n protocol_version = k5_input_get_uint64_le(in);\n if (protocol_version != 0) {\n *minor = ERR_NEGOEX_UNSUPPORTED_VERSION;\n return GSS_S_UNAVAILABLE;\n }\n\n offset = k5_input_get_uint32_le(in);\n count = k5_input_get_uint16_le(in);\n msg->schemes = vector_base(offset, count, GUID_LENGTH, msg_base, msg_len);\n msg->nschemes = count;\n if (msg->schemes == NULL) {\n *minor = ERR_NEGOEX_INVALID_MESSAGE_SIZE;\n return GSS_S_DEFECTIVE_TOKEN;\n }\n\n offset = k5_input_get_uint32_le(in);\n count = k5_input_get_uint16_le(in);\n p = vector_base(offset, count, EXTENSION_LENGTH, msg_base, msg_len);\n for (i = 0; i < count; i++) {\n extension_type = load_32_le(p + i * EXTENSION_LENGTH);\n if (extension_type & EXTENSION_FLAG_CRITICAL) {\n *minor = ERR_NEGOEX_UNSUPPORTED_CRITICAL_EXTENSION;\n return GSS_S_UNAVAILABLE;\n }\n }\n\n return GSS_S_COMPLETE;\n}\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n offset = k5_input_get_uint32_le(in);\n count = k5_input_get_uint16_le(in);\n p = vector_base(offset, count, EXTENSION_LENGTH, msg_base, msg_len);\n for (i = 0; i < count; i++) {\n extension_type = load_32_le(p + i * EXTENSION_LENGTH);\n if (extension_type & EXTENSION_FLAG_CRITICAL) {\n=======\n offset = k5_input_get_uint32_le(in);\n count = k5_input_get_uint16_le(in);\n p = vector_base(offset, count, EXTENSION_LENGTH, msg_base, msg_len);\n if (p == NULL) {\n *minor = ERR_NEGOEX_INVALID_MESSAGE_SIZE;\n return GSS_S_DEFECTIVE_TOKEN;\n }\n for (i = 0; i < count; i++) {\n extension_type = load_32_le(p + i * EXTENSION_LENGTH);\n if (extension_type & EXTENSION_FLAG_CRITICAL) {\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-42046: libcaca is a graphics library that renders images as colored ASCII art. Signed integer overflow is undefined behavior in C, so a sufficiently large canvas request can produce a negative or incorrect allocation size without being caught by the subsequent check. An attacker who can control canvas dimensions could trigger this overflow, resulting in an undersized buffer allocation followed by heap corruption when the library writes past the buffer boundary.\n\n# Vulnerable source (caca/canvas.c)\n```c\n/*\n * libcaca Colour ASCII-Art library\n * Copyright \u00a9 2002\u20142021 Sam Hocevar <sam@hocevar.net>\n * All Rights Reserved\n *\n * This library is free software. It comes without any warranty, to\n * the extent permitted by applicable law. You can redistribute it\n * and/or modify it under the terms of the Do What the Fuck You Want\n * to Public License, Version 2, as published by Sam Hocevar. See\n * http://www.wtfpl.net/ for more details.\n */\n\n/*\n * This file contains the main functions used by \\e libcaca applications\n * to initialise a drawing context.\n */\n\n#include \"config.h\"\n\n#if !defined(__KERNEL__)\n# include <stdio.h>\n# include <stdlib.h>\n# include <string.h>\n# include <time.h>\n# include <sys/types.h>\n# if defined(HAVE_UNISTD_H)\n# include <unistd.h>\n# endif\n#endif\n\n#include \"caca.h\"\n#include \"caca_internals.h\"\n\nstatic int caca_resize(caca_canvas_t *, int, int);\n\n/** \\brief Initialise a \\e libcaca canvas.\n *\n * Initialise internal \\e libcaca structures and the backend that will\n * be used for subsequent graphical operations. It must be the first\n * \\e libcaca function to be called in a function. caca_free_canvas()\n * should be called at the end of the program to free all allocated resources.\n *\n * Both the cursor and the canvas' handle are initialised at the top-left\n * corner.\n *\n * If an error occurs, NULL is returned and \\b errno is set accordingly:\n * - \\c EINVAL Specified width or height is invalid.\n * - \\c EOVERFLOW Specified width and height overflowed.\n * - \\c ENOMEM Not enough memory for the requested canvas size.\n *\n * \\param width The desired canvas width\n * \\param height The desired canvas height\n * \\return A libcaca canvas handle upon success, NULL if an error occurred.\n */\ncaca_canvas_t * caca_create_canvas(int width, int height)\n{\n caca_canvas_t *cv;\n\n if(width < 0 || height < 0)\n {\n seterrno(EINVAL);\n return NULL;\n }\n\n cv = malloc(sizeof(caca_canvas_t));\n\n if(!cv)\n goto nomem;\n\n cv->refcount = 0;\n cv->autoinc = 0;\n cv->resize_callback = NULL;\n cv->resize_data = NULL;\n\n cv->frame = 0;\n cv->framecount = 1;\n cv->frames = malloc(sizeof(struct caca_frame));\n if(!cv->frames)\n {\n free(cv);\n goto nomem;\n }\n\n cv->frames[0].width = cv->frames[0].height = 0;\n cv->frames[0].chars = NULL;\n cv->frames[0].attrs = NULL;\n cv->frames[0].x = cv->frames[0].y = 0;\n cv->frames[0].handlex = cv->frames[0].handley = 0;\n cv->frames[0].curattr = 0;\n cv->frames[0].name = strdup(\"frame#00000000\");\n\n _caca_load_frame_info(cv);\n caca_set_color_ansi(cv, CACA_DEFAULT, CACA_TRANSPARENT);\n\n cv->ndirty = 0;\n cv->dirty_disabled = 0;\n cv->ff = NULL;\n\n if(caca_resize(cv, width, height) < 0)\n {\n int saved_errno = geterrno();\n free(cv->frames[0].name);\n free(cv->frames);\n free(cv);\n seterrno(saved_errno);\n return NULL;\n }\n\n return cv;\n\nnomem:\n seterrno(ENOMEM);\n return NULL;\n}\n\n/** \\brief Manage a canvas.\n *\n * Lock a canvas to prevent it from being resized. If non-NULL,\n * the \\e callback function pointer will be called upon each\n * \\e caca_set_canvas_size call and if the returned value is zero, the\n * canvas resize request will be denied.\n *\n * This function is only useful for display drivers such as the \\e libcaca\n * library.\n *\n * If an error occurs, -1 is returned and \\b errno is set accordingly:\n * - \\c EBUSY The canvas is already being managed.\n *\n * \\param cv A libcaca canvas.\n * \\param callback An optional callback function pointer.\n * \\param p The argument to be passed to \\e callback.\n * \\return 0 in case of success, -1 if an error occurred.\n */\nint caca_manage_canvas(caca_canvas_t *cv, int (*callback)(void *), void *p)\n{\n if(cv->refcount)\n {\n seterrno(EBUSY);\n return -1;\n }\n\n cv->resize_callback = callback;\n cv->resize_data = p;\n cv->refcount = 1;\n\n return 0;\n}\n\n/** \\brief unmanage a canvas.\n *\n * unlock a canvas previously locked by caca_manage_canvas(). for safety\n * reasons, the callback and callback data arguments must be the same as for\n * the caca_manage_canvas() call.\n *\n * this function is only useful for display drivers such as the \\e libcaca\n * library.\n *\n * if an error occurs, -1 is returned and \\b errno is set accordingly:\n * - \\c einval the canvas is not managed, or the callback arguments do\n * not match.\n *\n * \\param cv a libcaca canvas.\n * \\param callback the \\e callback argument previously passed to\n * caca_manage_canvas().\n * \\param p the \\e p argument previously passed to caca_manage_canvas().\n * \\return 0 in case of success, -1 if an error occurred.\n */\nint caca_unmanage_canvas(caca_canvas_t *cv, int (*callback)(void *), void *p)\n{\n if(!cv->refcount\n || cv->resize_callback != callback || cv->resize_data != p)\n {\n seterrno(EINVAL);\n return -1;\n }\n\n cv->refcount = 0;\n\n return 0;\n}\n\n/** \\brief Resize a canvas.\n *\n * Set the canvas' width and height, in character cells.\n *\n * The contents of the canvas are preserved to the extent of the new\n * canvas size. Newly allocated character cells at the right and/or at\n * the bottom of the canvas are filled with spaces.\n *\n * If as a result of the resize the cursor coordinates fall outside the\n * new canvas boundaries, they are readjusted. For instance, if the\n * current X cursor coordinate is 11 and the requested width is 10, the\n * new X cursor coordinate will be 10.\n *\n * It is an error to try to resize the canvas if an output driver has\n * been attached to the canvas using caca_create_display(). You need to\n * remove the output driver using caca_free_display() before you can change\n * the canvas size again. However, the caca output driver can cause a\n * canvas resize through user interaction. See the caca_event() documentation\n * for more about this.\n *\n * If an error occurs, -1 is returned and \\b errno is set accordingly:\n * - \\c EINVAL Specified width or height is invalid.\n * - \\c EOVERFLOW Specified width and height overflowed.\n * - \\c EBUSY The canvas is in use by a display driver and cannot be resized.\n * - \\c ENOMEM Not enough memory for the requested canvas size. If this\n * happens, the canvas handle becomes invalid and should not be used.\n *\n * \\param cv A libcaca canvas.\n * \\param width The desired canvas width.\n * \\param height The desired canvas height.\n * \\return 0 in case of success, -1 if an error occurred.\n */\nint caca_set_canvas_size(caca_canvas_t *cv, int width, int height)\n{\n if(width < 0 || height < 0)\n {\n seterrno(EINVAL);\n return -1;\n }\n\n if(cv->refcount && cv->resize_callback\n && !cv->resize_callback(cv->resize_data))\n {\n seterrno(EBUSY);\n return -1;\n }\n\n return caca_resize(cv, width, height);\n}\n\n/** \\brief Get the canvas width.\n *\n * Return the current canvas' width, in character cells.\n *\n * This function never fails.\n *\n * \\param cv A libcaca canvas.\n * \\return The canvas width.\n */\nint caca_get_canvas_width(caca_canvas_t const *cv)\n{\n return cv->width;\n}\n\n/** \\brief Get the canvas height.\n *\n * Returns the current canvas' height, in character cells.\n *\n * This function never fails.\n *\n * \\param cv A libcaca canvas.\n * \\return The canvas height.\n */\nint caca_get_canvas_height(caca_canvas_t const *cv)\n{\n return cv->height;\n}\n\n/** \\brief Get the canvas character array.\n *\n * Return the current canvas' internal character array. The array elements\n * consist in native endian 32-bit Unicode values as returned by\n * caca_get_char().\n *\n * This function is probably only useful for \\e libcaca 's internal display\n * drivers.\n *\n * This function never fails.\n *\n * \\param cv A libcaca canvas.\n * \\return The canvas character array.\n */\nuint32_t const * caca_get_canvas_chars(caca_canvas_t const *cv)\n{\n return (uint32_t const *)cv->chars;\n}\n\n/** \\brief Get the canvas attribute array.\n *\n * Returns the current canvas' internal attribute array. The array elements\n * consist in native endian 32-bit attribute values as returned by\n * caca_get_attr().\n *\n * This function is probably only useful for \\e libcaca 's internal display\n * drivers.\n *\n * This function never fails.\n *\n * \\param cv A libcaca canvas.\n * \\return The canvas attribute array.\n */\nuint32_t const * caca_get_canvas_attrs(caca_canvas_t const *cv)\n{\n return (uint32_t const *)cv->attrs;\n}\n\n/** \\brief Free a \\e libcaca canvas.\n *\n * Free all resources allocated by caca_create_canvas(). The canvas\n * pointer becomes invalid and must no longer be used unless a new call\n * to caca_create_canvas() is made.\n *\n * If an error occurs, -1 is returned and \\b errno is set accordingly:\n * - \\c EBUSY The canvas is in use by a display driver and cannot be freed.\n *\n * \\param cv A libcaca canvas.\n * \\return 0 in case of success, -1 if an error occurred.\n */\nint caca_free_canvas(caca_canvas_t *cv)\n{\n int f;\n\n if(cv->refcount)\n {\n seterrno(EBUSY);\n return -1;\n }\n\n for(f = 0; f < cv->framecount; f++)\n {\n free(cv->frames[f].chars);\n free(cv->frames[f].attrs);\n free(cv->frames[f].name);\n }\n\n caca_canvas_set_figfont(cv, NULL);\n\n free(cv->frames);\n free(cv);\n\n return 0;\n}\n\n/** \\brief Generate a random integer within a range.\n *\n * Generate a random integer within the given range.\n *\n * This function never fails.\n *\n * \\param min The lower bound of the integer range.\n * \\param max The upper bound of the integer range.\n * \\return A random integer comprised between \\p min and \\p max - 1\n * (inclusive).\n */\nstatic caca_timer_t timer = {0, 0};\n\nint caca_rand(int min, int max)\n{\n static int need_init = 1;\n\n if(need_init)\n {\n srand(getpid() + _caca_getticks(&timer));\n need_init = 0;\n }\n\n return min + (int)((1.0 * (max - min)) * rand() / (RAND_MAX + 1.0));\n}\n\n\n/*\n * XXX: The following functions are local.\n */\n\nint caca_resize(caca_canvas_t *cv, int width, int height)\n{\n int x, y, f, old_width, old_height, old_size;\n\n /* Check for overflow */\n int new_size = width * height;\n if (new_size < 0 || (width > 0 && new_size / width != height))\n {\n seterrno(EOVERFLOW);\n return -1;\n }\n\n old_width = cv->width;\n old_height = cv->height;\n old_size = old_width * old_height;\n\n _caca_save_frame_info(cv);\n\n /* Preload new width and height values into the canvas to optimise\n * dirty rectangle handling */\n cv->width = width;\n cv->height = height;\n\n /* If width or height is smaller (or both), we have the opportunity to\n * reduce or even remove dirty rectangles */\n if(width < old_width || height < old_height)\n _caca_clip_dirty_rect_list(cv);\n\n /* Step 1: if new area is bigger, resize the memory area now. */\n if(new_size > old_size)\n {\n for(f = 0; f < cv->framecount; f++)\n {\n cv->frames[f].chars = realloc(cv->frames[f].chars,\n new_size * sizeof(uint32_t));\n cv->frames[f].attrs = realloc(cv->frames[f].attrs,\n new_size * sizeof(uint32_t));\n if(new_size && (!cv->frames[f].chars || !cv->frames[f].attrs))\n {\n seterrno(ENOMEM);\n return -1;\n }\n }\n }\n\n /* Step 2: move line data if necessary. */\n if(width == old_width)\n {\n /* Width did not change, which means we do not need to move data. */\n ;\n }\n else if(width > old_width)\n {\n /* New width is bigger than old width, which means we need to\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n# if defined(HAVE_UNISTD_H)\n# include <unistd.h>\n# endif\n#endif\n\n#include \"caca.h\"\n=======\n# if defined(HAVE_UNISTD_H)\n# include <unistd.h>\n# endif\n# include <limits.h>\n#endif\n\n#include \"caca.h\"\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n int x, y, f, old_width, old_height, old_size;\n\n /* Check for overflow */\n int new_size = width * height;\n if (new_size < 0 || (width > 0 && new_size / width != height))\n {\n seterrno(EOVERFLOW);\n return -1;\n }\n\n old_width = cv->width;\n old_height = cv->height;\n=======\n int x, y, f, old_width, old_height, old_size;\n\n /* Check for overflow */\n if (width != 0 && height > INT_MAX / width)\n {\n seterrno(EOVERFLOW);\n return -1;\n }\n int new_size = width * height;\n\n old_width = cv->width;\n old_height = cv->height;\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-45190: Improper input validation (CWE-20) in the Perl module Net::CIDR::Lite. Such inputs passed the numeric validators in add() and the address packers, and were then numerically coerced and re-encoded to a different address than a strict reader would use. Affects Net::CIDR::Lite before 0.24.\n\n# Vulnerable source (Lite.pm)\n```perl\n $self->add_any($_) for @_;\n $self;\n}\n\nsub add_any {\n my $self = shift;\n for (@_) {\n tr|/|| && do { $self->add($_); next };\n tr|-|| && do { $self->add_range($_); next };\n UNIVERSAL::isa($_, 'Net::CIDR::Lite') && do {\n $self->add_cidr($_); next\n };\n $self->add_ip($_), next;\n }\n $self;\n}\n\nsub add {\n my $self = shift;\n my ($ip, $mask) = split \"/\", shift;\n $self->_init($ip) || confess \"Can't determine ip format\" unless %$self;\n confess \"Bad mask $mask\"\n unless $mask =~ /^\\d+$/ and $mask <= $self->{NBITS}-8;\n $mask += 8;\n my $start = $self->{PACK}->($ip) & $self->{MASKS}[$mask]\n or confess \"Bad ip address: $ip\";\n my $end = $self->_add_bit($start, $mask);\n ++$$self{RANGES}{$start} || delete $$self{RANGES}{$start};\n --$$self{RANGES}{$end} || delete $$self{RANGES}{$end};\n $self;\n}\n\nsub clean {\n my $self = shift;\n return $self unless $self->{RANGES};\n my $ranges = $$self{RANGES};\n my $total;\n $$self{RANGES} = {\n map { $total ? ($total+=$$ranges{$_})? () : ($_=>-1)\n : do { $total+=$$ranges{$_}; ($_=>1) }\n /* ... */\n } elsif (_pack_ipv6($ip)) {\n $nbits = 136;\n $pack = \\&_pack_ipv6;\n $unpack = \\&_unpack_ipv6;\n } else {\n return;\n }\n $$self{PACK} = $pack;\n $$self{UNPACK} = $unpack;\n $$self{NBITS} = $nbits;\n $$self{MASKS} = $masks{$nbits} ||= [\n map { pack(\"B*\", substr(\"1\" x $_ . \"0\" x $nbits, 0, $nbits))\n } 0..$nbits\n ];\n $$self{RANGES} = {};\n $self;\n}\n\nsub _pack_ipv4 {\n my @nums = split /\\./, shift(), -1;\n return unless @nums == 4;\n for (@nums) {\n return unless /^\\d{1,3}$/ and !/^0\\d{1,2}$/ and $_ <= 255;\n }\n pack(\"CC*\", 0, @nums);\n}\n\nsub _unpack_ipv4 {\n join(\".\", unpack(\"xC*\", shift));\n}\n\nsub _pack_ipv6 {\n my $ip = shift;\n $ip =~ s/^::$/::0/;\n return if $ip =~ /^:/ and $ip !~ s/^::/:/;\n return if $ip =~ /:$/ and $ip !~ s/::$/:/;\n my @nums = split /:/, $ip, -1;\n return unless @nums <= 8;\n my ($empty, $ipv4, $str) = (0,'','');\n for (@nums) {\n return if $ipv4;\n $str .= \"0\" x (4-length) . $_, next if /^[a-fA-F\\d]{1,4}$/;\n do { return if $empty++ }, $str .= \"X\", next if $_ eq '';\n next if $ipv4 = _pack_ipv4($_);\n return;\n }\n return if $ipv4 and @nums > 6;\n return unless $empty or @nums == ($ipv4 ? 6 : 8);\n $str =~ s/X/\"0\" x (($ipv4 ? 25 : 33)-length($str))/e if $empty;\n pack(\"H*\", \"00\" . $str).substr($ipv4, 1);\n}\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n my ($ip, $mask) = split \"/\", shift;\n $self->_init($ip) || confess \"Can't determine ip format\" unless %$self;\n confess \"Bad mask $mask\"\n unless $mask =~ /^\\d+$/ and $mask <= $self->{NBITS}-8;\n $mask += 8;\n my $start = $self->{PACK}->($ip) & $self->{MASKS}[$mask]\n or confess \"Bad ip address: $ip\";\n=======\n my ($ip, $mask) = split \"/\", shift;\n $self->_init($ip) || confess \"Can't determine ip format\" unless %$self;\n confess \"Bad mask $mask\"\n unless $mask =~ /\\A[0-9]+\\z/ and $mask <= $self->{NBITS}-8;\n $mask += 8;\n my $start = $self->{PACK}->($ip) & $self->{MASKS}[$mask]\n or confess \"Bad ip address: $ip\";\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n my @nums = split /\\./, shift(), -1;\n return unless @nums == 4;\n for (@nums) {\n return unless /^\\d{1,3}$/ and !/^0\\d{1,2}$/ and $_ <= 255;\n }\n pack(\"CC*\", 0, @nums);\n}\n=======\n my @nums = split /\\./, shift(), -1;\n return unless @nums == 4;\n for (@nums) {\n return unless /\\A[0-9]{1,3}\\z/ and !/\\A0[0-9]{1,2}\\z/ and $_ <= 255;\n }\n pack(\"CC*\", 0, @nums);\n}\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n\nsub _pack_ipv6 {\n my $ip = shift;\n $ip =~ s/^::$/::0/;\n return if $ip =~ /^:/ and $ip !~ s/^::/:/;\n return if $ip =~ /:$/ and $ip !~ s/::$/:/;\n my @nums = split /:/, $ip, -1;\n return unless @nums <= 8;\n my ($empty, $ipv4, $str) = (0,'','');\n for (@nums) {\n return if $ipv4;\n $str .= \"0\" x (4-length) . $_, next if /^[a-fA-F\\d]{1,4}$/;\n do { return if $empty++ }, $str .= \"X\", next if $_ eq '';\n next if $ipv4 = _pack_ipv4($_);\n return;\n=======\n\nsub _pack_ipv6 {\n my $ip = shift;\n $ip =~ s/\\A::\\z/::0/;\n return if $ip =~ /\\A:/ and $ip !~ s/\\A::/:/;\n return if $ip =~ /:\\z/ and $ip !~ s/::\\z/:/;\n my @nums = split /:/, $ip, -1;\n return unless @nums <= 8;\n my ($empty, $ipv4, $str) = (0,'','');\n for (@nums) {\n return if $ipv4;\n $str .= \"0\" x (4-length) . $_, next if /\\A[a-fA-F0-9]{1,4}\\z/;\n do { return if $empty++ }, $str .= \"X\", next if $_ eq '';\n next if $ipv4 = _pack_ipv4($_);\n return;\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-45191: Improper input validation (CWE-20) in the Perl module Net::CIDR::Lite. When adding a network, the prefix-length portion after the slash was accepted as long as it consisted only of digits, with no rejection of a leading zero. A prefix length written with a leading zero, such as the 08 in 10.0.0.0/08 or the 00 in ::/00, was therefore accepted and read as its plain decimal value, whereas a strict reader treats a zero-padded number as malformed. A CIDR allow-list or deny-list built from attacker-influenced input consequently parses to a different prefix length than the author intended, an allow/deny-list inconsistency. Affects Net::CIDR::Lite before 0.24.\n\n# Vulnerable source (Lite.pm)\n```perl\n $self->add_any($_) for @_;\n $self;\n}\n\nsub add_any {\n my $self = shift;\n for (@_) {\n tr|/|| && do { $self->add($_); next };\n tr|-|| && do { $self->add_range($_); next };\n UNIVERSAL::isa($_, 'Net::CIDR::Lite') && do {\n $self->add_cidr($_); next\n };\n $self->add_ip($_), next;\n }\n $self;\n}\n\nsub add {\n my $self = shift;\n my ($ip, $mask) = split \"/\", shift;\n $self->_init($ip) || confess \"Can't determine ip format\" unless %$self;\n confess \"Bad mask $mask\"\n unless $mask =~ /\\A[0-9]+\\z/ and $mask <= $self->{NBITS}-8;\n $mask += 8;\n my $start = $self->{PACK}->($ip) & $self->{MASKS}[$mask]\n or confess \"Bad ip address: $ip\";\n my $end = $self->_add_bit($start, $mask);\n ++$$self{RANGES}{$start} || delete $$self{RANGES}{$start};\n --$$self{RANGES}{$end} || delete $$self{RANGES}{$end};\n $self;\n}\n\nsub clean {\n my $self = shift;\n return $self unless $self->{RANGES};\n my $ranges = $$self{RANGES};\n my $total;\n $$self{RANGES} = {\n map { $total ? ($total+=$$ranges{$_})? () : ($_=>-1)\n : do { $total+=$$ranges{$_}; ($_=>1) }\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n my ($ip, $mask) = split \"/\", shift;\n $self->_init($ip) || confess \"Can't determine ip format\" unless %$self;\n confess \"Bad mask $mask\"\n unless $mask =~ /\\A[0-9]+\\z/ and $mask <= $self->{NBITS}-8;\n $mask += 8;\n my $start = $self->{PACK}->($ip) & $self->{MASKS}[$mask]\n or confess \"Bad ip address: $ip\";\n=======\n my ($ip, $mask) = split \"/\", shift;\n $self->_init($ip) || confess \"Can't determine ip format\" unless %$self;\n confess \"Bad mask $mask\"\n unless defined $mask\n and $mask =~ /\\A(?:0|[1-9][0-9]*)\\z/\n and $mask <= $self->{NBITS}-8;\n $mask += 8;\n my $start = $self->{PACK}->($ip) & $self->{MASKS}[$mask]\n or confess \"Bad ip address: $ip\";\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-50593: Integer underflow and resultant out-of-bounds read (CWE-191/CWE-125) in Graphite (libgraphite2) before 1.3.15. graphite2 compiles and validates a font's Graphite 'silf' passes by running the VM at face-load time, so a crafted font (tests/fonts/underflow.ttf in the upstream regression suite) whose bytecode drives the offset out of range reads past the slot map. Reproduce: shape the text 'baaaaaab' against underflow.ttf via the public API (gr_make_file_face + gr_make_seg).\n\n# Vulnerable source (src/inc/opcodes.h)\n```c\n// seg = A reference to the Segment this code is running over.\n// is = The current slot index\n// isb = The original base slot index at the start of this rule\n// isf = The first positioned slot\n// isl = The last positioned slot\n// ip = The current instruction pointer\n// endPos = Position of advance of last cluster\n// dir = writing system directionality of the font\n\n\n// #define NOT_IMPLEMENTED assert(false)\n// #define NOT_IMPLEMENTED\n\n#define binop(op) const uint32 a = pop(); *sp = uint32(*sp) op a\n#define sbinop(op) const int32 a = pop(); *sp = int32(*sp) op a\n#define use_params(n) dp += n\n\n#define declare_params(n) const byte * param = dp; \\\n use_params(n);\n\n#define push(n) { *++sp = n; }\n#define pop() (*sp--)\n#define slotat(x) (map[(x)])\n#define DIE { is=seg.last(); status = Machine::died_early; EXIT(1); }\n#define POSITIONED 1\n\nSTARTOP(nop)\n do {} while (0);\nENDOP\n\nSTARTOP(push_byte)\n declare_params(1);\n push(int8(*param));\nENDOP\n\nSTARTOP(push_byte_u)\n declare_params(1);\n push(uint8(*param));\nENDOP\n\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\n#define push(n) { *++sp = n; }\n#define pop() (*sp--)\n#define slotat(x) (map[(x)])\n#define DIE { is=seg.last(); status = Machine::died_early; EXIT(1); }\n#define POSITIONED 1\n=======\n\n#define push(n) { *++sp = n; }\n#define pop() (*sp--)\n#define slotat(x) ((map + (x) >= &smap[-1] && map + (x) < smap.end()) ? \\\n map[(x)] : (status = Machine::slot_offset_out_bounds, nullptr))\n#define DIE { is=seg.last(); status = Machine::died_early; EXIT(1); }\n#define POSITIONED 1\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-6507: One-byte buffer overflow in dnsmasq 2.92: the DHCPv4 relay reply handler in rfc2131.c uses an off-by-one size when zeroing a DHCP option field, potentially writing one byte beyond the buffer boundary during relay processing.\n\n# Vulnerable source (src/rfc2131.c)\n```c\n struct dhcp_relay *relay;\n \n if (mess->giaddr.s_addr == 0 || mess->op != BOOTREPLY)\n return 0;\n\n for (relay = daemon->relay4; relay; relay = relay->next)\n {\n unsigned int return_iface = 0;\n\n if (relay->split_mode)\n\t{\n\t unsigned char *opt, *sopt;\n\t \n\t /* giaddr is our address on the returning interface in split mode. */\n\t if (mess->giaddr.s_addr == relay->uplink.addr4.s_addr &&\n\t (opt = option_find(mess, sz, OPTION_AGENT_ID, 1)))\n\t {\n\t if ((sopt = option_find1(option_ptr(opt, 0), option_ptr(opt, option_len(opt)), SUBOPT_REMOTE_ID, sizeof(unsigned int))))\n\t\treturn_iface = option_uint(sopt, 0, sizeof(unsigned int));\n\n\t /* delete agent info before return RFC 3046 para 2.1 */\n\t *opt = OPTION_END;\n\t memset(opt + 1, 0, option_len(opt) + 2);\n\t }\n\t}\n else if (mess->giaddr.s_addr == relay->local.addr4.s_addr)\n\treturn_iface = relay->iface_index;\n \n if (return_iface && (!relay->interface || wildcard_match(relay->interface, arrival_interface)))\n\treturn return_iface;\n }\n \n return 0;\t \n} \n\n\n#endif /* HAVE_DHCP */\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n\n\t /* delete agent info before return RFC 3046 para 2.1 */\n\t *opt = OPTION_END;\n\t memset(opt + 1, 0, option_len(opt) + 2);\n\t }\n\t}\n else if (mess->giaddr.s_addr == relay->local.addr4.s_addr)\n=======\n\n\t /* delete agent info before return RFC 3046 para 2.1 */\n\t *opt = OPTION_END;\n\t memset(opt + 1, 0, option_len(opt) + 1);\n\t }\n\t}\n else if (mess->giaddr.s_addr == relay->local.addr4.s_addr)\n>>>>>>> REPLACE"}]}
{"messages": [{"role": "system", "content": "You are a security engineer fixing a CVE. You are given the vulnerability description (symptom only) and the vulnerable source window. Author the MINIMAL fix as one or more SEARCH/REPLACE blocks. Follow these rules exactly:\n1. Each block is:\n<<<<<<< SEARCH\n<exact lines copied verbatim from the shown source window>\n=======\n<the replacement lines>\n>>>>>>> REPLACE\n2. The SEARCH text MUST appear verbatim in the shown source window \u2014 copy it exactly, including whitespace; do not invent or paraphrase it.\n3. Change as few lines as possible; keep the SEARCH span tight around the edit.\n4. Modify ONLY code visible in the shown source window.\n5. Output only the SEARCH/REPLACE block(s) with no other text.\n6. Prefer folding a new bound or check into an existing condition over adding a separate guard, when the upstream fix does so."}, {"role": "user", "content": "# CVE\nCVE-2026-7598: Integer overflow (CWE-190) in libssh2 1.11.1 leading to heap-buffer-overflow. Then _libssh2_store_str() calls _libssh2_htonu32 which writes a 4-byte length prefix past the 1-byte buffer (heap-buffer-overflow). The overflow occurs during local packet construction before any network I/O, making it triggerable from the public libssh2_userauth_list() / libssh2_userauth_password() APIs without a live SSH connection.\n\n# Vulnerable source (src/userauth.c)\n```c\n * Will yield successful login if \"none\" happens to be allowable for this user\n * Not a common configuration for any SSH server though\n * username should be NULL, or a null terminated string\n */\nstatic char *userauth_list(LIBSSH2_SESSION *session, const char *username,\n unsigned int username_len)\n{\n unsigned char reply_codes[4] =\n { SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE,\n SSH_MSG_USERAUTH_BANNER, 0 };\n /* packet_type(1) + username_len(4) + service_len(4) +\n service(14)\"ssh-connection\" + method_len(4) = 27 */\n unsigned long methods_len;\n unsigned int banner_len;\n unsigned char *s;\n int rc;\n\n if(session->userauth_list_state == libssh2_NB_state_idle) {\n /* Zero the whole thing out */\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n\n session->userauth_list_data_len = username_len + 27;\n\n if(session->userauth_list_data) {\n LIBSSH2_FREE(session, session->userauth_list_data);\n }\n\n s = session->userauth_list_data =\n LIBSSH2_ALLOC(session, session->userauth_list_data_len);\n if(!session->userauth_list_data) {\n _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for userauth_list\");\n return NULL;\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\", 14);\n _libssh2_store_u32(&s, 4); /* send \"none\" separately */\n /* ... */\n const char *username, unsigned int username_len,\n const unsigned char *password, unsigned int password_len,\n LIBSSH2_PASSWD_CHANGEREQ_FUNC((*passwd_change_cb)))\n{\n unsigned char *s;\n static const unsigned char reply_codes[4] = {\n SSH_MSG_USERAUTH_SUCCESS,\n SSH_MSG_USERAUTH_FAILURE,\n SSH_MSG_USERAUTH_PASSWD_CHANGEREQ,\n 0\n };\n int rc;\n\n if(session->userauth_pswd_state == libssh2_NB_state_idle) {\n /* Zero the whole thing out */\n memset(&session->userauth_pswd_packet_requirev_state, 0,\n sizeof(session->userauth_pswd_packet_requirev_state));\n\n /*\n * 40 = packet_type(1) + username_len(4) + service_len(4) +\n * service(14)\"ssh-connection\" + method_len(4) + method(8)\"password\" +\n * chgpwdbool(1) + password_len(4) */\n session->userauth_pswd_data_len = username_len + 40;\n\n session->userauth_pswd_data0 =\n (unsigned char) ~SSH_MSG_USERAUTH_PASSWD_CHANGEREQ;\n\n /* TODO: remove this alloc with a fixed buffer in the session\n struct */\n s = session->userauth_pswd_data =\n LIBSSH2_ALLOC(session, session->userauth_pswd_data_len);\n if(!session->userauth_pswd_data) {\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory for \"\n \"userauth-password request\");\n }\n\n *(s++) = SSH_MSG_USERAUTH_REQUEST;\n _libssh2_store_str(&s, username, username_len);\n _libssh2_store_str(&s, \"ssh-connection\", sizeof(\"ssh-connection\") - 1);\n /* ... */\n (session->userauth_pswd_state == libssh2_NB_state_sent2)) {\n if(session->userauth_pswd_state == libssh2_NB_state_sent1) {\n _libssh2_debug((session, LIBSSH2_TRACE_AUTH,\n \"Password change required\"));\n LIBSSH2_FREE(session, session->userauth_pswd_data);\n session->userauth_pswd_data = NULL;\n }\n if(passwd_change_cb) {\n if(session->userauth_pswd_state ==\n libssh2_NB_state_sent1) {\n passwd_change_cb(session,\n &session->userauth_pswd_newpw,\n &session->userauth_pswd_newpw_len,\n &session->abstract);\n if(!session->userauth_pswd_newpw) {\n return _libssh2_error(session,\n LIBSSH2_ERROR_PASSWORD_EXPIRED,\n \"Password expired, and \"\n \"callback failed\");\n }\n\n /* basic data_len + newpw_len(4) */\n if(username_len + password_len + 44 <= UINT_MAX) {\n session->userauth_pswd_data_len =\n username_len + password_len + 44;\n s = session->userauth_pswd_data =\n LIBSSH2_ALLOC(session,\n session->userauth_pswd_data_len);\n }\n else {\n s = session->userauth_pswd_data = NULL;\n session->userauth_pswd_data_len = 0;\n }\n\n if(!session->userauth_pswd_data) {\n LIBSSH2_FREE(session,\n session->userauth_pswd_newpw);\n session->userauth_pswd_newpw = NULL;\n return _libssh2_error(session, LIBSSH2_ERROR_ALLOC,\n \"Unable to allocate memory \"\n```"}, {"role": "assistant", "content": "<<<<<<< SEARCH\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n\n session->userauth_list_data_len = username_len + 27;\n\n if(session->userauth_list_data) {\n=======\n memset(&session->userauth_list_packet_requirev_state, 0,\n sizeof(session->userauth_list_packet_requirev_state));\n\n if(username_len > UINT32_MAX - 27) {\n _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"username_len out of bounds\");\n return NULL;\n }\n\n session->userauth_list_data_len = username_len + 27;\n\n if(session->userauth_list_data) {\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n * 40 = packet_type(1) + username_len(4) + service_len(4) +\n * service(14)\"ssh-connection\" + method_len(4) + method(8)\"password\" +\n * chgpwdbool(1) + password_len(4) */\n session->userauth_pswd_data_len = username_len + 40;\n\n session->userauth_pswd_data0 =\n=======\n * 40 = packet_type(1) + username_len(4) + service_len(4) +\n * service(14)\"ssh-connection\" + method_len(4) + method(8)\"password\" +\n * chgpwdbool(1) + password_len(4) */\n if(username_len > UINT32_MAX - 40) {\n return _libssh2_error(session, LIBSSH2_ERROR_PROTO,\n \"username_len out of bounds\");\n }\n\n session->userauth_pswd_data_len = username_len + 40;\n\n session->userauth_pswd_data0 =\n>>>>>>> REPLACE\n<<<<<<< SEARCH\n }\n\n /* basic data_len + newpw_len(4) */\n if(username_len + password_len + 44 <= UINT_MAX) {\n session->userauth_pswd_data_len =\n username_len + password_len + 44;\n s = session->userauth_pswd_data =\n=======\n }\n\n /* basic data_len + newpw_len(4) */\n if(username_len <= UINT32_MAX - password_len - 44) {\n session->userauth_pswd_data_len =\n username_len + password_len + 44;\n s = session->userauth_pswd_data =\n>>>>>>> REPLACE"}]}